Skip to content

Commit

Permalink
feat: Added sensors for current elec/gas accumulative consumption
Browse files Browse the repository at this point in the history
  • Loading branch information
BottlecapDave committed Aug 1, 2023
1 parent a29d4f5 commit d3315a5
Show file tree
Hide file tree
Showing 4 changed files with 218 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
from homeassistant.util.dt import (now)
import logging

from homeassistant.core import HomeAssistant

from homeassistant.helpers.update_coordinator import (
CoordinatorEntity
)
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorStateClass
)
from homeassistant.const import (
ENERGY_KILO_WATT_HOUR
)

from .base import (OctopusEnergyElectricitySensor)

from ..utils.consumption import (get_total_consumption)

_LOGGER = logging.getLogger(__name__)

class OctopusEnergyCurrentAccumulativeElectricityConsumption(CoordinatorEntity, OctopusEnergyElectricitySensor):
"""Sensor for displaying the current accumulative electricity consumption."""

def __init__(self, hass: HomeAssistant, coordinator, meter, point):
"""Init sensor."""
super().__init__(coordinator)
OctopusEnergyElectricitySensor.__init__(self, hass, meter, point)

self._state = None
self._latest_date = None
self._previous_total_consumption = None
self._attributes = {
"last_updated_timestamp": None
}

@property
def unique_id(self):
"""The id of the sensor."""
return f"octopus_energy_electricity_{self._serial_number}_{self._mpan}_current_accumulative_consumption"

@property
def name(self):
"""Name of the sensor."""
return f"Electricity {self._serial_number} {self._mpan} Current Accumulative Consumption"

@property
def device_class(self):
"""The type of sensor"""
return SensorDeviceClass.ENERGY

@property
def state_class(self):
"""The state class of sensor"""
return SensorStateClass.TOTAL

@property
def unit_of_measurement(self):
"""The unit of measurement of sensor"""
return ENERGY_KILO_WATT_HOUR

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

@property
def extra_state_attributes(self):
"""Attributes of the sensor."""
return self._attributes

@property
def last_reset(self):
"""Return the time when the sensor was last reset, if any."""
return self._latest_date

@property
def state(self):
"""Retrieve the latest electricity consumption"""
_LOGGER.debug('Updating OctopusEnergyCurrentAccumulativeElectricityConsumption')
consumption_result = self.coordinator.data

if (consumption_result is not None and len(consumption_result) > 0):
self._state = get_total_consumption(consumption_result)
if (self._state is not None):
self._latest_date = consumption_result[0]["interval_start"]
self._attributes["last_updated_timestamp"] = now()
self._attributes["charges"] = list(map(lambda charge: {
"from": charge["interval_start"],
"to": charge["interval_end"],
"consumption": charge["consumption"]
}, consumption_result))

return self._state

async def async_added_to_hass(self):
"""Call when entity about to be added to hass."""
# If not None, we got an initial value.
await super().async_added_to_hass()
state = await self.async_get_last_state()

if state is not None and self._state is None:
self._state = state.state

_LOGGER.debug(f'Restored OctopusEnergyCurrentAccumulativeElectricityConsumption state: {self._state}')
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
from homeassistant.util.dt import (now)
import logging

from homeassistant.core import HomeAssistant

from homeassistant.helpers.update_coordinator import (
CoordinatorEntity
)
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorStateClass
)
from homeassistant.const import (
ENERGY_KILO_WATT_HOUR
)

from .base import (OctopusEnergyGasSensor)

from ..utils.consumption import (get_total_consumption)

_LOGGER = logging.getLogger(__name__)

class OctopusEnergyCurrentAccumulativeGasConsumption(CoordinatorEntity, OctopusEnergyGasSensor):
"""Sensor for displaying the current accumulative gas consumption."""

def __init__(self, hass: HomeAssistant, coordinator, meter, point):
"""Init sensor."""
super().__init__(coordinator)
OctopusEnergyGasSensor.__init__(self, hass, meter, point)

self._state = None
self._latest_date = None
self._previous_total_consumption = None
self._attributes = {
"last_updated_timestamp": None
}

@property
def unique_id(self):
"""The id of the sensor."""
return f"octopus_energy_gas_{self._serial_number}_{self._mprn}_current_accumulative_consumption"

@property
def name(self):
"""Name of the sensor."""
return f"Gas {self._serial_number} {self._mprn} Current Accumulative Consumption"

@property
def device_class(self):
"""The type of sensor"""
return SensorDeviceClass.ENERGY

@property
def state_class(self):
"""The state class of sensor"""
return SensorStateClass.TOTAL

@property
def unit_of_measurement(self):
"""The unit of measurement of sensor"""
return ENERGY_KILO_WATT_HOUR

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

@property
def extra_state_attributes(self):
"""Attributes of the sensor."""
return self._attributes

@property
def last_reset(self):
"""Return the time when the sensor was last reset, if any."""
return self._latest_date

@property
def state(self):
"""The current consumption for the meter."""
_LOGGER.debug('Updating OctopusEnergyCurrentGasConsumption')
consumption_result = self.coordinator.data

if (consumption_result is not None and len(consumption_result) > 0):
self._state = get_total_consumption(consumption_result)
if (self._state is not None):
self._latest_date = consumption_result[0]["interval_start"]
self._attributes["last_updated_timestamp"] = now()
self._attributes["charges"] = list(map(lambda charge: {
"from": charge["interval_start"],
"to": charge["interval_end"],
"consumption": charge["consumption"]
}, consumption_result))

return self._state

async def async_added_to_hass(self):
"""Call when entity about to be added to hass."""
# If not None, we got an initial value.
await super().async_added_to_hass()
state = await self.async_get_last_state()

if state is not None and self._state is None:
self._state = state.state

_LOGGER.debug(f'Restored OctopusEnergyCurrentAccumulativeGasConsumption state: {self._state}')
5 changes: 4 additions & 1 deletion custom_components/octopus_energy/sensor.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from datetime import timedelta
import logging
from homeassistant.util.dt import (utcnow)
from homeassistant.core import HomeAssistant

from .electricity.current_consumption import OctopusEnergyCurrentElectricityConsumption
from .electricity.current_accumulative_consumption import OctopusEnergyCurrentAccumulativeElectricityConsumption
from .electricity.current_demand import OctopusEnergyCurrentElectricityDemand
from .electricity.current_rate import OctopusEnergyElectricityCurrentRate
from .electricity.next_rate import OctopusEnergyElectricityNextRate
Expand All @@ -23,6 +23,7 @@
from .gas.previous_accumulative_consumption_kwh import OctopusEnergyPreviousAccumulativeGasConsumptionKwh
from .gas.previous_accumulative_cost import OctopusEnergyPreviousAccumulativeGasCost
from .gas.current_consumption import OctopusEnergyCurrentGasConsumption
from .gas.current_accumlative_consumption import OctopusEnergyCurrentAccumulativeGasConsumption
from .gas.standing_charge import OctopusEnergyGasCurrentStandingCharge
from .gas.previous_accumulative_cost_override import OctopusEnergyPreviousAccumulativeGasCostOverride

Expand Down Expand Up @@ -119,6 +120,7 @@ async def async_setup_default_sensors(hass: HomeAssistant, entry, async_add_enti

consumption_coordinator = await async_create_current_consumption_coordinator(hass, client, meter["device_id"], True, live_consumption_refresh_in_minutes)
entities.append(OctopusEnergyCurrentElectricityConsumption(hass, consumption_coordinator, meter, point))
entities.append(OctopusEnergyCurrentAccumulativeElectricityConsumption(hass, consumption_coordinator, meter, point))
entities.append(OctopusEnergyCurrentElectricityDemand(hass, consumption_coordinator, meter, point))
else:
for meter in point["meters"]:
Expand Down Expand Up @@ -171,6 +173,7 @@ async def async_setup_default_sensors(hass: HomeAssistant, entry, async_add_enti

consumption_coordinator = await async_create_current_consumption_coordinator(hass, client, meter["device_id"], False, live_consumption_refresh_in_minutes)
entities.append(OctopusEnergyCurrentGasConsumption(hass, consumption_coordinator, meter, point))
entities.append(OctopusEnergyCurrentAccumulativeGasConsumption(hass, consumption_coordinator, meter, point))
else:
for meter in point["meters"]:
_LOGGER.info(f'Skipping gas meter due to no active agreement; mprn: {point["mprn"]}; serial number: {meter["serial_number"]}')
Expand Down
4 changes: 2 additions & 2 deletions custom_components/octopus_energy/utils/consumption.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@ def get_current_consumption_delta(current_datetime: datetime, current_total_cons
return None

if (current_datetime.date() == previous_updated.date()):
return (current_total_consumption - previous_total_consumption) / 1000
return (current_total_consumption - previous_total_consumption)

return current_total_consumption / 1000
return current_total_consumption

0 comments on commit d3315a5

Please sign in to comment.