Don't override temperature unit for sensors (#68910)

pull/68913/head
Erik Montnemery 2022-03-30 19:15:00 +02:00 committed by GitHub
parent 6d168d2672
commit 9471e4d77c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 61 additions and 7 deletions

View File

@ -36,7 +36,14 @@ from homeassistant.const import (
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
)
from homeassistant.core import CALLBACK_TYPE, Context, Event, HomeAssistant, callback
from homeassistant.core import (
CALLBACK_TYPE,
Context,
Event,
HomeAssistant,
callback,
split_entity_id,
)
from homeassistant.exceptions import HomeAssistantError, NoEntitySpecifiedError
from homeassistant.loader import bind_hass
from homeassistant.util import dt as dt_util, ensure_unique_string, slugify
@ -639,9 +646,11 @@ class Entity(ABC):
try:
unit_of_measure = attr.get(ATTR_UNIT_OF_MEASUREMENT)
units = self.hass.config.units
domain = split_entity_id(self.entity_id)[0]
if (
unit_of_measure in (TEMP_CELSIUS, TEMP_FAHRENHEIT)
and unit_of_measure != units.temperature_unit
and domain != "sensor"
):
prec = len(state) - state.index(".") - 1 if "." in state else 0
temp = units.temperature(float(state), unit_of_measure)

View File

@ -350,19 +350,64 @@ async def test_restore_sensor_restore_state(
@pytest.mark.parametrize(
"native_unit,custom_unit,state_unit,native_value,custom_value",
"device_class,native_unit,custom_unit,state_unit,native_value,custom_value",
[
# Smaller to larger unit, InHg is ~33x larger than hPa -> 1 more decimal
(PRESSURE_HPA, PRESSURE_INHG, PRESSURE_INHG, 1000.0, 29.53),
(PRESSURE_KPA, PRESSURE_HPA, PRESSURE_HPA, 1.234, 12.34),
(PRESSURE_HPA, PRESSURE_MMHG, PRESSURE_MMHG, 1000, 750),
(
SensorDeviceClass.PRESSURE,
PRESSURE_HPA,
PRESSURE_INHG,
PRESSURE_INHG,
1000.0,
29.53,
),
(
SensorDeviceClass.PRESSURE,
PRESSURE_KPA,
PRESSURE_HPA,
PRESSURE_HPA,
1.234,
12.34,
),
(
SensorDeviceClass.PRESSURE,
PRESSURE_HPA,
PRESSURE_MMHG,
PRESSURE_MMHG,
1000,
750,
),
# Not a supported pressure unit
(PRESSURE_HPA, "peer_pressure", PRESSURE_HPA, 1000, 1000),
(
SensorDeviceClass.PRESSURE,
PRESSURE_HPA,
"peer_pressure",
PRESSURE_HPA,
1000,
1000,
),
(
SensorDeviceClass.TEMPERATURE,
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
TEMP_FAHRENHEIT,
37.5,
99.5,
),
(
SensorDeviceClass.TEMPERATURE,
TEMP_FAHRENHEIT,
TEMP_CELSIUS,
TEMP_CELSIUS,
100,
38.0,
),
],
)
async def test_custom_unit(
hass,
enable_custom_integrations,
device_class,
native_unit,
custom_unit,
state_unit,
@ -384,7 +429,7 @@ async def test_custom_unit(
name="Test",
native_value=str(native_value),
native_unit_of_measurement=native_unit,
device_class=SensorDeviceClass.PRESSURE,
device_class=device_class,
unique_id="very_unique",
)