-
-
Notifications
You must be signed in to change notification settings - Fork 33.2k
/
Copy pathunit_system.py
414 lines (365 loc) · 15.6 KB
/
unit_system.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
"""Unit system helper class and methods."""
from __future__ import annotations
from dataclasses import dataclass
from numbers import Number
from typing import TYPE_CHECKING, Final
import voluptuous as vol
from homeassistant.const import (
ACCUMULATED_PRECIPITATION,
AREA,
LENGTH,
MASS,
PRESSURE,
TEMPERATURE,
UNIT_NOT_RECOGNIZED_TEMPLATE,
VOLUME,
WIND_SPEED,
UnitOfArea,
UnitOfLength,
UnitOfMass,
UnitOfPrecipitationDepth,
UnitOfPressure,
UnitOfSpeed,
UnitOfTemperature,
UnitOfVolume,
UnitOfVolumetricFlux,
)
from .unit_conversion import (
AreaConverter,
DistanceConverter,
PressureConverter,
SpeedConverter,
TemperatureConverter,
VolumeConverter,
)
if TYPE_CHECKING:
from homeassistant.components.sensor import SensorDeviceClass
_CONF_UNIT_SYSTEM_IMPERIAL: Final = "imperial"
_CONF_UNIT_SYSTEM_METRIC: Final = "metric"
_CONF_UNIT_SYSTEM_US_CUSTOMARY: Final = "us_customary"
AREA_UNITS = AreaConverter.VALID_UNITS
LENGTH_UNITS = DistanceConverter.VALID_UNITS
MASS_UNITS: set[str] = {
UnitOfMass.POUNDS,
UnitOfMass.OUNCES,
UnitOfMass.KILOGRAMS,
UnitOfMass.GRAMS,
}
PRESSURE_UNITS = PressureConverter.VALID_UNITS
VOLUME_UNITS = VolumeConverter.VALID_UNITS
WIND_SPEED_UNITS = SpeedConverter.VALID_UNITS
TEMPERATURE_UNITS: set[str] = {UnitOfTemperature.FAHRENHEIT, UnitOfTemperature.CELSIUS}
_VALID_BY_TYPE: dict[str, set[str] | set[str | None]] = {
LENGTH: LENGTH_UNITS,
ACCUMULATED_PRECIPITATION: LENGTH_UNITS,
WIND_SPEED: WIND_SPEED_UNITS,
TEMPERATURE: TEMPERATURE_UNITS,
MASS: MASS_UNITS,
VOLUME: VOLUME_UNITS,
PRESSURE: PRESSURE_UNITS,
AREA: AREA_UNITS,
}
def _is_valid_unit(unit: str, unit_type: str) -> bool:
"""Check if the unit is valid for it's type."""
if units := _VALID_BY_TYPE.get(unit_type):
return unit in units
return False
@dataclass(frozen=True, kw_only=True)
class UnitSystem:
"""A container for units of measure."""
_name: str
accumulated_precipitation_unit: UnitOfPrecipitationDepth
area_unit: UnitOfArea
length_unit: UnitOfLength
mass_unit: UnitOfMass
pressure_unit: UnitOfPressure
temperature_unit: UnitOfTemperature
volume_unit: UnitOfVolume
wind_speed_unit: UnitOfSpeed
_conversions: dict[tuple[SensorDeviceClass | str | None, str | None], str]
def __init__(
self,
name: str,
*,
accumulated_precipitation: UnitOfPrecipitationDepth,
area: UnitOfArea,
conversions: dict[tuple[SensorDeviceClass | str | None, str | None], str],
length: UnitOfLength,
mass: UnitOfMass,
pressure: UnitOfPressure,
temperature: UnitOfTemperature,
volume: UnitOfVolume,
wind_speed: UnitOfSpeed,
) -> None:
"""Initialize the unit system object."""
errors: str = ", ".join(
UNIT_NOT_RECOGNIZED_TEMPLATE.format(unit, unit_type)
for unit, unit_type in (
(accumulated_precipitation, ACCUMULATED_PRECIPITATION),
(area, AREA),
(temperature, TEMPERATURE),
(length, LENGTH),
(wind_speed, WIND_SPEED),
(volume, VOLUME),
(mass, MASS),
(pressure, PRESSURE),
)
if not _is_valid_unit(unit, unit_type)
)
if errors:
raise ValueError(errors)
super().__setattr__("_name", name)
super().__setattr__("accumulated_precipitation_unit", accumulated_precipitation)
super().__setattr__("area_unit", area)
super().__setattr__("length_unit", length)
super().__setattr__("mass_unit", mass)
super().__setattr__("pressure_unit", pressure)
super().__setattr__("temperature_unit", temperature)
super().__setattr__("volume_unit", volume)
super().__setattr__("wind_speed_unit", wind_speed)
super().__setattr__("_conversions", conversions)
def temperature(self, temperature: float, from_unit: str) -> float:
"""Convert the given temperature to this unit system."""
if not isinstance(temperature, Number):
raise TypeError(f"{temperature!s} is not a numeric value.")
return TemperatureConverter.convert(
temperature, from_unit, self.temperature_unit
)
def length(self, length: float | None, from_unit: str) -> float:
"""Convert the given length to this unit system."""
if not isinstance(length, Number):
raise TypeError(f"{length!s} is not a numeric value.")
# type ignore: https://github.com/python/mypy/issues/7207
return DistanceConverter.convert( # type: ignore[unreachable]
length, from_unit, self.length_unit
)
def accumulated_precipitation(self, precip: float | None, from_unit: str) -> float:
"""Convert the given length to this unit system."""
if not isinstance(precip, Number):
raise TypeError(f"{precip!s} is not a numeric value.")
# type ignore: https://github.com/python/mypy/issues/7207
return DistanceConverter.convert( # type: ignore[unreachable]
precip, from_unit, self.accumulated_precipitation_unit
)
def area(self, area: float | None, from_unit: str) -> float:
"""Convert the given area to this unit system."""
if not isinstance(area, Number):
raise TypeError(f"{area!s} is not a numeric value.")
# type ignore: https://github.com/python/mypy/issues/7207
return AreaConverter.convert( # type: ignore[unreachable]
area, from_unit, self.area_unit
)
def pressure(self, pressure: float | None, from_unit: str) -> float:
"""Convert the given pressure to this unit system."""
if not isinstance(pressure, Number):
raise TypeError(f"{pressure!s} is not a numeric value.")
# type ignore: https://github.com/python/mypy/issues/7207
return PressureConverter.convert( # type: ignore[unreachable]
pressure, from_unit, self.pressure_unit
)
def wind_speed(self, wind_speed: float | None, from_unit: str) -> float:
"""Convert the given wind_speed to this unit system."""
if not isinstance(wind_speed, Number):
raise TypeError(f"{wind_speed!s} is not a numeric value.")
# type ignore: https://github.com/python/mypy/issues/7207
return SpeedConverter.convert( # type: ignore[unreachable]
wind_speed, from_unit, self.wind_speed_unit
)
def volume(self, volume: float | None, from_unit: str) -> float:
"""Convert the given volume to this unit system."""
if not isinstance(volume, Number):
raise TypeError(f"{volume!s} is not a numeric value.")
# type ignore: https://github.com/python/mypy/issues/7207
return VolumeConverter.convert( # type: ignore[unreachable]
volume, from_unit, self.volume_unit
)
def as_dict(self) -> dict[str, str]:
"""Convert the unit system to a dictionary."""
return {
LENGTH: self.length_unit,
ACCUMULATED_PRECIPITATION: self.accumulated_precipitation_unit,
AREA: self.area_unit,
MASS: self.mass_unit,
PRESSURE: self.pressure_unit,
TEMPERATURE: self.temperature_unit,
VOLUME: self.volume_unit,
WIND_SPEED: self.wind_speed_unit,
}
def get_converted_unit(
self,
device_class: SensorDeviceClass | str | None,
original_unit: str | None,
) -> str | None:
"""Return converted unit given a device class or an original unit."""
return self._conversions.get((device_class, original_unit))
def get_unit_system(key: str) -> UnitSystem:
"""Get unit system based on key."""
if key == _CONF_UNIT_SYSTEM_US_CUSTOMARY:
return US_CUSTOMARY_SYSTEM
if key == _CONF_UNIT_SYSTEM_METRIC:
return METRIC_SYSTEM
raise ValueError(f"`{key}` is not a valid unit system key")
def _deprecated_unit_system(value: str) -> str:
"""Convert deprecated unit system."""
if value == _CONF_UNIT_SYSTEM_IMPERIAL:
return _CONF_UNIT_SYSTEM_US_CUSTOMARY
return value
validate_unit_system = vol.All(
vol.Lower,
_deprecated_unit_system,
vol.Any(_CONF_UNIT_SYSTEM_METRIC, _CONF_UNIT_SYSTEM_US_CUSTOMARY),
)
METRIC_SYSTEM = UnitSystem(
_CONF_UNIT_SYSTEM_METRIC,
accumulated_precipitation=UnitOfPrecipitationDepth.MILLIMETERS,
conversions={
# Force atmospheric pressures to hPa
**{
("atmospheric_pressure", unit): UnitOfPressure.HPA
for unit in UnitOfPressure
if unit != UnitOfPressure.HPA
},
# Convert non-metric area
("area", UnitOfArea.SQUARE_INCHES): UnitOfArea.SQUARE_CENTIMETERS,
("area", UnitOfArea.SQUARE_FEET): UnitOfArea.SQUARE_METERS,
("area", UnitOfArea.SQUARE_MILES): UnitOfArea.SQUARE_KILOMETERS,
("area", UnitOfArea.SQUARE_YARDS): UnitOfArea.SQUARE_METERS,
("area", UnitOfArea.ACRES): UnitOfArea.HECTARES,
# Convert non-metric distances
("distance", UnitOfLength.FEET): UnitOfLength.METERS,
("distance", UnitOfLength.INCHES): UnitOfLength.MILLIMETERS,
("distance", UnitOfLength.MILES): UnitOfLength.KILOMETERS,
("distance", UnitOfLength.NAUTICAL_MILES): UnitOfLength.KILOMETERS,
("distance", UnitOfLength.YARDS): UnitOfLength.METERS,
# Convert non-metric volumes of gas meters
("gas", UnitOfVolume.CENTUM_CUBIC_FEET): UnitOfVolume.CUBIC_METERS,
("gas", UnitOfVolume.CUBIC_FEET): UnitOfVolume.CUBIC_METERS,
# Convert non-metric precipitation
("precipitation", UnitOfLength.INCHES): UnitOfLength.MILLIMETERS,
# Convert non-metric precipitation intensity
(
"precipitation_intensity",
UnitOfVolumetricFlux.INCHES_PER_DAY,
): UnitOfVolumetricFlux.MILLIMETERS_PER_DAY,
(
"precipitation_intensity",
UnitOfVolumetricFlux.INCHES_PER_HOUR,
): UnitOfVolumetricFlux.MILLIMETERS_PER_HOUR,
# Convert non-metric pressure
("pressure", UnitOfPressure.PSI): UnitOfPressure.KPA,
("pressure", UnitOfPressure.INHG): UnitOfPressure.HPA,
# Convert non-metric speeds except knots to km/h
("speed", UnitOfSpeed.FEET_PER_SECOND): UnitOfSpeed.KILOMETERS_PER_HOUR,
("speed", UnitOfSpeed.INCHES_PER_SECOND): UnitOfSpeed.MILLIMETERS_PER_SECOND,
("speed", UnitOfSpeed.MILES_PER_HOUR): UnitOfSpeed.KILOMETERS_PER_HOUR,
(
"speed",
UnitOfVolumetricFlux.INCHES_PER_DAY,
): UnitOfVolumetricFlux.MILLIMETERS_PER_DAY,
(
"speed",
UnitOfVolumetricFlux.INCHES_PER_HOUR,
): UnitOfVolumetricFlux.MILLIMETERS_PER_HOUR,
# Convert non-metric volumes
("volume", UnitOfVolume.CENTUM_CUBIC_FEET): UnitOfVolume.CUBIC_METERS,
("volume", UnitOfVolume.CUBIC_FEET): UnitOfVolume.CUBIC_METERS,
("volume", UnitOfVolume.FLUID_OUNCES): UnitOfVolume.MILLILITERS,
("volume", UnitOfVolume.GALLONS): UnitOfVolume.LITERS,
# Convert non-metric volumes of water meters
("water", UnitOfVolume.CENTUM_CUBIC_FEET): UnitOfVolume.CUBIC_METERS,
("water", UnitOfVolume.CUBIC_FEET): UnitOfVolume.CUBIC_METERS,
("water", UnitOfVolume.GALLONS): UnitOfVolume.LITERS,
# Convert wind speeds except knots to km/h
**{
("wind_speed", unit): UnitOfSpeed.KILOMETERS_PER_HOUR
for unit in UnitOfSpeed
if unit not in (UnitOfSpeed.KILOMETERS_PER_HOUR, UnitOfSpeed.KNOTS)
},
},
area=UnitOfArea.SQUARE_METERS,
length=UnitOfLength.KILOMETERS,
mass=UnitOfMass.GRAMS,
pressure=UnitOfPressure.PA,
temperature=UnitOfTemperature.CELSIUS,
volume=UnitOfVolume.LITERS,
wind_speed=UnitOfSpeed.METERS_PER_SECOND,
)
US_CUSTOMARY_SYSTEM = UnitSystem(
_CONF_UNIT_SYSTEM_US_CUSTOMARY,
accumulated_precipitation=UnitOfPrecipitationDepth.INCHES,
conversions={
# Force atmospheric pressures to inHg
**{
("atmospheric_pressure", unit): UnitOfPressure.INHG
for unit in UnitOfPressure
if unit != UnitOfPressure.INHG
},
# Convert non-USCS areas
("area", UnitOfArea.SQUARE_METERS): UnitOfArea.SQUARE_FEET,
("area", UnitOfArea.SQUARE_CENTIMETERS): UnitOfArea.SQUARE_INCHES,
("area", UnitOfArea.SQUARE_MILLIMETERS): UnitOfArea.SQUARE_INCHES,
("area", UnitOfArea.SQUARE_KILOMETERS): UnitOfArea.SQUARE_MILES,
("area", UnitOfArea.HECTARES): UnitOfArea.ACRES,
# Convert non-USCS distances
("distance", UnitOfLength.CENTIMETERS): UnitOfLength.INCHES,
("distance", UnitOfLength.KILOMETERS): UnitOfLength.MILES,
("distance", UnitOfLength.METERS): UnitOfLength.FEET,
("distance", UnitOfLength.MILLIMETERS): UnitOfLength.INCHES,
# Convert non-USCS volumes of gas meters
("gas", UnitOfVolume.CUBIC_METERS): UnitOfVolume.CUBIC_FEET,
# Convert non-USCS precipitation
("precipitation", UnitOfLength.CENTIMETERS): UnitOfLength.INCHES,
("precipitation", UnitOfLength.MILLIMETERS): UnitOfLength.INCHES,
# Convert non-USCS precipitation intensity
(
"precipitation_intensity",
UnitOfVolumetricFlux.MILLIMETERS_PER_DAY,
): UnitOfVolumetricFlux.INCHES_PER_DAY,
(
"precipitation_intensity",
UnitOfVolumetricFlux.MILLIMETERS_PER_HOUR,
): UnitOfVolumetricFlux.INCHES_PER_HOUR,
# Convert non-USCS pressure
("pressure", UnitOfPressure.MBAR): UnitOfPressure.PSI,
("pressure", UnitOfPressure.CBAR): UnitOfPressure.PSI,
("pressure", UnitOfPressure.BAR): UnitOfPressure.PSI,
("pressure", UnitOfPressure.PA): UnitOfPressure.PSI,
("pressure", UnitOfPressure.HPA): UnitOfPressure.PSI,
("pressure", UnitOfPressure.KPA): UnitOfPressure.PSI,
("pressure", UnitOfPressure.MMHG): UnitOfPressure.INHG,
# Convert non-USCS speeds, except knots, to mph
("speed", UnitOfSpeed.METERS_PER_SECOND): UnitOfSpeed.MILES_PER_HOUR,
("speed", UnitOfSpeed.MILLIMETERS_PER_SECOND): UnitOfSpeed.INCHES_PER_SECOND,
("speed", UnitOfSpeed.KILOMETERS_PER_HOUR): UnitOfSpeed.MILES_PER_HOUR,
(
"speed",
UnitOfVolumetricFlux.MILLIMETERS_PER_DAY,
): UnitOfVolumetricFlux.INCHES_PER_DAY,
(
"speed",
UnitOfVolumetricFlux.MILLIMETERS_PER_HOUR,
): UnitOfVolumetricFlux.INCHES_PER_HOUR,
# Convert non-USCS volumes
("volume", UnitOfVolume.CUBIC_METERS): UnitOfVolume.CUBIC_FEET,
("volume", UnitOfVolume.LITERS): UnitOfVolume.GALLONS,
("volume", UnitOfVolume.MILLILITERS): UnitOfVolume.FLUID_OUNCES,
# Convert non-USCS volumes of water meters
("water", UnitOfVolume.CUBIC_METERS): UnitOfVolume.CUBIC_FEET,
("water", UnitOfVolume.LITERS): UnitOfVolume.GALLONS,
# Convert wind speeds except knots to mph
**{
("wind_speed", unit): UnitOfSpeed.MILES_PER_HOUR
for unit in UnitOfSpeed
if unit not in (UnitOfSpeed.KNOTS, UnitOfSpeed.MILES_PER_HOUR)
},
},
area=UnitOfArea.SQUARE_FEET,
length=UnitOfLength.MILES,
mass=UnitOfMass.POUNDS,
pressure=UnitOfPressure.PSI,
temperature=UnitOfTemperature.FAHRENHEIT,
volume=UnitOfVolume.GALLONS,
wind_speed=UnitOfSpeed.MILES_PER_HOUR,
)
IMPERIAL_SYSTEM = US_CUSTOMARY_SYSTEM
"""IMPERIAL_SYSTEM is deprecated. Please use US_CUSTOMARY_SYSTEM instead."""