Skip to content

Commit

Permalink
Added experimental charge state monitoring
Browse files Browse the repository at this point in the history
  • Loading branch information
dan-r committed Dec 31, 2023
1 parent 4a735e0 commit 4902436
Showing 1 changed file with 69 additions and 5 deletions.
74 changes: 69 additions & 5 deletions custom_components/ohme/binary_sensor.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Platform for sensor integration."""
from __future__ import annotations

import logging
from homeassistant.components.binary_sensor import (
BinarySensorDeviceClass,
BinarySensorEntity
Expand All @@ -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,
Expand Down Expand Up @@ -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)

Expand All @@ -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(
Expand Down

0 comments on commit 4902436

Please sign in to comment.