This commit is contained in:
skyboooox 2026-01-06 10:17:06 +08:00 committed by GitHub
commit 2d788fe38f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 32 additions and 1 deletions

View File

@ -804,6 +804,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)

View File

@ -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