"""Support for the Airly sensor service.""" from __future__ import annotations from typing import cast from homeassistant.components.sensor import ATTR_STATE_CLASS, SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( ATTR_ATTRIBUTION, ATTR_DEVICE_CLASS, ATTR_ICON, CONF_NAME, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import StateType from homeassistant.helpers.update_coordinator import CoordinatorEntity from . import AirlyDataUpdateCoordinator from .const import ( ATTR_API_PM1, ATTR_API_PRESSURE, ATTR_LABEL, ATTR_UNIT, ATTRIBUTION, DEFAULT_NAME, DOMAIN, MANUFACTURER, SENSOR_TYPES, ) PARALLEL_UPDATES = 1 async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback ) -> None: """Set up Airly sensor entities based on a config entry.""" name = entry.data[CONF_NAME] coordinator = hass.data[DOMAIN][entry.entry_id] sensors = [] for sensor in SENSOR_TYPES: # When we use the nearest method, we are not sure which sensors are available if coordinator.data.get(sensor): sensors.append(AirlySensor(coordinator, name, sensor)) async_add_entities(sensors, False) class AirlySensor(CoordinatorEntity, SensorEntity): """Define an Airly sensor.""" coordinator: AirlyDataUpdateCoordinator def __init__( self, coordinator: AirlyDataUpdateCoordinator, name: str, kind: str ) -> None: """Initialize.""" super().__init__(coordinator) description = SENSOR_TYPES[kind] self._attr_device_class = description[ATTR_DEVICE_CLASS] self._attr_extra_state_attributes = {ATTR_ATTRIBUTION: ATTRIBUTION} self._attr_icon = description[ATTR_ICON] self._attr_name = f"{name} {description[ATTR_LABEL]}" self._attr_state_class = description[ATTR_STATE_CLASS] self._attr_unique_id = ( f"{coordinator.latitude}-{coordinator.longitude}-{kind.lower()}" ) self._attr_unit_of_measurement = description[ATTR_UNIT] self.kind = kind self._state = None @property def state(self) -> StateType: """Return the state.""" self._state = self.coordinator.data[self.kind] if self.kind in [ATTR_API_PM1, ATTR_API_PRESSURE]: return round(cast(float, self._state)) return round(cast(float, self._state), 1) @property def device_info(self) -> DeviceInfo: """Return the device info.""" return { "identifiers": { ( DOMAIN, f"{self.coordinator.latitude}-{self.coordinator.longitude}", ) }, "name": DEFAULT_NAME, "manufacturer": MANUFACTURER, "entry_type": "service", }