|
| 1 | +"""Hanna Instruments data coordinator for Home Assistant. |
| 2 | +
|
| 3 | +This module provides the data coordinator for fetching and managing Hanna Instruments |
| 4 | +sensor data. |
| 5 | +""" |
| 6 | + |
| 7 | +from datetime import timedelta |
| 8 | +import logging |
| 9 | +from typing import Any |
| 10 | + |
| 11 | +from hanna_cloud import HannaCloudClient |
| 12 | +from requests.exceptions import RequestException |
| 13 | + |
| 14 | +from homeassistant.config_entries import ConfigEntry |
| 15 | +from homeassistant.core import HomeAssistant |
| 16 | +from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed |
| 17 | + |
| 18 | +from .const import DOMAIN |
| 19 | + |
| 20 | +type HannaConfigEntry = ConfigEntry[dict[str, HannaDataCoordinator]] |
| 21 | + |
| 22 | +_LOGGER = logging.getLogger(__name__) |
| 23 | + |
| 24 | + |
| 25 | +class HannaDataCoordinator(DataUpdateCoordinator[dict[str, Any]]): |
| 26 | + """Coordinator for fetching Hanna sensor data.""" |
| 27 | + |
| 28 | + def __init__( |
| 29 | + self, |
| 30 | + hass: HomeAssistant, |
| 31 | + config_entry: HannaConfigEntry, |
| 32 | + device: dict[str, Any], |
| 33 | + api_client: HannaCloudClient, |
| 34 | + ) -> None: |
| 35 | + """Initialize the Hanna data coordinator.""" |
| 36 | + self.api_client = api_client |
| 37 | + self.device_data = device |
| 38 | + super().__init__( |
| 39 | + hass, |
| 40 | + _LOGGER, |
| 41 | + name=f"{DOMAIN}_{self.device_identifier}", |
| 42 | + config_entry=config_entry, |
| 43 | + update_interval=timedelta(seconds=30), |
| 44 | + ) |
| 45 | + |
| 46 | + @property |
| 47 | + def device_identifier(self) -> str: |
| 48 | + """Return the device identifier.""" |
| 49 | + return self.device_data["DID"] |
| 50 | + |
| 51 | + def get_parameters(self) -> list[dict[str, Any]]: |
| 52 | + """Get all parameters from the sensor data.""" |
| 53 | + return self.api_client.parameters |
| 54 | + |
| 55 | + def get_parameter_value(self, key: str) -> Any: |
| 56 | + """Get the value for a specific parameter.""" |
| 57 | + for parameter in self.get_parameters(): |
| 58 | + if parameter["name"] == key: |
| 59 | + return parameter["value"] |
| 60 | + return None |
| 61 | + |
| 62 | + async def _async_update_data(self) -> dict[str, Any]: |
| 63 | + """Fetch latest sensor data from the Hanna API.""" |
| 64 | + try: |
| 65 | + readings = await self.hass.async_add_executor_job( |
| 66 | + self.api_client.get_last_device_reading, self.device_identifier |
| 67 | + ) |
| 68 | + except RequestException as e: |
| 69 | + raise UpdateFailed(f"Error communicating with Hanna API: {e}") from e |
| 70 | + except (KeyError, IndexError) as e: |
| 71 | + raise UpdateFailed(f"Error parsing Hanna API response: {e}") from e |
| 72 | + return readings |
0 commit comments