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
|
None
|
Returns:
| Type | Description |
|---|---|
None
|
None. |
Examples:
Add the entity in the present namespace.
adds the entity in the mqtt namespace.
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'
|
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
|
Returns:
| Type | Description |
|---|---|
str | None
|
The file path to the newly created namespace. Will be |
Examples:
Create a namespace that buffers state changes in memory and periodically writes them to disk.
Create an in-memory namespace that won't survive AppDaemon restarts.
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 |
required |
namespace
|
str
|
It's safe to ignore this parameter in most cases because the default namespace
will be used. However, if a |
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
|
-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 |
None
|
service_data
|
dict
|
Used as an additional dictionary to pass arguments into the |
required |
**data
|
Any
|
Any other keyword arguments get passed to the service call as |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
Result of the |
Any
|
|
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.
cancel_listen_event(handle, *, silent=False)
async
Cancel a callback for a specific event.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
handle
|
(str, Iterable[str])
|
Handle(s) returned from a previous call to |
required |
silent
|
bool
|
If |
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.
Cancel multiple callbacks.
cancel_listen_log(handle)
async
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 |
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 |
False
|
Returns:
| Type | Description |
|---|---|
bool
|
Boolean. |
Examples:
Don't display a warning if the handle is not found.
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 |
False
|
Returns:
| Type | Description |
|---|---|
bool
|
Boolean representing whether the timer was successfully canceled. |
Examples:
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 |
required |
Returns:
| Type | Description |
|---|---|
datetime
|
A localised Python |
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 ( |
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 |
Examples:
Define your callback
Create the task
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
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., |
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 ( |
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.
Switch to Locks Panel then return to Main panel after 10 seconds.
date()
async
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:
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:
deregister_endpoint(handle)
async
deregister_route(handle)
async
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 |
required |
namespace
|
str
|
Optional namespace to use. Defaults to using the app's current namespace. See the
|
None
|
Returns:
| Type | Description |
|---|---|
bool
|
|
Examples:
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
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
Examples:
Check if the entity light.living_room exist within the app's namespace
Check if the entity mqtt.security_settings exist within the mqtt namespace
if the app is operating in a different namespace like default
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'
|
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
|
stack_info
|
bool
|
If |
False
|
**kwargs
|
Keyword arguments |
{}
|
Returns:
| Type | Description |
|---|---|
None
|
None. |
Examples:
Log an error message to the error logfile of the system.
Log an error message with critical-level to the error logfile of the system.
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 |
required |
namespace
|
str
|
Namespace to use for the call. See the section on
|
None
|
**kwargs
|
optional
|
Zero or more keyword arguments that will be supplied as part of the event. |
{}
|
Returns:
| Type | Description |
|---|---|
None
|
None. |
Examples:
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:
format_dialogflow_response(speech=None)
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
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str | None
|
The friendly name of the entity if it exists or the entity id if not. |
Examples:
get_ad_version()
staticmethod
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 |
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 |
Examples:
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 |
Examples:
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:
get_app_pin()
async
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
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 |
Examples:
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
|
Returns:
| Type | Description |
|---|---|
Any | None
|
A string representing the value of the slot from the interaction model, or a hash of slots. |
Examples:
get_error_log()
get_main_log()
get_namespace()
Get the app's current namespace.
See :py:ref:app_namespaces for more information.
get_now(aware=True)
async
get_now_ts(aware=False)
async
get_pin_thread()
async
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 |
Examples:
get_scheduler_entries()
async
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 |
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 |
None
|
copy
|
bool
|
Whether to return a copy of the internal data. This is |
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.
Get the state of all switches in the system.
Get the state attribute of light.office_1.
Get the brightness attribute of light.office_1.
Get the entire state of light.office_1.
get_thread_info()
async
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
|
required |
Returns:
| Type | Description |
|---|---|
Logger
|
The underlying logger object used for the error log. |
Examples:
Log an error message to a user-defined logfile.
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 |
required |
Returns:
| Type | Description |
|---|---|
bool
|
The values (service, kwargs) supplied when the callback was initially created. |
Examples:
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 |
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 |
str
|
the callback was initially created. |
Examples:
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 |
tuple[datetime, int, dict] | None
|
|
tuple[datetime, int, dict] | None
|
|
tuple[datetime, int, dict] | None
|
|
Examples:
list_namespaces()
async
list_services(namespace='global')
List all services available within AppDaemon
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
str
|
Optional namespace to use. The default is |
'global'
|
Returns:
| Type | Description |
|---|---|
list[dict[str, str]]
|
List of dicts with keys |
Examples:
listen_event(callback, event=None, *, namespace=None, timeout=None, oneshot=False, pin=None, pin_thread=None, **kwargs)
async
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 |
required |
event
|
str | list[str]
|
Name of the event to subscribe to. Can be a standard Home Assistant
event such as |
None
|
namespace
|
str
|
Optional namespace to use. Defaults to using the app's current namespace. The
value |
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 |
False
|
pin
|
bool
|
Optional setting to override the default thread pinning behavior. By default, this is
effectively |
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 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 |
{}
|
Returns:
| Type | Description |
|---|---|
str | list[str]
|
A handle that can be used to cancel the callback. |
Examples:
Listen all "MODE_CHANGE" events.
Listen for a minimote event activating scene 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.
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 |
required |
level
|
str
|
Minimum level for logs to trigger the callback. Lower levels will be ignored. Default
is |
'INFO'
|
namespace
|
str
|
Namespace to use for the call. Defaults to |
'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 |
None
|
pin
|
bool
|
Optional setting to override the default thread pinning behavior. By default, this is
effectively |
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.
Sample callback:
Listen to all WARNING log messages of the main_log.
Listen to all WARNING log messages of a user-defined logfile.
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 |
required |
entity_id
|
str | Iterable[str]
|
Entity ID or a domain. If a domain is provided, e.g., |
None
|
namespace
|
str
|
Optional namespace to use. Defaults to using the app's current namespace. See
the |
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 |
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 |
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 If you use |
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 |
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 If |
False
|
oneshot
|
bool
|
If |
False
|
pin
|
bool
|
Optional setting to override the default thread pinning behavior. By default, this is
effectively |
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. |
Examples:
Listen for any state change and return the state attribute.
Listen for any state change involving a light and return the state attribute.
Listen for a state change involving light.office1 and return the state attribute.
Listen for a state change involving light.office1 and return the entire state as a dict.
Listen for a change involving the brightness attribute of light.office1 and return the brightness
attribute.
Listen for a state change involving light.office1 turning on and return the state attribute.
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.
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.
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'
|
log
|
str
|
Send the message to a specific log, either system or user_defined. System logs are
|
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 |
None
|
stack_info
|
bool
|
If |
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.
Log a message to the specified logfile.
Log a message with error-level to the main logfile of the system.
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.
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
|
|
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, |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
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:
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: If the |
required |
name
|
str
|
Name of the calling app or module. It is used only for logging purposes. |
None
|
aware
|
bool
|
If |
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
|
|
Examples:
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: If the |
required |
name
|
str
|
Name of the calling app or module. It is used only for logging purposes. |
None
|
aware
|
bool
|
If |
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 |
Examples:
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 |
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
|
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.
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.
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 |
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
|
None
|
**kwargs
|
optional
|
Zero or more keyword arguments. Extra keyword arguments will be stored alongside the service definition. |
{}
|
Returns:
| Type | Description |
|---|---|
None
|
None |
Examples:
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:
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
|
None
|
Returns:
| Type | Description |
|---|---|
None
|
None. |
Examples:
Delete the entity in the present namespace.
Delete the entity in the mqtt namespace.
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.
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:
restart_app(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 |
required |
start
|
(str, time)
|
Time the callback will be triggered. It should be either a Python |
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 |
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.
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 |
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
|
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 |
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 |
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.
Or you can just do the math yourself.
Run at a random time +/- 60 minutes from sunrise.
Run at a random time between 30 and 60 minutes before sunrise.
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 |
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
|
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 |
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 |
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.
Or you can just do the math yourself.
Run at a random time +/- 60 minutes from sunset.
Run at a random time between 30 and 60 minutes before sunset.
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 |
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.
|
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 |
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.
Run at 7:30pm every day using the parse_time() function.
Run every day at sunrise.
Run every day an hour after sunset.
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 |
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.
|
None
|
interval
|
(str, int, float, timedelta)
|
Time interval between callback triggers.
|
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 |
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 |
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.
|
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 |
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.
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 |
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 |
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 |
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.
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:
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:
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 |
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.
|
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 |
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.
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 |
required |
start
|
(str, time)
|
Time the callback will be triggered. It should be either a Python |
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 |
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.
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 |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
A handle that can be used with |
Examples:
Run a yaml-defined sequence called "sequence.front_room_scene".
Run an inline sequence.
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
|
|
set_app_pin(pin)
async
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:
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'
|
persist
|
bool
|
Whether to make the namespace persistent if a new one is created. Defaults to
|
True
|
Returns:
| Type | Description |
|---|---|
None
|
None. |
Examples:
Create a namespace that buffers state changes in memory and periodically writes them to disk.
Create an in-memory namespace that won't survive AppDaemon restarts.
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 |
required |
Returns:
| Type | Description |
|---|---|
None
|
None. |
Examples:
The following line should be put inside the initialize() function.
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
|
Returns:
| Type | Description |
|---|---|
bool | None
|
The specified mode or |
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 |
None
|
attributes
|
dict[str, Any]
|
Optional dictionary to use for the attributes. If replace is
|
None
|
replace
|
bool
|
Whether to replace rather than update the attributes. Defaults to |
False
|
check_existence
|
bool
|
Whether to check if the entity exists before setting the state. Defaults to
|
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.
Update the state and attribute of an entity.
Update the state of an entity within the specified namespace.
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 |
Note
This function is not available in sync apps.
Examples:
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:
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
|
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.
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:
stop_app(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:
Callback to handle the result:
sun_down()
async
sun_up()
async
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
|
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:
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
|
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:
time()
async
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: