Skip to content

Commit

Permalink
derive sensor unit_of_measurement from device_class (#200)
Browse files Browse the repository at this point in the history
* derive sensor unit_of_measurement from device_class

* remove unused _state variable

Co-authored-by: lbbrhzn <@lbbrhzn>
  • Loading branch information
lbbrhzn authored Nov 16, 2021
1 parent d21576d commit b859e15
Showing 1 changed file with 17 additions and 8 deletions.
25 changes: 17 additions & 8 deletions custom_components/ocpp/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
STATE_CLASS_TOTAL_INCREASING,
SensorEntity,
)
import homeassistant.const as ha
from homeassistant.const import (
CONF_MONITORED_VARIABLES,
DEVICE_CLASS_BATTERY,
Expand Down Expand Up @@ -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)

Expand All @@ -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."""
Expand All @@ -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):
Expand Down

0 comments on commit b859e15

Please sign in to comment.