homeassistant.util package

Submodules

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_hsv(iR: int, iG: int, iB: int) → typing.Tuple[int, int, int][source]

Convert an rgb color to its hsv representation.

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

Convert from RGB color to XY color.

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

Convert an hsv color into its rgb representation.

homeassistant.util.color.color_name_to_rgb(color_name)[source]

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.

homeassistant.util.color.color_temperature_kelvin_to_mired(kelvin_temperature)[source]

Convert degrees kelvin to mired shift.

homeassistant.util.color.color_temperature_mired_to_kelvin(mired_temperature)[source]

Convert absolute mired shift to degrees kelvin.

homeassistant.util.color.color_temperature_to_rgb(color_temperature_kelvin)[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) → typing.Tuple[int, int, int][source]

Convert from XYZ to RGB.

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

Convert an xy color to its hs representation.

homeassistant.util.color.rgb_hex_to_rgb_list(hex_string)[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)[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.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) → typing.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.

homeassistant.util.dt.parse_time(time_str)[source]

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

city

Alias for field number 5

country_code

Alias for field number 1

country_name

Alias for field number 2

ip

Alias for field number 0

latitude

Alias for field number 8

longitude

Alias for field number 9

region_code

Alias for field number 3

region_name

Alias for field number 4

time_zone

Alias for field number 7

use_metric

Alias for field number 10

zip_code

Alias for field number 6

homeassistant.util.location.detect_location_info()[source]

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: typing.Tuple[float, float], point2: typing.Tuple[float, float], miles: bool = False) → typing.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, loop: asyncio.events.AbstractEventLoop) → 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.get_user_site(deps_dir: str) → str[source]

Return user local library path.

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

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

Return boolean if install successful.

homeassistant.util.temperature module

Temperature util functions.

homeassistant.util.temperature.celsius_to_fahrenheit(celsius: float) → float[source]

Convert a temperature in Celsius to Fahrenheit.

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

Convert a temperature from one unit to another.

homeassistant.util.temperature.fahrenheit_to_celsius(fahrenheit: float) → 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) → None[source]

Bases: object

A container for units of measure.

as_dict() → dict[source]

Convert the unit system to a dictionary.

is_metric

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) → typing.Union[typing.List, typing.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().

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(key)[source]

Add an element to the end of the set.

discard(key)[source]

Discard an element from the set.

pop(last=True)[source]

Pop element of the end of the set.

Set last=False to pop from the beginning.

promote(key)[source]

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

update(*args)[source]

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: typing.Callable[[T], U], default: typing.Union[U, NoneType] = None) → typing.Union[U, NoneType][source]

Convert value to to_type, returns default if fails.

homeassistant.util.ensure_unique_string(preferred_string: str, current_strings: typing.Union[typing.Sequence[str], typing.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()[source]

Try to determine the local IP address of the machine.

homeassistant.util.get_random_string(length=10)[source]

Return a random string with letters and digits.

homeassistant.util.repr_helper(inp: typing.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.