ha-linak-desk/custom_components/linak_desk/sensor.py

95 lines
2.6 KiB
Python
Raw Normal View History

2023-03-17 18:26:04 +01:00
"""Linak Sensors"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any
from collections.abc import Callable
from homeassistant.components.sensor import (
SensorEntity,
SensorEntityDescription,
SensorDeviceClass,
)
from homeassistant.components.sensor import SensorStateClass
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import UnitOfSpeed, UnitOfLength
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import StateType
from .model import LinakBluetoothEntity, LinakDataUpdateCoordinator
from .api import Device
from .const import DOMAIN
@dataclass
class LinakSensorEntityDescriptionMixin:
"""Mixin for required keys"""
state_fn: Callable[[Device], Any]
@dataclass
class LinakSensorEntityDescription(
SensorEntityDescription, LinakSensorEntityDescriptionMixin
):
2023-11-01 19:47:12 +01:00
"""Describes Linak sensor entity"""
2023-03-17 18:26:04 +01:00
DEVICE_ENTITY_DESCRIPTIONS: list[LinakSensorEntityDescription] = [
LinakSensorEntityDescription(
device_class=SensorDeviceClass.DISTANCE,
key="height",
name="Height",
native_unit_of_measurement=UnitOfLength.MILLIMETERS,
state_class=SensorStateClass.MEASUREMENT,
state_fn=lambda device: device.height,
),
LinakSensorEntityDescription(
device_class=SensorDeviceClass.SPEED,
key="speed",
name="Speed",
native_unit_of_measurement=UnitOfSpeed.METERS_PER_SECOND,
state_class=SensorStateClass.MEASUREMENT,
state_fn=lambda device: device.speed / 1000,
),
]
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up the sensor platform"""
coordinator: LinakDataUpdateCoordinator = hass.data[DOMAIN][config_entry.entry_id]
async_add_entities(
LinakSensorEntity(coordinator, description)
for description in DEVICE_ENTITY_DESCRIPTIONS
)
class LinakSensorEntity(LinakBluetoothEntity, SensorEntity):
"""Linak desk sensor"""
entity_description: LinakSensorEntityDescription
def __init__(
self,
coordinator: LinakDataUpdateCoordinator,
entity_description: LinakSensorEntityDescription,
) -> None:
super().__init__(coordinator)
self._attr_unique_id = f"{self._device.mac}-{entity_description.key}"
self.entity_description = entity_description
@property
def native_value(self) -> StateType:
return self.entity_description.state_fn(self._device)