Get suggested_unit_of_measurement via unit converter's UNIT_CLASS (#119196)

Co-authored-by: Richard <rikroe@users.noreply.github.com>
Co-authored-by: Erik Montnemery <erik@montnemery.com>
This commit is contained in:
Richard Kroegel 2024-07-10 17:45:07 +02:00 committed by GitHub
parent 0e0a339517
commit 865190f0b0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 25 additions and 2 deletions

View File

@ -394,11 +394,20 @@ class SensorEntity(Entity, cached_properties=CACHED_PROPERTIES_WITH_ATTR_):
suggested_unit_of_measurement = self.suggested_unit_of_measurement
if suggested_unit_of_measurement is None:
# Fallback to suggested by the unit conversion rules
# Fallback to unit suggested by the unit conversion rules from device class
suggested_unit_of_measurement = self.hass.config.units.get_converted_unit(
self.device_class, self.native_unit_of_measurement
)
if suggested_unit_of_measurement is None and (
unit_converter := UNIT_CONVERTERS.get(self.device_class)
):
# If the device class is not known by the unit system but has a unit converter,
# fall back to the unit suggested by the unit converter's unit class.
suggested_unit_of_measurement = self.hass.config.units.get_converted_unit(
unit_converter.UNIT_CLASS, self.native_unit_of_measurement
)
if suggested_unit_of_measurement is None:
return UNDEFINED

View File

@ -942,7 +942,21 @@ async def test_custom_unit_change(
"1000000",
"1093613",
SensorDeviceClass.DISTANCE,
)
),
# Volume Storage (subclass of Volume)
(
US_CUSTOMARY_SYSTEM,
UnitOfVolume.LITERS,
UnitOfVolume.GALLONS,
UnitOfVolume.GALLONS,
UnitOfVolume.FLUID_OUNCES,
1000,
"1000",
"264",
"264",
"33814",
SensorDeviceClass.VOLUME_STORAGE,
),
],
)
async def test_unit_conversion_priority(