core/homeassistant/components/mysensors/notify.py

69 lines
2.2 KiB
Python
Raw Normal View History

"""MySensors notification service."""
2021-06-07 14:04:04 +00:00
from __future__ import annotations
from typing import Any
from homeassistant.components import mysensors
2022-01-08 19:55:24 +00:00
from homeassistant.components.notify import ATTR_TARGET, BaseNotificationService
from homeassistant.const import Platform
2021-06-07 14:04:04 +00:00
from homeassistant.core import HomeAssistant
from .const import DevId, DiscoveryInfo
2021-06-07 14:04:04 +00:00
async def async_get_service(
hass: HomeAssistant,
config: dict[str, Any],
discovery_info: DiscoveryInfo | None = None,
) -> BaseNotificationService | None:
"""Get the MySensors notification service."""
2021-03-06 17:33:55 +00:00
if not discovery_info:
return None
new_devices = mysensors.setup_mysensors_platform(
2022-01-08 19:55:24 +00:00
hass, Platform.NOTIFY, discovery_info, MySensorsNotificationDevice
2019-07-31 19:25:30 +00:00
)
if not new_devices:
return None
return MySensorsNotificationService(hass)
class MySensorsNotificationDevice(mysensors.device.MySensorsDevice):
"""Represent a MySensors Notification device."""
2021-06-07 14:04:04 +00:00
def send_msg(self, msg: str) -> None:
"""Send a message."""
2019-07-31 19:25:30 +00:00
for sub_msg in [msg[i : i + 25] for i in range(0, len(msg), 25)]:
# Max mysensors payload is 25 bytes.
self.gateway.set_child_value(
2019-07-31 19:25:30 +00:00
self.node_id, self.child_id, self.value_type, sub_msg
)
2021-06-07 14:04:04 +00:00
def __repr__(self) -> str:
"""Return the representation."""
return f"<MySensorsNotificationDevice {self.name}>"
class MySensorsNotificationService(BaseNotificationService):
"""Implement a MySensors notification service."""
2021-06-07 14:04:04 +00:00
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize the service."""
2021-06-07 14:04:04 +00:00
self.devices: dict[
DevId, MySensorsNotificationDevice
] = mysensors.get_mysensors_devices(
2022-01-08 19:55:24 +00:00
hass, Platform.NOTIFY
2021-06-07 14:04:04 +00:00
) # type: ignore[assignment]
2021-06-07 14:04:04 +00:00
async def async_send_message(self, message: str = "", **kwargs: Any) -> None:
"""Send a message to a user."""
target_devices = kwargs.get(ATTR_TARGET)
2019-07-31 19:25:30 +00:00
devices = [
device
for device in self.devices.values()
if target_devices is None or device.name in target_devices
]
for device in devices:
device.send_msg(message)