136 lines
4.3 KiB
Python
136 lines
4.3 KiB
Python
"""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
|