Skip to content

ADAPI

appdaemon.adbase

ADBase

app_config property writable

The full app configuration model for all the apps.

args instance-attribute

Dictionary of the app configuration

config = self.AD.config.model_dump(by_alias=True, exclude_unset=True) instance-attribute

Dictionary of the AppDaemon configuration

config_model property writable

The AppConfig model only for this app.

get_plugin_api(plugin_name) async

Get the plugin API for a specific plugin.

appdaemon.adapi

ADAPI

AppDaemon API class.

This class includes all native API calls to AppDaemon

AD = ad instance-attribute

Reference to the top-level AppDaemon container object

app_config instance-attribute

Dict of the full config for all apps. This meant to be read-only, and modifying it won't affect any behavior.

app_dir property writable

Top-level path to where AppDaemon looks for user's apps. Defaults to ./apps relative to the config directory, but can be overridden in appdaemon.app_dir in the appdaemon.yaml file.

args instance-attribute

Dict of this app's configuration. This meant to be read-only, and modifying it won't affect any behavior.

config instance-attribute

Dict of the AppDaemon configuration. This meant to be read-only, and modifying it won't affect any behavior.

config_dir property writable

Directory that contains the appdaemon.yaml file.

config_model property writable

The AppConfig model only for this app.

global_vars property writable

Globally locked attribute that can be used to share data between apps.

name property writable

The name for the app, as defined by it's key in the corresponding YAML file.

add_entity(entity_id, state, attributes=None, namespace=None) async

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

If an entity doesn't exists and needs to be created, this function can be used to create it locally. Please note this only creates the entity locally.

Parameters:

Name Type Description Default
entity_id str

The fully qualified entity id (including the device type).

required
state str

The state the entity is to have

required
attributes dict

The attributes the entity is to have

None
namespace str

Namespace to use for the call. See the section on namespaces <APPGUIDE.html#namespaces>__ for a detailed description. In most cases it is safe to ignore this parameter.

None

Returns:

Type Description
None

None.

Examples:

Add the entity in the present namespace.

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

adds the entity in the mqtt namespace.

>>> self.add_entity('mqtt.living_room_temperature', namespace='mqtt')

add_namespace(namespace, writeback='safe', persist=True) async

Add a user-defined namespace.

See the :py:ref:app_namespaces for more information.

Parameters:

Name Type Description Default
namespace str

The name of the new namespace to create

required
writeback optional

The writeback to be used. Defaults to safe, which writes every state change to disk. This can be problematic for namespaces that have a lot of state changes. Safe in this case refers data loss, rather than performance. The other option is hybrid, which buffers state changes.

'safe'
persist bool

Whether to make the namespace persistent. Persistent namespaces are stored in a database file and are reloaded when AppDaemon restarts. Defaults to True.

True

Returns:

Type Description
str | None

The file path to the newly created namespace. Will be None if not persistent.

Examples:

Create a namespace that buffers state changes in memory and periodically writes them to disk.

>>> self.add_namespace("on_disk", writeback="hybrid", persist=True)

Create an in-memory namespace that won't survive AppDaemon restarts.

>>> self.add_namespace("in_memory", persist=False)

call_service(service, namespace=None, timeout=-1, callback=None, **data) async

Calls a Service within AppDaemon.

Services represent specific actions, and are generally registered by plugins or provided by AppDaemon itself. The app calls the service only by referencing the service with a string in the format <domain>/<service>, so there is no direct coupling between apps and services. This allows any app to call any service, even ones from other plugins.

Services often require additional parameters, such as entity_id, which AppDaemon will pass to the service call as appropriate, if used when calling this function. This allows arbitrary data to be passed to the service calls.

Apps can also register their own services using their self.regsiter_service method.

Parameters:

Name Type Description Default
service str

The service name in the format <domain>/<service>. For example, light/turn_on.

required
namespace str

It's safe to ignore this parameter in most cases because the default namespace will be used. However, if a namespace is provided, the service call will be made in that namespace. If there's a plugin associated with that namespace, it will do the service call. If no namespace is given, AppDaemon will use the app's namespace, which can be set using the self.set_namespace method. See the section on namespaces <APPGUIDE.html#namespaces>__ for more information.

None
timeout str | int | float

The internal AppDaemon timeout for the service call. If no value is specified, the default timeout is 60s. The default value can be changed using the appdaemon.internal_function_timeout config setting.

-1
callback callable

The non-async callback to be executed when complete. It should accept a single argument, which will be the result of the service call. This is the recommended method for calling services which might take a long time to complete. This effectively bypasses the timeout argument because it only applies to this function, which will return immediately instead of waiting for the result if a callback is specified.

None
service_data dict

Used as an additional dictionary to pass arguments into the service_data field of the JSON that goes to Home Assistant. This is useful if you have a dictionary that you want to pass in that has a key like target which is otherwise used for the target argument.

required
**data Any

Any other keyword arguments get passed to the service call as service_data. Each service takes different parameters, so this will vary from service to service. For example, most services require entity_id. The parameters for each service can be found in the actions tab of developer tools in the Home Assistant web interface.

{}

Returns:

Type Description
Any

Result of the call_service function if any, see

Any

service call notes <APPGUIDE.html#some-notes-on-service-calls>__ 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")
>>> events = 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",
    )["result"]["response"]["calendar.home"]["events"]

MQTT ^^^^

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

Utility ^^^^^^^

It's important that the namespace arg is set to admin for these services, as they do not exist within the default namespace, and apps cannot exist in the admin namespace. If the namespace is not specified, calling the method will raise an exception.

>>> self.call_service("app/restart", app="notify_app", namespace="admin")
>>> self.call_service("app/stop", app="lights_app", namespace="admin")
>>> self.call_service("app/reload", namespace="admin")

cancel_listen_event(handle, *, silent=False) async

cancel_listen_event(handle: str, *, silent: bool = False) -> bool
cancel_listen_event(handle: Iterable[str], *, silent: bool = False) -> dict[str, bool]

Cancel a callback for a specific event.

Parameters:

Name Type Description Default
handle (str, Iterable[str])

Handle(s) returned from a previous call to listen_event().

required
silent bool

If True, no warning will be issued if the handle is not found. Defaults to False. This is useful if you want to cancel a callback that may or may not exist.

False

Returns:

Type Description
bool | dict[str, bool]

A single boolean if a single handle is passed, or a dict mapping the handles to boolean values. Each boolean

bool | dict[str, bool]

value will be the result of canceling the corresponding handle.

Examples:

Cancel a single callback.

>>> self.cancel_listen_event(handle)
True

Cancel multiple callbacks.

>>> result = self.cancel_listen_event([handle1, handle2])
>>> all(result.values())  # Check if all handles were canceled successfully
True

cancel_listen_log(handle) async

Cancels the log callback for the App.

Parameters:

Name Type Description Default
handle str

The handle returned when the listen_log call was made.

required

Returns:

Type Description
None

Boolean.

Examples:

>>> self.cancel_listen_log(handle)

cancel_listen_state(handle, name=None, silent=False) async

Cancel a listen_state() callback.

This will prevent any further calls to the callback function. Other state callbacks will not be affected.

Parameters:

Name Type Description Default
handle str

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

required
name str

The name of the app that registered the callback. Defaults to the name of the current app. This is useful if you want to get the information of a callback registered by another app.

None
silent bool

If True, no warning will be issued if the handle is not found.

False

Returns:

Type Description
bool

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)

cancel_sequence(sequence) async

Cancel an already running AppDaemon Sequence.

Parameters:

Name Type Description Default
sequence str | list[str] | Future

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

required

Returns:

Type Description
None

None.

Examples:

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

cancel_timer(handle, silent=False) async

Cancel a previously created timer.

Parameters:

Name Type Description Default
handle str

The handle returned from the original call to create the timer.

required
silent bool

Set to True to suppress warnings if the handle is not found. Defaults to False.

False

Returns:

Type Description
bool

Boolean representing whether the timer was successfully canceled.

Examples:

>>> self.cancel_timer(handle)
True
>>> self.cancel_timer(handle, silent=True)

convert_utc(utc)

Gets a datetime object for the specified UTC.

Home Assistant provides timestamps of several different sorts that can 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:

Name Type Description Default
utc str

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

required

Returns:

Type Description
datetime

A localised Python datetime object representing the timestamp.

create_task(coro, callback=None, name=None, **kwargs) async

Wrap the coro coroutine into a Task and schedule its execution. Return the Task object.

Uses AppDaemon's internal event loop to run the task, so the task will be run in the same thread as the app. Running an async method like this is useful for long-running tasks because it bypasses the timeout that AppDaemon otherwise imposes on callbacks.

The callback will be run in the app's thread, like other AppDaemon callbacks, and will have the normal timeout imposed on it.

See creating tasks <https://docs.python.org/3/library/asyncio-task.html#creating-tasks>_ for in the python documentation for more information.

Parameters:

Name Type Description Default
coro Coroutine[Any, Any, T]

The coroutine object (not coroutine function) to be executed.

required
callback Callable | None

The non-async callback to be executed when complete.

None
**kwargs optional

Any additional keyword arguments to send the callback.

{}

Returns:

Type Description
Task[T]

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

Examples:

Define your callback

>>> def my_callback(self, **kwargs: Any) -> Any: ...

Create the task

>>> task = self.create_task(asyncio.sleep(3), callback=self.my_callback)

Keyword Arguments ^^^^^^^^^^^^^^^^^ Define your callback with a custom keyword argument my_kwarg

>>> def my_callback(self, result: Any, my_kwarg: str, **kwargs: Any) -> Any:
        self.log(f"Result: {result}, my_kwarg: {my_kwarg}")

Use the custom keyword argument when creating the task

>>> task = self.create_task(asyncio.sleep(3), callback=self.my_callback, my_kwarg="special value")

dash_navigate(target, timeout=-1, ret=None, sticky=0, deviceid=None, dashid=None, skin=None)

Forces all connected Dashboards to navigate to a new URL.

Parameters:

Name Type Description Default
target str

Name of the new Dashboard to navigate to (e.g., /SensorPanel). Note that this value is not a URL.

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

-1
ret str

Dashboard to return to after the timeout has elapsed.

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

0
deviceid str

If set, only the device which has the same deviceid will navigate.

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

None
skin str

If set, the skin will change to the skin defined on the param.

None

Returns:

Type Description
None

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")

date() async

Get a date object representing the current local date.

Use this instead of the standard Python methods in order to correctly account for the time when using the time travel feature, which is usually done for testing.

Examples:

>>> self.date()
2019-08-15

datetime(aware=False) async

Get a datetime object representing the current local date and time.

Use this instead of the standard Python methods in order to correctly account for the time when using the time travel feature, which is usually done for testing.

Parameters:

Name Type Description Default
aware bool

Whether the resulting datetime object will be aware of timezone.

False

Examples:

>>> self.datetime()
2019-08-15 20:15:55.549379

depends_on_module(*modules) async

Registers a global_modules dependency for an app.

Parameters:

Name Type Description Default
*modules list[str]

Modules to register a dependency on.

()

Returns:

Type Description
None

None.

Examples:

>>> import some_module
>>> import another_module
>>> # later
>>> self.depends_on_module('some_module')

deregister_endpoint(handle) async

Removes a previously registered endpoint.

Parameters:

Name Type Description Default
handle str

A handle returned by a previous call to register_endpoint

required

Returns:

Type Description
None

None.

Examples:

>>> self.deregister_endpoint(handle)

deregister_route(handle) async

Removes a previously registered app route.

Parameters:

Name Type Description Default
handle str

A handle returned by a previous call to register_app_route

required

Returns:

Type Description
None

None.

Examples:

>>> self.deregister_route(handle)

deregister_service(service, namespace=None)

Deregister a service that had been previously registered.

This will immediately remove the service from AppDaemon's internal service registry, which will make it unavailable to other apps using the call_service() API call, as well as published as a service in the REST API

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:

Name Type Description Default
service str

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

required
namespace str

Optional namespace to use. Defaults to using the app's current namespace. See the namespace documentation <APPGUIDE.html#namespaces>__ for more information.

None

Returns:

Type Description
bool

True if the service was successfully deregistered, False otherwise.

Examples:

>>> self.deregister_service("myservices/service1")

entity_exists(entity_id, namespace=None) async

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:

Name Type Description Default
entity_id str

The fully qualified entity id (including the device type).

required
namespace str

Namespace to use for the call. See the section on namespaces <APPGUIDE.html#namespaces>__ for a detailed description. In most cases it is safe to ignore this parameter.

None

Returns:

Name Type Description
bool bool

True if the entity id exists, False otherwise.

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

error(msg, *args, level='INFO', ascii_encode=True, stack_info=False, stacklevel=1, extra=None, **kwargs)

Logs a message to AppDaemon's error logfile.

Parameters:

Name Type Description Default
msg str

The message to log.

required
*args

Positional arguments for populating the msg fields

()
level str

String representing the standard logger levels. Defaults to INFO.

'INFO'
ascii_encode bool

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

True
stack_info bool

If True the stack info will included.

False
**kwargs

Keyword arguments

{}

Returns:

Type Description
None

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")

fire_event(event, namespace=None, timeout=-1, **kwargs) async

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

Parameters:

Name Type Description Default
event str

Name of the event. Can be a standard Home Assistant event such as service_registered or an arbitrary custom event such as "MODE_CHANGE".

required
namespace str

Namespace to use for the call. See the section on namespaces <APPGUIDE.html#namespaces>__ for a detailed description. In most cases, it is safe to ignore this parameter.

None
**kwargs optional

Zero or more keyword arguments that will be supplied as part of the event.

{}

Returns:

Type Description
None

None.

Examples:

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

format_alexa_response(speech=None, card=None, title=None) staticmethod

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

Parameters:

Name Type Description Default
speech str

The text for Alexa to say.

None
card str

Text for the card.

None
title str

Title for the card.

None

Returns:

Type Description
dict

None.

Examples:

>>> ADAPI.format_alexa_response(speech = "Hello World", card = "Greetings to the world", title = "Hello")

format_dialogflow_response(speech=None)

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

Parameters:

Name Type Description Default
speech str

The text for Google Home to say.

None

Returns:

Type Description
Any | None

None.

Examples:

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

friendly_name(entity_id, namespace=None) async

Gets the Friendly Name of an entity.

Parameters:

Name Type Description Default
entity_id str

The fully qualified entity id (including the device type).

required
namespace str

Namespace to use for the call. See the section on namespaces <APPGUIDE.html#namespaces>__ for a detailed description. In most cases it is safe to ignore this parameter.

None

Returns:

Name Type Description
str str | None

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

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.

get_ad_version() staticmethod

Returns a string with the current version of AppDaemon.

Examples:

>>> version = self.get_ad_version()

get_alexa_error(data) staticmethod

Gets the error message from the Alexa API response.

Parameters:

Name Type Description Default
data dict

Response received from the Alexa API.

required

Returns:

Type Description
str | None

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

get_alexa_intent(data) staticmethod

Gets the Intent's name from the Alexa response.

Parameters:

Name Type Description Default
data dict

Response received from Alexa.

required

Returns:

Type Description
str | None

A string representing the Intent's name from the interaction model that was requested,

str | None

or None, if no Intent was received.

Examples:

>>> intent = ADAPI.get_alexa_intent(data)

get_alexa_slot_value(data, slot=None) staticmethod

Gets values for slots from the interaction model.

Parameters:

Name Type Description Default
data

The request data received from Alexa.

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

None

Returns:

Type Description
str | None

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)

get_app(name) async

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 Type Description Default
name str

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

required

Returns:

Type Description
ADAPI

An object reference to the class.

Examples:

>>> MyApp = self.get_app("MotionLights")
>>> MyApp.turn_light_on()

get_app_pin() async

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

Returns:

Name Type Description
bool bool

True if the App is pinned, False otherwise.

Examples:

>>> if self.get_app_pin(True):
>>>     self.log("App pinned!")

get_app_python_dependencies(app_name=None)

Get a list of paths to python files that this app depends on, even indirectly. If any of the files for these modules change, the app will be reloaded.

Parameters:

Name Type Description Default
app_name str

Name of the app to get dependencies for. If not provided, uses the current app's name.

None

Returns:

Type Description
list[Path]

Sorted list of paths to Python files that the given app depends on.

get_callback_entries() async

Gets information on AppDaemon callback entries.

Returns:

Type Description
list

A dictionary containing all the information for entries in the AppDaemon state,

list

and event callback table.

Examples:

>>> callbacks = self.get_callback_entries()

get_dialogflow_intent(data)

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

Parameters:

Name Type Description Default
data dict

Response received from Google Home.

required

Returns:

Type Description
Any | None

A string representing the Intent from the interaction model that was requested,

Any | None

or None, if no action was received.

Examples:

>>> intent = ADAPI.get_dialogflow_intent(data)

get_dialogflow_slot_value(data, slot=None) staticmethod

Gets slots' values from the interaction model.

Parameters:

Name Type Description Default
data

Response received from Google Home.

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

None

Returns:

Type Description
Any | None

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)

get_error_log()

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)

get_main_log()

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")

get_namespace()

Get the app's current namespace.

See :py:ref:app_namespaces for more information.

get_now(aware=True) async

Returns the current Local Date and Time.

Examples:

>>> self.get_now()
2019-08-16 21:17:41.098813-04:00

get_now_ts(aware=False) async

Returns the current Local Timestamp.

Examples:

>>> self.get_now_ts()
1565990318.728324

get_pin_thread() async

Finds out which thread the App is pinned to.

Returns:

Name Type Description
int int

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

Examples:

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

get_plugin_config(namespace=None) async

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:

Name Type Description Default
namespace str

Select the namespace of the plugin for which data is desired.

None

Returns:

Type Description
Any

A dictionary containing all the configuration information available

Any

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)

get_scheduler_entries() async

Gets information on AppDaemon scheduler entries.

Returns:

Type Description

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

Examples:

>>> schedule = self.get_scheduler_entries()

get_state(entity_id=None, attribute=None, default=None, namespace=None, copy=True, **kwargs) async

Get the state of an entity from AppDaemon's internals.

Home Assistant emits a state_changed event for every state change, which it sends to AppDaemon over the websocket connection made by the plugin. Appdaemon uses the data in these events to update its internal state. This method returns values from this internal state, so it does not make any external requests to Home Assistant.

Other plugins that emit state_changed events will also have their states tracked internally by AppDaemon.

It's common for entities to have a state that's always one of on, off, or unavailable. This applies to entities in the light, switch, binary_sensor, and input_boolean domains in Home Assistant, among others.

Parameters:

Name Type Description Default
entity_id str

Full entity ID or just a domain. If a full entity ID is provided, the result will be for that entity only. If a domain is provided, the result will be a dict that maps the entity IDs to their respective results.

None
attribute str

Optionally specify an attribute to return. If not used, the state of the entity will be returned. The value all can be used to return the entire state dict rather than a single value.

None
default any

The value to return when the entity or the attribute doesn't exist.

None
namespace str

Optional namespace to use. Defaults to using the app's current namespace. The current namespace can be changed using self.set_namespace. See the namespace documentation <APPGUIDE.html#namespaces>__ for more information.

None
copy bool

Whether to return a copy of the internal data. This is True by default in order to protect the user from accidentally modifying AppDaemon's internal data structures, which is dangerous and can cause undefined behavior. Only set this to False for read-only operations.

True

Returns:

Type Description
Any | dict[str, Any] | None

The state or attribute of the entity ID provided or a dict of that maps entity IDs to their respective

Any | dict[str, Any] | None

results. If called with no parameters, this will return the entire state dict.

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")

get_thread_info() async

Gets information on AppDaemon worker threads.

Returns:

Type Description
Any

A dictionary containing all the information for AppDaemon worker threads.

Examples:

>>> thread_info = self.get_thread_info()

get_timezone()

Returns the current time zone.

get_tz_offset()

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

get_user_log(log)

Gets the specified-user logger of the App.

Parameters:

Name Type Description Default
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.

required

Returns:

Type Description
Logger

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)

info_listen_event(handle) async

Gets information on an event callback from its handle.

Parameters:

Name Type Description Default
handle str

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

required

Returns:

Type Description
bool

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

Examples:

>>> service, kwargs = self.info_listen_event(handle)

info_listen_state(handle, name=None) async

Get information on state a callback from its handle.

Parameters:

Name Type Description Default
handle str

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

required
name str

The name of the app that registered the callback. Defaults to the name of the current app. This is useful if you want to get the information of a callback registered by another app.

None

Returns:

Type Description
str

The values supplied for namespace, entity, attribute, and kwargs when

str

the callback was initially created.

Examples:

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

info_timer(handle) async

Get information about a previously created timer.

Parameters:

Name Type Description Default
handle str

The handle returned from the original call to create the timer.

required

Returns:

Type Description
tuple[datetime, int, dict] | None

A tuple with the following values or None if handle is invalid or timer no longer exists.

tuple[datetime, int, dict] | None
  • time - datetime object representing the next time the callback will be fired
tuple[datetime, int, dict] | None
  • interval - repeat interval if applicable, 0 otherwise.
tuple[datetime, int, dict] | None
  • kwargs - the values supplied when the callback was initially created.

Examples:

>>> if (info := self.info_timer(handle)) is not None:
>>>     time, interval, kwargs = info

list_namespaces() async

Get a list of all the namespaces in AppDaemon.

Examples:

>>> self.list_namespaces()

list_services(namespace='global')

List all services available within AppDaemon

Parameters:

Name Type Description Default
namespace str

Optional namespace to use. The default is flobal, which will return services across all namespaces. See the namespace documentation <APPGUIDE.html#namespaces>__ for more information.

'global'

Returns:

Type Description
list[dict[str, str]]

List of dicts with keys namespace, domain, and service.

Examples:

>>> services = self.list_services()
>>> services = self.list_services("default")
>>> services = self.list_services("mqtt")

listen_event(callback, event=None, *, namespace=None, timeout=None, oneshot=False, pin=None, pin_thread=None, **kwargs) async

listen_event(callback: EventCallback, event: str | None = None, *, namespace: str | None = None, timeout: str | int | float | timedelta | None = None, oneshot: bool = False, pin: bool | None = None, pin_thread: int | None = None, **kwargs: Any | Callable[[Any], bool]) -> str
listen_event(callback: EventCallback, event: list[str], *, namespace: str | None = None, timeout: str | int | float | timedelta | None = None, oneshot: bool = False, pin: bool | None = None, pin_thread: int | None = None, **kwargs: Any | Callable[[Any], bool]) -> list[str]

Register a callback for a specific event, multiple events, or any event.

The callback needs to have the following form:

def my_callback(self, event_name: str, event_data: dict[str, Any], **kwargs: Any) -> None: ...

Parameters:

Name Type Description Default
callback EventCallback

Function that will be called when the event is fired. It must conform to the standard event callback format documented here <APPGUIDE.html#event-callbacks>__

required
event str | list[str]

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.

None
namespace str

Optional namespace to use. Defaults to using the app's current namespace. The value global will register the callback for all namespaces. See the namespace documentation <APPGUIDE.html#namespaces>__ for more information.

None
timeout (str, int, float, timedelta)

If supplied, the callback will be created as normal, but the callback will be removed after the timeout.

None
oneshot bool

If True, the callback will be automatically cancelled after the first state change that results in a callback. Defaults to False.

False
pin bool

Optional setting to override the default thread pinning behavior. By default, this is effectively True, and pin_thread gets set when the app starts.

None
pin_thread int

Specify which thread from the worker pool will run the callback. The threads each have an ID number. The ID numbers start at 0 and go through (number of threads - 1).

None
**kwargs optional

One or more keyword value pairs representing app-specific parameters to supply to the callback. If the event has data that matches one of these keywords, it will be filtered by the value passed in with this function. This means that if the value in the event data does not match, the callback will not be called. 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.

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:

Type Description
str | list[str]

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"])

listen_log(callback, level='INFO', namespace='admin', log=None, pin=None, pin_thread=None, **kwargs) async

Register a callback for whenever an app logs a message.

Parameters:

Name Type Description Default
callback Callable

Function that will be called when a message is logged. It must conform to the standard event callback format documented here <APPGUIDE.html#event-callbacks>__

required
level str

Minimum level for logs to trigger the callback. Lower levels will be ignored. Default is INFO.

'INFO'
namespace str

Namespace to use for the call. Defaults to admin for log callbacks. See the namespace documentation <APPGUIDE.html#namespaces>__ for more information.

'admin'
log str

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.

None
pin bool

Optional setting to override the default thread pinning behavior. By default, this is effectively True, and pin_thread gets set when the app starts.

None
pin_thread int

Specify which thread from the worker pool will run the callback. The threads each have an ID number. The ID numbers start at 0 and go through (number of threads - 1).

None
**kwargs optional

One or more keyword arguments to supply to the callback.

{}

Returns:

Type Description
list[str] | None

A handle that can be used to cancel the callback.

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")

listen_state(callback, entity_id=None, namespace=None, new=None, old=None, duration=None, attribute=None, timeout=None, immediate=False, oneshot=False, pin=None, pin_thread=None, **kwargs) async

listen_state(callback: StateCallbackType, entity_id: str | None, namespace: str | None = None, new: str | Callable[[Any], bool] | None = None, old: str | Callable[[Any], bool] | None = None, duration: str | int | float | timedelta | None = None, attribute: str | None = None, timeout: str | int | float | timedelta | None = None, immediate: bool = False, oneshot: bool = False, pin: bool | None = None, pin_thread: int | None = None, **kwargs: Any) -> str
listen_state(callback: StateCallbackType, entity_id: Iterable[str], namespace: str | None = None, new: str | Callable[[Any], bool] | None = None, old: str | Callable[[Any], bool] | None = None, duration: str | int | float | timedelta | None = None, attribute: str | None = None, timeout: str | int | float | timedelta | None = None, immediate: bool = False, oneshot: bool = False, pin: bool | None = None, pin_thread: int | None = None, **kwargs: Any) -> list[str]

Registers a callback to react to state changes.

The callback needs to have the following form:

def my_callback(self, entity: str, attribute: str, old: Any, new: Any, **kwargs: Any) -> None: ...

Parameters:

Name Type Description Default
callback StateCallbackType

Function that will be called when the callback gets triggered. It must conform to the standard state callback format documented here <APPGUIDE.html#state-callbacks>__

required
entity_id str | Iterable[str]

Entity ID or a domain. If a domain is provided, e.g., light, or binary_sensor the callback will be triggered for state changes of any entities in that domain. If a list of entities is provided, the callback will be registered for each of those entities.

None
namespace str

Optional namespace to use. Defaults to using the app's current namespace. See the namespace documentation <APPGUIDE.html#namespaces>__ for more information. Using the value global will register the callback for all namespaces.

None
new str | Callable[[Any], bool]

If given, the callback will only be invoked if the state of the selected attribute (usually state) matches this value in the new data. The data type is dependent on the specific entity and attribute. Values that look like ints or floats are often actually strings, so be careful when comparing them. The self.get_state() method is useful for checking the data type of the desired attribute. If new is a callable (lambda, function, etc), then it will be called with the new state, and the callback will only be invoked if the callable returns True.

None
old str | Callable[[Any], bool]

If given, the callback will only be invoked if the selected attribute (usually state) changed from this value in the new data. The data type is dependent on the specific entity and attribute. Values that look like ints or floats are often actually strings, so be careful when comparing them. The self.get_state() method is useful for checking the data type of the desired attribute. If old is a callable (lambda, function, etc), then it will be called with the old state, and the callback will only be invoked if the callable returns True.

None
duration str | int | float | timedelta

If supplied, the callback will not be invoked unless the desired state is maintained for that amount of time. This requires that a specific attribute is specified (or the default of state is used), and should be used in conjunction with either or both of the new and old parameters. 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.

None
attribute str

Optional name of an attribute to use for the new/old checks. If not specified, the default behavior is to use the value of state. Using the value all will cause the callback to get triggered for any change in state, and the new/old values used for the callback will be the entire state dict rather than the individual value of an attribute.

None
timeout str | int | float | timedelta

If given, the callback will be automatically removed after that amount of time. 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 removed.

None
immediate bool

If given, it enables the countdown for a delay parameter to start at the time. 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.

False
oneshot bool

If True, the callback will be automatically removed after the first time it gets invoked.

False
pin bool

Optional setting to override the default thread pinning behavior. By default, this is effectively True, and pin_thread gets set when the app starts.

None
pin_thread int

Specify which thread from the worker pool will run the callback. The threads each have an ID number. The ID numbers start at 0 and go through (number of threads - 1).

None
**kwargs Any

Arbitrary keyword parameters to be provided to the callback function when it is triggered.

{}
Note

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

Returns:

Type Description
str | list[str]

A string that uniquely identifies the callback and can be used to cancel it later if necessary. Since

str | list[str]

variables created within object methods are local to the function they are created in, it's recommended to

str | list[str]

store the handles in the app's instance variables, 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.lower() 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")

log(msg, *args, level='INFO', log=None, ascii_encode=None, stack_info=False, stacklevel=1, extra=None, **kwargs)

Logs a message to AppDaemon's main logfile.

Parameters:

Name Type Description Default
msg str

The message to log.

required
level str

String representing the standard logger levels. Defaults to INFO.

'INFO'
log str

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.

None
ascii_encode bool

Switch to disable the encoding of all log messages to ascii. Set this to false if you want to log UTF-8 characters (Default is controlled by appdaemon.ascii_encode, and is True unless modified).

None
stack_info bool

If True the stack info will included.

False
stacklevel int

Defaults to 1.

1
extra dict

Extra values to add to the log record

None

Returns:

Type Description
None

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)

namespace_exists(namespace) async

Check for the existence of a namespace.

See :py:ref:app_namespaces for more information.

Parameters:

Name Type Description Default
namespace str

The namespace to check for.

required

Returns:

Name Type Description
bool bool

True if the namespace exists, otherwise False.

now_is_between(start_time, end_time, name=None, now=None) async

Determine 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:

Name Type Description Default
start_time str

A string representation of the start time.

required
end_time str

A string representation of the end time.

required
name str

Name of the calling app or module. It is used only for logging purposes.

None
now str

If specified, now is used as the time for comparison instead of the current time. Useful for testing.

None

Returns:

Name Type Description
bool bool

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

Note

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

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

parse_datetime(time_str, name=None, aware=False, today=None, days_offset=0) async

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:

Name Type Description Default
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.

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

required
name str

Name of the calling app or module. It is used only for logging purposes.

None
aware bool

If True the created datetime object will be aware of timezone.

False
today bool

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

None
days_offset int

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

0

Returns:

Type Description
datetime

A datetime object, representing the time and date given in the

datetime

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

parse_time(time_str, name=None, aware=False, today=False, days_offset=0) async

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:

Name Type Description Default
time_str str

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

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

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

required
name str

Name of the calling app or module. It is used only for logging purposes.

None
aware bool

If True the created datetime object will be aware of timezone.

False
today bool

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

False
days_offset int

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

0

Returns:

Type Description
time

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

parse_utc_string(utc_string)

Convert a UTC to its string representation.

Parameters:

Name Type Description Default
utc_string str

A string that contains a date and time to convert.

required

Returns:

Type Description
float

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

register_endpoint(callback, endpoint=None, **kwargs) async

Registers an endpoint for API calls into the current App.

Parameters:

Name Type Description Default
callback Callable[[Any, dict], Any]

The function to be called when a request is made to the named endpoint.

required
endpoint str

The name of the endpoint to be used for the call (Default: None).

None

Keyword Args: **kwargs (optional): Zero or more keyword arguments.

Returns:

Type Description
str | None

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

register_route(callback, route=None, **kwargs) async

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:

Name Type Description Default
callback Callable[[Any, dict], Any]

The function to be called when a request is made to the named route. This must be an async function

required
route str

The name of the route to be used for the request (Default: the app's name).

None

Other Parameters:

Name Type Description
**kwargs optional

Zero or more keyword arguments.

Returns:

Type Description
str | None

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")

register_service(service, cb, namespace=None, **kwargs)

Register a service that can be called from other apps, the REST API, and the event stream.

This makes a function available to be called in other apps using call_service(...). The service function can accept arbitrary keyword arguments.

Registering services in namespaces that already have plugins is not recommended, as it can lead to some unpredictable behavior. Instead, it's recommended to use a user-defined namespace or one that is not tied to plugin.

Parameters:

Name Type Description Default
service str

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

required
cb Callable

The function to use for the service. This will accept both sync and async functions. Async functions are not recommended, as AppDaemon's threading model makes them unnecessary. Async functions run in the event loop along with AppDaemon internal functions, so any blocking or delays, can cause AppDaemon itself to hang.

required
namespace str

Optional namespace to use. Defaults to using the app's current namespace. See the namespace documentation <APPGUIDE.html#namespaces>__ for more information.

None
**kwargs optional

Zero or more keyword arguments. Extra keyword arguments will be stored alongside the service definition.

{}

Returns:

Type Description
None

None

Examples:

>>> self.register_service("myservices/service1", self.mycallback)
>>> async def mycallback(self, namespace: str, domain: str, service: str, kwargs):
>>>     self.log("Service called")

reload_apps()

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.

Returns:

Type Description
None

None.

Examples:

>>> self.reload_apps()

remove_entity(entity_id, namespace=None) async

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:

Name Type Description Default
entity_id str

The fully qualified entity id (including the device type).

required
namespace str

Namespace to use for the call. See the section on namespaces <APPGUIDE.html#namespaces>__ for a detailed description. In most cases it is safe to ignore this parameter.

None

Returns:

Type Description
None

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')

remove_namespace(namespace) async

Remove a user-defined namespace, which has a database file associated with it.

See :py:ref:app_namespaces for more information.

Parameters:

Name Type Description Default
namespace str

The namespace to be removed, which must not be the current namespace.

required

Returns:

Type Description
dict[str, Any] | None

The data within that namespace

Examples:

Removes the namespace called storage.

>>> self.remove_namespace("storage")

reset_timer(handle) async

Reset a previously created timer.

The timer must be actively running, and not a sun-related one like sunrise/sunset for it to be reset.

Parameters:

Name Type Description Default
handle str

The handle returned from the original call to create the timer.

required

Returns:

Type Description
bool

Boolean representing whether the timer reset was successful.

Examples:

>>> self.reset_timer(handle)
True

restart_app(app)

Restarts an App which can either be running or not.

Parameters:

Name Type Description Default
app str

Name of the app.

required

Returns:

Type Description
None

None.

Examples:

>>> self.restart_app("lights_app")

run_at(callback, start, *args, random_start=None, random_end=None, pin=None, pin_thread=None, **kwargs) async

Run a function once, at the specified time of day.

Parameters:

Name Type Description Default
callback Callable

Function that will be called at the specified time. It must conform to the standard scheduler callback format documented here <APPGUIDE.html#scheduler-callbacks>__.

required
start (str, time)

Time the callback will be triggered. It should be either a Python time object, datetime 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.

required
*args

Arbitrary positional arguments to be provided to the callback function when it is triggered.

()
random_start int

Start of range of the random time.

None
random_end int

End of range of the random time.

None
pin bool

Optional setting to override the default thread pinning behavior. By default, this is effectively True, and pin_thread gets set when the app starts.

None
pin_thread int

Specify which thread from the worker pool will run the callback. The threads each have an ID number. The ID numbers start at 0 and go through (number of threads - 1).

None
**kwargs

Arbitrary keyword parameters to be provided to the callback function when it is triggered.

{}

Returns:

Type Description
str

A handle that can be used to cancel the timer later before it's been executed.

Note

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 10:30am today, or 10:30am tomorrow if it is already after 10:30am.

>>> def delayed_callback(self, **kwargs): ...  # example callback
>>> handle = self.run_at(self.delayed_callback, datetime.time(10, 30, 0))

Run today at 04:00pm using the parse_time() function.

>>> def delayed_callback(self, **kwargs): ...  # example callback
>>> handle = self.run_at(self.delayed_callback, "04:00:00 PM")

Run at sunset.

>>> def delayed_callback(self, **kwargs): ...  # example callback
>>> handle = self.run_at(self.delayed_callback, "sunset")

Run an hour after sunrise.

>>> def delayed_callback(self, **kwargs): ...  # example callback
>>> handle = self.run_at(self.delayed_callback, "sunrise + 01:00:00")

run_at_sunrise(callback, *args, repeat=True, offset=None, random_start=None, random_end=None, pin=None, pin_thread=None, **kwargs) async

Runs a callback every day at or around sunrise.

Parameters:

Name Type Description Default
callback Callable

Function to be invoked at or around sunrise. It must conform to the standard Scheduler Callback format documented here <APPGUIDE.html#about-schedule-callbacks>__.

required
*args

Arbitrary positional arguments to be provided to the callback function when it is invoked.

()
repeat (bool, option)

Whether the callback should repeat every day. Defaults to True

True
offset int

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.

None
random_start int

Start of range of the random time.

None
random_end int

End of range of the random time.

None
pin bool

Optional setting to override the default thread pinning behavior. By default, this is effectively True, and pin_thread gets set when the app starts.

None
pin_thread int

Specify which thread from the worker pool will run the callback. The threads each have an ID number. The ID numbers start at 0 and go through (number of threads - 1).

None
**kwargs

Arbitrary keyword parameters to be provided to the callback function when it is triggered.

{}

Returns:

Type Description
str

A handle that can be used to cancel the timer.

Note

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

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

run_at_sunset(callback, *args, repeat=True, offset=None, random_start=None, random_end=None, pin=None, pin_thread=None, **kwargs) async

Runs a callback every day at or around sunset.

Parameters:

Name Type Description Default
callback Callable

Function to be invoked at or around sunset. It must conform to the standard Scheduler Callback format documented here <APPGUIDE.html#about-schedule-callbacks>__.

required
*args

Arbitrary positional arguments to be provided to the callback function when it is triggered.

()
repeat (bool, option)

Whether the callback should repeat every day. Defaults to True

True
offset int

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.

None
random_start int

Start of range of the random time.

None
random_end int

End of range of the random time.

None
pin bool

Optional setting to override the default thread pinning behavior. By default, this is effectively True, and pin_thread gets set when the app starts.

None
pin_thread int

Specify which thread from the worker pool will run the callback. The threads each have an ID number. The ID numbers start at 0 and go through (number of threads - 1).

None
**kwargs

Arbitrary keyword parameters to be provided to the callback function when it is triggered.

{}

Returns:

Type Description
str

A handle that can be used to cancel the timer.

Note

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)

run_daily(callback, start=None, *args, random_start=None, random_end=None, pin=None, pin_thread=None, **kwargs) async

Run a function at the same time every day.

Parameters:

Name Type Description Default
callback Callable

Function that will be called every day at the specified time. It must conform to the standard scheduler callback format documented here <APPGUIDE.html#scheduler-callbacks>__.

required
start (str, time, datetime)

Start time for the interval calculation. If this is in the future, this will be the first time the callback is triggered. If this is in the past, the intervals will be calculated forward from the start time, and the first trigger will be the first interval in the future.

  • If this is a str it will be parsed with :meth:~appdaemon.adapi.ADAPI.parse_time().
  • If this is a datetime.time object, the current date will be assumed.
  • If this is a datetime.datetime object, it will be used as is.
None
*args

Arbitrary positional arguments to be provided to the callback function when it is triggered.

()
random_start int

Start of range of the random time.

None
random_end int

End of range of the random time.

None
pin bool

Optional setting to override the default thread pinning behavior. By default, this is effectively True, and pin_thread gets set when the app starts.

None
pin_thread int

Specify which thread from the worker pool will run the callback. The threads each have an ID number, which start at 0 and go through (number of threads - 1).

None
**kwargs

Arbitrary keyword parameters to be provided to the callback function when it is triggered.

{}

Returns:

Type Description
str

A handle that can be used to cancel the timer later before it's been executed.

Note

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 day at 10:30am.

>>> self.run_daily(self.daily_callback, datetime.time(10, 30))

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

>>> handle = self.run_daily(self.daily_callback, "07:30:00 PM")

Run every day at sunrise.

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

Run every day an hour after sunset.

>>> handle = self.run_daily(self.daily_callback, "sunset + 01:00:00")

run_every(callback, start=None, interval=0, *args, random_start=None, random_end=None, pin=None, pin_thread=None, **kwargs) async

Run a function at a regular time interval.

Parameters:

Name Type Description Default
callback Callable

Function that will be called at the specified time interval. It must conform to the standard scheduler callback format documented here <APPGUIDE.html#scheduler-callbacks>__.

required
start (str, time, datetime)

Start time for the interval calculation. If this is in the future, this will be the first time the callback is triggered. If this is in the past, the intervals will be calculated forward from the start time, and the first trigger will be the first interval in the future.

  • If this is a str it will be parsed with :meth:~appdaemon.adapi.ADAPI.parse_time().
  • If this is a datetime.time object, the current date will be assumed.
  • If this is a datetime.datetime object, it will be used as is.
None
interval (str, int, float, timedelta)

Time interval between callback triggers.

  • If this is an int or float, it will be interpreted as seconds.
  • If this is a str it will be parsed with parse_timedelta()

    • HH:MM
    • HH:MM:SS
    • DD days, HH:MM:SS
  • If this is a timedelta object, the current date will be assumed.

0
*args

Arbitrary positional arguments to be provided to the callback function when it is triggered.

()
random_start int

Start of range of the random time.

None
random_end int

End of range of the random time.

None
pin bool

Optional setting to override the default thread pinning behavior. By default, this is effectively True, and pin_thread gets set when the app starts.

None
pin_thread int

Specify which thread from the worker pool will run the callback. The threads each have an ID number, which start at 0 and go through (number of threads - 1).

None
**kwargs

Arbitrary keyword parameters to be provided to the callback function when it is triggered.

{}

Returns:

Type Description
str

A handle that can be used to cancel the timer later before it's been executed.

Note

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

Examples:

Run every 10 minutes starting now.

.. code-block:: python :emphasize-lines: 3

class MyApp(ADAPI):
    def initialize(self):
        self.run_every(self.timed_callback, interval=datetime.timedelta(minutes=10))

    def timed_callback(self, **kwargs): ...  # example callback

Run every 5 minutes starting in 5 seconds.

.. code-block:: python :emphasize-lines: 3

class MyApp(ADAPI):
    def initialize(self):
        self.run_every(self.timed_callback, "now+5", 5 * 60)

    def timed_callback(self, **kwargs): ...  # example callback

Run every 17 minutes starting in 2 hours time.

.. code-block:: python :emphasize-lines: 5

class MyApp(ADAPI):
    def initialize(self):
        start = self.get_now() + datetime.timedelta(hours=2)
        interval = datetime.timedelta(minutes=17)
        self.run_every(self.timed_callback, start, interval)

    def timed_callback(self, **kwargs): ...  # example callback

run_hourly(callback, start=None, *args, random_start=None, random_end=None, pin=None, pin_thread=None, **kwargs) async

Run a function at the same time every hour.

Parameters:

Name Type Description Default
callback Callable

Function that will be called every hour starting at the specified time. It must conform to the standard scheduler callback format documented here <APPGUIDE.html#scheduler-callbacks>__.

required
start (str, time, datetime)

Start time for the interval calculation. If this is in the future, this will be the first time the callback is triggered. If this is in the past, the intervals will be calculated forward from the start time, and the first trigger will be the first interval in the future.

  • If this is a str it will be parsed with :meth:~appdaemon.adapi.ADAPI.parse_time().
  • If this is a datetime.time object, the current date will be assumed.
  • If this is a datetime.datetime object, it will be used as is.
None
*args

Arbitrary positional arguments to be provided to the callback function when it is triggered.

()
random_start int

Start of range of the random time.

None
random_end int

End of range of the random time.

None
pin bool

Optional setting to override the default thread pinning behavior. By default, this is effectively True, and pin_thread gets set when the app starts.

None
pin_thread int

Specify which thread from the worker pool will run the callback. The threads each have an ID number, which start at 0 and go through (number of threads - 1).

None
**kwargs

Arbitrary keyword parameters to be provided to the callback function when it is triggered.

{}

Returns:

Type Description
str

A handle that can be used to cancel the timer later before it's been executed.

Note

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)

run_in(callback, delay, *args, random_start=None, random_end=None, pin=None, pin_thread=None, **kwargs) async

Run a function after a specified delay.

This method should always be used instead of time.sleep().

Parameters:

Name Type Description Default
callback Callable

Function that will be called after the specified delay. It must conform to the standard scheduler callback format documented here <APPGUIDE.html#scheduler-callbacks>__.

required
delay (str, int, float, timedelta)

Delay before the callback is executed. Numbers will be interpreted as seconds. Strings can be in the format of SS, MM:SS, HH:MM:SS, or DD days, HH:MM:SS. If a timedelta object is given, it will be used as is.

required
*args

Arbitrary positional arguments to be provided to the callback function when it is triggered.

()
random_start int

Start of range of the random time.

None
random_end int

End of range of the random time.

None
pin bool

Optional setting to override the default thread pinning behavior. By default, this is effectively True, and pin_thread gets set when the app starts.

None
pin_thread int

Specify which thread from the worker pool will run the callback. The threads each have an ID number. The ID numbers start at 0 and go through (number of threads - 1).

None
**kwargs

Arbitrary keyword parameters to be provided to the callback function when it is triggered.

{}

Returns:

Type Description
str

A handle that can be used to cancel the timer later before it's been executed.

Note

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

>>> def delayed_callback(self, **kwargs): ... # example callback
>>> self.handle = self.run_in(self.delayed_callback, 0.5)

Run the specified callback after 2.7 seconds with a custom keyword arg title.

>>> def delayed_callback(self, title: str, **kwargs): ... # example callback
>>> self.handle = self.run_in(self.delayed_callback, 2.7, title="Delayed Callback Title")

run_in_executor(func, *args, **kwargs) async

Run a sync function from within an async function using a thread from AppDaemon's internal thread pool.

This essentially converts a sync function into an async function, which allows async functions to use it. This is useful for even short-ish functions (even <1s execution time) because it allows the event loop to continue processing other events while waiting for the function to complete. Blocking the event loop prevents AppDaemon's internals from running, which interferes with all other apps, and can cause issues with connection timeouts.

Parameters:

Name Type Description Default
func Callable[..., T]

The function to be executed.

required
*args optional

Any additional arguments to be used by the function

()
**kwargs optional

Any additional keyword arguments to be used by the function

{}

Returns:

Type Description
T

None

Examples:

>>> await self.run_in_executor(self.run_request)

run_in_thread(callback, thread, **kwargs)

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

Parameters:

Name Type Description Default
callback Callable

Function to be run on the new thread.

required
thread int

Thread number (0 - number of threads).

required
**kwargs

Arbitrary keyword parameters to be provided to the callback function when it is invoked.

{}

Returns:

Type Description
None

None.

Examples:

>>> self.run_in_thread(my_callback, 8)

run_minutely(callback, start=None, *args, random_start=None, random_end=None, pin=None, pin_thread=None, **kwargs) async

Run the callback at the same time every minute.

Parameters:

Name Type Description Default
callback Callable

Function that will be called every hour starting at the specified time. It must conform to the standard scheduler callback format documented here <APPGUIDE.html#scheduler-callbacks>__.

required
start (str, time, datetime)

Start time for the interval calculation. If this is in the future, this will be the first time the callback is triggered. If this is in the past, the intervals will be calculated forward from the start time, and the first trigger will be the first interval in the future.

  • If this is a str it will be parsed with :meth:~appdaemon.adapi.ADAPI.parse_time().
  • If this is a datetime.time object, the current date will be assumed.
  • If this is a datetime.datetime object, it will be used as is.
None
*args

Arbitrary positional arguments to be provided to the callback function when it is triggered.

()
random_start int

Start of range of the random time.

None
random_end int

End of range of the random time.

None
pin bool

Optional setting to override the default thread pinning behavior. By default, this is effectively True, and pin_thread gets set when the app starts.

None
pin_thread int

Specify which thread from the worker pool will run the callback. The threads each have an ID number, which start at 0 and go through (number of threads - 1).

None
**kwargs

Arbitrary keyword parameters to be provided to the callback function when it is triggered.

{}

Returns:

Type Description
str

A handle that can be used to cancel the timer later before it's been executed.

Note

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)

run_once(callback, start=None, *args, random_start=None, random_end=None, pin=None, pin_thread=None, **kwargs) async

Run a function once, at the specified time of day. This is essentially an alias for run_at().

Parameters:

Name Type Description Default
callback Callable

Function that will be called at the specified time. It must conform to the standard scheduler callback format documented here <APPGUIDE.html#scheduler-callbacks>__.

required
start (str, time)

Time the callback will be triggered. It should be either a Python time object, datetime 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.

None
*args

Arbitrary positional arguments to be provided to the callback function when it is triggered.

()
random_start int

Start of range of the random time.

None
random_end int

End of range of the random time.

None
pin bool

Optional setting to override the default thread pinning behavior. By default, this is effectively True, and pin_thread gets set when the app starts.

None
pin_thread int

Specify which thread from the worker pool will run the callback. The threads each have an ID number. The ID numbers start at 0 and go through (number of threads - 1).

None
**kwargs

Arbitrary keyword parameters to be provided to the callback function when it is triggered.

{}

Returns:

Type Description
str

A handle that can be used to cancel the timer later before it's been executed.

Note

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 10:30am today, or 10:30am tomorrow if it is already after 10:30am.

>>> def delayed_callback(self, **kwargs): ...  # example callback
>>> handle = self.run_once(self.delayed_callback, datetime.time(10, 30, 0))

Run today at 04:00pm using the parse_time() function.

>>> def delayed_callback(self, **kwargs): ...  # example callback
>>> handle = self.run_once(self.delayed_callback, "04:00:00 PM")

Run at sunset.

>>> def delayed_callback(self, **kwargs): ...  # example callback
>>> handle = self.run_once(self.delayed_callback, "sunset")

Run an hour after sunrise.

>>> def delayed_callback(self, **kwargs): ...  # example callback
>>> handle = self.run_once(self.delayed_callback, "sunrise + 01:00:00")

run_sequence(sequence, namespace=None) async

Run an AppDaemon Sequence.

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

Parameters:

Name Type Description Default
sequence str | list[dict[str, dict[str, str]]]

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

required
namespace str

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 <APPGUIDE.html#namespaces>__ for a detailed description. In most cases, it is safe to ignore this parameter.

None

Returns:

Type Description
Any

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")
>>> handle = self.run_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"}}
    ])

save_namespace(namespace=None) async

Saves the given state namespace to its corresponding file.

This is only relevant for persistent namespaces, which if not set to safe buffers changes in memory and only periodically writes them to disk. This function manually forces a write of all the changes since the last save to disk. See the :py:ref:app_namespaces docs section for more information.

Parameters:

Name Type Description Default
namespace str

Namespace to save. If not specified, the current app namespace will be used.

None

Returns:

Name Type Description
bool bool

True if the namespace was saved successfully, False otherwise.

set_app_pin(pin) async

Sets an App to be pinned or unpinned.

Parameters:

Name Type Description Default
pin bool

Sets whether the App becomes pinned or not.

required

Returns:

Type Description
None

None.

Examples:

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

>>> self.set_app_pin(True)

set_error_level(level)

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

Parameters:

Name Type Description Default
level str

Error level.

required

Returns:

Type Description
None

None.

Note

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

set_log_level(level)

Sets the log level for this App, which applies to the main log, error log, and all user logs.

Parameters:

Name Type Description Default
level str

Log level.

required

Returns:

Type Description
None

None.

Note

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

Examples:

>>> self.set_log_level("DEBUG")

set_namespace(namespace, writeback='safe', persist=True)

Set the current namespace of the app.

This will create a new namespace if it doesn't already exist. By default, this will be a persistent namespace with safe writeback, which means that all state changes will be stored to disk as they happen.

See the :py:ref:app_namespaces for more information.

Parameters:

Name Type Description Default
namespace str

Name of the new namespace

required
writeback str

The writeback to be used if a new namespace gets created. Will be safe by default.

'safe'
persist bool

Whether to make the namespace persistent if a new one is created. Defaults to True.

True

Returns:

Type Description
None

None.

Examples:

Create a namespace that buffers state changes in memory and periodically writes them to disk.

>>> self.set_namespace("on_disk", writeback="hybrid", persist=True)

Create an in-memory namespace that won't survive AppDaemon restarts.

>>> self.set_namespace("in_memory", persist=False)

set_pin_thread(thread) async

Sets the thread that the App will be pinned to.

Parameters:

Name Type Description Default
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.

required

Returns:

Type Description
None

None.

Examples:

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

>>> self.set_pin_thread(5)

set_production_mode(mode=True) async

Deactivates or activates the production mode in AppDaemon.

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

Parameters:

Name Type Description Default
mode bool

If it is True the production mode is activated, or deactivated otherwise.

True

Returns:

Type Description
bool | None

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

set_state(entity_id, state=None, namespace=None, attributes=None, replace=False, check_existence=True, **kwargs) async

Update the state of the specified entity.

This causes a state_changed event to be emitted in the entity's namespace. If that namespace is associated with a Home Assistant plugin, it will use the /api/states/<entity_id> endpoint of the REST API <https://developers.home-assistant.io/docs/api/rest/>__ to update the state of the entity. This method can be useful to create entities in Home Assistant, but they won't persist across restarts.

Parameters:

Name Type Description Default
entity_id str

The fully qualified entity id (including the device type).

required
state Any | None

New state value to be set.

None
namespace str

Optional namespace to use. Defaults to using the app's current namespace. See the namespace documentation <APPGUIDE.html#namespaces>__ for more information.

None
attributes dict[str, Any]

Optional dictionary to use for the attributes. If replace is False, then the attribute dict will use the built-in update method on this dict. If replace is True, then the attribute dict will be entirely replaced with this one.

None
replace bool

Whether to replace rather than update the attributes. Defaults to False. For plugin based entities, this is not recommended, as the plugin will mostly replace the new values, when next it updates.

False
check_existence bool

Whether to check if the entity exists before setting the state. Defaults to True, but it can be useful to set to False when using this method to create an entity.

True
**kwargs optional

Zero or more keyword arguments. Extra keyword arguments will be assigned as attributes.

{}

Returns:

Type Description
dict[str, Any] | None

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")

sleep(delay, result=None) async staticmethod

Pause execution for a certain time span

Parameters:

Name Type Description Default
delay float

Number of seconds to pause.

required
result optional

Result to return upon delay completion.

None

Returns:

Type Description
T

Result or None.

Note

This function is not available in sync apps.

Examples:

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

split_device_list(devices) staticmethod

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:

Name Type Description Default
devices str

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

required

Returns:

Type Description
list[str]

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

split_entity(entity_id, namespace=None) async

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:

Name Type Description Default
entity_id str

The fully qualified entity id (including the device type).

required
namespace str

Namespace to use for the call. See the section on namespaces <APPGUIDE.html#namespaces>__ for a detailed description. In most cases it is safe to ignore this parameter.

None

Returns:

Type Description
list

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

start_app(app)

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 are not taken into account.

Parameters:

Name Type Description Default
app str

Name of the app.

required

Returns:

Type Description
None

None.

Examples:

>>> self.start_app("lights_app")

stop_app(app)

Stops an App which is running.

Parameters:

Name Type Description Default
app str

Name of the app.

required

Returns:

Type Description
None

None.

Examples:

>>> self.stop_app("lights_app")

submit_to_executor(func, *args, callback=None, **kwargs)

Submit a sync function from within another sync function to be executed using a thread from AppDaemon's internal thread pool.

This function does not wait for the result of the submitted function and immediately returns a Future object. This is useful for executing long-running functions without blocking the thread for other callbacks. The result can be retrieved later using the Future object, but it's recommended to use a callback to handle the result instead.

Parameters:

Name Type Description Default
func Callable[..., T]

The function to be executed.

required
*args optional

Any additional arguments to be used by the function

()
callback optional

A callback function to be executed when the function has completed.

None
**kwargs optional

Any additional keyword arguments to be used by the function.

{}

Returns:

Type Description
Future[T]

A Future object representing the result of the function.

Examples:

Submit a long-running function to be executed in the background

>>> def initialize(self):
        self.long_future = self.submit_to_executor(self.long_request, url, callback=self.result_callback)

Long running function:

>>> def long_request(self, url: str):
        import requests
        res = requests.get(url)
        return res.json()

Callback to handle the result:

>>> def result_callback(self, result: dict, **kwargs):
        # Set the attributes of a sensor with the result
        self.set_state("sensor.url_result", state="ready", attributes=result, replace=True)

sun_down() async

Determines if the sun is currently down.

Returns:

Name Type Description
bool bool

True if the sun is down, False otherwise.

Examples:

>>> if self.sun_down():
>>>    #do something

sun_up() async

Determines if the sun is currently up.

Returns:

Name Type Description
bool bool

True if the sun is up, False otherwise.

Examples:

>>> if self.sun_up():
>>>    #do something

sunrise(aware=False, today=False, days_offset=0) async

Return a datetime object that represent when a sunrise will occur.

Parameters:

Name Type Description Default
aware bool

Whether the resulting datetime object will be aware of timezone.

False
today bool

Defaults to False, which will return the first sunrise in the future, regardless of the day. If set to True, the function will return the sunrise for the current day, even if it is in the past.

False
days_offset int

Specify the number of days (positive or negative) for the sunrise. This can only be used in combination with the today flag

0

Examples:

>>> self.sunrise()
2023-02-02 07:11:50.150554
>>> self.sunrise(today=True)
2023-02-01 07:12:20.272403

sunset(aware=False, today=False, days_offset=0) async

Return a datetime object that represent when a sunset will occur.

Parameters:

Name Type Description Default
aware bool

Whether the resulting datetime object will be aware of timezone.

False
today bool

Defaults to False, which will return the first sunset in the future, regardless of the day. If set to True, the function will return the sunset for the current day, even if it is in the past.

False
days_offset int

Specify the number of days (positive or negative) for the sunset. This can only be used in combination with the today flag

0

Examples:

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

time() async

Get a time object representing the current local time.

Use this instead of the standard Python methods in order to correctly account for the time when using the time travel feature, which is usually done for testing.

Examples:

>>> self.time()
20:15:31.295751

timer_running(handle) async

Check if a previously created timer is still running.

Parameters:

Name Type Description Default
handle str

The handle returned from the original call to create the timer.

required

Returns:

Type Description
bool

Boolean representing whether the timer is still running.

Examples:

>>> self.timer_running(handle)
True