ha-2gis-weather/custom_components/two_gis_weather/sensor.py
2025-11-04 11:21:01 +06:00

57 lines
1.9 KiB
Python

from __future__ import annotations
from homeassistant.components.sensor import SensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import UnitOfPressure, UnitOfSpeed, UnitOfTemperature
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN
from .coordinator import TwoGisWeatherUpdateCoordinator
SENSOR_SPECS = [
("feels_like", "Feels like", UnitOfTemperature.CELSIUS),
("wind_speed", "Wind speed", UnitOfSpeed.METERS_PER_SECOND),
("wind_bearing", "Wind bearing", None),
("pressure", "Pressure", UnitOfPressure.HPA),
("description", "Weather description", None),
("icon", "2GIS icon", None),
]
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
coordinator: TwoGisWeatherUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]
entities: list[SensorEntity] = []
for key, name, unit in SENSOR_SPECS:
entities.append(TwoGisWeatherSensor(coordinator, entry, key, name, unit))
async_add_entities(entities)
class TwoGisWeatherSensor(CoordinatorEntity[TwoGisWeatherUpdateCoordinator], SensorEntity):
_attr_has_entity_name = True
def __init__(
self,
coordinator: TwoGisWeatherUpdateCoordinator,
entry: ConfigEntry,
key: str,
name: str,
unit: str | None,
) -> None:
super().__init__(coordinator)
self._entry = entry
self._key = key
self._attr_name = name
self._attr_unique_id = f"{entry.entry_id}_sensor_{key}"
self._attr_native_unit_of_measurement = unit
@property
def native_value(self):
current = (self.coordinator.data or {}).get("current", {})
return current.get(self._key)