homeassistant.util package


homeassistant.util.async_ module

Asyncio backports for Python 3.4.3 compatibility.

homeassistant.util.async_.fire_coroutine_threadsafe(coro, loop)[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.

homeassistant.util.async_.run_callback_threadsafe(loop, callback, *args)[source]

Submit a callback object to a given event loop.

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

homeassistant.util.async_.run_coroutine_threadsafe(coro, loop)[source]

Submit a coroutine object to a given event loop.

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

homeassistant.util.color module

Color util methods.

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

Convert an rgb color to its hs representation.

homeassistant.util.color.color_RGB_to_hsv(iR: int, iG: int, iB: int) → 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) → 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) → 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) → 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


Convert color name to RGB hex value.

homeassistant.util.color.color_rgb_to_hex(r, g, b)[source]

Return a RGB color from a hex color string.

homeassistant.util.color.color_rgb_to_rgbw(r, g, b)[source]

Convert an rgb color to an rgbw representation.

homeassistant.util.color.color_rgbw_to_rgb(r, g, b, w)[source]

Convert an rgbw color to an rgb representation.


Convert degrees kelvin to mired shift.


Convert absolute mired shift to degrees kelvin.


Return an hs color from a color temperature in Kelvin.


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) → Tuple[int, int, int][source]

Convert from XYZ to RGB.

homeassistant.util.color.color_xy_to_RGB(vX: float, vY: float) → Tuple[int, int, int][source]

Convert from XY to a normalized RGB.

homeassistant.util.color.color_xy_to_hs(vX: float, vY: float) → Tuple[float, float][source]

Convert an xy color to its hs representation.


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

homeassistant.util.distance module

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 module

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.


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.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) → Union[datetime.tzinfo, NoneType][source]

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

Async friendly.

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

Get now in specified time zone.

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

Convert a date string to a date object.

homeassistant.util.dt.parse_datetime(dt_str: str) → datetime.datetime[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.


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

Return None if invalid.

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: datetime.date = None) → datetime.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.location module

Module with location helpers.

detect_location_info and elevation are mocked by default during tests.

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

Bases: tuple


Alias for field number 5


Alias for field number 1


Alias for field number 2


Alias for field number 0


Alias for field number 8


Alias for field number 9


Alias for field number 3


Alias for field number 4


Alias for field number 7


Alias for field number 10


Alias for field number 6


Detect location information.

homeassistant.util.location.distance(lat1, lon1, lat2, lon2)[source]

Calculate the distance in meters between two points.

Async friendly.

homeassistant.util.location.elevation(latitude, longitude)[source]

Return elevation for given latitude and longitude.

homeassistant.util.location.vincenty(point1: Tuple[float, float], point2: Tuple[float, float], miles: bool = False) → Union[float, NoneType][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.package module

Helpers to install PyPi packages.

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.check_package_exists(package: str) → bool[source]

Check if a package is installed globally or in lib_dir.

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

homeassistant.util.package.install_package(package: str, upgrade: bool = True, target: Union[str, NoneType] = None, constraints: Union[str, NoneType] = None) → bool[source]

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

Return boolean if install successful.


Return if we run in a virtual environtment.

homeassistant.util.temperature module

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.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.unit_system module

Unit system helper class and methods.

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

Bases: object

A container for units of measure.

as_dict() → dict[source]

Convert the unit system to a dictionary.


Determine if this is the metric unit system.

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

Convert the given length to this unit system.

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

Convert the given temperature 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.yaml module

YAML utility functions.

class homeassistant.util.yaml.NodeListClass[source]

Bases: list

Wrapper class to be able to add attributes on a list.

class homeassistant.util.yaml.NodeStrClass[source]

Bases: str

Wrapper class to be able to add attributes on a string.

class homeassistant.util.yaml.SafeLineLoader(stream)[source]

Bases: yaml.loader.SafeLoader

Loader class that keeps track of line numbers.

compose_node(parent: yaml.nodes.Node, index) → yaml.nodes.Node[source]

Annotate a node with the first line it was seen.

homeassistant.util.yaml.clear_secret_cache() → None[source]

Clear the secret cache.

Async friendly.

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

Dump YAML to a string and remove null.

homeassistant.util.yaml.load_yaml(fname: str) → Union[List, Dict][source]

Load a YAML file.

homeassistant.util.yaml.represent_odict(dump, tag, mapping, flow_style=None)[source]

Like BaseRepresenter.represent_mapping but does not issue the sort().

homeassistant.util.yaml.save_yaml(path, data)[source]

Save YAML to a file.

Module contents

Helper methods for various modules.

class homeassistant.util.OrderedEnum[source]

Bases: enum.Enum

Taken from Python 3.4.0 docs.

class homeassistant.util.OrderedSet(iterable=None)[source]

Bases: collections.abc.MutableSet

Ordered set taken from http://code.activestate.com/recipes/576694/.


Add an element to the end of the set.


Discard an element from the set.


Pop element of the end of the set.

Set last=False to pop from the beginning.


Promote element to beginning of the set, add if not there.


Add elements from args to the set.

class homeassistant.util.Throttle(min_time, limit_no_throttle=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, to_type: Callable[[T], U], default: Union[U, NoneType] = None) → Union[U, NoneType][source]

Convert value to to_type, returns default if fails.

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

Return a string that is not present in current_strings.

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


Try to determine the local IP address of the machine.


Return a random string with letters and digits.

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]

Sanitize a filename by removing .. / and .

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

Sanitize a path by removing ~ and ..

homeassistant.util.slugify(text: str) → str[source]

Slugify a given text.