11"""Platform for sensor integration."""
22from __future__ import annotations
33
4+ import aiohttp
45import logging
56
7+ from datetime import timedelta
8+ from typing import Any , Callable , Dict
9+
610from homeassistant .components .sensor import (SensorDeviceClass , SensorEntity ,
711 SensorStateClass )
812from homeassistant .config_entries import ConfigEntry
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
1925async 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
3339class 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