Skip to content

Commit c5bae6b

Browse files
improved state update
1 parent aae7c28 commit c5bae6b

File tree

2 files changed

+29
-16
lines changed

2 files changed

+29
-16
lines changed

custom_components/precoscombustiveis/dgeg.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ async def getStation(self, id: str) -> Station:
6060
) as res:
6161
if res.status == 200 and res.content_type == "application/json":
6262
json = await res.json()
63-
_LOGGER.debug("Station details %s", json)
63+
#_LOGGER.debug("Station details %s", json)
6464
return Station(
6565
id,
6666
json['resultado'])
@@ -71,7 +71,4 @@ async def getStation(self, id: str) -> Station:
7171
async def testStation(self, id: str) -> bool:
7272
"""Test if stationId exists."""
7373
station = await self.getStation(id)
74-
_LOGGER.debug("station.name %s", station.name)
75-
_LOGGER.debug("station.name %s", station.fuels)
76-
_LOGGER.debug("result %s", (not station.name and not station.fuels))
7774
return not (not station.name and not station.fuels)

custom_components/precoscombustiveis/sensor.py

Lines changed: 28 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
"""Platform for sensor integration."""
22
from __future__ import annotations
33

4+
import aiohttp
45
import logging
56

7+
from datetime import timedelta
8+
from typing import Any, Callable, Dict
9+
610
from homeassistant.components.sensor import (SensorDeviceClass, SensorEntity,
711
SensorStateClass)
812
from homeassistant.config_entries import ConfigEntry
@@ -15,19 +19,21 @@
1519
_LOGGER = logging.getLogger(__name__)
1620
_LOGGER.setLevel(logging.DEBUG)
1721

22+
# Time between updating data from API
23+
SCAN_INTERVAL = timedelta(minutes=60)
1824

1925
async def async_setup_entry(hass: HomeAssistant,
2026
config_entry: ConfigEntry,
21-
async_add_entities):
27+
async_add_entities: Callable):
2228
"""Setup sensor platform."""
2329
session = async_get_clientsession(hass, True)
2430
api = DGEG(session)
2531

2632
config = config_entry.data
2733
station = await api.getStation(config["stationId"])
28-
34+
2935
sensors = [PrecosCombustiveisSensor(api, config["stationId"], station, fuel["TipoCombustivel"]) for fuel in station.fuels]
30-
async_add_entities(sensors)
36+
async_add_entities(sensors, update_before_add=True)
3137

3238

3339
class PrecosCombustiveisSensor(SensorEntity):
@@ -39,11 +45,12 @@ def __init__(self, api: DGEG, stationId: float, station: Station, fuelName: str)
3945
self._stationId = stationId
4046
self._station = station
4147
self._fuelName = fuelName
42-
self._state = 0
4348
self._icon = DEFAULT_ICON
4449
self._unit_of_measurement = UNIT_OF_MEASUREMENT
4550
self._device_class = SensorDeviceClass.MONETARY
4651
self._state_class = SensorStateClass.TOTAL
52+
self._state = None
53+
self._available = True
4754

4855
@property
4956
def name(self) -> str:
@@ -55,6 +62,11 @@ def unique_id(self) -> str:
5562
"""Return the unique ID of the sensor."""
5663
return f"{DOMAIN}-{self._stationId}-{self._fuelName}".lower()
5764

65+
@property
66+
def available(self) -> bool:
67+
"""Return True if entity is available."""
68+
return self._available
69+
5870
@property
5971
def state(self) -> float:
6072
return self._state
@@ -77,20 +89,24 @@ def icon(self):
7789
return self._icon
7890

7991
@property
80-
def extra_state_attributes(self):
92+
def device_state_attributes(self) -> Dict[str, Any]:
8193
"""Return the state attributes."""
8294
return {
8395
"brand": self._station.brand,
8496
"Name": self._station.name,
8597
"stationType": self._station.type,
86-
"lastUpdate": self._station.lastUpdate,
98+
"lastPriceUpdate": self._station.lastUpdate,
8799
}
88100

89101
async def async_update(self) -> None:
90102
"""Fetch new state data for the sensor."""
91-
api = self._api
92-
station = await api.getStation(self._stationId)
93-
if (station):
94-
fuel = [f for f in self._station.fuels if f["TipoCombustivel"] == self._fuelName][0]
95-
if (fuel):
96-
self._state = float(fuel["Preco"].replace(" €/litro", "").replace(",", "."))
103+
try:
104+
api = self._api
105+
station = await api.getStation(self._stationId)
106+
if (station):
107+
fuel = [f for f in self._station.fuels if f["TipoCombustivel"] == self._fuelName][0]
108+
if (fuel):
109+
self._state = float(fuel["Preco"].replace(" €/litro", "").replace(",", "."))
110+
except aiohttp.ClientError as err:
111+
self._available = False
112+
_LOGGER.exception("Error updating data from DGEG API. %s", err)

0 commit comments

Comments
 (0)