Skip to content

Commit 33d26fc

Browse files
Refinements
1 parent b84f9fe commit 33d26fc

File tree

4 files changed

+47
-24
lines changed

4 files changed

+47
-24
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ Assuming you have already installed and configured HACS, follow these steps:
2929
9. Ready! Now continue with the configuration.
3030

3131
## Manual
32-
Manual instalation is not recomended
32+
Manual installation is not recomended
3333

3434
# Configuration
3535

custom_components/precoscombustiveis/dgeg.py

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
import aiohttp
33
import logging
44

5+
from datetime import datetime
6+
57
from .const import (
68
API_URI_TEMPLATE
79
)
@@ -35,19 +37,33 @@ def type(self):
3537

3638
@property
3739
def address(self):
38-
return [
39-
self._data["Morada"]["Morada"],
40-
self._data["Morada"]["Localidade"],
41-
self._data["Morada"]["CodPostal"]
42-
]
43-
40+
if self._data["Morada"]:
41+
return [
42+
self._data["Morada"]["Morada"],
43+
self._data["Morada"]["Localidade"],
44+
self._data["Morada"]["CodPostal"]
45+
]
46+
else:
47+
return None
48+
4449
@property
4550
def fuels(self):
4651
return self._data["Combustiveis"]
4752

4853
@property
49-
def lastUpdate(self):
50-
return self._data["DataAtualizacao"]
54+
def lastUpdate(self) -> datetime:
55+
return datetime.strptime(
56+
self._data["DataAtualizacao"],
57+
'%d-%m-%Y %H:%M')
58+
59+
def getPrice(self, fuelType) -> float:
60+
fuel = [f for f in self._data["Combustiveis"] if f["TipoCombustivel"] == fuelType][0]
61+
if (fuel):
62+
return float(fuel["Preco"]
63+
.replace(" €/litro", "")
64+
.replace(",", "."))
65+
else:
66+
return 0
5167

5268

5369
class DGEG:
@@ -68,7 +84,6 @@ async def getStation(self, id: str) -> Station:
6884
) as res:
6985
if res.status == 200 and res.content_type == "application/json":
7086
json = await res.json()
71-
# _LOGGER.debug("Station details %s", json)
7287
return Station(
7388
id,
7489
json['resultado'])

custom_components/precoscombustiveis/sensor.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,14 @@
55
import logging
66

77
from datetime import timedelta
8-
from typing import Any, Callable, Dict
8+
from typing import Any, Dict
99

1010
from homeassistant.components.sensor import (SensorDeviceClass, SensorEntity,
1111
SensorStateClass)
1212
from homeassistant.config_entries import ConfigEntry
1313
from homeassistant.core import HomeAssistant
1414
from homeassistant.helpers.aiohttp_client import async_get_clientsession
15+
from homeassistant.helpers.entity_platform import AddEntitiesCallback
1516

1617
from .const import (
1718
DEFAULT_ICON,
@@ -29,7 +30,7 @@
2930

3031
async def async_setup_entry(hass: HomeAssistant,
3132
config_entry: ConfigEntry,
32-
async_add_entities: Callable):
33+
async_add_entities: AddEntitiesCallback):
3334
"""Setup sensor platform."""
3435
session = async_get_clientsession(hass, True)
3536
api = DGEG(session)
@@ -107,22 +108,21 @@ def attribution(self):
107108
def extra_state_attributes(self) -> Dict[str, Any]:
108109
"""Return the state attributes."""
109110
return {
111+
"GasStationId": self._stationId,
110112
"Brand": self._station.brand,
111113
"Name": self._station.name,
112114
"Address": self._station.address,
113-
"stationType": self._station.type,
114-
"lastPriceUpdate": self._station.lastUpdate,
115+
"StationType": self._station.type,
116+
"LastPriceUpdate": self._station.lastUpdate,
115117
}
116118

117119
async def async_update(self) -> None:
118120
"""Fetch new state data for the sensor."""
119121
try:
120122
api = self._api
121-
station = await api.getStation(self._stationId)
122-
if (station):
123-
fuel = [f for f in self._station.fuels if f["TipoCombustivel"] == self._fuelName][0]
124-
if (fuel):
125-
self._state = float(fuel["Preco"].replace(" €/litro", "").replace(",", "."))
123+
gasStation = await api.getStation(self._stationId)
124+
if (gasStation):
125+
self._state = gasStation.getPrice(self._fuelName)
126126
except aiohttp.ClientError as err:
127127
self._available = False
128128
_LOGGER.exception("Error updating data from DGEG API. %s", err)

example.py

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import asyncio
22
import aiohttp
33

4+
from datetime import datetime
45
from custom_components.precoscombustiveis.dgeg import DGEG, Station
56

67
async def main():
@@ -15,10 +16,17 @@ async def main():
1516

1617
station = await api.getStation(stationId)
1718
if (station):
18-
print ("Station Id......:", station.id)
19-
print ("Station Name....:", station.name)
20-
print ("Station Brand...:", station.brand)
21-
print ("Station Address.:", station.address)
22-
print ("Station Type....:", station.type)
19+
print ("Station Id.......:", station.id)
20+
print ("Station Name.....:", station.name)
21+
print ("Station Brand....:", station.brand)
22+
print ("Station Address..:", station.address)
23+
print ("Station Type.....:", station.type)
24+
print ("Last Update......:", station.lastUpdate)
25+
print (station.fuels)
26+
print ("Gasóleo simples..:", station.getPrice("Gasóleo simples"))
27+
print ("Gasóleo especial.:", station.getPrice("Gasóleo especial"))
28+
else:
29+
print ("Gas Station not found!")
30+
2331

2432
asyncio.get_event_loop().run_until_complete(main())

0 commit comments

Comments
 (0)