2019-03-24 17:37:31 +00:00
|
|
|
"""Pressure util functions."""
|
2021-07-18 12:43:47 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2019-03-24 17:37:31 +00:00
|
|
|
from numbers import Number
|
|
|
|
|
|
|
|
from homeassistant.const import (
|
2019-12-09 15:42:10 +00:00
|
|
|
PRESSURE,
|
2021-08-12 05:30:35 +00:00
|
|
|
PRESSURE_BAR,
|
2021-11-10 08:44:05 +00:00
|
|
|
PRESSURE_CBAR,
|
2019-03-24 17:37:31 +00:00
|
|
|
PRESSURE_HPA,
|
|
|
|
PRESSURE_INHG,
|
2021-10-01 15:08:04 +00:00
|
|
|
PRESSURE_KPA,
|
2019-12-09 15:42:10 +00:00
|
|
|
PRESSURE_MBAR,
|
2022-01-24 21:57:56 +00:00
|
|
|
PRESSURE_MMHG,
|
2019-12-09 15:42:10 +00:00
|
|
|
PRESSURE_PA,
|
2019-03-24 17:37:31 +00:00
|
|
|
PRESSURE_PSI,
|
|
|
|
UNIT_NOT_RECOGNIZED_TEMPLATE,
|
|
|
|
)
|
|
|
|
|
2021-07-20 12:13:51 +00:00
|
|
|
VALID_UNITS: tuple[str, ...] = (
|
2021-07-18 12:43:47 +00:00
|
|
|
PRESSURE_PA,
|
|
|
|
PRESSURE_HPA,
|
2021-10-01 15:08:04 +00:00
|
|
|
PRESSURE_KPA,
|
2021-08-12 05:30:35 +00:00
|
|
|
PRESSURE_BAR,
|
2021-11-10 08:44:05 +00:00
|
|
|
PRESSURE_CBAR,
|
2021-07-18 12:43:47 +00:00
|
|
|
PRESSURE_MBAR,
|
|
|
|
PRESSURE_INHG,
|
|
|
|
PRESSURE_PSI,
|
2022-01-24 21:57:56 +00:00
|
|
|
PRESSURE_MMHG,
|
2021-07-18 12:43:47 +00:00
|
|
|
)
|
2019-03-24 17:37:31 +00:00
|
|
|
|
2021-07-20 12:13:51 +00:00
|
|
|
UNIT_CONVERSION: dict[str, float] = {
|
2019-03-24 17:37:31 +00:00
|
|
|
PRESSURE_PA: 1,
|
|
|
|
PRESSURE_HPA: 1 / 100,
|
2021-10-01 15:08:04 +00:00
|
|
|
PRESSURE_KPA: 1 / 1000,
|
2021-08-12 05:30:35 +00:00
|
|
|
PRESSURE_BAR: 1 / 100000,
|
2021-11-10 08:44:05 +00:00
|
|
|
PRESSURE_CBAR: 1 / 1000,
|
2019-03-24 17:37:31 +00:00
|
|
|
PRESSURE_MBAR: 1 / 100,
|
|
|
|
PRESSURE_INHG: 1 / 3386.389,
|
|
|
|
PRESSURE_PSI: 1 / 6894.757,
|
2022-01-24 21:57:56 +00:00
|
|
|
PRESSURE_MMHG: 1 / 133.322,
|
2019-03-24 17:37:31 +00:00
|
|
|
}
|
|
|
|
|
2022-09-22 06:50:08 +00:00
|
|
|
NORMALIZED_UNIT = PRESSURE_PA
|
|
|
|
|
2019-03-24 17:37:31 +00:00
|
|
|
|
2022-09-22 05:18:00 +00:00
|
|
|
def convert(value: float, from_unit: str, to_unit: str) -> float:
|
2019-03-24 17:37:31 +00:00
|
|
|
"""Convert one unit of measurement to another."""
|
2022-09-22 05:18:00 +00:00
|
|
|
if from_unit not in VALID_UNITS:
|
|
|
|
raise ValueError(UNIT_NOT_RECOGNIZED_TEMPLATE.format(from_unit, PRESSURE))
|
|
|
|
if to_unit not in VALID_UNITS:
|
|
|
|
raise ValueError(UNIT_NOT_RECOGNIZED_TEMPLATE.format(to_unit, PRESSURE))
|
2019-03-24 17:37:31 +00:00
|
|
|
|
|
|
|
if not isinstance(value, Number):
|
2019-08-23 16:53:33 +00:00
|
|
|
raise TypeError(f"{value} is not of numeric type")
|
2019-03-24 17:37:31 +00:00
|
|
|
|
2022-09-22 05:18:00 +00:00
|
|
|
if from_unit == to_unit:
|
2019-03-24 17:37:31 +00:00
|
|
|
return value
|
|
|
|
|
2022-09-22 05:18:00 +00:00
|
|
|
pascals = value / UNIT_CONVERSION[from_unit]
|
|
|
|
return pascals * UNIT_CONVERSION[to_unit]
|