2017-11-14 09:36:18 +00:00
|
|
|
"""Temperature helpers for Home Assistant."""
|
2021-03-17 17:34:19 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2017-11-14 09:36:18 +00:00
|
|
|
from numbers import Number
|
|
|
|
|
2021-07-20 12:13:51 +00:00
|
|
|
from homeassistant.const import PRECISION_HALVES, PRECISION_TENTHS
|
2017-11-14 09:36:18 +00:00
|
|
|
from homeassistant.core import HomeAssistant
|
2022-09-28 14:05:31 +00:00
|
|
|
from homeassistant.util.unit_conversion import TemperatureConverter
|
2017-11-14 09:36:18 +00:00
|
|
|
|
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
def display_temp(
|
2021-07-20 12:13:51 +00:00
|
|
|
hass: HomeAssistant, temperature: float | None, unit: str, precision: float
|
2021-03-17 17:34:19 +00:00
|
|
|
) -> float | None:
|
2018-02-28 18:59:47 +00:00
|
|
|
"""Convert temperature into preferred units/precision for display."""
|
2017-11-14 09:36:18 +00:00
|
|
|
temperature_unit = unit
|
|
|
|
ha_unit = hass.config.units.temperature_unit
|
|
|
|
|
|
|
|
if temperature is None:
|
|
|
|
return temperature
|
|
|
|
|
|
|
|
# If the temperature is not a number this can cause issues
|
|
|
|
# with Polymer components, so bail early there.
|
|
|
|
if not isinstance(temperature, Number):
|
2019-08-23 16:53:33 +00:00
|
|
|
raise TypeError(f"Temperature is not a number: {temperature}")
|
2017-11-14 09:36:18 +00:00
|
|
|
|
2020-03-12 10:52:20 +00:00
|
|
|
if temperature_unit != ha_unit:
|
2022-09-28 14:05:31 +00:00
|
|
|
temperature = TemperatureConverter.convert(
|
|
|
|
temperature, temperature_unit, ha_unit
|
|
|
|
)
|
2017-11-14 09:36:18 +00:00
|
|
|
|
|
|
|
# Round in the units appropriate
|
2018-02-28 18:59:47 +00:00
|
|
|
if precision == PRECISION_HALVES:
|
|
|
|
temperature = round(temperature * 2) / 2.0
|
|
|
|
elif precision == PRECISION_TENTHS:
|
|
|
|
temperature = round(temperature, 1)
|
2017-11-14 09:36:18 +00:00
|
|
|
# Integer as a fall back (PRECISION_WHOLE)
|
2018-02-28 18:59:47 +00:00
|
|
|
else:
|
|
|
|
temperature = round(temperature)
|
|
|
|
|
|
|
|
return temperature
|