2016-03-07 23:20:48 +01:00
|
|
|
"""Temperature util functions."""
|
2016-07-31 14:24:49 -06:00
|
|
|
from homeassistant.const import (
|
|
|
|
TEMP_CELSIUS,
|
|
|
|
TEMP_FAHRENHEIT,
|
|
|
|
UNIT_NOT_RECOGNIZED_TEMPLATE,
|
|
|
|
TEMPERATURE
|
|
|
|
)
|
2015-08-16 21:36:33 -07:00
|
|
|
|
2016-04-19 20:30:44 -07:00
|
|
|
|
2016-07-23 13:07:08 -05:00
|
|
|
def fahrenheit_to_celsius(fahrenheit: float) -> float:
|
2016-03-07 23:20:48 +01:00
|
|
|
"""Convert a Fahrenheit temperature to Celsius."""
|
2015-08-16 21:36:33 -07:00
|
|
|
return (fahrenheit - 32.0) / 1.8
|
|
|
|
|
|
|
|
|
2016-07-23 13:07:08 -05:00
|
|
|
def celsius_to_fahrenheit(celsius: float) -> float:
|
2016-03-07 23:20:48 +01:00
|
|
|
"""Convert a Celsius temperature to Fahrenheit."""
|
2016-04-19 20:30:44 -07:00
|
|
|
return celsius * 1.8 + 32.0
|
2016-07-31 14:24:49 -06:00
|
|
|
|
|
|
|
|
|
|
|
def convert(temperature: float, from_unit: str, to_unit: str) -> float:
|
|
|
|
"""Convert a temperature from one unit to another."""
|
|
|
|
if from_unit not in (TEMP_CELSIUS, TEMP_FAHRENHEIT):
|
|
|
|
raise ValueError(UNIT_NOT_RECOGNIZED_TEMPLATE.format(from_unit,
|
|
|
|
TEMPERATURE))
|
|
|
|
if to_unit not in (TEMP_CELSIUS, TEMP_FAHRENHEIT):
|
|
|
|
raise ValueError(UNIT_NOT_RECOGNIZED_TEMPLATE.format(to_unit,
|
|
|
|
TEMPERATURE))
|
|
|
|
|
|
|
|
if from_unit == to_unit:
|
|
|
|
return temperature
|
|
|
|
elif from_unit == TEMP_CELSIUS:
|
|
|
|
return celsius_to_fahrenheit(temperature)
|
|
|
|
else:
|
|
|
|
return round(fahrenheit_to_celsius(temperature), 1)
|