feat: Einstellungen, Neustart, Diagnose-Sensoren und Diagnose-Download

This commit is contained in:
Michael Sauer
2026-09-16 16:08:47 +02:00
parent be0a8e21b6
commit cc318c9d25
13 changed files with 608 additions and 1 deletions
+8 -1
View File
@@ -13,7 +13,14 @@ from .api import NinlightClient
from .const import DEFAULT_TOKEN, DOMAIN
from .coordinator import NinlightConfigEntry, NinlightCoordinator
PLATFORMS: list[Platform] = [Platform.LIGHT]
PLATFORMS: list[Platform] = [
Platform.BUTTON,
Platform.LIGHT,
Platform.NUMBER,
Platform.SELECT,
Platform.SENSOR,
Platform.SWITCH,
]
async def async_setup_entry(hass: HomeAssistant, entry: NinlightConfigEntry) -> bool:
+34
View File
@@ -0,0 +1,34 @@
"""Reboot button of a ninlight lamp. A factory reset is deliberately not offered."""
from __future__ import annotations
from homeassistant.components.button import ButtonDeviceClass, ButtonEntity
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import NinlightConfigEntry, NinlightCoordinator
from .entity import NinlightEntity
PARALLEL_UPDATES = 0
async def async_setup_entry(
hass: HomeAssistant,
entry: NinlightConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
async_add_entities([NinlightRebootButton(entry.runtime_data)])
class NinlightRebootButton(NinlightEntity, ButtonEntity):
"""Restart the lamp."""
_attr_device_class = ButtonDeviceClass.RESTART
_attr_entity_category = EntityCategory.CONFIG
def __init__(self, coordinator: NinlightCoordinator) -> None:
super().__init__(coordinator, "reboot")
async def async_press(self) -> None:
await self.coordinator.async_call(lambda client: client.reboot())
+27
View File
@@ -0,0 +1,27 @@
"""Diagnostics download for ninlight lamps."""
from __future__ import annotations
from typing import Any
from homeassistant.components.diagnostics import async_redact_data
from homeassistant.const import CONF_HOST, CONF_TOKEN
from homeassistant.core import HomeAssistant
from .coordinator import NinlightConfigEntry
TO_REDACT = {CONF_TOKEN, CONF_HOST, "ssid", "mac", "ip", "sta_ip"}
async def async_get_config_entry_diagnostics(
hass: HomeAssistant, entry: NinlightConfigEntry
) -> dict[str, Any]:
coordinator = entry.runtime_data
return async_redact_data(
{
"entry": {"data": dict(entry.data), "options": dict(entry.options)},
"state": coordinator.data.state,
"info": coordinator.data.info,
},
TO_REDACT,
)
+69
View File
@@ -0,0 +1,69 @@
"""Fade and transition settings of a ninlight lamp."""
from __future__ import annotations
from dataclasses import dataclass
from homeassistant.components.number import (
NumberDeviceClass,
NumberEntity,
NumberEntityDescription,
NumberMode,
)
from homeassistant.const import EntityCategory, UnitOfTime
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import NinlightConfigEntry, NinlightCoordinator
from .entity import NinlightEntity
PARALLEL_UPDATES = 0
@dataclass(frozen=True, kw_only=True)
class NinlightNumberDescription(NumberEntityDescription):
"""A millisecond setting stored under `key` in the lamp state."""
entity_category: EntityCategory = EntityCategory.CONFIG
device_class: NumberDeviceClass = NumberDeviceClass.DURATION
native_unit_of_measurement: str = UnitOfTime.MILLISECONDS
native_min_value: float = 0
native_step: float = 50
mode: NumberMode = NumberMode.BOX
NUMBERS = (
NinlightNumberDescription(key="fade_in", translation_key="fade_in", native_max_value=10_000),
NinlightNumberDescription(key="fade_out", translation_key="fade_out", native_max_value=10_000),
NinlightNumberDescription(
key="transition_default", translation_key="transition_default", native_max_value=60_000
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: NinlightConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
async_add_entities(NinlightNumber(entry.runtime_data, description) for description in NUMBERS)
class NinlightNumber(NinlightEntity, NumberEntity):
"""One millisecond setting."""
entity_description: NinlightNumberDescription
def __init__(
self, coordinator: NinlightCoordinator, description: NinlightNumberDescription
) -> None:
super().__init__(coordinator, description.key)
self.entity_description = description
@property
def native_value(self) -> int | None:
value = self.coordinator.data.state.get(self.entity_description.key)
return int(value) if value is not None else None
async def async_set_native_value(self, value: float) -> None:
await self.coordinator.async_set_state(**{self.entity_description.key: int(value)})
+43
View File
@@ -0,0 +1,43 @@
"""Power-on behaviour of a ninlight lamp."""
from __future__ import annotations
from homeassistant.components.select import SelectEntity
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import NinlightConfigEntry, NinlightCoordinator
from .entity import NinlightEntity
PARALLEL_UPDATES = 0
# POB_NAMES in the firmware's nl_api.c
POWER_ON_OPTIONS = ["last", "on", "off"]
async def async_setup_entry(
hass: HomeAssistant,
entry: NinlightConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
async_add_entities([NinlightPowerOnSelect(entry.runtime_data)])
class NinlightPowerOnSelect(NinlightEntity, SelectEntity):
"""What the lamp does when power returns."""
_attr_entity_category = EntityCategory.CONFIG
_attr_translation_key = "power_on_behaviour"
_attr_options = POWER_ON_OPTIONS
def __init__(self, coordinator: NinlightCoordinator) -> None:
super().__init__(coordinator, "power_on_behaviour")
@property
def current_option(self) -> str | None:
value = self.coordinator.data.state.get("power_on_behaviour")
return value if value in POWER_ON_OPTIONS else None
async def async_select_option(self, option: str) -> None:
await self.coordinator.async_set_state(power_on_behaviour=option)
+135
View File
@@ -0,0 +1,135 @@
"""Diagnostic sensors of a ninlight lamp."""
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,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.util import dt as dt_util
from .coordinator import NinlightConfigEntry, NinlightCoordinator, NinlightData
from .entity import NinlightEntity
PARALLEL_UPDATES = 0
# A new boot time is only published when it moves by more than this: uptime and the local
# clock drift a few seconds against each other on every poll.
BOOT_TIME_TOLERANCE = timedelta(seconds=60)
def _wifi(data: NinlightData) -> dict[str, Any]:
wifi = data.info.get("wifi")
return wifi if isinstance(wifi, dict) else {}
@dataclass(frozen=True, kw_only=True)
class NinlightSensorDescription(SensorEntityDescription):
"""A sensor reading one value out of the lamp data."""
value_fn: Callable[[NinlightData], Any]
entity_category: EntityCategory = EntityCategory.DIAGNOSTIC
SENSORS = (
NinlightSensorDescription(
key="rssi",
device_class=SensorDeviceClass.SIGNAL_STRENGTH,
native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS_MILLIWATT,
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda data: _wifi(data).get("rssi"),
),
NinlightSensorDescription(
key="ip_address",
translation_key="ip_address",
entity_registry_enabled_default=False,
value_fn=lambda data: _wifi(data).get("ip"),
),
NinlightSensorDescription(
key="free_heap",
translation_key="free_heap",
device_class=SensorDeviceClass.DATA_SIZE,
native_unit_of_measurement=UnitOfInformation.BYTES,
state_class=SensorStateClass.MEASUREMENT,
entity_registry_enabled_default=False,
value_fn=lambda data: data.info.get("free_heap"),
),
NinlightSensorDescription(
key="last_ota_error",
translation_key="last_ota_error",
entity_registry_enabled_default=False,
value_fn=lambda data: data.info.get("last_ota_error"),
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: NinlightConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
coordinator = entry.runtime_data
entities: list[SensorEntity] = [NinlightSensor(coordinator, d) for d in SENSORS]
entities.append(NinlightBootTimeSensor(coordinator))
async_add_entities(entities)
class NinlightSensor(NinlightEntity, SensorEntity):
"""A plain diagnostic value."""
entity_description: NinlightSensorDescription
def __init__(
self, coordinator: NinlightCoordinator, description: NinlightSensorDescription
) -> None:
super().__init__(coordinator, description.key)
self.entity_description = description
@property
def native_value(self) -> Any:
return self.entity_description.value_fn(self.coordinator.data)
class NinlightBootTimeSensor(NinlightEntity, SensorEntity):
"""When the lamp last started - a timestamp instead of an ever-growing uptime."""
_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: NinlightCoordinator) -> None:
super().__init__(coordinator, "boot_time")
self._boot: datetime | None = None
self._update_boot()
def _update_boot(self) -> None:
uptime = self.coordinator.data.info.get("uptime")
if not isinstance(uptime, int | float):
return
boot = dt_util.utcnow() - timedelta(seconds=uptime)
if self._boot is None or abs(boot - self._boot) > BOOT_TIME_TOLERANCE:
self._boot = boot
@callback
def _handle_coordinator_update(self) -> None:
self._update_boot()
super()._handle_coordinator_update()
@property
def native_value(self) -> datetime | None:
return self._boot
+43
View File
@@ -0,0 +1,43 @@
"""Wake-on-change switch of a ninlight lamp."""
from __future__ import annotations
from typing import Any
from homeassistant.components.switch import SwitchEntity
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import NinlightConfigEntry, NinlightCoordinator
from .entity import NinlightEntity
PARALLEL_UPDATES = 0
async def async_setup_entry(
hass: HomeAssistant,
entry: NinlightConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
async_add_entities([NinlightWakeSwitch(entry.runtime_data)])
class NinlightWakeSwitch(NinlightEntity, SwitchEntity):
"""Turn the lamp on when its colour, temperature or brightness is changed."""
_attr_entity_category = EntityCategory.CONFIG
_attr_translation_key = "wake_on_change"
def __init__(self, coordinator: NinlightCoordinator) -> None:
super().__init__(coordinator, "wake_on_change")
@property
def is_on(self) -> bool:
return bool(self.coordinator.data.state.get("wake_on_change"))
async def async_turn_on(self, **kwargs: Any) -> None:
await self.coordinator.async_set_state(wake_on_change=True)
async def async_turn_off(self, **kwargs: Any) -> None:
await self.coordinator.async_set_state(wake_on_change=False)