From 490243638b9923d0d2604e5380b9fc7aa5696df9 Mon Sep 17 00:00:00 2001 From: Daniel Raper Date: Sun, 31 Dec 2023 00:31:57 +0000 Subject: [PATCH] Added experimental charge state monitoring --- custom_components/ohme/binary_sensor.py | 74 +++++++++++++++++++++++-- 1 file changed, 69 insertions(+), 5 deletions(-) diff --git a/custom_components/ohme/binary_sensor.py b/custom_components/ohme/binary_sensor.py index d8bad2b..92af83d 100644 --- a/custom_components/ohme/binary_sensor.py +++ b/custom_components/ohme/binary_sensor.py @@ -1,6 +1,6 @@ """Platform for sensor integration.""" from __future__ import annotations - +import logging from homeassistant.components.binary_sensor import ( BinarySensorDeviceClass, BinarySensorEntity @@ -12,7 +12,9 @@ from .const import DOMAIN, DATA_COORDINATORS, COORDINATOR_CHARGESESSIONS, DATA_CLIENT from .coordinator import OhmeChargeSessionsCoordinator from .utils import charge_graph_in_slot +from time import time +_LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: core.HomeAssistant, @@ -97,6 +99,13 @@ def __init__( self._state = False self._client = client + # Cache the last power readings + self._last_reading = None + self._last_reading_in_slot = False + + # Allow a state override + self._override_until = None + self.entity_id = generate_entity_id( "binary_sensor.{}", "ohme_car_charging", hass=hass) @@ -115,13 +124,68 @@ def unique_id(self) -> str: @property def is_on(self) -> bool: - if self.coordinator.data and self.coordinator.data["power"]: - # Assume the car is actively charging if drawing over 0 watts - self._state = self.coordinator.data["power"]["watt"] > 0 + return self._state + + def _calculate_state(self) -> bool: + """Some trickery to get the charge state to update quickly.""" + # If we have overriden the state, return the current value until that time + if self._override_until and time() < self._override_until: + _LOGGER.debug("State overridden to False for 310s") + return self._state + + # We have passed override check, reset it + self._override_until = None + + power = self.coordinator.data["power"]["watt"] + + # No last reading to go off, use power draw based state only - this lags + if not self._last_reading: + _LOGGER.debug("Last reading not found, default to power > 0") + return power > 0 + + # Get power from last reading + lr_power = self._last_reading["power"]["watt"] + + # 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 + + # 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. + if lr_power > 0 and power / lr_power < 0.6 and not in_charge_slot and lr_in_charge_slot: + _LOGGER.debug("Charge stop behaviour seen - overriding to False for 310 seconds") + self._override_until = time() + 310 # Override for 5 mins (and a bit) + return False + + # Its possible that this is the 'transitionary' reading - slots updated but not power + # Override _last_reading_in_slot and see what happens next time around + elif lr_power > 0 and not in_charge_slot and lr_in_charge_slot: + _LOGGER.debug("Possible transitionary reading. Treating as slot boundary in next tick.") + self._last_reading_in_slot = True + + # Fallback to the old way + return power > 0 + + @callback + def _handle_coordinator_update(self) -> None: + """Update data.""" + # If we have power info and the car is plugged in, calculate state. Otherwise, false + if self.coordinator.data and self.coordinator.data["power"] and self.coordinator.data['mode'] != "DISCONNECTED": + self._state = self._calculate_state() else: self._state = False - return self._state + self._last_reading = self.coordinator.data + self._last_updated = utcnow() + + self.async_write_ha_state() class PendingApprovalBinarySensor(