AppDaemon API Reference

A number of api calls are native to AppDaemon and will exist in any App as they are inherited through the plugin API. If the get_plugin_api() style of declarations is used, these functions will become available via an object created by the get_ad_api() call:

import adbase as ad

class Test(ad.ADBase):

    def initialize(self):

        self.adapi = self.get_ad_api()
        handle = self.adapi.run_in(callback, 20)

These calls are documented below.

App Creation

To create apps based on just the AppDaemon base API, use some code like the following:

import adbase as ad

class MyApp(ad.ADBase):

  def initialize(self):

Entity Class

As manipulating entities is a core center point of writing automation apps, easy access and manipulation of entities is very important. AppDaemon supports the ability to access entities as class objects in their own right, via the api call get_entity(entity). This AD does by creating an object which links to the given entity within a specified namespace per app, using an Entity class which can be used within the app. When this is done, the returned object allows to maximise the OOP nature of python while working with entities. AD will do this, even if the entity doesn’t actually exist in AD at that point in time. If this is the case, the returned object can be used to add the entity. for example:

import adbase as ad

class TestApp(ad.ADBase):

    def initialize(self):

        self.adapi = self.get_ad_api()
        self.adapi.run_in(self.callback, 20)

        # get light entity class
        self.kitchen_light = self.adapi.get_entity("light.kitchen_ceiling_light", namespace="hass")

    def callback(self, cb_args):
        if self.kitchen_ceiling_light.is_state("off"):
            self.kitchen_ceiling_light.turn_on(brightness=200)

Reference

Entity API

appdaemon.entity.Entity.add(self, state: str | int | float = None, attributes: dict = None) None

Adds a non-existent entity, by creating it within a namespaces.

It should be noted that this api call, is mainly for creating AD internal entities. If wanting to create an entity within an external system, do check the system’s documentation

Parameters:
  • state (optional) – The state the new entity is to have

  • attributes (optional) – The attributes the new entity is to have

Returns:

None

Examples

>>> self.my_entity = self.get_entity("zigbee.living_room_light")

create the entity entity.

>>> self.my_entity.add(state="off", attributes={"friendly_name": "Living Room Light"})
appdaemon.entity.Entity.call_service(self, service: str, **kwargs: Any | None) Any

Calls an entity supported Service within AppDaemon.

This function can call only services that are tied to the entity, and provide any required parameters.

Parameters:
  • service (str) – The service name, without the domain (e.g “toggle”)

  • **kwargs (optional) – Zero or more keyword arguments.

Keyword Arguments:
  • **kwargs – Each service has different parameter requirements. This argument allows you to specify a comma-separated list of keyword value pairs, e.g., state = on. These parameters will be different for every service and can be discovered using the developer tools.

  • return_result (bool, option) – If return_result is provided and set to True AD will attempt to wait for the result, and return it after execution

  • callback – The non-async callback to be executed when complete.

Returns:

Result of the call_service function if any

Examples

HASS

>>> self.my_entity = self.get_entity("light.office_1")
>>> self.my_entity.call_service("turn_on", color_name = "red")
appdaemon.entity.Entity.copy(self, copy: bool = True) dict

Gets the complete state of the entity within AD.

This is essentially a helper function, to get all data about an entity

Parameters:

copy (bool) – If set to False, it will not make a deep copy of the entity. This can help with speed of accessing the data

appdaemon.entity.Entity.exists(self) bool

Checks the existence of the entity in AD.

appdaemon.entity.Entity.get_state(self, attribute: str = None, default: Any = None, copy: bool = True, **kwargs: Any | None) Any

Gets the state of any entity within AD.

Parameters:
  • attribute (str, optional) – Name of an attribute within the entity state object. If this parameter is specified in addition to a fully qualified entity_id, a single value representing the attribute will be returned. The value all for attribute has special significance and will return the entire state dictionary for the specified entity rather than an individual attribute value.

  • default (any, optional) – The value to return when the requested attribute or the whole entity doesn’t exist (Default: None).

  • copy (bool, optional) – By default, a copy of the stored state object is returned. When you set copy to False, you get the same object as is stored internally by AppDaemon. Avoiding the copying brings a small performance gain, but also gives you write-access to the internal AppDaemon data structures, which is dangerous. Only disable copying when you can guarantee not to modify the returned state object, e.g., you do read-only operations.

  • **kwargs (optional) – Zero or more keyword arguments.

Keyword Args:

Returns:

The entire state of the entity at that given time, if if get_state() is called with no parameters. This will consist of a dictionary with a key for each entity. Under that key will be the standard entity state information.

Examples

>>> self.my_entity = self.get_entity("light.office_1")

Get the state attribute of light.office_1.

>>> state = self.my_entity.get_state("light.office_1")

Get the brightness attribute of light.office_1.

>>> state = self.my_entity.get_state(attribute="brightness")

Get the entire state of light.office_1.

>>> state = self.my_entity.get_state(attribute="all")
appdaemon.entity.Entity.listen_state(self, callback: Callable, **kwargs: Any | None) str

Registers a callback to react to state changes.

This function allows the user to register a callback for a wide variety of state changes.

Parameters:
  • callback – Function to be invoked when the requested state change occurs. It must conform to the standard State Callback format documented here

  • **kwargs (optional) – Zero or more keyword arguments.

Keyword Arguments:
  • attribute (str, optional) –

    Name of an attribute within the entity state object. If this parameter is specified in addition to a fully qualified entity_id. listen_state() will subscribe to changes for just that attribute within that specific entity. The new and old parameters in the callback function will be provided with a single value representing the attribute.

    The value all for attribute has special significance and will listen for any state change within the specified entity, and supply the callback functions with the entire state dictionary for the specified entity rather than an individual attribute value.

  • new (optional) – If new is supplied as a parameter, callbacks will only be made if the state of the selected attribute (usually state) in the new state match the value of new. The parameter type is defined by the namespace or plugin that is responsible for the entity. If it looks like a float, list, or dictionary, it may actually be a string.

  • old (optional) – If old is supplied as a parameter, callbacks will only be made if the state of the selected attribute (usually state) in the old state match the value of old. The same caveats on types for the new parameter apply to this parameter.

  • duration (int, optional) –

    If duration is supplied as a parameter, the callback will not fire unless the state listened for is maintained for that number of seconds. This requires that a specific attribute is specified (or the default of state is used), and should be used in conjunction with the old or new parameters, or both. When the callback is called, it is supplied with the values of entity, attr, old, and new that were current at the time the actual event occurred, since the assumption is that none of them have changed in the intervening period.

    If you use duration when listening for an entire device type rather than a specific entity, or for all state changes, you may get unpredictable results, so it is recommended that this parameter is only used in conjunction with the state of specific entities.

  • timeout (int, optional) – If timeout is supplied as a parameter, the callback will be created as normal, but after timeout seconds, the callback will be removed. If activity for the listened state has occurred that would trigger a duration timer, the duration timer will still be fired even though the callback has been deleted.

  • immediate (bool, optional) –

    It enables the countdown for a delay parameter to start at the time, if given. If the duration parameter is not given, the callback runs immediately. What this means is that after the callback is registered, rather than requiring one or more state changes before it runs, it immediately checks the entity’s states based on given parameters. If the conditions are right, the callback runs immediately at the time of registering. This can be useful if, for instance, you want the callback to be triggered immediately if a light is already on, or after a duration if given.

    If immediate is in use, and new and duration are both set, AppDaemon will check if the entity is already set to the new state and if so it will start the clock immediately. If new and duration are not set, immediate will trigger the callback immediately and report in its callback the new parameter as the present state of the entity. If attribute is specified, the state of the attribute will be used instead of state. In these cases, old will be ignored and when the callback is triggered, its state will be set to None.

  • oneshot (bool, optional) – If True, the callback will be automatically cancelled after the first state change that results in a callback.

  • pin (bool, optional) – If True, the callback will be pinned to a particular thread.

  • pin_thread (int, optional) – Sets which thread from the worker pool the callback will be run by (0 - number of threads -1).

  • *kwargs (optional) – Zero or more keyword arguments that will be supplied to the callback when it is called.

Notes

The old and new args can be used singly or together.

Returns:

A unique identifier that can be used to cancel the callback if required. Since variables created within object methods are local to the function they are created in, and in all likelihood, the cancellation will be invoked later in a different function, it is recommended that handles are stored in the object namespace, e.g., self.handle.

Examples

>>> self.my_entity = self.get_entity("light.office_1")

Listen for a state change involving light.office1 and return the state attribute.

>>> self.handle = self.my_entity.listen_state(self.my_callback)

Listen for a change involving the brightness attribute of light.office1 and return the brightness attribute.

>>> self.handle = self.my_entity.listen_state(self.my_callback, attribute = "brightness")

Listen for a state change involving light.office1 turning on and return the state attribute.

>>> self.handle = self.my_entity.listen_state(self.my_callback, new = "on")

Listen for a change involving light.office1 changing from brightness 100 to 200 and return the brightness attribute.

>>> self.handle = self.my_entity.listen_state(self.my_callback, attribute = "brightness", old = "100", new = "200")

Listen for a state change involving light.office1 changing to state on and remaining on for a minute.

>>> self.handle = self.my_entity.listen_state(self.my_callback, new = "on", duration = 60)

Listen for a state change involving light.office1 changing to state on and remaining on for a minute trigger the delay immediately if the light is already on.

>>> self.handle = self.my_entity.listen_state(self.my_callback, new = "on", duration = 60, immediate = True)
appdaemon.entity.Entity.is_state(self, state: Any) bool

Checks the state of the entity against the given state

This helper function supports using both iterable and non-iterable data

Parameters:

state (any) – The state or iterable set of state data, to check against

Example

>>> light_entity_object.is_state("on")
>>> media_object.is_state(["playing", "paused"])
appdaemon.entity.Entity.set_namespace(self, namespace: str) None

Sets a new namespace for the Entity to use from that point forward. It should be noted that when this function is used, a different entity will be referenced. Since each entity is tied to a certain namespace, at every point in time.

Parameters:

namespace (str) – Name of the new namespace

Returns:

None.

Examples

>>> # access entity in Hass namespace
>>> self.my_entity = self.get_entity("light.living_room")
>>> # want to copy the same entity into another namespace
>>> entity_data = self.my_entity.copy()
>>> self.my_entity.set_namespace("my_namespace")
>>> self.my_entity.set_state(**entity_data)
appdaemon.entity.Entity.set_state(self, **kwargs: Any | None) dict

Updates the state of the specified entity.

Parameters:

**kwargs (optional) – Zero or more keyword arguments.

Keyword Arguments:
  • state – New state value to be set.

  • attributes (optional) – Entity’s attributes to be updated.

  • replace (bool, optional) – If a replace flag is given and set to True and attributes is provided, AD will attempt to replace its internal entity register with the newly supplied attributes completely. This can be used to replace attributes in an entity which are no longer needed. Do take note this is only possible for internal entity state. For plugin based entities, this is not recommended, as the plugin will mostly replace the new values, when next it updates.

Returns:

A dictionary that represents the new state of the updated entity.

Examples

>>> self.my_entity = self.get_entity("light.living_room")

Update the state of an entity.

>>> self.my_entity.set_state(state="off")

Update the state and attribute of an entity.

>>> self.my_entity.set_state(state = "on", attributes = {"color_name": "red"})
appdaemon.entity.Entity.toggle(self, **kwargs: Any | None) Any

Generic function, used to toggle the entity ON/OFF if supported. This function will attempt to call the toggle service if registered, either by an app or plugin within the entity’s namespace. So therefore its only functional, if the service toggle exists within the namespace the entity is operating in.

Keyword Arguments:

**kwargs – Toggle services depending on the namespace functioning within has different parameter requirements. This argument allows you to specify a comma-separated list of keyword value pairs, e.g., transition = 3. These parameters will be different for every service being used.

appdaemon.entity.Entity.turn_off(self, **kwargs: Any | None) Any

Generic function, used to turn the entity OFF if supported. This function will attempt to call the turn_off service if registered, either by an app or plugin within the entity’s namespace. So therefore its only functional, if the service turn_off exists within the namespace the entity is operating in.

Keyword Arguments:

**kwargs – Turn_off services depending on the namespace functioning within has different parameter requirements. This argument allows you to specify a comma-separated list of keyword value pairs, e.g., transition = 3. These parameters will be different for every service being used.

appdaemon.entity.Entity.turn_on(self, **kwargs: Any | None) Any

Generic helper function, used to turn the entity ON if supported. This function will attempt to call the turn_on service if registered, either by an app or plugin within the entity’s namespace. So therefore its only functional, if the service turn_on exists within the namespace the entity is operating in.

Keyword Arguments:

**kwargs – Turn_on services depending on the namespace functioning within has different parameter requirements. This argument allows you to specify a comma-separated list of keyword value pairs, e.g., transition = 3. These parameters will be different for every service being used.

async appdaemon.entity.Entity.wait_state(self, state: Any, attribute: str | int = None, duration: int | float = 0, timeout: int | float = None) None

Used to wait for the state of an entity’s attribute

This API call is only functional within an async function. It should be noted that when instanciated, the api checks immediately if its already on the required state, and if it is, it will continue.

Parameters:
  • state (Any) – The state to wait for, for the entity to be in before continuing

  • attribute (str) – The entity’s attribute to use, if not using the entity’s state

  • duration (int|float) – How long the state is to hold, before continuing

  • timeout (int|float) – How long to wait for the state to be achieved, before timing out. When it times out, a appdaemon.exceptions.TimeOutException is raised

Returns:

None

Examples

>>> from appdaemon.exceptions import TimeOutException
>>>
>>> async def run_my_sequence(self):
>>>     sequence_object = self.get_entity("sequence.run_the_thing")
>>>     await sequence_object.call_service("run")
>>>     try:
>>>         await sequence_object.wait_state("idle", timeout=30) # wait for it to completely run
>>>     except TimeOutException:
>>>         pass # didn't complete on time

In addition to the above, there are a couple of property attributes the Entity class supports: - entity_id - namespace - domain - entity_name - state - attributes - friendly_name - last_changed - last_changed_seconds

State

appdaemon.adapi.ADAPI.get_state(self, entity_id: str = None, attribute: str = None, default: Any = None, copy: bool = True, **kwargs: Any | None) Any

Gets the state of any component within Home Assistant.

State updates are continuously tracked, so this call runs locally and does not require AppDaemon to call back to Home Assistant. In other words, states are updated using a push-based approach instead of a pull-based one.

Parameters:
  • entity_id (str, optional) – This is the name of an entity or device type. If just a device type is provided, e.g., light or binary_sensor, get_state() will return a dictionary of all devices of that type, indexed by the entity_id, containing all the state for each entity. If a fully qualified entity_id is provided, get_state() will return the state attribute for that entity, e.g., on or off for a light.

  • attribute (str, optional) – Name of an attribute within the entity state object. If this parameter is specified in addition to a fully qualified entity_id, a single value representing the attribute will be returned. The value all for attribute has special significance and will return the entire state dictionary for the specified entity rather than an individual attribute value.

  • default (any, optional) – The value to return when the requested attribute or the whole entity doesn’t exist (Default: None).

  • copy (bool, optional) – By default, a copy of the stored state object is returned. When you set copy to False, you get the same object as is stored internally by AppDaemon. Avoiding the copying brings a small performance gain, but also gives you write-access to the internal AppDaemon data structures, which is dangerous. Only disable copying when you can guarantee not to modify the returned state object, e.g., you do read-only operations.

  • **kwargs (optional) – Zero or more keyword arguments.

Keyword Arguments:

namespace (str, optional) – Namespace to use for the call. See the section on namespaces for a detailed description. In most cases, it is safe to ignore this parameter.

Returns:

The entire state of Home Assistant at that given time, if if get_state() is called with no parameters. This will consist of a dictionary with a key for each entity. Under that key will be the standard entity state information.

Examples

Get the state of the entire system.

>>> state = self.get_state()

Get the state of all switches in the system.

>>> state = self.get_state("switch")

Get the state attribute of light.office_1.

>>> state = self.get_state("light.office_1")

Get the brightness attribute of light.office_1.

>>> state = self.get_state("light.office_1", attribute="brightness")

Get the entire state of light.office_1.

>>> state = self.get_state("light.office_1", attribute="all")
appdaemon.adapi.ADAPI.set_state(self, entity_id: str, **kwargs: Any | None) dict

Updates the state of the specified entity.

Parameters:
  • entity_id (str) – The fully qualified entity id (including the device type).

  • **kwargs (optional) – Zero or more keyword arguments.

Keyword Arguments:
  • state – New state value to be set.

  • attributes (optional) – Entity’s attributes to be updated.

  • namespace (str, optional) – If a namespace is provided, AppDaemon will change the state of the given entity in the given namespace. On the other hand, if no namespace is given, AppDaemon will use the last specified namespace or the default namespace. See the section on namespaces for a detailed description. In most cases, it is safe to ignore this parameter.

  • replace (bool, optional) – If a replace flag is given and set to True and attributes is provided, AD will attempt to replace its internal entity register with the newly supplied attributes completely. This can be used to replace attributes in an entity which are no longer needed. Do take note this is only possible for internal entity state. For plugin based entities, this is not recommended, as the plugin will mostly replace the new values, when next it updates.

Returns:

A dictionary that represents the new state of the updated entity.

Examples

Update the state of an entity.

>>> self.set_state("light.office_1", state="off")

Update the state and attribute of an entity.

>>> self.set_state(entity_id="light.office_1", state = "on", attributes = {"color_name": "red"})

Update the state of an entity within the specified namespace.

>>> self.set_state("light.office_1", state="off", namespace ="hass")
appdaemon.adapi.ADAPI.listen_state(self, callback: Callable, entity_id: str | list = None, **kwargs: Any | None) str | list

Registers a callback to react to state changes.

This function allows the user to register a callback for a wide variety of state changes.

Parameters:
  • callback – Function to be invoked when the requested state change occurs. It must conform to the standard State Callback format documented here

  • entity_id (str|list, optional) – name of an entity or device type. If just a device type is provided, e.g., light, or binary_sensor. listen_state() will subscribe to state changes of all devices of that type. If a fully qualified entity_id is provided, listen_state() will listen for state changes for just that entity. If a list of entities, it will subscribe for those entities, and return their handles

  • **kwargs (optional) – Zero or more keyword arguments.

Keyword Arguments:
  • attribute (str, optional) –

    Name of an attribute within the entity state object. If this parameter is specified in addition to a fully qualified entity_id. listen_state() will subscribe to changes for just that attribute within that specific entity. The new and old parameters in the callback function will be provided with a single value representing the attribute.

    The value all for attribute has special significance and will listen for any state change within the specified entity, and supply the callback functions with the entire state dictionary for the specified entity rather than an individual attribute value.

  • new (optional) – If new is supplied as a parameter, callbacks will only be made if the state of the selected attribute (usually state) in the new state match the value of new. The parameter type is defined by the namespace or plugin that is responsible for the entity. If it looks like a float, list, or dictionary, it may actually be a string. If new is a callable (lambda, function, etc), then it will be invoked with the new state, and if it returns True, it will be considered to match.

  • old (optional) – If old is supplied as a parameter, callbacks will only be made if the state of the selected attribute (usually state) in the old state match the value of old. The same caveats on types for the new parameter apply to this parameter. If old is a callable (lambda, function, etc), then it will be invoked with the old state, and if it returns a True, it will be considered to match.

  • duration (int, optional) –

    If duration is supplied as a parameter, the callback will not fire unless the state listened for is maintained for that number of seconds. This requires that a specific attribute is specified (or the default of state is used), and should be used in conjunction with the old or new parameters, or both. When the callback is called, it is supplied with the values of entity, attr, old, and new that were current at the time the actual event occurred, since the assumption is that none of them have changed in the intervening period.

    If you use duration when listening for an entire device type rather than a specific entity, or for all state changes, you may get unpredictable results, so it is recommended that this parameter is only used in conjunction with the state of specific entities.

  • timeout (int, optional) – If timeout is supplied as a parameter, the callback will be created as normal, but after timeout seconds, the callback will be removed. If activity for the listened state has occurred that would trigger a duration timer, the duration timer will still be fired even though the callback has been deleted.

  • immediate (bool, optional) –

    It enables the countdown for a delay parameter to start at the time, if given. If the duration parameter is not given, the callback runs immediately. What this means is that after the callback is registered, rather than requiring one or more state changes before it runs, it immediately checks the entity’s states based on given parameters. If the conditions are right, the callback runs immediately at the time of registering. This can be useful if, for instance, you want the callback to be triggered immediately if a light is already on, or after a duration if given.

    If immediate is in use, and new and duration are both set, AppDaemon will check if the entity is already set to the new state and if so it will start the clock immediately. If new and duration are not set, immediate will trigger the callback immediately and report in its callback the new parameter as the present state of the entity. If attribute is specified, the state of the attribute will be used instead of state. In these cases, old will be ignored and when the callback is triggered, its state will be set to None.

  • oneshot (bool, optional) – If True, the callback will be automatically cancelled after the first state change that results in a callback.

  • namespace (str, optional) – Namespace to use for the call. See the section on namespaces for a detailed description. In most cases, it is safe to ignore this parameter. The value global for namespace has special significance and means that the callback will listen to state updates from any plugin.

  • pin (bool, optional) – If True, the callback will be pinned to a particular thread.

  • pin_thread (int, optional) – Sets which thread from the worker pool the callback will be run by (0 - number of threads -1).

  • *kwargs (optional) – Zero or more keyword arguments that will be supplied to the callback when it is called.

Notes

The old and new args can be used singly or together.

Returns:

A unique identifier that can be used to cancel the callback if required. Since variables created within object methods are local to the function they are created in, and in all likelihood, the cancellation will be invoked later in a different function, it is recommended that handles are stored in the object namespace, e.g., self.handle.

Examples

Listen for any state change and return the state attribute.

>>> self.handle = self.listen_state(self.my_callback)

Listen for any state change involving a light and return the state attribute.

>>> self.handle = self.listen_state(self.my_callback, "light")

Listen for a state change involving light.office1 and return the state attribute.

>>> self.handle = self.listen_state(self.my_callback, entity_id="light.office_1")

Listen for a state change involving light.office1 and return the entire state as a dict.

>>> self.handle = self.listen_state(self.my_callback, "light.office_1", attribute = "all")

Listen for a change involving the brightness attribute of light.office1 and return the brightness attribute.

>>> self.handle = self.listen_state(self.my_callback, "light.office_1", attribute = "brightness")

Listen for a state change involving light.office1 turning on and return the state attribute.

>>> self.handle = self.listen_state(self.my_callback, "light.office_1", new = "on")

Listen for a state change involving light.office1 turning on when the previous state was not unknown or unavailable, and return the state attribute.

>>> self.handle = self.listen_state(self.my_callback, "light.office_1", new = "on", old=lambda x: x not in ["unknown", "unavailable"])

Listen for a change involving light.office1 changing from brightness 100 to 200 and return the brightness attribute.

>>> self.handle = self.listen_state(self.my_callback, "light.office_1", attribute="brightness", old="100", new="200")

Listen for a state change involving light.office1 changing to state on and remaining on for a minute.

>>> self.handle = self.listen_state(self.my_callback, "light.office_1", new="on", duration=60)

Listen for a state change involving light.office1 changing to state on and remaining on for a minute trigger the delay immediately if the light is already on.

>>> self.handle = self.listen_state(self.my_callback, "light.office_1", new="on", duration=60, immediate=True)

Listen for a state change involving light.office1 and light.office2 changing to state on.

>>> self.handle = self.listen_state(self.my_callback, ["light.office_1", "light.office2"], new="on")
appdaemon.adapi.ADAPI.cancel_listen_state(self, handle: str, silent=False) bool

Cancels a listen_state() callback.

This will mean that the App will no longer be notified for the specific state change that has been cancelled. Other state changes will continue to be monitored.

Parameters:
  • handle – The handle returned when the listen_state() call was made.

  • silent (bool, optional) – If True, no warning will be issued if the handle is not found.

Returns:

Boolean.

Examples

>>> self.cancel_listen_state(self.office_light_handle)

Don’t display a warning if the handle is not found.

>>> self.cancel_listen_state(self.dummy_handle, silent=True)
appdaemon.adapi.ADAPI.info_listen_state(self, handle: str) dict

Gets information on state a callback from its handle.

Parameters:

handle – The handle returned when the listen_state() call was made.

Returns:

The values supplied for entity, attribute, and kwargs when the callback was initially created.

Examples

>>> entity, attribute, kwargs = self.info_listen_state(self.handle)

Time

appdaemon.adapi.ADAPI.parse_utc_string(self, utc_string: str) datetime

Converts a UTC to its string representation.

Parameters:

utc_string (str) – A string that contains a date and time to convert.

Returns:

An POSIX timestamp that is equivalent to the date and time contained in utc_string.

appdaemon.adapi.ADAPI.get_tz_offset(self) float

Returns the timezone difference between UTC and Local Time in minutes.

appdaemon.adapi.ADAPI.convert_utc(utc) datetime

Gets a datetime object for the specified UTC.

Home Assistant provides timestamps of several different sorts that may be used to gain additional insight into state changes. These timestamps are in UTC and are coded as ISO 8601 combined date and time strings. This function will accept one of these strings and convert it to a localised Python datetime object representing the timestamp.

Parameters:

utc – An ISO 8601 encoded date and time string in the following format: 2016-07-13T14:24:02.040658-04:00

Returns:

A localised Python datetime object representing the timestamp.

appdaemon.adapi.ADAPI.sun_up(self) bool

Determines if the sun is currently up.

Returns:

True if the sun is up, False otherwise.

Return type:

bool

Examples

>>> if self.sun_up():
>>>    #do something
appdaemon.adapi.ADAPI.sun_down(self) bool

Determines if the sun is currently down.

Returns:

True if the sun is down, False otherwise.

Return type:

bool

Examples

>>> if self.sun_down():
>>>    #do something
appdaemon.adapi.ADAPI.parse_time(self, time_str: str, name: str = None, aware: bool = False, today=False, days_offset=0) time

Creates a time object from its string representation.

This functions takes a string representation of a time, or sunrise, or sunset offset and converts it to a datetime.time object.

Parameters:
  • time_str (str) –

    A string representation of the datetime with one of the following formats:

    1. HH:MM:SS[.ss] - the time in Hours Minutes, Seconds and Microseconds, 24 hour format.

    b. sunrise|sunset [+|- HH:MM:SS[.ss]] - time of the next sunrise or sunset with an optional positive or negative offset in Hours Minutes, Seconds and Microseconds.

    1. N deg rising|setting - time the sun will be at N degrees of elevation while either rising or setting

    If the HH:MM:SS.ss format is used, the resulting datetime object will have today’s date.

  • name (str, optional) – Name of the calling app or module. It is used only for logging purposes.

  • aware (bool, optional) – If True the created datetime object will be aware of timezone.

  • today (bool, optional) – Instead of the default behavior which is to return the next sunrise/sunset that will occur, setting this flag to true will return today’s sunrise/sunset even if it is in the past

  • days_offset (int, optional) – Specify the number of days (positive or negative) for the sunset/sunrise. This can only be used in combination with the today flag

Returns:

A time object, representing the time given in the time_str argument.

Examples

>>> self.parse_time("17:30:00")
17:30:00
>>> time = self.parse_time("sunrise")
04:33:17
>>> time = self.parse_time("sunset + 00:30:00")
19:18:48
>>> time = self.parse_time("sunrise + 01:00:00")
05:33:17
appdaemon.adapi.ADAPI.parse_datetime(self, time_str: str, name=None, aware=False, today=False, days_offset=0) datetime

Creates a datetime object from its string representation.

This function takes a string representation of a date and time, or sunrise, or sunset offset and converts it to a datetime object.

Parameters:
  • time_str (str) –

    A string representation of the datetime with one of the following formats:

    a. YY-MM-DD-HH:MM:SS[.ss] - the date and time in Year, Month, Day, Hours, Minutes, Seconds and Microseconds, 24 hour format.

    1. HH:MM:SS[.ss] - the time in Hours Minutes, Seconds and Microseconds, 24 hour format.

    c. sunrise|sunset [+|- HH:MM:SS[.ss]] - time of the next sunrise or sunset with an optional positive or negative offset in Hours Minutes, Seconds and Microseconds.

    If the HH:MM:SS.ss format is used, the resulting datetime object will have today’s date.

  • name (str, optional) – Name of the calling app or module. It is used only for logging purposes.

  • aware (bool, optional) – If True the created datetime object will be aware of timezone.

  • today (bool, optional) – Instead of the default behavior which is to return the next sunrise/sunset that will occur, setting this flag to true will return today’s sunrise/sunset even if it is in the past

  • days_offset (int, optional) – Specify the number of days (positive or negative) for the sunset/sunrise. This can only be used in combination with the today flag

Returns:

A datetime object, representing the time and date given in the time_str argument.

Examples

>>> self.parse_datetime("2018-08-09 17:30:00")
2018-08-09 17:30:00
>>> self.parse_datetime("17:30:00.01")
2019-08-15 17:30:00.010000
>>> self.parse_datetime("sunrise")
2019-08-16 05:33:17
>>> self.parse_datetime("sunset + 00:30:00")
2019-08-16 19:18:48
>>> self.parse_datetime("sunrise + 01:00:00")
2019-08-16 06:33:17
appdaemon.adapi.ADAPI.get_now(self) datetime

Returns the current Local Date and Time.

Examples

>>> self.get_now()
2019-08-16 21:17:41.098813+00:00
appdaemon.adapi.ADAPI.get_now_ts(self) int

Returns the current Local Timestamp.

Examples

>>> self.get_now_ts()
1565990318.728324
appdaemon.adapi.ADAPI.now_is_between(self, start_time: str, end_time: str, name=None, now=None) bool

Determines if the current time is within the specified start and end times.

This function takes two string representations of a time, or sunrise or sunset offset and returns true if the current time is between those 2 times. Its implementation can correctly handle transitions across midnight.

Parameters:
  • start_time (str) – A string representation of the start time.

  • end_time (str) – A string representation of the end time.

  • name (str, optional) – Name of the calling app or module. It is used only for logging purposes.

  • now (str, optional) – If specified, now is used as the time for comparison instead of the current time. Useful for testing.

Returns:

True if the current time is within the specified start and end times, False otherwise.

Return type:

bool

Notes

The string representation of the start_time and end_time should follows one of these formats:

  1. HH:MM:SS - the time in Hours Minutes and Seconds, 24 hour format.

b. sunrise|sunset [+|- HH:MM:SS]- time of the next sunrise or sunset with an optional positive or negative offset in Hours Minutes, and Seconds.

Examples

>>> if self.now_is_between("17:30:00", "08:00:00"):
>>>     #do something
>>> if self.now_is_between("sunset - 00:45:00", "sunrise + 00:45:00"):
>>>     #do something
appdaemon.adapi.ADAPI.sunrise(self, aware=False, today=False, days_offset=0) datetime

Returns a datetime object that represents the next time Sunrise will occur.

Parameters:
  • aware (bool, optional) – Specifies if the created datetime object will be aware of timezone or not.

  • today (bool, optional) – Instead of the default behavior which is to return the next sunrise that will occur, setting this flag to true will return today’s sunrise even if it is in the past

  • days_offset (int, optional) – Specify the number of days (positive or negative) for the sunset. This can only be used in combination with the today flag

Examples

>>> self.sunrise()
2023-02-02 07:11:50.150554
>>> self.sunrise(today=True)
2023-02-01 07:12:20.272403
appdaemon.adapi.ADAPI.sunset(self, aware=False, today=False, days_offset=0) datetime

Returns a datetime object that represents the next time Sunset will occur.

Parameters:

aware (bool, optional) –

Specifies if the created datetime object will be

aware of timezone or not.

today (bool, optional): Instead of the default behavior which is to return the next sunset that will occur, setting this flag to true will return

today’s sunset even if it is in the past

days_offset (int, optional): Specify the number of days (positive or negative) for the sunset. This can only be used in combination with the today

flag

Examples

>>> self.sunset()
2023-02-01 18:09:00.730704
>>> self.sunset(today=True, days_offset=1)
2023-02-02 18:09:46.252314
appdaemon.adapi.ADAPI.time(self) time

Returns a localised time object representing the current Local Time.

Use this in preference to the standard Python ways to discover the current time, especially when using the “Time Travel” feature for testing.

Examples

>>> self.time()
20:15:31.295751
appdaemon.adapi.ADAPI.datetime(self, aware=False) datetime

Returns a datetime object representing the current Local Date and Time.

Use this in preference to the standard Python ways to discover the current datetime, especially when using the “Time Travel” feature for testing.

Parameters:

aware (bool, optional) – Specifies if the created datetime object will be aware of timezone or not.

Examples

>>> self.datetime()
2019-08-15 20:15:55.549379
appdaemon.adapi.ADAPI.date(self) date

Returns a localised date object representing the current Local Date.

Use this in preference to the standard Python ways to discover the current date, especially when using the “Time Travel” feature for testing.

Examples

>>> self.date()
2019-08-15
appdaemon.adapi.ADAPI.get_timezone(self) str

Returns the current time zone.

Scheduler

appdaemon.adapi.ADAPI.timer_running(self, handle: str) bool

Checks if a previously created timer is still running.

Parameters:

handle – A handle value returned from the original call to create the timer.

Returns:

Boolean.

Examples

>>> self.timer_running(handle)
appdaemon.adapi.ADAPI.cancel_timer(self, handle: str, silent=False) bool

Cancels a previously created timer.

Parameters:
  • handle – A handle value returned from the original call to create the timer.

  • silent – (boolean, optional) don’t issue a warning if the handle is invalid - this can sometimes occur due to race conditions and is usually harmless.

  • False (Defaults to)

Returns:

Boolean.

Examples

>>> self.cancel_timer(handle)
>>> self.cancel_timer(handle, True)
appdaemon.adapi.ADAPI.info_timer(self, handle: str) tuple | None

Gets information on a scheduler event from its handle.

Parameters:

handle – The handle returned when the scheduler call was made.

Returns:

time - datetime object representing the next time the callback will be fired

interval - repeat interval if applicable, 0 otherwise.

kwargs - the values supplied when the callback was initially created.

or None - if handle is invalid or timer no longer exists.

Examples

>>> time, interval, kwargs = self.info_timer(handle)
appdaemon.adapi.ADAPI.reset_timer(self, handle: str) bool

Resets a previously created timer.

Parameters:

handle – A valid handle value returned from the original call to create the timer. The timer must be actively running, and not a Sun related one like sunrise/sunset for it to be resetted.

Returns:

Boolean, true if the reset succeeded.

Examples

>>> self.reset_timer(handle)
appdaemon.adapi.ADAPI.run_in(self, callback: Callable, delay: int, **kwargs) str

Runs the callback in a defined number of seconds.

This is used to add a delay, for instance, a 60 second delay before a light is turned off after it has been triggered by a motion detector. This callback should always be used instead of time.sleep() as discussed previously.

Parameters:
  • callback – Function to be invoked when the requested state change occurs. It must conform to the standard Scheduler Callback format documented here.

  • delay (float) – Delay, in seconds before the callback is invoked.

  • **kwargs (optional) – Zero or more keyword arguments.

Keyword Arguments:
  • random_start (int) – Start of range of the random time.

  • random_end (int) – End of range of the random time.

  • pin (bool, optional) – If True, the callback will be pinned to a particular thread.

  • pin_thread (int, optional) – Specify which thread from the worker pool the callback will be run by (0 - number of threads -1).

  • **kwargs – Arbitrary keyword parameters to be provided to the callback function when it is invoked.

Returns:

A handle that can be used to cancel the timer.

Notes

The random_start value must always be numerically lower than random_end value, they can be negative to denote a random offset before and event, or positive to denote a random offset after an event.

Examples

Run the specified callback after 10 seconds.

>>> self.handle = self.run_in(self.run_in_c, 10)

Run the specified callback after 10 seconds with a keyword arg (title).

>>> self.handle = self.run_in(self.run_in_c, 5, title = "run_in5")
appdaemon.adapi.ADAPI.run_once(self, callback: Callable, start: time | str, **kwargs)

Runs the callback once, at the specified time of day.

Parameters:
  • callback – Function to be invoked at the specified time of day. It must conform to the standard Scheduler Callback format documented here.

  • start – Should be either a Python time object or a parse_time() formatted string that specifies when the callback will occur. If the time specified is in the past, the callback will occur the next day at the specified time.

  • **kwargs (optional) – Zero or more keyword arguments.

Keyword Arguments:
  • random_start (int) – Start of range of the random time.

  • random_end (int) – End of range of the random time.

  • pin (bool, optional) – If True, the callback will be pinned to a particular thread.

  • pin_thread (int, optional) – Specify which thread from the worker pool the callback will be run by (0 - number of threads -1).

  • **kwargs – Arbitrary keyword parameters to be provided to the callback function when it is invoked.

Returns:

A handle that can be used to cancel the timer.

Notes

The random_start value must always be numerically lower than random_end value, they can be negative to denote a random offset before and event, or positive to denote a random offset after an event.

Examples

Run at 4pm today, or 4pm tomorrow if it is already after 4pm.

>>> runtime = datetime.time(16, 0, 0)
>>> handle = self.run_once(self.run_once_c, runtime)

Run today at 10:30 using the parse_time() function.

>>> handle = self.run_once(self.run_once_c, "10:30:00")

Run at sunset.

>>> handle = self.run_once(self.run_once_c, "sunset")

Run an hour after sunrise.

>>> handle = self.run_once(self.run_once_c, "sunrise + 01:00:00")
appdaemon.adapi.ADAPI.run_at(self, callback: Callable, start: datetime | str, **kwargs)

Runs the callback once, at the specified time of day.

Parameters:
  • callback – Function to be invoked at the specified time of day. It must conform to the standard Scheduler Callback format documented here.

  • start – Should be either a Python datetime object or a parse_time() formatted string that specifies when the callback will occur.

  • **kwargs (optional) – Zero or more keyword arguments.

Keyword Arguments:
  • random_start (int) – Start of range of the random time.

  • random_end (int) – End of range of the random time.

  • pin (bool, optional) – If True, the callback will be pinned to a particular thread.

  • pin_thread (int, optional) – Specify which thread from the worker pool the callback will be run by (0 - number of threads -1).

  • **kwargs – Arbitrary keyword parameters to be provided to the callback function when it is invoked.

Returns:

A handle that can be used to cancel the timer.

Notes

The random_start value must always be numerically lower than random_end value, they can be negative to denote a random offset before and event, or positive to denote a random offset after an event.

The run_at() function will raise an exception if the specified time is in the past.

Examples

Run at 4pm today.

>>> runtime = datetime.time(16, 0, 0)
>>> today = datetime.date.today()
>>> event = datetime.datetime.combine(today, runtime)
>>> handle = self.run_at(self.run_at_c, event)

Run today at 10:30 using the parse_time() function.

>>> handle = self.run_at(self.run_at_c, "10:30:00")

Run on a specific date and time.

>>> handle = self.run_at(self.run_at_c, "2018-12-11 10:30:00")

Run at the next sunset.

>>> handle = self.run_at(self.run_at_c, "sunset")

Run an hour after the next sunrise.

>>> handle = self.run_at(self.run_at_c, "sunrise + 01:00:00")
appdaemon.adapi.ADAPI.run_daily(self, callback: Callable, start: time | str, **kwargs)

Runs the callback at the same time every day.

Parameters:
  • callback – Function to be invoked every day at the specified time. It must conform to the standard Scheduler Callback format documented here.

  • start – Should be either a Python time object or a parse_time() formatted string that specifies when the callback will occur. If the time specified is in the past, the callback will occur the next day at the specified time. When specifying sunrise or sunset relative times using the parse_datetime() format, the time of the callback will be adjusted every day to track the actual value of sunrise or sunset.

  • **kwargs (optional) – Zero or more keyword arguments.

Keyword Arguments:
  • random_start (int) – Start of range of the random time.

  • random_end (int) – End of range of the random time.

  • pin (bool, optional) – If True, the callback will be pinned to a particular thread.

  • pin_thread (int, optional) – Specify which thread from the worker pool the callback will be run by (0 - number of threads -1).

  • **kwargs – Arbitrary keyword parameters to be provided to the callback function when it is invoked.

Returns:

A handle that can be used to cancel the timer.

Notes

The random_start value must always be numerically lower than random_end value, they can be negative to denote a random offset before and event, or positive to denote a random offset after an event.

Examples

Run daily at 7pm.

>>> runtime = datetime.time(19, 0, 0)
>>> self.run_daily(self.run_daily_c, runtime)

Run at 10:30 every day using the parse_time() function.

>>> handle = self.run_daily(self.run_daily_c, "10:30:00")

Run every day at sunrise.

>>> handle = self.run_daily(self.run_daily_c, "sunrise")

Run every day an hour after sunset.

>>> handle = self.run_daily(self.run_daily_c, "sunset + 01:00:00")
appdaemon.adapi.ADAPI.run_hourly(self, callback, start, **kwargs)

Runs the callback at the same time every hour.

Parameters:
  • callback – Function to be invoked every hour at the specified time. It must conform to the standard Scheduler Callback format documented here.

  • start – A Python time object that specifies when the callback will occur, the hour component of the time object is ignored. If the time specified is in the past, the callback will occur the next hour at the specified time. If time is not supplied, the callback will start an hour from the time that run_hourly() was executed.

  • **kwargs (optional) – Zero or more keyword arguments.

Keyword Arguments:
  • random_start (int) – Start of range of the random time.

  • random_end (int) – End of range of the random time.

  • pin (bool, optional) – If True, the callback will be pinned to a particular thread.

  • pin_thread (int, optional) – Specify which thread from the worker pool the callback will be run by (0 - number of threads -1).

  • **kwargs – Arbitrary keyword parameters to be provided to the callback function when it is invoked.

Returns:

A handle that can be used to cancel the timer.

Notes

The random_start value must always be numerically lower than random_end value, they can be negative to denote a random offset before and event, or positive to denote a random offset after an event.

Examples

Run every hour, on the hour.

>>> runtime = datetime.time(0, 0, 0)
>>> self.run_hourly(self.run_hourly_c, runtime)
appdaemon.adapi.ADAPI.run_minutely(self, callback: Callable, start: time, **kwargs) str

Runs the callback at the same time every minute.

Parameters:
  • callback – Function to be invoked every minute. It must conform to the standard Scheduler Callback format documented here.

  • start – A Python time object that specifies when the callback will occur, the hour and minute components of the time object are ignored. If the time specified is in the past, the callback will occur the next minute at the specified time. If time is not supplied, the callback will start a minute from the time that run_minutely() was executed.

  • **kwargs (optional) – Zero or more keyword arguments.

Keyword Arguments:
  • random_start (int) – Start of range of the random time.

  • random_end (int) – End of range of the random time.

  • pin (bool, optional) – If True, the callback will be pinned to a particular thread.

  • pin_thread (int, optional) – Specify which thread from the worker pool the callback will be run by (0 - number of threads -1).

  • **kwargs – Arbitrary keyword parameters to be provided to the callback function when it is invoked.

Returns:

A handle that can be used to cancel the timer.

Notes

The random_start value must always be numerically lower than random_end value, they can be negative to denote a random offset before and event, or positive to denote a random offset after an event.

Examples

Run every minute on the minute.

>>> time = datetime.time(0, 0, 0)
>>> self.run_minutely(self.run_minutely_c, time)
appdaemon.adapi.ADAPI.run_every(self, callback: Callable, start: datetime, interval: int, **kwargs) str

Runs the callback with a configurable delay starting at a specific time.

Parameters:
  • callback – Function to be invoked when the time interval is reached. It must conform to the standard Scheduler Callback format documented here.

  • start – A Python datetime object that specifies when the initial callback will occur, or can take the now string alongside an added offset. If given in the past, it will be executed in the next interval time.

  • interval – Frequency (expressed in seconds) in which the callback should be executed.

  • **kwargs – Arbitrary keyword parameters to be provided to the callback function when it is invoked.

Keyword Arguments:
  • random_start (int) – Start of range of the random time.

  • random_end (int) – End of range of the random time.

  • pin (bool, optional) – If True, the callback will be pinned to a particular thread.

  • pin_thread (int, optional) – Specify which thread from the worker pool the callback will be run by (0 - number of threads -1).

Returns:

A handle that can be used to cancel the timer.

Notes

The random_start value must always be numerically lower than random_end value, they can be negative to denote a random offset before and event, or positive to denote a random offset after an event.

Examples

Run every 17 minutes starting in 2 hours time.

>>> self.run_every(self.run_every_c, time, 17 * 60)

Run every 10 minutes starting now.

>>> self.run_every(self.run_every_c, "now", 10 * 60)

Run every 5 minutes starting now plus 5 seconds.

>>> self.run_every(self.run_every_c, "now+5", 5 * 60)
appdaemon.adapi.ADAPI.run_at_sunset(self, callback: Callable, **kwargs) str

Runs a callback every day at or around sunset.

Parameters:
  • callback – Function to be invoked at or around sunset. It must conform to the standard Scheduler Callback format documented here.

  • **kwargs – Arbitrary keyword parameters to be provided to the callback function when it is invoked.

Keyword Arguments:
  • offset (int, optional) – The time in seconds that the callback should be delayed after sunset. A negative value will result in the callback occurring before sunset. This parameter cannot be combined with random_start or random_end.

  • random_start (int) – Start of range of the random time.

  • random_end (int) – End of range of the random time.

  • pin (bool, optional) – If True, the callback will be pinned to a particular thread.

  • pin_thread (int, optional) – Specify which thread from the worker pool the callback will be run by (0 - number of threads -1).

Returns:

A handle that can be used to cancel the timer.

Notes

The random_start value must always be numerically lower than random_end value, they can be negative to denote a random offset before and event, or positive to denote a random offset after an event.

Examples

Example using timedelta.

>>> self.run_at_sunset(self.sun, offset = datetime.timedelta(minutes = -45).total_seconds())

Or you can just do the math yourself.

>>> self.run_at_sunset(self.sun, offset = 30 * 60)

Run at a random time +/- 60 minutes from sunset.

>>> self.run_at_sunset(self.sun, random_start = -60*60, random_end = 60*60)

Run at a random time between 30 and 60 minutes before sunset.

>>> self.run_at_sunset(self.sun, random_start = -60*60, random_end = 30*60)
appdaemon.adapi.ADAPI.run_at_sunrise(self, callback: Callable, **kwargs) str

Runs a callback every day at or around sunrise.

Parameters:
  • callback – Function to be invoked at or around sunrise. It must conform to the standard Scheduler Callback format documented here.

  • **kwargs – Arbitrary keyword parameters to be provided to the callback function when it is invoked.

Keyword Arguments:
  • offset (int, optional) – The time in seconds that the callback should be delayed after sunrise. A negative value will result in the callback occurring before sunrise. This parameter cannot be combined with random_start or random_end.

  • random_start (int) – Start of range of the random time.

  • random_end (int) – End of range of the random time.

  • pin (bool, optional) – If True, the callback will be pinned to a particular thread.

  • pin_thread (int, optional) – Specify which thread from the worker pool the callback will be run by (0 - number of threads -1).

Returns:

A handle that can be used to cancel the timer.

Notes

The random_start value must always be numerically lower than random_end value, they can be negative to denote a random offset before and event, or positive to denote a random offset after an event.

Examples

Run 45 minutes before sunset.

>>> self.run_at_sunrise(self.sun, offset = datetime.timedelta(minutes = -45).total_seconds())

Or you can just do the math yourself.

>>> self.run_at_sunrise(self.sun, offset = 30 * 60)

Run at a random time +/- 60 minutes from sunrise.

>>> self.run_at_sunrise(self.sun, random_start = -60*60, random_end = 60*60)

Run at a random time between 30 and 60 minutes before sunrise.

>>> self.run_at_sunrise(self.sun, random_start = -60*60, random_end = 30*60)

Service

appdaemon.adapi.ADAPI.register_service(self, service: str, cb: Callable, **kwargs: Any | None) None

Registers a service that can be called from other apps, the REST API and the Event Stream

Using this function, an App can register a function to be available in the service registry. This will automatically make it available to other apps using the call_service() API call, as well as publish it as a service in the REST API and make it available to the call_service command in the event stream. It should be noted that registering services within a plugin’s namespace is a bad idea. It could work, but not always reliable It is recommended to make use of this api, within a user definded namespace, or one not tied to a plugin.

Parameters:
  • service – Name of the service, in the format domain/service. If the domain does not exist it will be created

  • cb – A reference to the function to be called when the service is requested. This function may be a regular function, or it may be async. Note that if it is an async function, it will run on AppDaemon’s main loop meaning that any issues with the service could result in a delay of AppDaemon’s core functions.

Keyword Arguments:

namespace (str, optional) – Namespace to use for the call. See the section on namespaces for a detailed description. In most cases, it is safe to ignore this parameter.

Returns:

None

Examples

>>> self.register_service("myservices/service1", self.mycallback)
>>> async def mycallback(self, namespace, domain, service, kwargs):
>>>     self.log("Service called")
appdaemon.adapi.ADAPI.deregister_service(self, service: str, **kwargs: Any | None) bool

Deregisters a service that had been previously registered

Using this function, an App can deregister a service call, it has initially registered in the service registry. This will automatically make it unavailable to other apps using the call_service() API call, as well as published as a service in the REST API and make it unavailable to the call_service command in the event stream. This function can only be used, within the app that registered it in the first place

Parameters:

service – Name of the service, in the format domain/service.

Keyword Arguments:

namespace (str, optional) – Namespace to use for the call. See the section on namespaces for a detailed description. In most cases, it is safe to ignore this parameter.

Returns:

Bool

Examples

>>> self.deregister_service("myservices/service1")
appdaemon.adapi.ADAPI.list_services(self, **kwargs: Any | None) list

List all services available within AD

Using this function, an App can request all available services within AD

Parameters:

**kwargs (optional) – Zero or more keyword arguments.

Keyword Arguments:
  • **kwargs – Each service has different parameter requirements. This argument allows you to specify a comma-separated list of keyword value pairs, e.g., namespace = global.

  • namespace (str, optional) – If a namespace is provided, AppDaemon will request the services within the given namespace. On the other hand, if no namespace is given, AppDaemon will use the last specified namespace or the default namespace. To get all services across AD, pass global. See the section on namespaces for a detailed description. In most cases, it is safe to ignore this parameter.

Returns:

All services within the requested namespace

Examples

>>> self.list_services(namespace="global")
appdaemon.adapi.ADAPI.call_service(self, service: str, **kwargs: Any | None) Any

Calls a Service within AppDaemon.

This function can call any service and provide any required parameters. By default, there are standard services that can be called within AD. Other services that can be called, are dependent on the plugin used, or those registered by individual apps using the register_service api. In a future release, all available services can be found using AD’s Admin UI. For listed services, the part before the first period is the domain, and the part after is the service name. For instance, light/turn_on has a domain of light and a service name of turn_on.

The default behaviour of the call service api is not to wait for any result, typically known as “fire and forget”. If it is required to get the results of the call, keywords “return_result” or “callback” can be added.

Parameters:
  • service (str) – The service name.

  • **kwargs (optional) – Zero or more keyword arguments.

Keyword Arguments:
  • **kwargs – Each service has different parameter requirements. This argument allows you to specify a comma-separated list of keyword value pairs, e.g., entity_id = light.office_1. These parameters will be different for every service and can be discovered using the developer tools. Most all service calls require an entity_id.

  • namespace (str, optional) – If a namespace is provided, AppDaemon will change the state of the given entity in the given namespace. On the other hand, if no namespace is given, AppDaemon will use the last specified namespace or the default namespace. See the section on namespaces for a detailed description. In most cases, it is safe to ignore this parameter.

  • return_result (str, option) – If return_result is provided and set to True AD will attempt to wait for the result, and return it after execution. In the case of Home Assistant calls that do not return values this may seem pointless, but it does force the call to be synchronous with respect to Home Assistant whcih can in turn highlight slow performing services if they timeout or trigger thread warnings.

  • callback – The non-async callback to be executed when complete.

  • hass_result (False, Home Assistant Specific) – Mark the service call to Home Assistant as returnng a value. If set to True, the call to Home Assistant will specifically request a return result. If this flag is set for a service that does not return a result, Home Assistant will respond with an error, which AppDaemon will log. If this flag is NOT set for a service that does returns a result, Home Assistant will respond with an error, which AppDaemon will log. Note: if you specify hass_result you must also set return_result or the result from HomeAssistant will not be propagated to your app. See Some Notes on Service Calls

  • hass_timeout (Home Assistant Specific) – time in seconds to wait for Home Assistant’s response for this specific service call. If not specified defaults to the value of the q_timeout parameter in the HASS plugin configuration, which itself defaults to 30 seconds. See Some Notes on Service Calls

  • suppress_log_messages (Home Assistant Specific, False) – if set to True Appdaemon will suppress logging of warnings for service calls to Home Assistant, specifically timeouts and non OK statuses. Use this flag and set it to True to supress these log messages if you are performing your own error checking as described here

Returns:

Result of the call_service function if any, see service call notes for more details.

Examples

HASS

>>> self.call_service("light/turn_on", entity_id = "light.office_lamp", color_name = "red")
>>> self.call_service("notify/notify", title = "Hello", message = "Hello World")
>>> self.call_service("calendar/get_events", entity_id="calendar.home", start_date_time="2024-08-25 00:00:00", end_date_time="2024-08-27 00:00:00", return_result=True, hass_result=True, hass_timeout=10)

MQTT

>>> call_service("mqtt/subscribe", topic="homeassistant/living_room/light", qos=2)
>>> call_service("mqtt/publish", topic="homeassistant/living_room/light", payload="on")

Utility

>>> call_service("app/restart", app="notify_app", namespace="appdaemon")
>>> call_service("app/stop", app="lights_app", namespace="appdaemon")
>>> call_service("app/reload", namespace="appdaemon")

For Utility, it is important that the namespace arg is set to appdaemon as no app can work within that namespace. If not namespace is specified, calling this function will rise an error.

Sequence

appdaemon.adapi.ADAPI.run_sequence(self, sequence: str | list, **kwargs: Any | None)

Run an AppDaemon Sequence. Sequences are defined in a valid apps.yaml file or inline, and are sequences of service calls.

Parameters:
  • sequence – The sequence name, referring to the correct entry in apps.yaml, or a list containing actual commands to run

  • **kwargs (optional) – Zero or more keyword arguments.

Keyword Arguments:

namespace (str, optional) – If a namespace is provided, AppDaemon will change the state of the given entity in the given namespace. On the other hand, if no namespace is given, AppDaemon will use the last specified namespace or the default namespace. See the section on namespaces for a detailed description. In most cases, it is safe to ignore this parameter.

Returns:

A handle that can be used with cancel_sequence() to terminate the script.

Examples

Run a yaml-defined sequence called “sequence.front_room_scene”.

>>> handle = self.run_sequence("sequence.front_room_scene")

Run an inline sequence.

>>> handle = self.run_sequence([{"light/turn_on": {"entity_id": "light.office_1"}}, {"sleep": 5}, {"light.turn_off":
{"entity_id": "light.office_1"}}])
appdaemon.adapi.ADAPI.cancel_sequence(self, sequence: Any) None

Cancel an already running AppDaemon Sequence.

Parameters:

sequence – The sequence as configured to be cancelled, or the sequence entity_id or future object

Returns:

None.

Examples

>>> self.cancel_sequence("sequence.living_room_lights")

Events

appdaemon.adapi.ADAPI.listen_event(self, callback: Callable, event: str | list = None, **kwargs: Any | None) str | list

Registers a callback for a specific event, or any event.

Parameters:
  • callback – Function to be invoked when the event is fired. It must conform to the standard Event Callback format documented here

  • event (str|list, optional) – Name of the event to subscribe to. Can be a standard Home Assistant event such as service_registered, an arbitrary custom event such as “MODE_CHANGE” or a list of events [“pressed”, “released”]. If no event is specified, listen_event() will subscribe to all events.

  • **kwargs (optional) – Zero or more keyword arguments.

Keyword Arguments:
  • oneshot (bool, optional) – If True, the callback will be automatically cancelled after the first state change that results in a callback.

  • namespace (str, optional) – Namespace to use for the call. See the section on namespaces for a detailed description. In most cases, it is safe to ignore this parameter. The value global for namespace has special significance, and means that the callback will listen to state updates from any plugin.

  • pin (bool, optional) – If True, the callback will be pinned to a particular thread.

  • pin_thread (int, optional) – Specify which thread from the worker pool the callback will be run by (0 - number of threads -1).

  • timeout (int, optional) – If timeout is supplied as a parameter, the callback will be created as normal, but after timeout seconds, the callback will be removed.

  • **kwargs (optional) –

    One or more keyword value pairs representing App specific parameters to supply to the callback. If the keywords match values within the event data, they will act as filters, meaning that if they don’t match the values, the callback will not fire. If the values provided are callable (lambda, function, etc), then they’ll be invoked with the events content, and if they return True, they’ll be considered to match.

    As an example of this, a Minimote controller when activated will generate an event called zwave.scene_activated, along with 2 pieces of data that are specific to the event - entity_id and scene. If you include keyword values for either of those, the values supplied to the listen_event() call must match the values in the event or it will not fire. If the keywords do not match any of the data in the event they are simply ignored.

    Filtering will work with any event type, but it will be necessary to figure out the data associated with the event to understand what values can be filtered on. This can be achieved by examining Home Assistant’s logfiles when the event fires.

Returns:

A handle that can be used to cancel the callback.

Examples

Listen all “MODE_CHANGE” events.

>>> self.listen_event(self.mode_event, "MODE_CHANGE")

Listen for a minimote event activating scene 3.

>>> self.listen_event(self.generic_event, "zwave.scene_activated", scene_id = 3)

Listen for a minimote event activating scene 3 from a specific minimote .

>>> self.listen_event(self.generic_event, "zwave.scene_activated", entity_id = "minimote_31", scene_id = 3)

Listen for a minimote event activating scene 3 from certain minimote (starting with 3), matched with code.

>>> self.listen_event(self.generic_event, "zwave.scene_activated", entity_id = lambda x: x.starts_with("minimote_3"), scene_id = 3)

Listen for some custom events of a button being pressed.

>>> self.listen_event(self.button_event, ["pressed", "released"])
appdaemon.adapi.ADAPI.cancel_listen_event(self, handle: str) bool

Cancels a callback for a specific event.

Parameters:

handle – A handle returned from a previous call to listen_event().

Returns:

Boolean.

Examples

>>> self.cancel_listen_event(handle)
appdaemon.adapi.ADAPI.info_listen_event(self, handle: str) bool

Gets information on an event callback from its handle.

Parameters:

handle – The handle returned when the listen_event() call was made.

Returns:

The values (service, kwargs) supplied when the callback was initially created.

Examples

>>> service, kwargs = self.info_listen_event(handle)
appdaemon.adapi.ADAPI.fire_event(self, event: str, **kwargs: Any | None) None

Fires an event on the AppDaemon bus, for apps and plugins.

Parameters:
  • event – Name of the event. Can be a standard Home Assistant event such as service_registered or an arbitrary custom event such as “MODE_CHANGE”.

  • **kwargs (optional) – Zero or more keyword arguments.

Keyword Arguments:
  • namespace (str, optional) – Namespace to use for the call. See the section on namespaces for a detailed description. In most cases, it is safe to ignore this parameter.

  • **kwargs (optional) – Zero or more keyword arguments that will be supplied as part of the event.

Returns:

None.

Examples

>>> self.fire_event("MY_CUSTOM_EVENT", jam="true")

Logging

appdaemon.adapi.ADAPI.log(self, msg: str, *args, **kwargs) None

Logs a message to AppDaemon’s main logfile.

Parameters:
  • msg (str) – The message to log.

  • **kwargs (optional) – Zero or more keyword arguments.

Keyword Arguments:
  • level (str, optional) – The log level of the message - takes a string representing the standard logger levels (Default: "WARNING").

  • ascii_encode (bool, optional) – Switch to disable the encoding of all log messages to ascii. Set this to false if you want to log UTF-8 characters (Default: True).

  • log (str, optional) – Send the message to a specific log, either system or user_defined. System logs are main_log, error_log, diag_log or access_log. Any other value in use here must have a corresponding user-defined entity in the logs section of appdaemon.yaml.

  • stack_info (bool, optional) – If True the stack info will included.

Returns:

None.

Examples

Log a message to the main logfile of the system.

>>> self.log("Log Test: Parameter is %s", some_variable)

Log a message to the specified logfile.

>>> self.log("Log Test: Parameter is %s", some_variable, log="test_log")

Log a message with error-level to the main logfile of the system.

>>> self.log("Log Test: Parameter is %s", some_variable, level = "ERROR")

Log a message using placeholders to the main logfile of the system.

>>> self.log("Line: __line__, module: __module__, function: __function__, Msg: Something bad happened")

Log a WARNING message (including the stack info) to the main logfile of the system.

>>> self.log("Stack is", some_value, level="WARNING", stack_info=True)
appdaemon.adapi.ADAPI.error(self, msg, *args, **kwargs)

Logs a message to AppDaemon’s error logfile.

Parameters:
  • msg (str) – The message to log.

  • **kwargs (optional) – Zero or more keyword arguments.

Keyword Arguments:
  • level (str, optional) – The log level of the message - takes a string representing the standard logger levels.

  • ascii_encode (bool, optional) – Switch to disable the encoding of all log messages to ascii. Set this to false if you want to log UTF-8 characters (Default: True).

  • log (str, optional) – Send the message to a specific log, either system or user_defined. System logs are main_log, error_log, diag_log or access_log. Any other value in use here must have a corresponding user-defined entity in the logs section of appdaemon.yaml.

Returns:

None.

Examples

Log an error message to the error logfile of the system.

>>> self.error("Some Warning string")

Log an error message with critical-level to the error logfile of the system.

>>> self.error("Some Critical string", level = "CRITICAL")
appdaemon.adapi.ADAPI.listen_log(self, callback: Callable, level='INFO', **kwargs) str

Registers the App to receive a callback every time an App logs a message.

Parameters:
  • callback (function) – Function to be called when a message is logged.

  • level (str) – Logging level to be used - lower levels will not be forwarded to the app (Default: "INFO").

  • **kwargs (optional) – Zero or more keyword arguments.

Keyword Arguments:
  • log (str, optional) – Name of the log to listen to, default is all logs. The name should be one of the 4 built in types main_log, error_log, diag_log or access_log or a user defined log entry.

  • pin (bool, optional) – If True, the callback will be pinned to a particular thread.

  • pin_thread (int, optional) – Specify which thread from the worker pool the callback will be run by (0 - number of threads -1).

Returns:

A unique identifier that can be used to cancel the callback if required. Since variables created within object methods are local to the function they are created in, and in all likelihood, the cancellation will be invoked later in a different function, it is recommended that handles are stored in the object namespace, e.g., self.handle.

Examples

Listen to all WARNING log messages of the system.

>>> self.handle = self.listen_log(self.cb, "WARNING")

Sample callback:

>>> def log_message(self, name, ts, level, type, message, kwargs):

Listen to all WARNING log messages of the main_log.

>>> self.handle = self.listen_log(self.cb, "WARNING", log="main_log")

Listen to all WARNING log messages of a user-defined logfile.

>>> self.handle = self.listen_log(self.cb, "WARNING", log="my_custom_log")
appdaemon.adapi.ADAPI.cancel_listen_log(self, handle: str) None

Cancels the log callback for the App.

Parameters:

handle – The handle returned when the listen_log call was made.

Returns:

Boolean.

Examples

>>> self.cancel_listen_log(handle)
appdaemon.adapi.ADAPI.get_main_log(self) Any

Returns the underlying logger object used for the main log.

Examples

Log a critical message to the main logfile of the system.

>>> log = self.get_main_log()
>>> log.critical("Log a critical error")
appdaemon.adapi.ADAPI.get_error_log(self) Any

Returns the underlying logger object used for the error log.

Examples

Log an error message to the error logfile of the system.

>>> error_log = self.get_error_log()
>>> error_log.error("Log an error", stack_info=True, exc_info=True)
appdaemon.adapi.ADAPI.get_user_log(self, log) Any

Gets the specified-user logger of the App.

Parameters:

log (str) – The name of the log you want to get the underlying logger object from, as described in the logs section of appdaemon.yaml.

Returns:

The underlying logger object used for the error log.

Examples

Log an error message to a user-defined logfile.

>>> log = self.get_user_log("test_log")
>>> log.error("Log an error", stack_info=True, exc_info=True)
appdaemon.adapi.ADAPI.set_log_level(self, level: str) None

Sets a specific log level for the App.

Parameters:

level (str) – Log level.

Returns:

None.

Notes

Supported log levels: INFO, WARNING, ERROR, CRITICAL, DEBUG, NOTSET.

Examples

>>> self.set_log_level("DEBUG")
appdaemon.adapi.ADAPI.set_error_level(self, level: str) None

Sets the log level to send to the error logfile of the system.

Parameters:

level (str) – Error level.

Returns:

None.

Notes

Supported log levels: INFO, WARNING, ERROR, CRITICAL, DEBUG, NOTSET.

Dashboard

appdaemon.adapi.ADAPI.dash_navigate(self, target: str, timeout=-1, ret=None, sticky=0, deviceid=None, dashid=None) None

Forces all connected Dashboards to navigate to a new URL.

Parameters:
  • target (str) – Name of the new Dashboard to navigate to (e.g., /SensorPanel). Note that this value is not a URL.

  • timeout (int) – Length of time to stay on the new dashboard before returning to the original. This argument is optional and if not specified, the navigation will be permanent. Note that if there is a click or touch on the new panel before the timeout expires, the timeout will be cancelled.

  • ret (str) – Dashboard to return to after the timeout has elapsed.

  • sticky (int) – Specifies whether or not to return to the original dashboard after it has been clicked on. The default behavior (sticky=0) is to remain on the new dashboard if clicked, or return to the original otherwise. By using a different value (sticky= 5), clicking the dashboard will extend the amount of time (in seconds), but it will return to the original dashboard after a period of inactivity equal to timeout.

  • deviceid (str) – If set, only the device which has the same deviceid will navigate.

  • dashid (str) – If set, all devices currently on a dashboard which the title contains the substring dashid will navigate. ex: if dashid is “kichen”, it will match devices which are on “kitchen lights”, “kitchen sensors”, “ipad - kitchen”, etc.

Returns:

None.

Examples

Switch to AlarmStatus Panel then return to current panel after 10 seconds.

>>> self.dash_navigate("/AlarmStatus", timeout=10)

Switch to Locks Panel then return to Main panel after 10 seconds.

>>> self.dash_navigate("/Locks", timeout=10, ret="/SensorPanel")

Namespace

appdaemon.adapi.ADAPI.set_namespace(self, namespace: str) None

Sets a new namespace for the App to use from that point forward.

Parameters:

namespace (str) – Name of the new namespace

Returns:

None.

Examples

>>> self.set_namespace("hass1")
appdaemon.adapi.ADAPI.get_namespace(self) str

Returns the App’s namespace.

appdaemon.adapi.ADAPI.list_namespaces(self) list

Returns a list of available namespaces.

Examples

>>> self.list_namespaces()
appdaemon.adapi.ADAPI.save_namespace(self, **kwargs) None

Saves entities created in user-defined namespaces into a file.

This way, when AD restarts these entities will be reloaded into AD with its previous states within the namespace. This can be used as a basic form of non-volatile storage of entity data. Depending on the configuration of the namespace, this function can be setup to constantly be running automatically or only when AD shutdown. This function also allows for users to manually execute the command as when needed.

Parameters:

**kwargs (optional) – Zero or more keyword arguments.

Keyword Arguments:

namespace (str, optional) – Namespace to use for the call. See the section on namespaces for a detailed description. In most cases it is safe to ignore this parameter.

Returns:

None.

Examples

Save all entities of the default namespace.

>>> self.save_namespace()

Services

Note: A service call always uses the app’s default namespace. Although namespaces allow a new and easy way to work with multiple namespaces from within a single App, it is essential to understand how they work before using them in service’s calls. See the section on namespaces for a detailed description.

AppDaemon has a predefined list of namespaces that can be used only for particular services. Listed below are the services by namespace.

admin namespace only:

app/create

Used to create a new app. For this service to be used, the module must be existing and provided with the module’s class. If no app name is given, the module name will be used as the app’s name by default. The service call also accepts app_file if wanting to create the app within a certain yaml file. Or app_dir, if wanting the created app’s yaml file within a certain directory. If no file or directory is given, by default the app yaml file will be generated in a directory ad_apps, using the app’s name. It should be noted that app_dir and app_file when specified, will be created within the AD’s apps directory.

data = {}
data["module"] = "web_app"
data["class"] = "WebApp"
data["namespace"] = "admin"
data["app"] = "web_app3"
data["endpoint"] = "endpoint3"
data["app_dir"] = "web_apps"
data["app_file"] = "web_apps.yaml"

self.call_service("app/create", **data)

app/edit

Used to edit an existing app. This way, an app’ args can be edited in realtime with new args

>>> self.call_service("app/edit", app="light_app", module="light_system", namespace="admin")

app/remove

Used to remove an existing app. This way, an existing app will be deleted. If the app is the last app in the yaml file, the file will be deleted

>>> self.call_service("app/remove", app="light_app", namespace="admin")

app/start

Starts an app that has been terminated. The app name arg is required.

>>> self.call_service("app/start", app="light_app", namespace="admin")

app/stop

Stops a running app. The app name arg is required.

>>> self.call_service("app/stop", app="light_app", namespace="admin")

app/restart

Restarts a running app. This service basically stops and starts the app. The app name arg is required.

>>> self.call_service("app/restart", app="light_app", namespace="admin")

app/reload

Checks for an app update. Useful if AD is running in production mode, and app changes need to be checked and loaded.

>>> self.call_service("app/reload", namespace="admin")

app/enable

Enables a disabled app, so it can be loaded by AD.

>>> self.call_service("app/enable", app="living_room_app", namespace="admin")

app/disable

Disables an enabled app, so it cannot be loaded by AD. This service call is persistent, so even if AD restarts, the app will not be restarted

>>> self.call_service("app/disable", app="living_room_app", namespace="admin")

production_mode/set

Sets the production mode AD is running on. The value of the mode arg has to be True or False.

>>> self.call_service("production_mode/set", mode=True, namespace="admin")

All namespaces except global, and admin:

state/add_entity

Adds an existing entity to the required namespace.

>>> self.call_service("state/set", entity_id="sensor.test", state="on", attributes={"friendly_name" : "Sensor Test"}, namespace="default")

state/set

Sets the state of an entity. This service allows any key-worded args to define what entity’s values need to be set.

>>> self.call_service("state/set", entity_id="sensor.test", state="on", attributes={"friendly_name" : "Sensor Test"}, namespace="default")

state/remove_entity

Removes an existing entity from the required namespace.

>>> self.call_service("state/remove_entity", entity_id="sensor.test", namespace="default")

All namespaces except admin:

event/fire

Fires an event within the specified namespace. The event arg is required.

>>> self.call_service("event/fire", event="test_event", entity_id="appdaemon.test", namespace="hass")

rules namespace only:

sequence/run

Runs a predefined sequence. The entity_id arg with the sequence full-qualified entity name is required.

>>> self.call_service("sequence/run", entity_id ="sequence.christmas_lights", namespace="rules")

sequence/cancel

Cancels a predefined sequence. The entity_id arg with the sequence full-qualified entity name is required.

>>> self.call_service("sequence/cancel", entity_id ="sequence.christmas_lights", namespace="rules")

Threading

appdaemon.adapi.ADAPI.set_app_pin(self, pin: bool) None

Sets an App to be pinned or unpinned.

Parameters:

pin (bool) – Sets whether the App becomes pinned or not.

Returns:

None.

Examples

The following line should be put inside the initialize() function.

>>> self.set_app_pin(True)
appdaemon.adapi.ADAPI.get_app_pin(self) bool

Finds out if the current App is currently pinned or not.

Returns:

True if the App is pinned, False otherwise.

Return type:

bool

Examples

>>> if self.get_app_pin(True):
>>>     self.log("App pinned!")
appdaemon.adapi.ADAPI.set_pin_thread(self, thread: int) None

Sets the thread that the App will be pinned to.

Parameters:

thread (int) – Number of the thread to pin to. Threads start at 0 and go up to the number of threads specified in appdaemon.yaml -1.

Returns:

None.

Examples

The following line should be put inside the initialize() function.

>>> self.set_pin_thread(5)
appdaemon.adapi.ADAPI.get_pin_thread(self) int

Finds out which thread the App is pinned to.

Returns:

The thread number or -1 if the App is not pinned.

Return type:

int

Examples

>>> thread = self.get_pin_thread():
>>> self.log(f"I'm pinned to thread: {thread}")

Async

appdaemon.adapi.ADAPI.create_task(self, coro: Callable, callback=None, **kwargs) Future

Schedules a Coroutine to be executed.

Parameters:
  • coro – The coroutine object (not coroutine function) to be executed.

  • callback – The non-async callback to be executed when complete.

  • **kwargs (optional) – Any additional keyword arguments to send the callback.

Returns:

A Future, which can be cancelled by calling f.cancel().

Examples

>>> f = self.create_task(asyncio.sleep(3), callback=self.coro_callback)
>>>
>>> def coro_callback(self, kwargs):
async appdaemon.adapi.ADAPI.run_in_executor(self, func: Callable, *args, **kwargs) Callable
Runs a Sync function from within an Async function using Executor threads.

The function is actually awaited during execution

Parameters:
  • func – The function to be executed.

  • *args (optional) – Any additional arguments to be used by the function

  • **kwargs (optional) – Any additional keyword arguments to be used by the function

Returns:

None

Examples

>>> await self.run_in_executor(self.run_request)
async appdaemon.adapi.ADAPI.sleep(delay: float, result=None) None

Pause execution for a certain time span (not available in sync apps)

Parameters:
  • delay (float) – Number of seconds to pause.

  • result (optional) – Result to return upon delay completion.

Returns:

Result or None.

Notes

This function is not available in sync apps.

Examples

>>> async def myfunction(self):
>>>     await self.sleep(5)

Utility

appdaemon.adapi.ADAPI.get_app(self, name: str) Callable

Gets the instantiated object of another app running within the system.

This is useful for calling functions or accessing variables that reside in different apps without requiring duplication of code.

Parameters:

name (str) – Name of the app required. This is the name specified in header section of the config file, not the module or class.

Returns:

An object reference to the class.

Examples

>>> MyApp = self.get_app("MotionLights")
>>> MyApp.turn_light_on()
appdaemon.adapi.ADAPI.get_ad_version() str

Returns a string with the current version of AppDaemon.

Examples

>>> version = self.get_ad_version()
appdaemon.adapi.ADAPI.entity_exists(self, entity_id: str, **kwargs: Any | None) bool

Checks the existence of an entity in AD.

When working with multiple AD namespaces, it is possible to specify the namespace, so that it checks within the right namespace in in the event the app is working in a different namespace. Also when using this function, it is also possible to check if an AppDaemon entity exists.

Parameters:
  • entity_id (str) – The fully qualified entity id (including the device type).

  • **kwargs (optional) – Zero or more keyword arguments.

Keyword Arguments:

namespace (str, optional) – Namespace to use for the call. See the section on namespaces for a detailed description. In most cases it is safe to ignore this parameter.

Returns:

True if the entity id exists, False otherwise.

Return type:

bool

Examples

Check if the entity light.living_room exist within the app’s namespace

>>> if self.entity_exists("light.living_room"):
>>>     #do something

Check if the entity mqtt.security_settings exist within the mqtt namespace if the app is operating in a different namespace like default

>>> if self.entity_exists("mqtt.security_settings", namespace = "mqtt"):
>>>    #do something
appdaemon.adapi.ADAPI.split_entity(self, entity_id: str, **kwargs) list

Splits an entity into parts.

This utility function will take a fully qualified entity id of the form light.hall_light and split it into 2 values, the device and the entity, e.g. light and hall_light.

Parameters:
  • entity_id (str) – The fully qualified entity id (including the device type).

  • **kwargs (optional) – Zero or more keyword arguments.

Keyword Arguments:

namespace (str, optional) – Namespace to use for the call. See the section on namespaces for a detailed description. In most cases it is safe to ignore this parameter.

Returns:

A list with 2 entries, the device and entity respectively.

Examples

Do some action if the device of the entity is scene.

>>> device, entity = self.split_entity(entity_id)
>>> if device == "scene":
>>>     #do something specific to scenes
appdaemon.adapi.ADAPI.remove_entity(self, entity_id: str, **kwargs) None

Deletes an entity created within a namespaces.

If an entity was created, and its deemed no longer needed, by using this function, the entity can be removed from AppDaemon permanently.

Parameters:
  • entity_id (str) – The fully qualified entity id (including the device type).

  • **kwargs (optional) – Zero or more keyword arguments.

Keyword Arguments:

namespace (str, optional) – Namespace to use for the call. See the section on namespaces for a detailed description. In most cases it is safe to ignore this parameter.

Returns:

None.

Examples

Delete the entity in the present namespace.

>>> self.remove_entity('sensor.living_room')

Delete the entity in the mqtt namespace.

>>> self.remove_entity('mqtt.living_room_temperature', namespace = 'mqtt')
appdaemon.adapi.ADAPI.split_device_list(devices: str) list

Converts a comma-separated list of device types to an iterable list.

This is intended to assist in use cases where the App takes a list of entities from an argument, e.g., a list of sensors to monitor. If only one entry is provided, an iterable list will still be returned to avoid the need for special processing.

Parameters:

devices (str) – A comma-separated list of devices to be split (without spaces).

Returns:

A list of split devices with 1 or more entries.

Examples

>>> for sensor in self.split_device_list(self.args["sensors"]):
>>>    #do something for each sensor, e.g., make a state subscription
appdaemon.adapi.ADAPI.get_plugin_config(self, **kwargs) Any

Gets any useful metadata that the plugin may have available.

For instance, for the HASS plugin, this will return Home Assistant configuration data such as latitude and longitude.

Parameters:

**kwargs (optional) – Zero or more keyword arguments.

Keyword Arguments:

namespace (str) – Select the namespace of the plugin for which data is desired.

Returns:

A dictionary containing all the configuration information available from the Home Assistant /api/config endpoint.

Examples

>>> config = self.get_plugin_config()
>>> self.log(f'My current position is {config["latitude"]}(Lat), {config["longitude"]}(Long)')
My current position is 50.8333(Lat), 4.3333(Long)
appdaemon.adapi.ADAPI.friendly_name(self, entity_id: str, **kwargs) str

Gets the Friendly Name of an entity.

Parameters:
  • entity_id (str) – The fully qualified entity id (including the device type).

  • **kwargs (optional) – Zero or more keyword arguments.

Keyword Arguments:

namespace (str, optional) – Namespace to use for the call. See the section on namespaces for a detailed description. In most cases it is safe to ignore this parameter.

Returns:

The friendly name of the entity if it exists or the entity id if not.

Return type:

str

Examples

>>> tracker = "device_tracker.andrew"
>>> friendly_name = self.friendly_name(tracker)
>>> tracker_state = self.get_tracker_state(tracker)
>>> self.log(f"{tracker}  ({friendly_name}) is {tracker_state}.")
device_tracker.andrew (Andrew Tracker) is on.
appdaemon.adapi.ADAPI.set_production_mode(self, mode=True) bool

Deactivates or activates the production mode in AppDaemon.

When called without declaring passing any arguments, mode defaults to True.

Parameters:

mode (bool) – If it is True the production mode is activated, or deactivated otherwise.

Returns:

The specified mode or None if a wrong parameter is passed.

appdaemon.adapi.ADAPI.start_app(self, app: str, **kwargs) None

Starts an App which can either be running or not.

This Api call cannot start an app which has already been disabled in the App Config. It essentially only runs the initialize() function in the app, and changes to attributes like class name or app config is not taken into account.

Parameters:
  • app (str) – Name of the app.

  • **kwargs (optional) – Zero or more keyword arguments.

Returns:

None.

Examples

>>> self.start_app("lights_app")
appdaemon.adapi.ADAPI.stop_app(self, app: str, **kwargs) None

Stops an App which is running.

Parameters:
  • app (str) – Name of the app.

  • **kwargs (optional) – Zero or more keyword arguments.

Returns:

None.

Examples

>>> self.stop_app("lights_app")
appdaemon.adapi.ADAPI.restart_app(self, app: str, **kwargs) None

Restarts an App which can either be running or not.

Parameters:
  • app (str) – Name of the app.

  • **kwargs (optional) – Zero or more keyword arguments.

Returns:

None.

Examples

>>> self.restart_app("lights_app")
appdaemon.adapi.ADAPI.reload_apps(self, **kwargs) None

Reloads the apps, and loads up those that have changes made to their .yaml or .py files.

This utility function can be used if AppDaemon is running in production mode, and it is needed to reload apps that changes have been made to.

Parameters:

**kwargs (optional) – Zero or more keyword arguments.

Returns:

None.

Examples

>>> self.reload_apps()

Dialogflow

appdaemon.adapi.ADAPI.get_dialogflow_intent(self, data: dict) Any | None

Gets the intent’s action from the Google Home response.

Parameters:

data – Response received from Google Home.

Returns:

A string representing the Intent from the interaction model that was requested, or None, if no action was received.

Examples

>>> intent = ADAPI.get_dialogflow_intent(data)
appdaemon.adapi.ADAPI.get_dialogflow_slot_value(data, slot=None) Any | None

Gets slots’ values from the interaction model.

Parameters:
  • data – Response received from Google Home.

  • slot (str) – Name of the slot. If a name is not specified, all slots will be returned as a dictionary. If a name is specified but is not found, None will be returned.

Returns:

A string representing the value of the slot from the interaction model, or a hash of slots.

Examples

>>> beer_type = ADAPI.get_dialogflow_intent(data, "beer_type")
>>> all_slots = ADAPI.get_dialogflow_intent(data)
appdaemon.adapi.ADAPI.format_dialogflow_response(self, speech=None) Any | None

Formats a response to be returned to Google Home, including speech.

Parameters:

speech (str) – The text for Google Home to say.

Returns:

None.

Examples

>>> ADAPI.format_dialogflow_response(speech = "Hello World")

Alexa

appdaemon.adapi.ADAPI.get_alexa_intent(data: dict) str | None

Gets the Intent’s name from the Alexa response.

Parameters:

data – Response received from Alexa.

Returns:

A string representing the Intent’s name from the interaction model that was requested, or None, if no Intent was received.

Examples

>>> intent = ADAPI.get_alexa_intent(data)
appdaemon.adapi.ADAPI.get_alexa_slot_value(data, slot=None) str | None

Gets values for slots from the interaction model.

Parameters:
  • data – The request data received from Alexa.

  • slot – Name of the slot. If a name is not specified, all slots will be returned as a dictionary. If a name is specified but is not found, None will be returned.

Returns:

A string representing the value of the slot from the interaction model, or a hash of slots.

Examples

>>> beer_type = ADAPI.get_alexa_intent(data, "beer_type")
>>> all_slots = ADAPI.get_alexa_intent(data)
appdaemon.adapi.ADAPI.format_alexa_response(speech=None, card=None, title=None) dict

Formats a response to be returned to Alex including speech and a card.

Parameters:
  • speech (str) – The text for Alexa to say.

  • card (str) – Text for the card.

  • title (str) – Title for the card.

Returns:

None.

Examples

>>> ADAPI.format_alexa_response(speech = "Hello World", card = "Greetings to the world", title = "Hello")
appdaemon.adapi.ADAPI.get_alexa_error(data: dict) str | None

Gets the error message from the Alexa API response.

Parameters:

data – Response received from the Alexa API .

Returns:

A string representing the value of message, or None if no error message was received.

API

appdaemon.adapi.ADAPI.register_endpoint(self, callback: Callable[[Any, dict], Any], endpoint: str = None, **kwargs: Any | None) str

Registers an endpoint for API calls into the current App.

Parameters:
  • callback – The function to be called when a request is made to the named endpoint.

  • endpoint (str, optional) – The name of the endpoint to be used for the call (Default: None).

  • endpoints (This must be unique across all)

  • given (and when not)

  • endpoint. (the name of the app is used as the)

  • instance. (It is possible to register multiple endpoints to a single app)

Keyword Arguments:

**kwargs (optional) – Zero or more keyword arguments.

Returns:

A handle that can be used to remove the registration.

Examples

It should be noted that the register function, should return a string (can be empty), and an HTTP OK status response (e.g., 200. If this is not added as a returned response, the function will generate an error each time it is processed. If the POST request contains JSON data, the decoded data will be passed as the argument to the callback. Otherwise the callback argument will contain the query string. A request kwarg contains the http request object.

>>> self.register_endpoint(self.my_callback)
>>> self.register_endpoint(self.alexa_cb, "alexa")
>>> async def alexa_cb(self, json_obj, kwargs):
>>>     self.log(json_obj)
>>>     response = {"message": "Hello World"}
>>>     return response, 200
appdaemon.adapi.ADAPI.deregister_endpoint(self, handle: str) None

Removes a previously registered endpoint.

Parameters:

handle – A handle returned by a previous call to register_endpoint

Returns:

None.

Examples

>>> self.deregister_endpoint(handle)

WebRoute ~~~

appdaemon.adapi.ADAPI.register_route(self, callback: Callable[[Any, dict], Any], route: str = None, **kwargs: Any | None) str
Registers a route for Web requests into the current App.

By registering an app web route, this allows to make use of AD’s internal web server to serve web clients. All routes registered using this api call, can be accessed using http://AD_IP:Port/app/route.

Parameters:
  • callback – The function to be called when a request is made to the named route. This must be an async function

  • route (str, optional) – The name of the route to be used for the request (Default: the app’s name).

Keyword Arguments:

**kwargs (optional) – Zero or more keyword arguments.

Returns:

A handle that can be used to remove the registration.

Examples

It should be noted that the register function, should return a aiohttp Response.

>>> from aiohttp import web
>>> def initialize(self):
>>>   self.register_route(my_callback)
>>>   self.register_route(stream_cb, "camera")
>>>
>>> async def camera(self, request, kwargs):
>>>   return web.Response(text="test", content_type="text/html")
appdaemon.adapi.ADAPI.deregister_route(self, handle: str) None

Removes a previously registered app route.

Parameters:

handle – A handle returned by a previous call to register_app_route

Returns:

None.

Examples

>>> self.deregister_route(handle)

Other

appdaemon.adapi.ADAPI.run_in_thread(self, callback: Callable, thread: int, **kwargs) None

Schedules a callback to be run in a different thread from the current one.

Parameters:
  • callback – Function to be run on the new thread.

  • thread (int) – Thread number (0 - number of threads).

  • **kwargs – Arbitrary keyword parameters to be provided to the callback function when it is invoked.

Returns:

None.

Examples

>>> self.run_in_thread(my_callback, 8)
appdaemon.adapi.ADAPI.submit_to_executor(self, func: Callable, *args, **kwargs) Future
Submits a Sync function from within another Sync function to be executed using Executor threads.

The function is not waited to be executed. As it submits and continues the rest of the code. This can be useful if wanting to execute a long running code, and don’t want it to hold up the thread for other callbacks.

Parameters:
  • func – The function to be executed.

  • *args (optional) – Any additional arguments to be used by the function

  • **kwargs (optional) – Any additional keyword arguments to be used by the function.

  • callback (Part of the keyword arguments will be the)

  • execution (which will be ran when the function has completed)

Returns:

A Future, which can be cancelled by calling f.cancel().

Examples

>>>
>>> def state_cb(self, *args, **kwargs): # callback from an entity
>>>     # need to run a 30 seconds task, so need to free up the thread
>>>     # need to get results, so will pass a callback for it
>>>     # callback can be ignored, if the result is not needed
>>>     f = self.submit_to_executor(self.run_request, url, callback=self.result_callback)
>>>
>>> def run_request(self, url): # long running function
>>>     import requests
>>>     res = requests.get(url)
>>>     return res.json()
>>>
>>> def result_callback(self, kwargs):
>>>     result = kwargs["result"]
>>>     self.set_state("sensor.something", state="ready", attributes=result, replace=True) # picked up by another app
>>>     # <other processing that is needed>
appdaemon.adapi.ADAPI.get_thread_info(self) Any

Gets information on AppDaemon worker threads.

Returns:

A dictionary containing all the information for AppDaemon worker threads.

Examples

>>> thread_info = self.get_thread_info()
appdaemon.adapi.ADAPI.get_scheduler_entries(self)

Gets information on AppDaemon scheduler entries.

Returns:

A dictionary containing all the information for entries in the AppDaemon scheduler.

Examples

>>> schedule = self.get_scheduler_entries()
appdaemon.adapi.ADAPI.get_callback_entries(self) list

Gets information on AppDaemon callback entries.

Returns:

A dictionary containing all the information for entries in the AppDaemon state, and event callback table.

Examples

>>> callbacks = self.get_callback_entries()
appdaemon.adapi.ADAPI.depends_on_module(self, *modules: str) None

Registers a global_modules dependency for an app.

Parameters:

*modules – Modules to register a dependency on.

Returns:

None.

Examples

>>> import somemodule
>>> import anothermodule
>>> # later
>>> self.depends_on_module([somemodule)