Skip to content

Commit

Permalink
[#62] An unexpected error occured while loading the data.
Browse files Browse the repository at this point in the history
  • Loading branch information
Stéphane Senart committed Oct 7, 2024
1 parent f6747a3 commit 0958ad2
Show file tree
Hide file tree
Showing 7 changed files with 147 additions and 109 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [1.3.8] - 2024-10-07

### Fixed
[#62](https://github.com/ssenart/home-assistant-gazpar/issues/62): An unexpected error occured while loading the data.

## [1.3.7] - 2024-10-05

## Changed
Expand Down
2 changes: 1 addition & 1 deletion custom_components/gazpar/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,5 @@
"requirements": [
"pygazpar==1.2.3"
],
"version": "1.3.7"
"version": "1.3.8"
}
14 changes: 11 additions & 3 deletions custom_components/gazpar/manifest.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,25 @@
import json
import os
import asyncio


# --------------------------------------------------------------------------------------------
class Manifest:

# ---------------------------------
@staticmethod
def version():
async def version():

manifestFilePath = f"{os.path.dirname(__file__)}/manifest.json"

with open(manifestFilePath) as jsonFile:
manifest = json.load(jsonFile)
loop = asyncio.get_event_loop()
manifest = await loop.run_in_executor(None, Manifest.load_manifest, manifestFilePath)

return manifest["version"]

# ---------------------------------
@staticmethod
def load_manifest(manifestFilePath):
with open(manifestFilePath) as jsonFile:
manifest = json.load(jsonFile)
return manifest
40 changes: 27 additions & 13 deletions custom_components/gazpar/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import json
import logging
import traceback
import asyncio
from datetime import datetime

from pygazpar.client import Client
Expand All @@ -11,14 +12,15 @@
from typing import Any

from custom_components.gazpar.util import Util
from custom_components.gazpar.manifest import Manifest

import voluptuous as vol

from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_NAME, CONF_PASSWORD, CONF_USERNAME, CONF_SCAN_INTERVAL, UnitOfEnergy
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.event import track_time_interval, call_later
from homeassistant.helpers.event import async_call_later, async_track_time_interval

_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -50,7 +52,7 @@


# --------------------------------------------------------------------------------------------
def setup_platform(hass, config, add_entities, discovery_info=None):
async def async_setup_platform(hass, config, add_entities, discovery_info=None):
"""Configure the platform and add the Gazpar sensor."""

_LOGGER.debug("Initializing Gazpar platform...")
Expand Down Expand Up @@ -80,8 +82,18 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
scan_interval = config[CONF_SCAN_INTERVAL]
_LOGGER.debug(f"scan_interval={scan_interval}")

account = GazparAccount(hass, name, username, password, pceIdentifier, wait_time, tmpdir, scan_interval, datasource)
version = await Manifest.version()
_LOGGER.debug(f"version={version}")

account = GazparAccount(hass, name, username, password, pceIdentifier, version, wait_time, tmpdir, scan_interval, datasource)
add_entities(account.sensors, True)

if hass is not None:
async_call_later(hass, 5, account.async_update_gazpar_data)
async_track_time_interval(hass, account.async_update_gazpar_data, account._scan_interval)
else:
await account.async_update_gazpar_data(None)

_LOGGER.debug("Gazpar platform initialization has completed successfully")
except BaseException:
_LOGGER.error("Gazpar platform initialization has failed with exception : %s", traceback.format_exc())
Expand All @@ -93,12 +105,13 @@ class GazparAccount:
"""Representation of a Gazpar account."""

# ----------------------------------
def __init__(self, hass, name: str, username: str, password: str, pceIdentifier: str, wait_time: int, tmpdir: str, scan_interval: timedelta, datasource: str):
def __init__(self, hass, name: str, username: str, password: str, pceIdentifier: str, version: str, wait_time: int, tmpdir: str, scan_interval: timedelta, datasource: str):
"""Initialise the Gazpar account."""
self._name = name
self._username = username
self._password = password
self._pceIdentifier = pceIdentifier
self._version = version
self._wait_time = wait_time
self._tmpdir = tmpdir
self._scan_interval = scan_interval
Expand All @@ -110,14 +123,8 @@ def __init__(self, hass, name: str, username: str, password: str, pceIdentifier:
self.sensors.append(
GazparSensor(name, PropertyName.ENERGY.value, UnitOfEnergy.KILO_WATT_HOUR, self))

if hass is not None:
call_later(hass, 5, self.update_gazpar_data)
track_time_interval(hass, self.update_gazpar_data, self._scan_interval)
else:
self.update_gazpar_data(None)

# ----------------------------------
def update_gazpar_data(self, event_time):
async def async_update_gazpar_data(self, event_time):
"""Fetch new state data for the sensor."""

_LOGGER.debug("Querying PyGazpar library for new data...")
Expand All @@ -135,7 +142,8 @@ def update_gazpar_data(self, event_time):
else:
raise Exception(f"Invalid datasource value: '{self._datasource}' (valid values are: json | excel | test)")

self._dataByFrequency = client.loadSince(self._pceIdentifier, 1095)
loop = asyncio.get_event_loop()
self._dataByFrequency = await loop.run_in_executor(None, client.loadSince, self._pceIdentifier, 1095)

_LOGGER.debug(f"data={json.dumps(self._dataByFrequency, indent=2)}")

Expand Down Expand Up @@ -165,6 +173,12 @@ def pceIdentifier(self):
"""Return the PCE identifier."""
return self._pceIdentifier

# ----------------------------------
@property
def version(self):
"""Return the version."""
return self._version

# ----------------------------------
@property
def tmpdir(self):
Expand Down Expand Up @@ -233,7 +247,7 @@ def icon(self):
def extra_state_attributes(self):
"""Return the state attributes of the sensor."""

return Util.toAttributes(self._account.username, self._account.pceIdentifier, self._dataByFrequency, self._account.errorMessages)
return Util.toAttributes(self._account.username, self._account.pceIdentifier, self._account.version, self._dataByFrequency, self._account.errorMessages)

# ----------------------------------
def update(self):
Expand Down
8 changes: 3 additions & 5 deletions custom_components/gazpar/util.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
from pygazpar.enum import PropertyName, Frequency
from homeassistant.const import CONF_USERNAME, ATTR_ATTRIBUTION, ATTR_UNIT_OF_MEASUREMENT, ATTR_FRIENDLY_NAME, ATTR_ICON, ATTR_DEVICE_CLASS, UnitOfEnergy
from homeassistant.components.sensor import ATTR_STATE_CLASS, SensorStateClass, SensorDeviceClass
from homeassistant.components.sensor.const import ATTR_STATE_CLASS, SensorStateClass, SensorDeviceClass
from typing import Any, Union

from custom_components.gazpar.manifest import Manifest

HA_ATTRIBUTION = "Data provided by GrDF"

ICON_GAS = "mdi:fire"
Expand Down Expand Up @@ -52,11 +50,11 @@ def toState(pygazparData: dict[str, list[dict[str, Any]]]) -> Union[float, None]

# ----------------------------------
@staticmethod
def toAttributes(username: str, pceIdentifier: str, pygazparData: dict[str, list[dict[str, Any]]], errorMessages: list[str]) -> dict[str, Any]:
def toAttributes(username: str, pceIdentifier: str, version: str, pygazparData: dict[str, list[dict[str, Any]]], errorMessages: list[str]) -> dict[str, Any]:

res = {
ATTR_ATTRIBUTION: HA_ATTRIBUTION,
ATTR_VERSION: Manifest.version(),
ATTR_VERSION: version,
CONF_USERNAME: username,
ATTR_PCE: pceIdentifier,
ATTR_UNIT_OF_MEASUREMENT: UnitOfEnergy.KILO_WATT_HOUR,
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@
--extra-index-url https://pypi.org/simple
flake8
pytest
pytest-asyncio
pygazpar
homeassistant
Loading

0 comments on commit 0958ad2

Please sign in to comment.