Michaels Befund: die Integration ist nicht dasselbe wie die von ninlight. Verglichen und die Luecken geschlossen - alle Felder gibt es in der Firmware schon, sie waren nur nicht bedienbar: * number: fade_in, fade_out, transition_default in Millisekunden, mit den Grenzen der Firmware (10 s, 10 s, 60 s). * select: Einschaltverhalten (last, on, off). * switch: bei Aenderung einschalten. * light: Uebergangszeit beim Ein- und Ausschalten. HA rechnet in Sekunden, das Geraet in Millisekunden; laengeres als 60 s wird gekappt, sonst wiese das Geraet die ganze Anfrage mit 400 ab. Ohne Angabe wird kein Feld geschickt, sonst ueberschriebe jeder Schaltbefehl die Vorgabe. * sensor: letzter Update-Fehler und Startzeit (Zeitstempel statt einer Laufzeit, die jede Abfrage weiterlaeuft), beide ab Werk aus. * diagnostics.py: Diagnosedaten zum Herunterladen, ohne Token, Adressen, MAC und SSID. * config_flow: Neu-Konfigurieren von Adresse und Token, mit Gegenprobe der MAC - ein Tippfehler in der Adresse soll nicht still den falschen Eintrag umbiegen. * Hinweis in den Reparaturen, wenn ein Geraet noch auf dem oeffentlichen Werks-Token steht. Nicht uebernommen: die Auswahl sacn_layout. ninstrip ist immer rgb, ein Strip hat keinen Masterkanal - eine Auswahl mit einer Option waere nur Zierde. 241 Tests, 97 %. Die Kappung der Uebergangszeit per Mutation gegengeprueft.
170 lines
5.8 KiB
Python
170 lines
5.8 KiB
Python
"""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,
|
|
UnitOfInformation,
|
|
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"),
|
|
),
|
|
# 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
|