"""Diagnosewerte eines ninstrip.""" from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from datetime import datetime, timedelta from typing import Any from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorStateClass, ) from homeassistant.const import ( SIGNAL_STRENGTH_DECIBELS_MILLIWATT, EntityCategory, UnitOfElectricCurrent, UnitOfInformation, UnitOfPower, UnitOfTime, ) from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.util import dt as dt_util from .coordinator import NinstripConfigEntry, NinstripCoordinator, NinstripData from .entity import NinstripEntity # Die Laufzeit springt bei jeder Abfrage um ein paar Sekunden; daraus eine # Startzeit zu rechnen ergaebe sonst dauernd einen neuen Zeitstempel. Wie # ha-ninlight. BOOT_TIME_TOLERANCE = timedelta(seconds=30) @dataclass(frozen=True, kw_only=True) class NinstripSensorDescription(SensorEntityDescription): """Beschreibung samt Zugriff auf den Wert.""" value: Callable[[NinstripData], Any] def _wifi(data: NinstripData, key: str) -> Any: wifi = data.info.get("wifi") return wifi.get(key) if isinstance(wifi, dict) else None def _strip(data: NinstripData, key: str) -> Any: strip = data.info.get("strip") return strip.get(key) if isinstance(strip, dict) else None SENSORS: tuple[NinstripSensorDescription, ...] = ( # Von Haus aus an: die Adresse ist das, was man im Alltag sucht - fuer die # Firmware-API, zum Anpingen oder um ein Geraet wiederzufinden. Wie in # ha-ninlight. NinstripSensorDescription( key="ip_address", translation_key="ip_address", entity_category=EntityCategory.DIAGNOSTIC, value=lambda d: _wifi(d, "ip"), ), NinstripSensorDescription( key="rssi", translation_key="rssi", device_class=SensorDeviceClass.SIGNAL_STRENGTH, native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS_MILLIWATT, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, value=lambda d: _wifi(d, "rssi"), ), NinstripSensorDescription( key="uptime", translation_key="uptime", native_unit_of_measurement=UnitOfTime.SECONDS, device_class=SensorDeviceClass.DURATION, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, value=lambda d: d.info.get("uptime"), ), NinstripSensorDescription( key="free_heap", translation_key="free_heap", native_unit_of_measurement=UnitOfInformation.BYTES, device_class=SensorDeviceClass.DATA_SIZE, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, value=lambda d: d.info.get("free_heap"), ), # Sagt, ob die Strombegrenzung gerade herunterregelt. 100 heisst: nein. NinstripSensorDescription( key="power_scale", translation_key="power_scale", native_unit_of_measurement="%", state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, value=lambda d: _strip(d, "power_scale"), ), # 0 mA heisst entweder "zieht gerade nichts" oder "misst gar nicht" - # aeltere Firmware ohne Shunt meldet ebenfalls 0. Von aussen nicht zu # unterscheiden, und keine Heuristik dagegen: Schwaeche der Geraete-API. NinstripSensorDescription( key="current", translation_key="current", device_class=SensorDeviceClass.CURRENT, native_unit_of_measurement=UnitOfElectricCurrent.MILLIAMPERE, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, value=lambda d: _strip(d, "current_ma"), ), NinstripSensorDescription( key="power", translation_key="power", device_class=SensorDeviceClass.POWER, native_unit_of_measurement=UnitOfPower.WATT, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, value=lambda d: _strip(d, "power_w"), ), # Was bei der letzten Aktualisierung schiefging - leer, solange nichts # schiefging. Aus der Ferne der einzige Hinweis darauf. NinstripSensorDescription( key="last_ota_error", translation_key="last_ota_error", entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, value=lambda d: d.info.get("last_ota_error"), ), ) async def async_setup_entry( hass: HomeAssistant, entry: NinstripConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: coordinator = entry.runtime_data entitaeten: list[SensorEntity] = [NinstripSensor(coordinator, d) for d in SENSORS] entitaeten.append(NinstripBootTimeSensor(coordinator)) async_add_entities(entitaeten) class NinstripSensor(NinstripEntity, SensorEntity): entity_description: NinstripSensorDescription def __init__( self, coordinator: NinstripCoordinator, description: NinstripSensorDescription ) -> None: super().__init__(coordinator, description.key) self.entity_description = description @property def native_value(self) -> Any: return self.entity_description.value(self.coordinator.data) class NinstripBootTimeSensor(NinstripEntity, SensorEntity): """Wann der Strip zuletzt gestartet ist - ein Zeitstempel statt einer Laufzeit, die jede Abfrage weiterlaeuft.""" _attr_device_class = SensorDeviceClass.TIMESTAMP _attr_entity_category = EntityCategory.DIAGNOSTIC _attr_entity_registry_enabled_default = False _attr_translation_key = "boot_time" def __init__(self, coordinator: NinstripCoordinator) -> None: super().__init__(coordinator, "boot_time") self._boot: datetime | None = None self._boot_aktualisieren() def _boot_aktualisieren(self) -> None: uptime = self.coordinator.data.info.get("uptime") if not isinstance(uptime, (int, float)): return boot = dt_util.utcnow() - timedelta(seconds=uptime) # Nur uebernehmen, wenn er wirklich abweicht - sonst wandert der # Zeitstempel bei jeder Abfrage um die Messungenauigkeit. if self._boot is None or abs(boot - self._boot) > BOOT_TIME_TOLERANCE: self._boot = boot @callback def _handle_coordinator_update(self) -> None: self._boot_aktualisieren() super()._handle_coordinator_update() @property def native_value(self) -> datetime | None: return self._boot