homeassistant-zoneminder-alarm/custom_components/zoneminder_alarm/sensor.py

71 lines
2.1 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.sensor import (
SensorEntity,
)
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."""
sensors = []
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:
sensors.append(ZMSensorAlarm(zm_client, monitor))
add_entities(sensors)
class ZMSensorAlarm(SensorEntity):
"""Representation of a Sensor."""
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")
state = int(data["status"])
if state == 0:
self._state = "Normal"
if state == 1:
self._state = "Warnung"
if state == 2:
self._state = "Alarm"
@property
def native_value(self):
return self._state
def _get_data(self, command: str):
return self._client.get_state(
f"api/monitors/alarm/id:{self._monitor.id}/command:{command}.json"
)