hass-core/homeassistant/components/zoneminder/switch.py

82 lines
2.5 KiB
Python
Raw Normal View History

"""Support for ZoneMinder switches."""
from __future__ import annotations
import logging
2022-09-06 14:01:09 +02:00
from typing import Any
import voluptuous as vol
2022-09-19 15:05:29 +02:00
from zoneminder.monitor import Monitor, MonitorState
from zoneminder.zm import ZoneMinder
2020-10-07 16:28:49 +02:00
from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchEntity
from homeassistant.const import CONF_COMMAND_OFF, CONF_COMMAND_ON
from homeassistant.core import HomeAssistant
2020-10-07 16:28:49 +02:00
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
2020-10-07 16:28:49 +02:00
from . import DOMAIN as ZONEMINDER_DOMAIN
_LOGGER = logging.getLogger(__name__)
2019-07-31 12:25:30 -07:00
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
2020-10-07 16:28:49 +02:00
vol.Required(CONF_COMMAND_ON): cv.string,
vol.Required(CONF_COMMAND_OFF): cv.string,
2019-07-31 12:25:30 -07:00
}
)
def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
2020-10-07 16:28:49 +02:00
"""Set up the ZoneMinder switch platform."""
2019-07-31 12:25:30 -07:00
2020-10-07 16:28:49 +02:00
on_state = MonitorState(config.get(CONF_COMMAND_ON))
off_state = MonitorState(config.get(CONF_COMMAND_OFF))
switches = []
2022-09-19 15:05:29 +02:00
zm_client: ZoneMinder
2020-10-07 16:28:49 +02:00
for zm_client in hass.data[ZONEMINDER_DOMAIN].values():
2021-10-31 18:35:27 +01:00
if not (monitors := zm_client.get_monitors()):
2020-10-07 16:28:49 +02:00
_LOGGER.warning("Could not fetch monitors from ZoneMinder")
return
2020-10-07 16:28:49 +02:00
for monitor in monitors:
switches.append(ZMSwitchMonitors(monitor, on_state, off_state))
add_entities(switches)
class ZMSwitchMonitors(SwitchEntity):
"""Representation of a ZoneMinder switch."""
2019-07-31 12:25:30 -07:00
icon = "mdi:record-rec"
2022-09-19 15:05:29 +02:00
def __init__(self, monitor: Monitor, on_state: str, off_state: str) -> None:
"""Initialize the switch."""
self._monitor = monitor
self._on_state = on_state
self._off_state = off_state
2022-09-19 15:05:29 +02:00
self._state: bool | None = None
self._attr_name = f"{monitor.name} State"
2022-09-06 14:01:09 +02:00
def update(self) -> None:
"""Update the switch value."""
self._state = self._monitor.function == self._on_state
@property
2022-09-19 15:05:29 +02:00
def is_on(self) -> bool | None:
"""Return True if entity is on."""
return self._state
2022-09-06 14:01:09 +02:00
def turn_on(self, **kwargs: Any) -> None:
"""Turn the entity on."""
self._monitor.function = self._on_state
2022-09-06 14:01:09 +02:00
def turn_off(self, **kwargs: Any) -> None:
"""Turn the entity off."""
self._monitor.function = self._off_state