Skip to content

Commit

Permalink
Slot evaluation skip
Browse files Browse the repository at this point in the history
  • Loading branch information
dan-r committed Feb 1, 2024
1 parent 81d2927 commit 92d77df
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion custom_components/ohme/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
SensorStateClass,
SensorEntity
)
import json
import hashlib
import logging
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from homeassistant.const import UnitOfPower, UnitOfEnergy, UnitOfElectricCurrent, UnitOfElectricPotential
from homeassistant.core import HomeAssistant, callback
Expand All @@ -15,6 +18,8 @@
from .coordinator import OhmeChargeSessionsCoordinator, OhmeStatisticsCoordinator, OhmeAdvancedSettingsCoordinator
from .utils import charge_graph_next_slot, charge_graph_slot_list

_LOGGER = logging.getLogger(__name__)

async def async_setup_entry(
hass: core.HomeAssistant,
config_entry: config_entries.ConfigEntry,
Expand Down Expand Up @@ -359,6 +364,7 @@ def _handle_coordinator_update(self) -> None:
class SlotListSensor(CoordinatorEntity[OhmeChargeSessionsCoordinator], SensorEntity):
"""Sensor for next smart charge slot end time."""
_attr_name = "Charge Slots"
_last_hash = None

def __init__(
self,
Expand Down Expand Up @@ -393,12 +399,26 @@ def native_value(self):
"""Return pre-calculated state."""
return self._state

def _hash_rule(self):
"""Generate a hashed representation of the current charge rule."""
serial = json.dumps(self.coordinator.data['appliedRule'], sort_keys=True)
sha1 = hashlib.sha1(serial.encode('utf-8')).hexdigest()
return sha1

@callback
def _handle_coordinator_update(self) -> None:
"""Get a list of charge slots."""
if self.coordinator.data is None or self.coordinator.data["mode"] == "DISCONNECTED":
if self.coordinator.data is None or self.coordinator.data["mode"] == "DISCONNECTED" or self.coordinator.data["mode"] == "FINISHED_CHARGE":
self._state = None
self._last_hash = None
else:
rule_hash = self._hash_rule()

# Rule has not changed, no point evaluating slots again
if rule_hash == self._last_hash:
_LOGGER.debug("Slot evaluation skipped - rule has not changed")
return

slots = charge_graph_slot_list(
self.coordinator.data['startTime'], self.coordinator.data['chargeGraph']['points'])

Expand All @@ -407,6 +427,9 @@ def _handle_coordinator_update(self) -> None:

# Make sure we return None/Unknown if the list is empty
self._state = None if self._state == "" else self._state

# Store hash of the last rule
self._last_hash = self._hash_rule()

self._last_updated = utcnow()
self.async_write_ha_state()

0 comments on commit 92d77df

Please sign in to comment.