core/homeassistant/components/notion/sensor.py

78 lines
2.4 KiB
Python
Raw Normal View History

"""Support for Notion sensors."""
from dataclasses import dataclass
from aionotion.sensor.models import ListenerKind
from homeassistant.components.sensor import (
2021-12-15 20:46:48 +00:00
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
2021-12-15 20:46:48 +00:00
SensorStateClass,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import UnitOfTemperature
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from . import NotionEntity
from .const import DOMAIN, LOGGER, SENSOR_TEMPERATURE
from .model import NotionEntityDescriptionMixin
@dataclass
class NotionSensorDescription(SensorEntityDescription, NotionEntityDescriptionMixin):
"""Describe a Notion sensor."""
SENSOR_DESCRIPTIONS = (
NotionSensorDescription(
key=SENSOR_TEMPERATURE,
name="Temperature",
2021-12-15 20:46:48 +00:00
device_class=SensorDeviceClass.TEMPERATURE,
native_unit_of_measurement=UnitOfTemperature.CELSIUS,
2021-12-15 20:46:48 +00:00
state_class=SensorStateClass.MEASUREMENT,
listener_kind=ListenerKind.TEMPERATURE,
),
)
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
"""Set up Notion sensors based on a config entry."""
coordinator = hass.data[DOMAIN][entry.entry_id]
async_add_entities(
[
NotionSensor(
coordinator,
listener_id,
sensor.uuid,
sensor.bridge.id,
sensor.system_id,
description,
2019-07-31 19:25:30 +00:00
)
for listener_id, listener in coordinator.data.listeners.items()
for description in SENSOR_DESCRIPTIONS
if description.listener_kind == listener.listener_kind
and (sensor := coordinator.data.sensors[listener.sensor_id])
]
)
class NotionSensor(NotionEntity, SensorEntity):
"""Define a Notion sensor."""
@callback
def _async_update_from_latest_data(self) -> None:
"""Fetch new state data for the sensor."""
listener = self.coordinator.data.listeners[self._listener_id]
if listener.listener_kind == ListenerKind.TEMPERATURE:
2023-04-23 09:24:39 +00:00
self._attr_native_value = round(listener.status.temperature, 1) # type: ignore[attr-defined]
else:
LOGGER.error(
"Unknown listener type for sensor %s",
self.coordinator.data.sensors[self._sensor_id],
2019-07-31 19:25:30 +00:00
)