"""The Linky Tariff integration.""" from __future__ import annotations import logging from typing import Any from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_IEEE, CONF_SCAN_INTERVAL from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import DataUpdateCoordinator from .const import ( DOMAIN, CONF_POLL_INTERVAL, CLUSTER_ID, ATTRIBUTE_ID, ENDPOINT_ID, PLATFORMS, ) _LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Linky Tariff from a config entry.""" hass.data.setdefault(DOMAIN, {}) coordinator = LinkyTariffCoordinator( hass, entry.data[CONF_IEEE], entry.options.get(CONF_POLL_INTERVAL, entry.data.get(CONF_POLL_INTERVAL, 60)), ) await coordinator.async_config_entry_first_refresh() hass.data[DOMAIN][entry.entry_id] = coordinator await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) entry.async_on_unload(entry.add_update_listener(async_update_options)) return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS): hass.data[DOMAIN].pop(entry.entry_id) return unload_ok async def async_update_options(hass: HomeAssistant, entry: ConfigEntry) -> None: """Update options.""" await hass.config_entries.async_reload(entry.entry_id) class LinkyTariffCoordinator(DataUpdateCoordinator): """Class to manage fetching Linky Tariff data.""" def __init__(self, hass: HomeAssistant, ieee: str, poll_interval: int) -> None: """Initialize.""" super().__init__( hass, _LOGGER, name=DOMAIN, update_interval=poll_interval, ) self.ieee = ieee self._attr = None async def _async_update_data(self) -> dict[str, Any]: """Fetch data from ZHA device.""" try: result = await self.hass.services.async_call( "zha_toolkit", "attr_read", { "ieee": self.ieee, "endpoint_id": ENDPOINT_ID, "cluster_id": CLUSTER_ID, "attribute_id": ATTRIBUTE_ID, "manufacturer": None, }, blocking=True, return_response=True, ) if result and "value" in result: return { "value": result["value"], "last_update": self.hass.config.time_utc(), } return {"value": "unknown", "last_update": self.hass.config.time_utc()} except Exception as ex: _LOGGER.error("Error reading Linky tariff: %s", ex) return {"value": "error", "last_update": self.hass.config.time_utc()}