homeassistant.util package


homeassistant.util.async_ module

Asyncio backports for Python 3.4.3 compatibility.

homeassistant.util.async_.asyncio_run(main: Awaitable[_T], *, debug: bool = False) → _T[source]

Minimal re-implementation of asyncio.run (since 3.7).

homeassistant.util.async_.fire_coroutine_threadsafe(coro: 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.

homeassistant.util.async_.run_callback_threadsafe(loop: asyncio.events.AbstractEventLoop, callback: Callable, *args) → concurrent.futures._base.Future[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: Union[Coroutine, Generator], loop: asyncio.events.AbstractEventLoop) → concurrent.futures._base.Future[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: 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) → 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

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_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_temperature_kelvin_to_mired(kelvin_temperature: float) → float[source]

Convert degrees kelvin to mired shift.

homeassistant.util.color.color_temperature_mired_to_kelvin(mired_temperature: float) → float[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) → 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.

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

homeassistant.util.dt.as_timestamp(dt_value: datetime.datetime) → 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: datetime.datetime, seconds: List[int], minutes: List[int], hours: List[int]) → datetime.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) → Optional[datetime.tzinfo][source]

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

Async friendly.

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

Get now in specified time zone.

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

Convert a date string to a date object.

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

homeassistant.util.dt.parse_time(time_str: str) → Optional[datetime.time][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: Optional[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

homeassistant.util.location.detect_location_info() → Optional[homeassistant.util.location.LocationInfo][source]

Detect location information.

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

Calculate the distance in meters between two points.

Async friendly.

homeassistant.util.location.elevation(latitude: float, longitude: float) → int[source]

Return elevation for given latitude and longitude.

homeassistant.util.location.vincenty(point1: Tuple[float, float], point2: Tuple[float, float], miles: bool = False) → Optional[float][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.install_package(package: str, upgrade: bool = True, target: Optional[str] = None, constraints: Optional[str] = None) → bool[source]

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

Return boolean if install successful.

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

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: Optional[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.

volume(volume: Optional[float], 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.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: int) → 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, str][source]

Load a YAML file.

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

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

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

Save YAML to a file.

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

Load secrets and embed it into the configuration YAML.

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: Optional[Iterable[T]] = None)[source]

Bases: typing.MutableSet

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

add(key: T) → None[source]

Add an element to the end of the set.

discard(key: T) → None[source]

Discard an element from the set.

pop(last: bool = True) → T[source]

Pop element of the end of the set.

Set last=False to pop from the beginning.

promote(key: T) → None[source]

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

update(*args) → None[source]

Add elements from args to the set.

class homeassistant.util.Throttle(min_time: datetime.timedelta, limit_no_throttle: Optional[datetime.timedelta] = 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: Optional[U] = None) → Optional[U][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, ..

homeassistant.util.get_local_ip() → str[source]

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