Normalize temperature statistics to °C (#52297)

* Normalize temperature statistics to °C

* Fix tests

* Support temperature conversion to and from K, improve tests

* Fix test

* Add tests, pylint
This commit is contained in:
Erik Montnemery 2021-06-30 14:17:58 +02:00 committed by GitHub
parent 508f9a8296
commit 0476c7f9ee
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 153 additions and 12 deletions

View file

@ -4,6 +4,7 @@ from __future__ import annotations
import datetime
import itertools
import logging
from typing import Callable
from homeassistant.components.recorder import history, statistics
from homeassistant.components.sensor import (
@ -31,10 +32,13 @@ from homeassistant.const import (
PRESSURE_PA,
PRESSURE_PSI,
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
TEMP_KELVIN,
)
from homeassistant.core import HomeAssistant, State
import homeassistant.util.dt as dt_util
import homeassistant.util.pressure as pressure_util
import homeassistant.util.temperature as temperature_util
from . import DOMAIN
@ -57,7 +61,7 @@ DEVICE_CLASS_UNITS = {
DEVICE_CLASS_TEMPERATURE: TEMP_CELSIUS,
}
UNIT_CONVERSIONS = {
UNIT_CONVERSIONS: dict[str, dict[str, Callable]] = {
DEVICE_CLASS_ENERGY: {
ENERGY_KILO_WATT_HOUR: lambda x: x,
ENERGY_WATT_HOUR: lambda x: x / 1000,
@ -74,6 +78,11 @@ UNIT_CONVERSIONS = {
PRESSURE_PA: lambda x: x / pressure_util.UNIT_CONVERSION[PRESSURE_PA],
PRESSURE_PSI: lambda x: x / pressure_util.UNIT_CONVERSION[PRESSURE_PSI],
},
DEVICE_CLASS_TEMPERATURE: {
TEMP_CELSIUS: lambda x: x,
TEMP_FAHRENHEIT: temperature_util.fahrenheit_to_celsius,
TEMP_KELVIN: temperature_util.kelvin_to_celsius,
},
}
WARN_UNSUPPORTED_UNIT = set()
@ -169,7 +178,7 @@ def _normalize_states(
_LOGGER.warning("%s has unknown unit %s", entity_id, unit)
continue
fstates.append((UNIT_CONVERSIONS[device_class][unit](fstate), state)) # type: ignore
fstates.append((UNIT_CONVERSIONS[device_class][unit](fstate), state))
return DEVICE_CLASS_UNITS[device_class], fstates
@ -229,6 +238,7 @@ def compile_statistics(
_sum = last_stats[entity_id][0]["sum"]
for fstate, state in fstates:
if "last_reset" not in state.attributes:
continue
if (last_reset := state.attributes["last_reset"]) != old_last_reset: