Skip to content

Commit

Permalink
Refinements
Browse files Browse the repository at this point in the history
  • Loading branch information
netsoft-ruidias committed Jul 1, 2022
1 parent b84f9fe commit 33d26fc
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 24 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ Assuming you have already installed and configured HACS, follow these steps:
9. Ready! Now continue with the configuration.

## Manual
Manual instalation is not recomended
Manual installation is not recomended

# Configuration

Expand Down
33 changes: 24 additions & 9 deletions custom_components/precoscombustiveis/dgeg.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
import aiohttp
import logging

from datetime import datetime

from .const import (
API_URI_TEMPLATE
)
Expand Down Expand Up @@ -35,19 +37,33 @@ def type(self):

@property
def address(self):
return [
self._data["Morada"]["Morada"],
self._data["Morada"]["Localidade"],
self._data["Morada"]["CodPostal"]
]

if self._data["Morada"]:
return [
self._data["Morada"]["Morada"],
self._data["Morada"]["Localidade"],
self._data["Morada"]["CodPostal"]
]
else:
return None

@property
def fuels(self):
return self._data["Combustiveis"]

@property
def lastUpdate(self):
return self._data["DataAtualizacao"]
def lastUpdate(self) -> datetime:
return datetime.strptime(
self._data["DataAtualizacao"],
'%d-%m-%Y %H:%M')

def getPrice(self, fuelType) -> float:
fuel = [f for f in self._data["Combustiveis"] if f["TipoCombustivel"] == fuelType][0]
if (fuel):
return float(fuel["Preco"]
.replace(" €/litro", "")
.replace(",", "."))
else:
return 0


class DGEG:
Expand All @@ -68,7 +84,6 @@ 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)
return Station(
id,
json['resultado'])
Expand Down
18 changes: 9 additions & 9 deletions custom_components/precoscombustiveis/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@
import logging

from datetime import timedelta
from typing import Any, Callable, Dict
from typing import Any, Dict

from homeassistant.components.sensor import (SensorDeviceClass, SensorEntity,
SensorStateClass)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.entity_platform import AddEntitiesCallback

from .const import (
DEFAULT_ICON,
Expand All @@ -29,7 +30,7 @@

async def async_setup_entry(hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: Callable):
async_add_entities: AddEntitiesCallback):
"""Setup sensor platform."""
session = async_get_clientsession(hass, True)
api = DGEG(session)
Expand Down Expand Up @@ -107,22 +108,21 @@ def attribution(self):
def extra_state_attributes(self) -> Dict[str, Any]:
"""Return the state attributes."""
return {
"GasStationId": self._stationId,
"Brand": self._station.brand,
"Name": self._station.name,
"Address": self._station.address,
"stationType": self._station.type,
"lastPriceUpdate": self._station.lastUpdate,
"StationType": self._station.type,
"LastPriceUpdate": self._station.lastUpdate,
}

async def async_update(self) -> None:
"""Fetch new state data for the sensor."""
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(",", "."))
gasStation = await api.getStation(self._stationId)
if (gasStation):
self._state = gasStation.getPrice(self._fuelName)
except aiohttp.ClientError as err:
self._available = False
_LOGGER.exception("Error updating data from DGEG API. %s", err)
18 changes: 13 additions & 5 deletions example.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import asyncio
import aiohttp

from datetime import datetime
from custom_components.precoscombustiveis.dgeg import DGEG, Station

async def main():
Expand All @@ -15,10 +16,17 @@ async def main():

station = await api.getStation(stationId)
if (station):
print ("Station Id......:", station.id)
print ("Station Name....:", station.name)
print ("Station Brand...:", station.brand)
print ("Station Address.:", station.address)
print ("Station Type....:", station.type)
print ("Station Id.......:", station.id)
print ("Station Name.....:", station.name)
print ("Station Brand....:", station.brand)
print ("Station Address..:", station.address)
print ("Station Type.....:", station.type)
print ("Last Update......:", station.lastUpdate)
print (station.fuels)
print ("Gasóleo simples..:", station.getPrice("Gasóleo simples"))
print ("Gasóleo especial.:", station.getPrice("Gasóleo especial"))
else:
print ("Gas Station not found!")


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

0 comments on commit 33d26fc

Please sign in to comment.