Skip to content

Commit

Permalink
add sensor properties for long term statistics (#121)
Browse files Browse the repository at this point in the history
* add sensor properties for long term statistics

* fix typo: isnumeric

* fix typo: isnumeric

Co-authored-by: lbbrhzn <@lbbrhzn>
  • Loading branch information
lbbrhzn authored Aug 22, 2021
1 parent 47519b5 commit 0aa64dc
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 13 deletions.
10 changes: 5 additions & 5 deletions custom_components/ocpp/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from homeassistant.helpers import device_registry

from .api import CentralSystem
from .const import CONF_CPID, CONF_CSID, DOMAIN, PLATFORMS
from .const import CONF_CPID, CONF_CSID, DEFAULT_CPID, DEFAULT_CSID, DOMAIN, PLATFORMS

_LOGGER: logging.Logger = logging.getLogger(__package__)
logging.getLogger(DOMAIN).setLevel(logging.DEBUG)
Expand All @@ -32,16 +32,16 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
""" Create Central System Device """
dr.async_get_or_create(
config_entry_id=entry.entry_id,
identifiers={(DOMAIN, entry.data[CONF_CSID])},
name=entry.data[CONF_CSID],
identifiers={(DOMAIN, entry.data.get(CONF_CSID, DEFAULT_CSID))},
name=entry.data.get(CONF_CSID, DEFAULT_CSID),
model="OCPP Central System",
)

""" Create Charge Point Device """
dr.async_get_or_create(
config_entry_id=entry.entry_id,
identifiers={(DOMAIN, entry.data[CONF_CPID])},
name=entry.data[CONF_CPID],
identifiers={(DOMAIN, entry.data.get(CONF_CPID, DEFAULT_CPID))},
name=entry.data.get(CONF_CPID, DEFAULT_CPID),
default_model="OCPP Charge Point",
via_device=((DOMAIN), central_sys.id),
)
Expand Down
70 changes: 64 additions & 6 deletions custom_components/ocpp/sensor.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,29 @@
"""Sensor platform for ocpp."""

from homeassistant.const import CONF_MONITORED_VARIABLES
from homeassistant.helpers.entity import Entity
import datetime

import homeassistant
from homeassistant.components.sensor import STATE_CLASS_MEASUREMENT, SensorEntity
from homeassistant.const import (
CONF_MONITORED_VARIABLES,
DEVICE_CLASS_CURRENT,
DEVICE_CLASS_ENERGY,
DEVICE_CLASS_POWER,
DEVICE_CLASS_TEMPERATURE,
DEVICE_CLASS_VOLTAGE,
)

from ocpp.v16.enums import UnitOfMeasure

from .api import CentralSystem
from .const import CONF_CPID, DOMAIN, ICON
from .const import CONF_CPID, DEFAULT_CPID, DOMAIN, ICON
from .enums import HAChargerDetails, HAChargerSession, HAChargerStatuses


async def async_setup_entry(hass, entry, async_add_devices):
"""Configure the sensor platform."""
central_system = hass.data[DOMAIN][entry.entry_id]
cp_id = entry.data[CONF_CPID]
cp_id = entry.data.get(CONF_CPID, DEFAULT_CPID)

entities = []

Expand All @@ -36,7 +48,7 @@ async def async_setup_entry(hass, entry, async_add_devices):
async_add_devices(entities, False)


class ChargePointMetric(Entity):
class ChargePointMetric(SensorEntity):
"""Individual sensor for charge point metrics."""

def __init__(
Expand All @@ -51,6 +63,7 @@ def __init__(
self.metric = metric
self._state = None
self._extra_attr = {}
self._last_reset = homeassistant.util.dt.utc_from_timestamp(0)

@property
def name(self):
Expand All @@ -65,7 +78,17 @@ def unique_id(self):
@property
def state(self):
"""Return the state of the sensor."""
return self.central_system.get_metric(self.cp_id, self.metric)
old_state = self._state
new_state = self.central_system.get_metric(self.cp_id, self.metric)
self._state = new_state
if (
(self.device_class is DEVICE_CLASS_ENERGY)
and (new_state is not None)
and (old_state is not None)
and (new_state < old_state)
):
self._last_reset = datetime.datetime.now()
return self._state

@property
def available(self) -> bool:
Expand Down Expand Up @@ -103,6 +126,41 @@ def extra_state_attributes(self):
"""Return the state attributes."""
return self.central_system.get_extra_attr(self.cp_id, self.metric)

@property
def state_class(self):
"""Return the state class of the sensor."""
return STATE_CLASS_MEASUREMENT

This comment has been minimized.

Copy link
@drc38

drc38 Aug 27, 2021

Collaborator

@lbbrhzn , should we use STATE_CLASS_TOTAL_INCREASING for energy metrics which are monotonically increasing? The HA documentation is somewhat confusing showing energy in both classes

This comment has been minimized.

Copy link
@lbbrhzn

lbbrhzn Aug 27, 2021

Owner

@drc38, Yes! STATE_CLASS_TOTAL_INCREASING seems more appropriate than STATE_CLASS_MEASUREMENT for energy measurements. It automatically resets when the new value is lower than the old value instead of using the last_reset property.

This comment has been minimized.

Copy link
@lbbrhzn

lbbrhzn Aug 27, 2021

Owner

@drc38 Seems this state class was introduced quite recently, it is not part of of the latest home assistant release (2021.8.8)


@property
def device_class(self):
"""Return the device class of the sensor."""
if self.unit_of_measurement in [
UnitOfMeasure.wh.value,
UnitOfMeasure.kwh.value,
]:
return DEVICE_CLASS_ENERGY
elif self.unit_of_measurement in [
UnitOfMeasure.w.value,
UnitOfMeasure.kw.value,
]:
return DEVICE_CLASS_POWER
elif self.unit_of_measurement in [
UnitOfMeasure.celsius.value,
UnitOfMeasure.fahrenheit.value,
]:
return DEVICE_CLASS_TEMPERATURE
elif self.unit_of_measurement in [UnitOfMeasure.a.value]:
return DEVICE_CLASS_CURRENT
elif self.unit_of_measurement in [UnitOfMeasure.v.value]:
return DEVICE_CLASS_VOLTAGE
else:
return None

@property
def last_reset(self):
"""Return the time when a metered value wwas ;ast reset."""
return self._last_reset

async def async_update(self):
"""Get the latest data and update the states."""
pass
4 changes: 2 additions & 2 deletions custom_components/ocpp/switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@
from homeassistant.components.switch import SwitchEntity

from .api import CentralSystem
from .const import CONF_CPID, DOMAIN, ICON, SWITCHES
from .const import CONF_CPID, DEFAULT_CPID, DOMAIN, ICON, SWITCHES


async def async_setup_entry(hass, entry, async_add_devices):
"""Configure the sensor platform."""
central_system = hass.data[DOMAIN][entry.entry_id]
cp_id = entry.data[CONF_CPID]
cp_id = entry.data.get(CONF_CPID, DEFAULT_CPID)

entities = []

Expand Down

0 comments on commit 0aa64dc

Please sign in to comment.