homeassistant.util

Helper methods for various modules.

class homeassistant.util.OrderedEnum[source]

Bases: enum.Enum

Taken from Python 3.4.0 docs.

class homeassistant.util.Throttle(min_time: timedelta, limit_no_throttle: timedelta | None = None)[source]

Bases: object

A class for throttling the execution of tasks.

This method decorator adds a cooldown to a method to prevent it from being called more then 1 time within the timedelta interval min_time after it returned its result.

Calling a method a second time during the interval will return None.

Pass keyword argument no_throttle=True to the wrapped method to make the call not throttled.

Decorator takes in an optional second timedelta interval to throttle the ‘no_throttle’ calls.

Adds a datetime attribute last_call to the method.

homeassistant.util.convert(value: T | None, to_type: Callable[[T], U], default: U | None = None) → U | None[source]

Convert value to to_type, returns default if fails.

homeassistant.util.ensure_unique_string(preferred_string: str, current_strings: Iterable[str] | KeysView[str]) → str[source]

Return a string that is not present in current_strings.

If preferred string exists will append _2, _3, ..

homeassistant.util.get_local_ip

Try to determine the local IP address of the machine.

homeassistant.util.get_random_string(length: int = 10) → str[source]

Return a random string with letters and digits.

homeassistant.util.raise_if_invalid_filename(filename: str) → None[source]

Check if a filename is valid.

Raises a ValueError if the filename is invalid.

homeassistant.util.raise_if_invalid_path(path: str) → None[source]

Check if a path is valid.

Raises a ValueError if the path is invalid.

homeassistant.util.repr_helper(inp: Any) → str[source]

Help creating a more readable string representation of objects.

homeassistant.util.sanitize_filename(filename: str) → str[source]

Check if a filename is safe.

Only to be used to compare to original filename to check if changed. If result changed, the given path is not safe and should not be used, raise an error.

DEPRECATED.

homeassistant.util.sanitize_path(path: str) → str[source]

Check if a path is safe.

Only to be used to compare to original path to check if changed. If result changed, the given path is not safe and should not be used, raise an error.

DEPRECATED.

homeassistant.util.slugify(text: str, *, separator: str = '_') → str[source]

Slugify a given text.

homeassistant.util.yaml

YAML utility functions.

class homeassistant.util.yaml.Input(name: str)[source]

Bases: object

Input that should be substituted.

classmethod from_node(loader: yaml.loader.Loader, node: yaml.nodes.Node) → homeassistant.util.yaml.objects.Input[source]

Create a new placeholder from a node.

name: str = None
homeassistant.util.yaml.dump(_dict: dict) → str[source]

Dump YAML to a string and remove null.

homeassistant.util.yaml.save_yaml(path: str, data: dict) → None[source]

Save YAML to a file.

class homeassistant.util.yaml.Secrets(config_dir: pathlib.Path)[source]

Bases: object

Store secrets while loading YAML.

get(requester_path: str, secret: str) → str[source]

Return the value of a secret.

homeassistant.util.yaml.load_yaml(fname: str, secrets: Secrets | None = None) → JSON_TYPE[source]

Load a YAML file.

homeassistant.util.yaml.secret_yaml(loader: homeassistant.util.yaml.loader.SafeLineLoader, node: yaml.nodes.Node) → Union[list, dict, str][source]

Load secrets and embed it into the configuration YAML.

homeassistant.util.yaml.parse_yaml(content: str | TextIO, secrets: Secrets | None = None) → JSON_TYPE[source]

Load a YAML file.

exception homeassistant.util.yaml.UndefinedSubstitution(input_name: str)[source]

Bases: Exception

Error raised when we find a substitution that is not defined.

homeassistant.util.yaml.extract_inputs(obj: Any) → set[str][source]

Extract input from a structure.

homeassistant.util.yaml.substitute(obj: Any, substitutions: dict[str, Any]) → Any[source]

Substitute values.

homeassistant.util.aiohttp

Utilities to help with aiohttp.

class homeassistant.util.aiohttp.MockRequest(content: bytes, mock_source: str, method: str = 'GET', status: int = 200, headers: dict[str, str] | None = None, query_string: str | None = None, url: str = '')[source]

Bases: object

Mock an aiohttp request.

property content

Return the body as text.

async json() → Any[source]

Return the body as JSON.

mock_source: str | None = None
async post() → multidict._multidict.MultiDict[source]

Return POST parameters.

property query

Return a dictionary with the query variables.

async text() → str[source]

Return the body as text.

class homeassistant.util.aiohttp.MockStreamReader(content: bytes)[source]

Bases: object

Small mock to imitate stream reader.

async read(byte_count: int = -1) → bytes[source]

Read bytes.

homeassistant.util.async_

Asyncio utilities.

homeassistant.util.async_.check_loop() → None[source]

Warn if called inside the event loop.

homeassistant.util.async_.fire_coroutine_threadsafe(coro: collections.abc.Coroutine, loop: asyncio.events.AbstractEventLoop) → None[source]

Submit a coroutine object to a given event loop.

This method does not provide a way to retrieve the result and is intended for fire-and-forget use. This reduces the work involved to fire the function on the loop.

async homeassistant.util.async_.gather_with_concurrency(limit: int, *tasks: Any, return_exceptions: bool = False) → Any[source]

Wrap asyncio.gather to limit the number of concurrent tasks.

From: https://stackoverflow.com/a/61478547/9127614

homeassistant.util.async_.protect_loop(func: Callable) → Callable[source]

Protect function from running in event loop.

homeassistant.util.async_.run_callback_threadsafe(loop: AbstractEventLoop, callback: Callable[..., T], *args: Any) → concurrent.futures.Future[T][source]

Submit a callback object to a given event loop.

Return a concurrent.futures.Future to access the result.

homeassistant.util.async_.shutdown_run_callback_threadsafe(loop: asyncio.events.AbstractEventLoop) → None[source]

Call when run_callback_threadsafe should prevent creating new futures.

We must finish all callbacks before the executor is shutdown or we can end up in a deadlock state where:

executor.result() is waiting for its ._condition and the executor shutdown is trying to .join() the executor thread.

This function is considered irreversible and should only ever be called when Home Assistant is going to shutdown and python is going to exit.

homeassistant.util.color

Color util methods.

class homeassistant.util.color.GamutType(red: homeassistant.util.color.XYPoint, green: homeassistant.util.color.XYPoint, blue: homeassistant.util.color.XYPoint)[source]

Bases: object

Represents the Gamut of a light.

blue: XYPoint = None
green: XYPoint = None
red: XYPoint = None
class homeassistant.util.color.XYPoint(x: float, y: float)[source]

Bases: object

Represents a CIE 1931 XY coordinate pair.

x: float = None
y: float = None
homeassistant.util.color.check_point_in_lamps_reach(p: tuple[float, float], Gamut: GamutType) → bool[source]

Check if the provided XYPoint can be recreated by a Hue lamp.

homeassistant.util.color.check_valid_gamut(Gamut: homeassistant.util.color.GamutType) → bool[source]

Check if the supplied gamut is valid.

homeassistant.util.color.color_RGB_to_hs(iR: float, iG: float, iB: float) → tuple[float, float][source]

Convert an rgb color to its hs representation.

homeassistant.util.color.color_RGB_to_hsv(iR: float, iG: float, iB: float) → tuple[float, float, float][source]

Convert an rgb color to its hsv representation.

Hue is scaled 0-360 Sat is scaled 0-100 Val is scaled 0-100

homeassistant.util.color.color_RGB_to_xy(iR: int, iG: int, iB: int, Gamut: GamutType | None = None) → tuple[float, float][source]

Convert from RGB color to XY color.

homeassistant.util.color.color_RGB_to_xy_brightness(iR: int, iG: int, iB: int, Gamut: GamutType | None = None) → tuple[float, float, int][source]

Convert from RGB color to XY color.

homeassistant.util.color.color_hs_to_RGB(iH: float, iS: float) → tuple[int, int, int][source]

Convert an hsv color into its rgb representation.

homeassistant.util.color.color_hs_to_xy(iH: float, iS: float, Gamut: GamutType | None = None) → tuple[float, float][source]

Convert an hs color to its xy representation.

homeassistant.util.color.color_hsb_to_RGB(fH: float, fS: float, fB: float) → tuple[int, int, int][source]

Convert a hsb into its rgb representation.

homeassistant.util.color.color_hsv_to_RGB(iH: float, iS: float, iV: float) → tuple[int, int, int][source]

Convert an hsv color into its rgb representation.

Hue is scaled 0-360 Sat is scaled 0-100 Val is scaled 0-100

homeassistant.util.color.color_name_to_rgb(color_name: str) → tuple[int, int, int][source]

Convert color name to RGB hex value.

homeassistant.util.color.color_rgb_to_hex(r: int, g: int, b: int) → str[source]

Return a RGB color from a hex color string.

homeassistant.util.color.color_rgb_to_rgbw(r: int, g: int, b: int) → tuple[int, int, int, int][source]

Convert an rgb color to an rgbw representation.

homeassistant.util.color.color_rgb_to_rgbww(r: int, g: int, b: int, min_mireds: int, max_mireds: int) → tuple[int, int, int, int, int][source]

Convert an rgb color to an rgbww representation.

homeassistant.util.color.color_rgbw_to_rgb(r: int, g: int, b: int, w: int) → tuple[int, int, int][source]

Convert an rgbw color to an rgb representation.

homeassistant.util.color.color_rgbww_to_rgb(r: int, g: int, b: int, cw: int, ww: int, min_mireds: int, max_mireds: int) → tuple[int, int, int][source]

Convert an rgbww color to an rgb representation.

homeassistant.util.color.color_temperature_kelvin_to_mired(kelvin_temperature: float) → int[source]

Convert degrees kelvin to mired shift.

homeassistant.util.color.color_temperature_mired_to_kelvin(mired_temperature: float) → int[source]

Convert absolute mired shift to degrees kelvin.

homeassistant.util.color.color_temperature_to_hs(color_temperature_kelvin: float) → tuple[float, float][source]

Return an hs color from a color temperature in Kelvin.

homeassistant.util.color.color_temperature_to_rgb(color_temperature_kelvin: float) → tuple[float, float, float][source]

Return an RGB color from a color temperature in Kelvin.

This is a rough approximation based on the formula provided by T. Helland http://www.tannerhelland.com/4435/convert-temperature-rgb-algorithm-code/

homeassistant.util.color.color_xy_brightness_to_RGB(vX: float, vY: float, ibrightness: int, Gamut: GamutType | None = None) → tuple[int, int, int][source]

Convert from XYZ to RGB.

homeassistant.util.color.color_xy_to_RGB(vX: float, vY: float, Gamut: GamutType | None = None) → tuple[int, int, int][source]

Convert from XY to a normalized RGB.

homeassistant.util.color.color_xy_to_hs(vX: float, vY: float, Gamut: GamutType | None = None) → tuple[float, float][source]

Convert an xy color to its hs representation.

homeassistant.util.color.cross_product(p1: homeassistant.util.color.XYPoint, p2: homeassistant.util.color.XYPoint) → float[source]

Calculate the cross product of two XYPoints.

homeassistant.util.color.get_closest_point_to_line(A: homeassistant.util.color.XYPoint, B: homeassistant.util.color.XYPoint, P: homeassistant.util.color.XYPoint) → homeassistant.util.color.XYPoint[source]

Find the closest point from P to a line defined by A and B.

This point will be reproducible by the lamp as it is on the edge of the gamut.

homeassistant.util.color.get_closest_point_to_point(xy_tuple: tuple[float, float], Gamut: GamutType) → tuple[float, float][source]

Get the closest matching color within the gamut of the light.

Should only be used if the supplied color is outside of the color gamut.

homeassistant.util.color.get_distance_between_two_points(one: homeassistant.util.color.XYPoint, two: homeassistant.util.color.XYPoint) → float[source]

Calculate the distance between two XYPoints.

homeassistant.util.color.rgb_hex_to_rgb_list(hex_string: str) → list[int][source]

Return an RGB color value list from a hex color string.

homeassistant.util.decorator

Decorator utility functions.

class homeassistant.util.decorator.Registry[source]

Bases: dict

Registry of items.

register(name: collections.abc.Hashable) → Callable[[CALLABLE_T], CALLABLE_T][source]

Return decorator to register item with a specific name.

homeassistant.util.distance

Distance util functions.

homeassistant.util.distance.convert(value: float, unit_1: str, unit_2: str) → float[source]

Convert one unit of measurement to another.

homeassistant.util.dt

Helper methods to handle the time in Home Assistant.

homeassistant.util.dt.as_local(dattim: datetime.datetime) → datetime.datetime[source]

Convert a UTC datetime object to local time zone.

homeassistant.util.dt.as_timestamp(dt_value: dt.datetime | str) → float[source]

Convert a date/time into a unix time (seconds since 1970).

homeassistant.util.dt.as_utc(dattim: datetime.datetime) → datetime.datetime[source]

Return a datetime as UTC time.

Assumes datetime without tzinfo to be in the DEFAULT_TIME_ZONE.

homeassistant.util.dt.find_next_time_expression_time(now: dt.datetime, seconds: list[int], minutes: list[int], hours: list[int]) → dt.datetime[source]

Find the next datetime from now for which the time expression matches.

The algorithm looks at each time unit separately and tries to find the next one that matches for each. If any of them would roll over, all time units below that are reset to the first matching value.

Timezones are also handled (the tzinfo of the now object is used), including daylight saving time.

homeassistant.util.dt.get_age(date: datetime.datetime) → str[source]

Take a datetime and return its “age” as a string.

The age can be in second, minute, hour, day, month or year. Only the biggest unit is considered, e.g. if it’s 2 days and 3 hours, “2 days” will be returned. Make sure date is not in the future, or else it won’t work.

homeassistant.util.dt.get_time_zone(time_zone_str: str) → dt.tzinfo | None[source]

Get time zone from string. Return None if unable to determine.

Async friendly.

homeassistant.util.dt.now(time_zone: dt.tzinfo | None = None) → dt.datetime[source]

Get now in specified time zone.

homeassistant.util.dt.parse_date(dt_str: str) → dt.date | None[source]

Convert a date string to a date object.

homeassistant.util.dt.parse_datetime(dt_str: str) → dt.datetime | None[source]

Parse a string and return a datetime.datetime.

This function supports time zone offsets. When the input contains one, the output uses a timezone with a fixed offset from UTC. Raises ValueError if the input is well formatted but not a valid datetime. Returns None if the input isn’t well formatted.

homeassistant.util.dt.parse_time(time_str: str) → dt.time | None[source]

Parse a time string (00:20:00) into Time object.

Return None if invalid.

homeassistant.util.dt.parse_time_expression(parameter: Any, min_value: int, max_value: int) → list[int][source]

Parse the time expression part and return a list of times to match.

homeassistant.util.dt.set_default_time_zone(time_zone: datetime.tzinfo) → None[source]

Set a default time zone to be used when none is specified.

Async friendly.

homeassistant.util.dt.start_of_local_day(dt_or_d: dt.date | dt.datetime | None = None) → dt.datetime[source]

Return local datetime object of start of day from date or datetime.

homeassistant.util.dt.utc_from_timestamp(timestamp: float) → datetime.datetime[source]

Return a UTC time from a timestamp.

homeassistant.util.dt.utcnow() → datetime.datetime[source]

Get now in UTC time.

homeassistant.util.json

JSON utility functions.

exception homeassistant.util.json.SerializationError[source]

Bases: homeassistant.exceptions.HomeAssistantError

Error serializing the data to JSON.

exception homeassistant.util.json.WriteError[source]

Bases: homeassistant.exceptions.HomeAssistantError

Error writing the data.

homeassistant.util.json.find_paths_unserializable_data(bad_data: Any, *, dump: Callable[[Any], str] = <function dumps>) → dict[str, Any][source]

Find the paths to unserializable data.

This method is slow! Only use for error handling.

homeassistant.util.json.format_unserializable_data(data: dict[str, Any]) → str[source]

Format output of find_paths in a friendly way.

Format is comma separated: <path>=<value>(<type>)

homeassistant.util.json.load_json(filename: str, default: list | dict | None = None) → list | dict[source]

Load JSON data from a file and return as dict or list.

Defaults to returning empty dict if file is not found.

homeassistant.util.json.save_json(filename: str, data: list | dict, private: bool = False, *, encoder: type[json.JSONEncoder] | None = None) → None[source]

Save JSON data to a file.

Returns True on success.

homeassistant.util.location

Module with location helpers.

detect_location_info and elevation are mocked by default during tests.

class homeassistant.util.location.LocationInfo(ip, country_code, region_code, region_name, city, zip_code, time_zone, latitude, longitude, use_metric)[source]

Bases: tuple

city

Alias for field number 4

country_code

Alias for field number 1

ip

Alias for field number 0

latitude

Alias for field number 7

longitude

Alias for field number 8

region_code

Alias for field number 2

region_name

Alias for field number 3

time_zone

Alias for field number 6

use_metric

Alias for field number 9

zip_code

Alias for field number 5

async homeassistant.util.location.async_detect_location_info(session: aiohttp.ClientSession) → LocationInfo | None[source]

Detect location information.

homeassistant.util.location.distance(lat1: float | None, lon1: float | None, lat2: float, lon2: float) → float | None[source]

Calculate the distance in meters between two points.

Async friendly.

homeassistant.util.location.vincenty(point1: tuple[float, float], point2: tuple[float, float], miles: bool = False) → float | None[source]

Vincenty formula (inverse method) to calculate the distance.

Result in kilometers or miles between two points on the surface of a spheroid.

Async friendly.

homeassistant.util.logging

Logging utilities.

class homeassistant.util.logging.HideSensitiveDataFilter(text: str)[source]

Bases: logging.Filter

Filter API password calls.

filter(record: logging.LogRecord) → bool[source]

Hide sensitive data in messages.

class homeassistant.util.logging.HomeAssistantQueueHandler(queue)[source]

Bases: logging.handlers.QueueHandler

Process the log in another thread.

handle(record: logging.LogRecord) → Any[source]

Conditionally emit the specified logging record.

Depending on which filters have been added to the handler, push the new records onto the backing Queue.

The default python logger Handler acquires a lock in the parent class which we do not need as SimpleQueue is already thread safe.

See https://bugs.python.org/issue24645

homeassistant.util.logging.async_activate_log_queue_handler(hass: homeassistant.core.HomeAssistant) → None[source]

Migrate the existing log handlers to use the queue.

This allows us to avoid blocking I/O and formatting messages in the event loop as log messages are written in another thread.

homeassistant.util.logging.async_create_catching_coro(target: collections.abc.Coroutine) → collections.abc.Coroutine[source]

Wrap a coroutine to catch and log exceptions.

The exception will be logged together with a stacktrace of where the coroutine was wrapped.

target: target coroutine.

homeassistant.util.logging.catch_log_coro_exception(target: Coroutine[Any, Any, Any], format_err: Callable[..., Any], *args: Any) → Coroutine[Any, Any, Any][source]

Decorate a coroutine to catch and log exceptions.

homeassistant.util.logging.catch_log_exception(func: Callable[..., Any], format_err: Callable[..., Any], *args: Any) → Callable[(Ellipsis, None)] | Callable[..., Awaitable[None]][source]

Decorate a callback to catch and log exceptions.

homeassistant.util.logging.log_exception(format_err: Callable[[...], Any], *args: Any) → None[source]

Log an exception with additional context.

homeassistant.util.network

Network utilities.

homeassistant.util.network.is_invalid(address: IPv4Address | IPv6Address) → bool[source]

Check if an address is invalid.

homeassistant.util.network.is_ip_address(address: str) → bool[source]

Check if a given string is an IP address.

Check if an address is link local.

homeassistant.util.network.is_local(address: IPv4Address | IPv6Address) → bool[source]

Check if an address is loopback or private.

homeassistant.util.network.is_loopback(address: IPv4Address | IPv6Address) → bool[source]

Check if an address is a loopback address.

homeassistant.util.network.is_private(address: IPv4Address | IPv6Address) → bool[source]

Check if an address is a private address.

homeassistant.util.network.normalize_url(address: str) → str[source]

Normalize a given URL.

homeassistant.util.package

Helpers to install PyPi packages.

async homeassistant.util.package.async_get_user_site(deps_dir: str) → str[source]

Return user local library path.

This function is a coroutine.

homeassistant.util.package.install_package(package: str, upgrade: bool = True, target: str | None = None, constraints: str | None = None, find_links: str | None = None, no_cache_dir: bool | None = False) → bool[source]

Install a package on PyPi. Accepts pip compatible package strings.

Return boolean if install successful.

homeassistant.util.package.is_docker_env() → bool[source]

Return True if we run in a docker env.

homeassistant.util.package.is_installed(package: str) → bool[source]

Check if a package is installed and will be loaded when we import it.

Returns True when the requirement is met. Returns False when the package is not installed or doesn’t meet req.

homeassistant.util.package.is_virtual_env() → bool[source]

Return if we run in a virtual environment.

homeassistant.util.pil

PIL utilities.

Can only be used by integrations that have pillow in their requirements.

homeassistant.util.pil.draw_box(draw: ImageDraw, box: tuple[float, float, float, float], img_width: int, img_height: int, text: str = '', color: tuple[int, int, int] = (255, 255, 0)) → None[source]

Draw a bounding box on and image.

The bounding box is defined by the tuple (y_min, x_min, y_max, x_max) where the coordinates are floats in the range [0.0, 1.0] and relative to the width and height of the image.

For example, if an image is 100 x 200 pixels (height x width) and the bounding box is (0.1, 0.2, 0.5, 0.9), the upper-left and bottom-right coordinates of the bounding box will be (40, 10) to (180, 50) (in (x,y) coordinates).

homeassistant.util.pressure

Pressure util functions.

homeassistant.util.pressure.convert(value: float, unit_1: str, unit_2: str) → float[source]

Convert one unit of measurement to another.

homeassistant.util.ruamel_yaml

ruamel.yaml utility functions.

class homeassistant.util.ruamel_yaml.ExtSafeConstructor(preserve_quotes: Optional[bool] = None, loader: Any = None)[source]

Bases: ruamel.yaml.constructor.SafeConstructor

Extended SafeConstructor.

name: str | None = None
yaml_constructors = {'tag:yaml.org,2002:null': <function SafeConstructor.construct_yaml_null>, 'tag:yaml.org,2002:bool': <function SafeConstructor.construct_yaml_bool>, 'tag:yaml.org,2002:int': <function SafeConstructor.construct_yaml_int>, 'tag:yaml.org,2002:float': <function SafeConstructor.construct_yaml_float>, 'tag:yaml.org,2002:binary': <function SafeConstructor.construct_yaml_binary>, 'tag:yaml.org,2002:timestamp': <function SafeConstructor.construct_yaml_timestamp>, 'tag:yaml.org,2002:omap': <function SafeConstructor.construct_yaml_omap>, 'tag:yaml.org,2002:pairs': <function SafeConstructor.construct_yaml_pairs>, 'tag:yaml.org,2002:set': <function SafeConstructor.construct_yaml_set>, 'tag:yaml.org,2002:str': <function SafeConstructor.construct_yaml_str>, 'tag:yaml.org,2002:seq': <function SafeConstructor.construct_yaml_seq>, 'tag:yaml.org,2002:map': <function SafeConstructor.construct_yaml_map>, None: <function _yaml_unsupported>, '!secret': <function secret_yaml>, '!include': <function _include_yaml>}
exception homeassistant.util.ruamel_yaml.UnsupportedYamlError[source]

Bases: homeassistant.exceptions.HomeAssistantError

Unsupported YAML.

exception homeassistant.util.ruamel_yaml.WriteError[source]

Bases: homeassistant.exceptions.HomeAssistantError

Error writing the data.

homeassistant.util.ruamel_yaml.load_yaml(fname: str, round_trip: bool = False) → Union[list, dict, str][source]

Load a YAML file.

homeassistant.util.ruamel_yaml.object_to_yaml(data: Union[list, dict, str]) → str[source]

Create yaml string from object.

homeassistant.util.ruamel_yaml.save_yaml(fname: str, data: Union[list, dict, str]) → None[source]

Save a YAML file.

homeassistant.util.ruamel_yaml.yaml_to_object(data: str) → Union[list, dict, str][source]

Create object from yaml string.

homeassistant.util.ssl

Helper to create SSL contexts.

homeassistant.util.ssl.client_context() → ssl.SSLContext[source]

Return an SSL context for making requests.

homeassistant.util.ssl.server_context_intermediate() → ssl.SSLContext[source]

Return an SSL context following the Mozilla recommendations.

TLS configuration follows the best-practice guidelines specified here: https://wiki.mozilla.org/Security/Server_Side_TLS Intermediate guidelines are followed.

homeassistant.util.ssl.server_context_modern() → ssl.SSLContext[source]

Return an SSL context following the Mozilla recommendations.

TLS configuration follows the best-practice guidelines specified here: https://wiki.mozilla.org/Security/Server_Side_TLS Modern guidelines are followed.

homeassistant.util.temperature

Temperature util functions.

homeassistant.util.temperature.celsius_to_fahrenheit(celsius: float, interval: bool = False) → float[source]

Convert a temperature in Celsius to Fahrenheit.

homeassistant.util.temperature.celsius_to_kelvin(celsius: float, interval: bool = False) → float[source]

Convert a temperature in Celsius to Fahrenheit.

homeassistant.util.temperature.convert(temperature: float, from_unit: str, to_unit: str, interval: bool = False) → float[source]

Convert a temperature from one unit to another.

homeassistant.util.temperature.fahrenheit_to_celsius(fahrenheit: float, interval: bool = False) → float[source]

Convert a temperature in Fahrenheit to Celsius.

homeassistant.util.temperature.kelvin_to_celsius(kelvin: float, interval: bool = False) → float[source]

Convert a temperature in Kelvin to Celsius.

homeassistant.util.unit_system

Unit system helper class and methods.

class homeassistant.util.unit_system.UnitSystem(name: str, temperature: str, length: str, volume: str, mass: str, pressure: str)[source]

Bases: object

A container for units of measure.

as_dict() → dict[str, str][source]

Convert the unit system to a dictionary.

property is_metric

Determine if this is the metric unit system.

length(length: float | None, from_unit: str) → float[source]

Convert the given length to this unit system.

pressure(pressure: float | None, from_unit: str) → float[source]

Convert the given pressure to this unit system.

temperature(temperature: float, from_unit: str) → float[source]

Convert the given temperature to this unit system.

volume(volume: float | None, from_unit: str) → float[source]

Convert the given volume to this unit system.

homeassistant.util.unit_system.is_valid_unit(unit: str, unit_type: str) → bool[source]

Check if the unit is valid for it’s type.

homeassistant.util.volume

Volume conversion util functions.

homeassistant.util.volume.convert(volume: float, from_unit: str, to_unit: str) → float[source]

Convert a temperature from one unit to another.