Skip to content

Commit

Permalink
improved state update
Browse files Browse the repository at this point in the history
  • Loading branch information
netsoft-ruidias committed Jun 23, 2022
1 parent aae7c28 commit c5bae6b
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 16 deletions.
5 changes: 1 addition & 4 deletions custom_components/precoscombustiveis/dgeg.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'])
Expand All @@ -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)
40 changes: 28 additions & 12 deletions custom_components/precoscombustiveis/sensor.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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):
Expand All @@ -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:
Expand All @@ -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
Expand All @@ -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(",", "."))
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)

0 comments on commit c5bae6b

Please sign in to comment.