Skip to content

Commit

Permalink
Cache event history to disk, to avoid useless http calls
Browse files Browse the repository at this point in the history
  • Loading branch information
nlz242 committed Dec 21, 2023
1 parent 741b0ad commit d980674
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion custom_components/hilo/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from __future__ import annotations

from datetime import datetime, timedelta, timezone
from os.path import isfile

from homeassistant.components.integration.sensor import METHOD_LEFT, IntegrationSensor
from homeassistant.components.sensor import (
Expand Down Expand Up @@ -29,6 +30,7 @@
from pyhilo.device import HiloDevice
from pyhilo.event import Event
from pyhilo.util import from_utc_timestamp
import ruyaml as yaml

from . import Hilo, HiloEntity
from .const import (
Expand Down Expand Up @@ -507,10 +509,11 @@ def __init__(self, hilo, device, scan_interval):
super().__init__(hilo, name=self._attr_name, device=device)
self._attr_unique_id = slugify(self._attr_name)
LOG.debug(f"Setting up RewardSensor entity: {self._attr_name}")
self._history_state_yaml: str = "hilo_eventhistory_state.yaml"
self.scan_interval = timedelta(seconds=REWARD_SCAN_INTERVAL)
self._attr_native_unit_of_measurement = hilo._hass.config.currency
self._state = 0
self._history = []
self._history = self._load_history()
self.async_update = Throttle(self.scan_interval)(self._async_update)

@property
Expand Down Expand Up @@ -589,6 +592,20 @@ async def _async_update(self):
season["events"] = events
new_history.append(season)
self._history = new_history
self._save_history(new_history)

def _load_history(self) -> list:
history: list = []
if isfile(self._history_state_yaml):
with open(self._history_state_yaml) as yaml_file:
LOG.debug("Loading history state from yaml")
history = yaml.load(yaml_file, Loader=yaml.Loader)
return history

def _save_history(self, history: list):
with open(self._history_state_yaml, "w") as yaml_file:
LOG.debug("Saving history state to yaml file")
yaml.dump(history, yaml_file, Dumper=yaml.RoundTripDumper)


class HiloChallengeSensor(HiloEntity, RestoreEntity, SensorEntity):
Expand Down

0 comments on commit d980674

Please sign in to comment.