diff --git a/custom_components/xiaomi_home/miot/miot_device.py b/custom_components/xiaomi_home/miot/miot_device.py index e2431c3..32f15d8 100644 --- a/custom_components/xiaomi_home/miot/miot_device.py +++ b/custom_components/xiaomi_home/miot/miot_device.py @@ -812,6 +812,25 @@ class MIoTDevice: except Exception: # pylint: disable=broad-except unit_map['μS/cm'] = 'μS/cm' unit_map['mWh'] = 'mWh' + # Handle UnitOfFrequency and UnitOfRotationalSpeed separately since + # they might not be available in all HA versions + try: + # pylint: disable=import-outside-toplevel + from homeassistant.const import ( # type: ignore + UnitOfFrequency, + UnitOfRotationalSpeed, + ) + unit_map['Hz'] = UnitOfFrequency.HERTZ + unit_map['hz'] = UnitOfFrequency.HERTZ + unit_map['RPM'] = UnitOfRotationalSpeed.REVOLUTIONS_PER_MINUTE + unit_map['rpm'] = UnitOfRotationalSpeed.REVOLUTIONS_PER_MINUTE + unit_map['r/min'] = UnitOfRotationalSpeed.REVOLUTIONS_PER_MINUTE + except Exception: # pylint: disable=broad-except + unit_map['Hz'] = 'Hz' + unit_map['hz'] = 'Hz' + unit_map['RPM'] = 'RPM' + unit_map['rpm'] = 'rpm' + unit_map['r/min'] = 'r/min' return unit_map.get(spec_unit, None) diff --git a/custom_components/xiaomi_home/sensor.py b/custom_components/xiaomi_home/sensor.py index 02371c9..a702c13 100644 --- a/custom_components/xiaomi_home/sensor.py +++ b/custom_components/xiaomi_home/sensor.py @@ -52,7 +52,11 @@ from typing import Any from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback -from homeassistant.components.sensor import SensorEntity, SensorDeviceClass +from homeassistant.components.sensor import ( + SensorEntity, + SensorDeviceClass, + SensorStateClass, +) from homeassistant.components.sensor import DEVICE_CLASS_UNITS from .miot.miot_device import MIoTDevice, MIoTPropertyEntity @@ -102,6 +106,8 @@ class Sensor(MIoTPropertyEntity, SensorEntity): self._attr_device_class = spec.device_class if spec.external_unit: self._attr_native_unit_of_measurement = spec.external_unit + elif spec.unit and spec.unit not in {'none', 'no_unit'}: + self._attr_native_unit_of_measurement = spec.unit else: # device_class is not empty but unit is empty. # Set the default unit according to device_class. @@ -115,6 +121,12 @@ class Sensor(MIoTPropertyEntity, SensorEntity): # Set state_class if spec.state_class: self._attr_state_class = spec.state_class + elif ( + spec.value_range + or spec.format_ in (int, float) + or self._attr_native_unit_of_measurement + ): + self._attr_state_class = SensorStateClass.MEASUREMENT # Set icon if spec.icon and not self.device_class: self._attr_icon = spec.icon