Skip to content

Commit

Permalink
Remove deprecated acculumative energy sensor
Browse files Browse the repository at this point in the history
  • Loading branch information
dan-r committed Oct 24, 2024
1 parent 81e9b96 commit 3806d5c
Show file tree
Hide file tree
Showing 8 changed files with 7 additions and 121 deletions.
4 changes: 0 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ This integration exposes the following entities:
* Sensors (Other)
* CT Reading (Amps) - Reading from attached CT clamp
* Energy Usage (kWh) - Energy used in the current/last session. *This is supported by the energy dashboard.*
* Accumulative Energy Usage (kWh) - Deprecated - Total energy used by the charger (If enabled in options)
* Battery State of Charge (%) - If your car is API connected this is read from the car, if not it is how much charge Ohme thinks it has added
* Switches (Settings) - **Only options available to your charger model will show**
* Lock Buttons - Locks buttons on charger
Expand All @@ -82,7 +81,6 @@ This integration exposes the following entities:
Some options can be set from the 'Configure' menu in Home Assistant:
* Never update an ongoing session - Override the default behaviour of the target time, percentage and preconditioning inputs and only ever update the schedule, not the current session. This was added as changing the current session can cause issues for customers on Intelligent Octopus Go.
* Don't collapse charge slots - By default, adjacent slots are merged into one. This option shows every slot, as shown in the Ohme app.
* Enable accumulative energy usage sensor - Enable the sensor showing an all-time incrementing energy usage counter. This causes issues with some accounts.


## Coordinators
Expand All @@ -102,7 +100,5 @@ The coordinators are listed with their refresh intervals below. Relevant coordin
* OhmeAdvancedSettingsCoordinator (1m refresh)
* Sensors: CT reading sensor
* Binary Sensors: Charger online
* OhmeStatisticsCoordinator (30m refresh)
* Sensors: Accumulative energy usage
* OhmeChargeSchedulesCoordinator (10m refresh)
* Inputs: Target time, target percentage and preconditioning (If car disconnected)
21 changes: 1 addition & 20 deletions custom_components/ohme/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from .const import *
from .utils import get_option
from .api_client import OhmeApiClient
from .coordinator import OhmeChargeSessionsCoordinator, OhmeStatisticsCoordinator, OhmeAccountInfoCoordinator, OhmeAdvancedSettingsCoordinator, OhmeChargeSchedulesCoordinator
from .coordinator import OhmeChargeSessionsCoordinator, OhmeAccountInfoCoordinator, OhmeAdvancedSettingsCoordinator, OhmeChargeSchedulesCoordinator
from homeassistant.exceptions import ConfigEntryNotReady

_LOGGER = logging.getLogger(__name__)
Expand Down Expand Up @@ -40,35 +40,16 @@ async def async_setup_entry(hass, entry):
coordinators = [
OhmeChargeSessionsCoordinator(hass=hass), # COORDINATOR_CHARGESESSIONS
OhmeAccountInfoCoordinator(hass=hass), # COORDINATOR_ACCOUNTINFO
OhmeStatisticsCoordinator(hass=hass), # COORDINATOR_STATISTICS
OhmeAdvancedSettingsCoordinator(hass=hass), # COORDINATOR_ADVANCED
OhmeChargeSchedulesCoordinator(hass=hass) # COORDINATOR_SCHEDULES
]

# We can function without these so setup can continue
coordinators_optional = [
OhmeStatisticsCoordinator,
OhmeAdvancedSettingsCoordinator
]

coordinators_skipped = []

# Skip statistics coordinator if we don't need it
if not get_option(hass, "enable_accumulative_energy"):
coordinators_skipped.append(OhmeStatisticsCoordinator)

for coordinator in coordinators:
# If we should skip this coordinator
skip = False
for skipped in coordinators_skipped:
if isinstance(coordinator, skipped):
skip = True
break

if skip:
_LOGGER.debug(f"Skipping initial load of {coordinator.__class__.__name__}")
continue

# Catch failures if this is an 'optional' coordinator
try:
await coordinator.async_config_entry_first_refresh()
Expand Down
15 changes: 0 additions & 15 deletions custom_components/ohme/api_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,14 +95,6 @@ async def async_refresh_session(self):

# Internal methods

def _last_second_of_month_timestamp(self):
"""Get the last second of this month."""
dt = datetime.today()
dt = dt.replace(day=1) + timedelta(days=32)
dt = dt.replace(day=1, hour=0, minute=0, second=0,
microsecond=0) - timedelta(seconds=1)
return int(dt.timestamp()*1e3)

async def _handle_api_error(self, url, resp):
"""Raise an exception if API response failed."""
if resp.status != 200:
Expand Down Expand Up @@ -335,13 +327,6 @@ async def async_update_device_info(self, is_retry=False):

return True

async def async_get_charge_statistics(self):
"""Get charge statistics. Currently this is just for all time (well, Jan 2019)."""
end_ts = self._last_second_of_month_timestamp()
resp = await self._get_request(f"/v1/chargeSessions/summary/users/{self._user_id}?&startTs={self._provision_date}&endTs={end_ts}&granularity=MONTH")

return resp['totalStats']

async def async_get_advanced_settings(self):
"""Get advanced settings (mainly for CT clamp reading)"""
resp = await self._get_request(f"/v1/chargeDevices/{self._serial}/advancedSettings")
Expand Down
3 changes: 0 additions & 3 deletions custom_components/ohme/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,6 @@ async def async_step_init(self, options):
) : bool,
vol.Required(
"never_collapse_slots", default=self._config_entry.options.get("never_collapse_slots", False)
) : bool,
vol.Required(
"enable_accumulative_energy", default=self._config_entry.options.get("enable_accumulative_energy", False)
) : bool
}), errors=errors
)
5 changes: 2 additions & 3 deletions custom_components/ohme/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,5 @@

COORDINATOR_CHARGESESSIONS = 0
COORDINATOR_ACCOUNTINFO = 1
COORDINATOR_STATISTICS = 2
COORDINATOR_ADVANCED = 3
COORDINATOR_SCHEDULES = 4
COORDINATOR_ADVANCED = 2
COORDINATOR_SCHEDULES = 3
23 changes: 1 addition & 22 deletions custom_components/ohme/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,28 +55,6 @@ async def _async_update_data(self):
raise UpdateFailed("Error communicating with API")


class OhmeStatisticsCoordinator(DataUpdateCoordinator):
"""Coordinator to update statistics from API periodically.
(But less so than the others)"""

def __init__(self, hass):
"""Initialise coordinator."""
super().__init__(
hass,
_LOGGER,
name="Ohme Charger Statistics",
update_interval=timedelta(minutes=30),
)
self._client = hass.data[DOMAIN][DATA_CLIENT]

async def _async_update_data(self):
"""Fetch data from API endpoint."""
try:
return await self._client.async_get_charge_statistics()

except BaseException:
raise UpdateFailed("Error communicating with API")

class OhmeAdvancedSettingsCoordinator(DataUpdateCoordinator):
"""Coordinator to pull CT clamp reading."""

Expand All @@ -98,6 +76,7 @@ async def _async_update_data(self):
except BaseException:
raise UpdateFailed("Error communicating with API")


class OhmeChargeSchedulesCoordinator(DataUpdateCoordinator):
"""Coordinator to pull charge schedules."""

Expand Down
54 changes: 2 additions & 52 deletions custom_components/ohme/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity import generate_entity_id
from homeassistant.util.dt import (utcnow)
from .const import DOMAIN, DATA_CLIENT, DATA_COORDINATORS, DATA_SLOTS, COORDINATOR_CHARGESESSIONS, COORDINATOR_STATISTICS, COORDINATOR_ADVANCED
from .coordinator import OhmeChargeSessionsCoordinator, OhmeStatisticsCoordinator, OhmeAdvancedSettingsCoordinator
from .const import DOMAIN, DATA_CLIENT, DATA_COORDINATORS, DATA_SLOTS, COORDINATOR_CHARGESESSIONS, COORDINATOR_ADVANCED
from .coordinator import OhmeChargeSessionsCoordinator, OhmeAdvancedSettingsCoordinator
from .utils import next_slot, get_option, slot_list, slot_list_str

_LOGGER = logging.getLogger(__name__)
Expand All @@ -28,7 +28,6 @@ async def async_setup_entry(
coordinators = hass.data[DOMAIN][DATA_COORDINATORS]

coordinator = coordinators[COORDINATOR_CHARGESESSIONS]
stats_coordinator = coordinators[COORDINATOR_STATISTICS]
adv_coordinator = coordinators[COORDINATOR_ADVANCED]

sensors = [PowerDrawSensor(coordinator, hass, client),
Expand All @@ -41,9 +40,6 @@ async def async_setup_entry(
SlotListSensor(coordinator, hass, client),
BatterySOCSensor(coordinator, hass, client)]

if get_option(hass, "enable_accumulative_energy"):
sensors.append(AccumulativeEnergyUsageSensor(stats_coordinator, hass, client))

async_add_entities(sensors, update_before_add=True)


Expand Down Expand Up @@ -213,52 +209,6 @@ def native_value(self):
return self.coordinator.data['clampAmps']


class AccumulativeEnergyUsageSensor(CoordinatorEntity[OhmeStatisticsCoordinator], SensorEntity):
"""Sensor for total energy usage."""
_attr_name = "Accumulative Energy Usage"
_attr_native_unit_of_measurement = UnitOfEnergy.WATT_HOUR
_attr_suggested_unit_of_measurement = UnitOfEnergy.KILO_WATT_HOUR
_attr_suggested_display_precision = 1
_attr_device_class = SensorDeviceClass.ENERGY
_attr_state_class = SensorStateClass.TOTAL

def __init__(
self,
coordinator: OhmeStatisticsCoordinator,
hass: HomeAssistant,
client):
super().__init__(coordinator=coordinator)

self._state = None
self._attributes = {}
self._last_updated = None
self._client = client

self.entity_id = generate_entity_id(
"sensor.{}", "ohme_accumulative_energy", hass=hass)

self._attr_device_info = hass.data[DOMAIN][DATA_CLIENT].get_device_info(
)

@property
def unique_id(self) -> str:
"""Return the unique ID of the sensor."""
return self._client.get_unique_id("accumulative_energy")

@property
def icon(self):
"""Icon of the sensor."""
return "mdi:lightning-bolt"

@property
def native_value(self):
"""Get value from data returned from API by coordinator"""
if self.coordinator.data and self.coordinator.data['energyChargedTotalWh']:
return self.coordinator.data['energyChargedTotalWh']

return None


class EnergyUsageSensor(CoordinatorEntity[OhmeChargeSessionsCoordinator], SensorEntity):
"""Sensor for total energy usage."""
_attr_name = "Energy"
Expand Down
3 changes: 1 addition & 2 deletions custom_components/ohme/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@
"email": "Email address",
"password": "Password",
"never_session_specific": "Never update an ongoing session",
"never_collapse_slots": "Don't collapse charge slots",
"enable_accumulative_energy": "Enable accumulative energy sensor"
"never_collapse_slots": "Don't collapse charge slots"
},
"data_description": {
"password": "If you are not changing your credentials, leave the password field empty.",
Expand Down

0 comments on commit 3806d5c

Please sign in to comment.