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