From b859e154f1ef39c8faa6e89891caf35b140b96d1 Mon Sep 17 00:00:00 2001 From: lbbrhzn Date: Wed, 17 Nov 2021 00:49:56 +0100 Subject: [PATCH] derive sensor unit_of_measurement from device_class (#200) * derive sensor unit_of_measurement from device_class * remove unused _state variable Co-authored-by: lbbrhzn <@lbbrhzn> --- custom_components/ocpp/sensor.py | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/custom_components/ocpp/sensor.py b/custom_components/ocpp/sensor.py index 58a3d3b0..9677d38e 100644 --- a/custom_components/ocpp/sensor.py +++ b/custom_components/ocpp/sensor.py @@ -6,6 +6,7 @@ STATE_CLASS_TOTAL_INCREASING, SensorEntity, ) +import homeassistant.const as ha from homeassistant.const import ( CONF_MONITORED_VARIABLES, DEVICE_CLASS_BATTERY, @@ -59,7 +60,6 @@ def __init__( self.central_system = central_system self.cp_id = cp_id self.metric = metric - self._state = None self._extra_attr = {} self._last_reset = homeassistant.util.dt.utc_from_timestamp(0) @@ -73,12 +73,6 @@ def unique_id(self): """Return the unique id of this sensor.""" return ".".join([DOMAIN, self.cp_id, self.metric, "sensor"]) - @property - def state(self): - """Return the state of the sensor.""" - self._state = self.central_system.get_metric(self.cp_id, self.metric) - return self._state - @property def available(self) -> bool: """Return if sensor is available.""" @@ -87,7 +81,22 @@ def available(self) -> bool: @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" - return self.central_system.get_ha_unit(self.cp_id, self.metric) + unit_of_measurement = None + if self.device_class is DEVICE_CLASS_BATTERY: + unit_of_measurement = ha.PERCENTAGE + elif self.device_class is DEVICE_CLASS_CURRENT: + unit_of_measurement = ha.ELECTRIC_CURRENT_AMPERE + elif self.device_class is DEVICE_CLASS_ENERGY: + unit_of_measurement = ha.ENERGY_KILO_WATT_HOUR + elif self.device_class is DEVICE_CLASS_POWER: + unit_of_measurement = ha.POWER_KILO_WATT + elif self.device_class is DEVICE_CLASS_TEMPERATURE: + unit_of_measurement = ha.TEMP_CELSIUS + elif self.device_class is DEVICE_CLASS_TIMESTAMP: + unit_of_measurement = None + elif self.device_class is DEVICE_CLASS_VOLTAGE: + unit_of_measurement = ha.ELECTRIC_POTENTIAL_VOLT + return unit_of_measurement @property def should_poll(self):