homeassistant-zoneminder-alarm/custom_components/switch.py

80 lines
2.4 KiB
Python
Raw Normal View History

2022-01-24 22:35:55 +01:00
"""Support for ZoneMinder switches."""
from __future__ import annotations
import logging
from zoneminder.monitor import Monitor
from zoneminder.zm import ZoneMinder
from homeassistant.components.switch import SwitchEntity
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from homeassistant.components.zoneminder import DOMAIN as ZONEMINDER_DOMAIN
_LOGGER = logging.getLogger(__name__)
def setup_platform(
hass: HomeAssistant,
config: ConfigType, # pylint: disable=unused-argument
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None, # pylint: disable=unused-argument
) -> None:
"""Set up the ZoneMinder switch platform."""
switches = []
for zm_client in hass.data[ZONEMINDER_DOMAIN].values():
if not (monitors := zm_client.get_monitors()):
_LOGGER.warning("Could not fetch monitors from ZoneMinder")
return
for monitor in monitors:
switches.append(ZMSwitchMonitors(zm_client, monitor))
add_entities(switches)
class ZMSwitchMonitors(SwitchEntity):
"""Representation of a ZoneMinder switch."""
icon = "mdi:alarm-bell"
def __init__(self, client: ZoneMinder, monitor: Monitor):
"""Initialize the switch."""
self._client = client
self._monitor = monitor
self._state = None
@property
def name(self):
"""Return the name of the switch."""
return f"{self._monitor.name} Alarm Status"
def update(self):
"""Update the switch value."""
data = self._get_data("status")
self._state = int(data["status"]) > 0
def _get_data(self, command: str):
return self._client.get_state(
f"api/monitors/alarm/id:{self._monitor.id}/command:{command}.json"
)
@property
def is_on(self):
"""Return True if entity is on."""
return self._state
def turn_on(self, **kwargs):
"""Turn the entity on."""
result = self._get_data("on")
data = self._get_data("status")
self._state = int(data["status"]) > 0
return result
def turn_off(self, **kwargs):
"""Turn the entity off."""
result = self._get_data("off")
data = self._get_data("status")
self._state = int(data["status"]) > 0
return result