Skip to content

Commit

Permalink
Added slot boundary check back in
Browse files Browse the repository at this point in the history
  • Loading branch information
dan-r committed Jan 1, 2024
1 parent dc3228e commit 2c5163d
Showing 1 changed file with 24 additions and 5 deletions.
29 changes: 24 additions & 5 deletions custom_components/ohme/binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ def __init__(

# Cache the last power readings
self._last_reading = None
self._last_reading_in_slot = False

self.entity_id = generate_entity_id(
"binary_sensor.{}", "ohme_car_charging", hass=hass)
Expand All @@ -126,15 +127,33 @@ def _calculate_state(self) -> bool:
"""Some trickery to get the charge state to update quickly."""
power = self.coordinator.data["power"]["watt"]

# If no last reading or no batterySoc, fallback to power > 0
if not self._last_reading or not self._last_reading['batterySoc']:
# If no last reading or no batterySoc/power, fallback to power > 0
if not self._last_reading or not self._last_reading['batterySoc'] or not self._last_reading['power']:
return power > 0

# If Wh has positive delta and a nonzero power reading, we are charging
# See if we are in a charge slot now and if we were for the last reading
in_charge_slot = charge_graph_in_slot(
self.coordinator.data['startTime'], self.coordinator.data['chargeGraph']['points'])
lr_in_charge_slot = self._last_reading_in_slot
lr_power = self._last_reading["power"]["watt"]
# Store this for next time
self._last_reading_in_slot = in_charge_slot

# If:
# - Power has dropped by 40% since the last reading
# - Last reading we were in a charge slot
# - Now we are not in a charge slot
# The charge has stopped but the power reading is lagging.
# This condition makes sure we get the charge state updated on the tick immediately after charge stop.
if lr_power > 0 and power / lr_power < 0.6 and not in_charge_slot and lr_in_charge_slot:
return False

# Failing that, we use the watt hours field to check charge state:
# - If Wh has positive delta and a nonzero power reading, we are charging
# This isn't ideal - eg. quirk of MG ZS in #13, so need to revisit
delta = self.coordinator.data['batterySoc']['wh'] - self._last_reading['batterySoc']['wh']
wh_delta = self.coordinator.data['batterySoc']['wh'] - self._last_reading['batterySoc']['wh']

return delta > 0 and power > 0
return wh_delta > 0 and power > 0

@callback
def _handle_coordinator_update(self) -> None:
Expand Down

0 comments on commit 2c5163d

Please sign in to comment.