From c5bae6be3010bbb8f35b764397dbd412efa819c0 Mon Sep 17 00:00:00 2001 From: Rui Dias Date: Thu, 23 Jun 2022 16:53:45 +0100 Subject: [PATCH] improved state update --- custom_components/precoscombustiveis/dgeg.py | 5 +-- .../precoscombustiveis/sensor.py | 40 +++++++++++++------ 2 files changed, 29 insertions(+), 16 deletions(-) diff --git a/custom_components/precoscombustiveis/dgeg.py b/custom_components/precoscombustiveis/dgeg.py index 89fabf5..b35b56a 100644 --- a/custom_components/precoscombustiveis/dgeg.py +++ b/custom_components/precoscombustiveis/dgeg.py @@ -60,7 +60,7 @@ async def getStation(self, id: str) -> Station: ) as res: if res.status == 200 and res.content_type == "application/json": json = await res.json() - _LOGGER.debug("Station details %s", json) + #_LOGGER.debug("Station details %s", json) return Station( id, json['resultado']) @@ -71,7 +71,4 @@ async def getStation(self, id: str) -> Station: async def testStation(self, id: str) -> bool: """Test if stationId exists.""" station = await self.getStation(id) - _LOGGER.debug("station.name %s", station.name) - _LOGGER.debug("station.name %s", station.fuels) - _LOGGER.debug("result %s", (not station.name and not station.fuels)) return not (not station.name and not station.fuels) diff --git a/custom_components/precoscombustiveis/sensor.py b/custom_components/precoscombustiveis/sensor.py index 82b5c82..d5d7517 100644 --- a/custom_components/precoscombustiveis/sensor.py +++ b/custom_components/precoscombustiveis/sensor.py @@ -1,8 +1,12 @@ """Platform for sensor integration.""" from __future__ import annotations +import aiohttp import logging +from datetime import timedelta +from typing import Any, Callable, Dict + from homeassistant.components.sensor import (SensorDeviceClass, SensorEntity, SensorStateClass) from homeassistant.config_entries import ConfigEntry @@ -15,19 +19,21 @@ _LOGGER = logging.getLogger(__name__) _LOGGER.setLevel(logging.DEBUG) +# Time between updating data from API +SCAN_INTERVAL = timedelta(minutes=60) async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry, - async_add_entities): + async_add_entities: Callable): """Setup sensor platform.""" session = async_get_clientsession(hass, True) api = DGEG(session) config = config_entry.data station = await api.getStation(config["stationId"]) - + sensors = [PrecosCombustiveisSensor(api, config["stationId"], station, fuel["TipoCombustivel"]) for fuel in station.fuels] - async_add_entities(sensors) + async_add_entities(sensors, update_before_add=True) class PrecosCombustiveisSensor(SensorEntity): @@ -39,11 +45,12 @@ def __init__(self, api: DGEG, stationId: float, station: Station, fuelName: str) self._stationId = stationId self._station = station self._fuelName = fuelName - self._state = 0 self._icon = DEFAULT_ICON self._unit_of_measurement = UNIT_OF_MEASUREMENT self._device_class = SensorDeviceClass.MONETARY self._state_class = SensorStateClass.TOTAL + self._state = None + self._available = True @property def name(self) -> str: @@ -55,6 +62,11 @@ def unique_id(self) -> str: """Return the unique ID of the sensor.""" return f"{DOMAIN}-{self._stationId}-{self._fuelName}".lower() + @property + def available(self) -> bool: + """Return True if entity is available.""" + return self._available + @property def state(self) -> float: return self._state @@ -77,20 +89,24 @@ def icon(self): return self._icon @property - def extra_state_attributes(self): + def device_state_attributes(self) -> Dict[str, Any]: """Return the state attributes.""" return { "brand": self._station.brand, "Name": self._station.name, "stationType": self._station.type, - "lastUpdate": self._station.lastUpdate, + "lastPriceUpdate": self._station.lastUpdate, } async def async_update(self) -> None: """Fetch new state data for the sensor.""" - api = self._api - station = await api.getStation(self._stationId) - if (station): - fuel = [f for f in self._station.fuels if f["TipoCombustivel"] == self._fuelName][0] - if (fuel): - self._state = float(fuel["Preco"].replace(" €/litro", "").replace(",", ".")) \ No newline at end of file + try: + api = self._api + station = await api.getStation(self._stationId) + if (station): + fuel = [f for f in self._station.fuels if f["TipoCombustivel"] == self._fuelName][0] + if (fuel): + self._state = float(fuel["Preco"].replace(" €/litro", "").replace(",", ".")) + except aiohttp.ClientError as err: + self._available = False + _LOGGER.exception("Error updating data from DGEG API. %s", err) \ No newline at end of file