Skip to content

AppDaemon Plugins

HASS

Services

  • HassPlugin.check_register_service
    • Registers a service with AppDaemon.services
    • Uses HassPlugin.call_plugin_service to call services over the websocket

appdaemon.plugins.hass.hassapi

Hass

Bases: ADBase, ADAPI

HASS API class for the users to inherit from.

This class provides an interface to the HassPlugin object that connects to Home Assistant.

android_tts(device, tts_text, media_stream='music_stream', critical=False)

Convenience method for correctly creating a TTS notification for Android devices.

For more information see: Text-to-Speech Notifications <https://companion.home-assistant.io/docs/notifications/notifications-basic#text-to-speech-notifications>_

Parameters:

Name Type Description Default
device str

Name of the device to notify on. This gets combined with notify/mobile_app_<device> to determine which notification service to call.

required
tts_text str

String of text to translate into speech

required
media_stream optional

Defaults to music_stream.

'music_stream'
critical bool

Defaults to False. If set to True, the notification will use the correct settings to have the TTS at the maximum possible volume. For more information see Critical Notifications <https://companion.home-assistant.io/docs/notifications/critical-notifications/#android>_

False

anyone_home(person=True, namespace=None) async

Determines if the house/apartment is occupied.

A convenience function to determine if one or more person is home. Use this in preference to getting the state of group.all_devices() as it avoids a race condition when using state change callbacks for device trackers.

Parameters:

Name Type Description Default
person boolean

If set to True, use person rather than device_tracker as the device type to query

True
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
bool

Returns True if anyone is at home, False otherwise.

Examples:

>>> if self.anyone_home():
>>>     do something
>>> if self.anyone_home(person=True):
>>>     do something

area_devices(area_name_or_id)

Get the list of device IDs tied to a given area ID or name.

See area functions <https://www.home-assistant.io/docs/configuration/templating/#areas>_ for more information.

area_entities(area_name_or_id)

Get the list of entity IDs tied to a given area ID or name.

See area functions <https://www.home-assistant.io/docs/configuration/templating/#areas>_ for more information.

area_id(lookup_value)

Get the area ID for a given device ID, entity ID, or area name.

See area functions <https://www.home-assistant.io/docs/configuration/templating/#areas>_ for more information.

area_name(lookup_value)

Get the area name for a given device ID, entity ID, or area ID.

See area functions <https://www.home-assistant.io/docs/configuration/templating/#areas>_ for more information.

areas()

Get the full list of area IDs.

See area functions <https://www.home-assistant.io/docs/configuration/templating/#areas>_ for more information.

backup_full(name=None, password=None, compressed=None, location=None, homeassistant_exclude_database=None, timeout=30, hass_timeout=10) async

Create a full backup.

Action hassio.backup_full <https://www.home-assistant.io/integrations/hassio/#action-hassiobackup_full>_

Parameters:

Name Type Description Default
name str

By default, the current date and time are used in your local time, which you have set in your general settings.

None
password str

Optional password for backup.

None
compressed bool

False to create uncompressed backups.

None
location str

Alternate backup location instead of using the default location for backups.

None
homeassistant_exclude_database bool

Exclude the Home Assistant database file from backup.

None
timeout str | int | float

Timeout for the app thread to wait for a response from the main thread.

30
hass_timeout str | int | float

Timeout for AppDaemon waiting on a response from Home Assistant to respond to the backup request. Cannot be set lower than the timeout value.

10

Returns:

Name Type Description
dict dict

Response from the backup service.

backup_partial(addons=None, folders=None, name=None, password=None, compressed=None, location=None, homeassistant=None, homeassistant_exclude_database=None, timeout=30, hass_timeout=10) async

Create a partial backup.

Action hassio.backup_partial <https://www.home-assistant.io/integrations/hassio/#action-hassiobackup_partial>_

Parameters:

Name Type Description Default
addons Iterable[str]

List of add-on slugs to backup.

None
folders Iterable[str]

List of directories to backup.

None
name str

Name of the backup file. Default is the current date and time in the user's local time.

None
password str

Optional password for backup.

None
compressed bool

False to create uncompressed backups. Defaults to True.

None
location str

Alternate backup location instead of using the default location for backups.

None
homeassistant bool

Include Home Assistant and associated config in backup. Defaults to False.

None
homeassistant_exclude_database bool

Exclude the Home Assistant database file from backup. Defaults to False.

None
timeout str | int | float

Timeout for the app thread to wait for a response from the main thread.

30
hass_timeout str | int | float

Timeout for AppDaemon waiting on a response from Home Assistant to respond to the backup request. Cannot be set lower than the timeout value.

10

Returns:

Name Type Description
dict dict

Response from the backup service.

call_service(*args, timeout=None, **kwargs) async

call_service(service: str, namespace: str | None = None, timeout: str | int | float | None = None, callback: ServiceCallback | None = None, hass_timeout: str | int | float | None = None, suppress_log_messages: bool = False, **data) -> Any

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.

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

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

required
hass_timeout str | int | float

Only applicable to the Hass plugin. Sets the amount of time to wait for a response from Home Assistant. If no value is specified, the default timeout is 10s. The default value can be changed using the ws_timeout setting the in the Hass plugin configuration in appdaemon.yaml. Even if no data is returned from the service call, Home Assistant will still send an acknowledgement back to AppDaemon, which this timeout applies to. Note that this is separate from the timeout. If timeout is shorter than this one, it will trigger before this one does.

required
suppress_log_messages bool

Only applicable to the Hass plugin. If this is set to True, Appdaemon will suppress logging of warnings for service calls to Home Assistant, specifically timeouts and non OK statuses. Use this flag and set it to True to suppress these log messages if you are performing your own error checking as described here <APPGUIDE.html#some-notes-on-service-calls>__

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

required

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

check_for_entity(entity_id, namespace=None) async

Uses the REST API to check if an entity exists instead of checking AppDaemon's internal state.

Parameters:

Name Type Description Default
entity_id str

Fully qualified id.

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
bool

Bool of whether the entity exists.

constrain_input_boolean(value)

Returns True if unconstrained - all input_booleans match the desired state. Desired state defaults to on

constrain_input_select(value)

Returns True if unconstrained - all inputs match a desired state.

constrain_person(value=None)

Returns True if unconstrained

constrain_presence(value=None)

Returns True if unconstrained

device_attr(device_or_entity_id, attr_name)

Get the value of attr_name for the given device or entity ID.

See device functions <https://www.home-assistant.io/docs/configuration/templating/#devices>_ for more information.

Attributes vary by device , but some common device attributes include: - area_id - configuration_url - manufacturer - model - name_by_user - name - sw_version

device_entities(device_id)

Get a list of entities that are associated with a given device ID.

See device functions <https://www.home-assistant.io/docs/configuration/templating/#devices>_ for more information.

device_id(entity_id)

Get the device ID for a given entity ID or device name.

See device functions <https://www.home-assistant.io/docs/configuration/templating/#devices>_ for more information.

everyone_home(person=True, namespace=None) async

Determine if all family's members at home.

A convenience function to determine if everyone is home. Use this in preference to getting the state of group.all_devices() as it avoids a race condition when using state change callbacks for device trackers.

Parameters:

Name Type Description Default
person boolean

If set to True, use person rather than device_tracker as the device type to query

True
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
bool

Returns True if everyone is at home, False otherwise.

Examples:

>>> if self.everyone_home():
>>>    do something
>>> if self.everyone_home(person=True):
>>>    do something

get_calendar_events(entity_id='calendar.localcalendar', days=1, hours=None, minutes=None, namespace=None)

Retrieve calendar events for a specified entity within a given number of days.

Each dict contains the following keys: summary, description, start, and end. The start and end keys are converted to datetime objects.

Parameters:

Name Type Description Default
entity_id str

The ID of the calendar entity to retrieve events from. Defaults to "calendar.localcalendar".

'calendar.localcalendar'
days int

The number of days to look ahead for events. Defaults to 1.

1
hours int

The number of hours to look ahead for events. Defaults to None.

None
minutes int

The number of minutes to look ahead for events. Defaults to None.

None
namespace str

If provided, changes the namespace for the service call. Defaults to the current namespace of the app, so it's safe to ignore this parameter most of the time. See the section on namespaces <APPGUIDE.html#namespaces>__ for a detailed description.

None

Returns:

Type Description
list[dict[str, str | datetime]] | None

list[dict]: A list of dicts representing the calendar events.

Examples:

>>> events = self.get_calendar_events()
>>> for event in events:
>>>     self.log(f'{event["summary"]} starts at {event["start"]}')

get_history(entity_id, days=None, start_time=None, end_time=None, minimal_response=False, no_attributes=False, significant_changes_only=False, callback=None, namespace=None) async

Gets access to the HA Database. This is a convenience function that allows accessing the HA Database, so the history state of a device can be retrieved. It allows for a level of flexibility when retrieving the data, and returns it as a dictionary list. Caution must be taken when using this, as depending on the size of the database, it can take a long time to process.

Hits the /api/history/period/<timestamp> endpoint. See https://developers.home-assistant.io/docs/api/rest for more information

Parameters:

Name Type Description Default
entity_id str

Fully qualified id of the device to be querying, e.g., light.office_lamp or scene.downstairs_on This can be any entity_id in the database. If this is left empty, the state of all entities will be retrieved within the specified time. If both end_time and start_time explained below are declared, and entity_id is specified, the specified entity_id will be ignored and the history states of all entity_id in the database will be retrieved within the specified time.

required
days int

The days from the present-day walking backwards that is required from the database.

None
start_time optional

The start time from when the data should be retrieved. This should be the furthest time backwards, like if we wanted to get data from now until two days ago. Your start time will be the last two days datetime. start_time time can be either a UTC aware time string like 2019-04-16 12:00:03+01:00 or a datetime.datetime object.

None
end_time optional

The end time from when the data should be retrieved. This should be the latest time like if we wanted to get data from now until two days ago. Your end time will be today's datetime end_time time can be either a UTC aware time string like 2019-04-16 12:00:03+01:00 or a datetime.datetime object. It should be noted that it is not possible to declare only end_time. If only end_time is declared without start_time or days, it will revert to default to the latest history state. When end_time is specified, it is not possible to declare entity_id. If entity_id is specified, end_time will be ignored.

None
minimal_response bool
False
no_attributes bool
False
significant_changes_only bool
False
callback callable

If wanting to access the database to get a large amount of data, using a direct call to this function will take a long time to run and lead to AD cancelling the task. To get around this, it is better to pass a function, which will be responsible of receiving the result from the database. The signature of this function follows that of a scheduler call.

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
list[list[dict[str, Any]]] | None

An iterable list of entity_ids and their history state.

Examples:

Get device state over the last 5 days.

>>> data = self.get_history(entity_id = "light.office_lamp", days = 5)

Get device state over the last 2 days and walk forward.

>>> import datetime
>>> from datetime import timedelta
>>> start_time = datetime.datetime.now() - timedelta(days = 2)
>>> data = self.get_history(entity_id = "light.office_lamp", start_time = start_time)

Get device state from yesterday and walk 5 days back.

>>> import datetime
>>> from datetime import timedelta
>>> end_time = datetime.datetime.now() - timedelta(days = 1)
>>> data = self.get_history(end_time = end_time, days = 5)

get_logbook(entity=None, start_time=None, end_time=None, days=None, callback=None, namespace=None) async

Gets access to the HA Database. This is a convenience function that allows accessing the HA Database. Caution must be taken when using this, as depending on the size of the database, it can take a long time to process.

Hits the /api/logbook/<timestamp> endpoint. See https://developers.home-assistant.io/docs/api/rest for more information

Parameters:

Name Type Description Default
entity str

Fully qualified id of the device to be querying, e.g., light.office_lamp or scene.downstairs_on. This can be any entity_id in the database. This method does not support multiple entity IDs. If no entity is specified, then all logbook entries for the period will be returned.

None
start_time datetime

The start time of the period covered. Defaults to 1 day before the time of the request.

None
end_time datetime

The end time of the period covered. Defaults to the current time if the days argument is also used.

None
days int

Number of days before the end time to include

None
callback Callable

Callback to run with the results of the request. The callback needs to take a single argument, a future object.

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
list[dict[str, str | datetime]] | None

A list of dictionaries, each representing a single entry for a

list[dict[str, str | datetime]] | None

single entity. The value for the when key of each dictionary

list[dict[str, str | datetime]] | None

gets converted to a datetime object with a timezone.

Examples:

>>> data = self.get_logbook("light.office_lamp")
>>> data = self.get_logbook("light.office_lamp", days=5)

get_service_info(service)

Get some information about what kind of data the service expects to receive, which is helpful for debugging.

The resulting dict is identical to the one returned sending get_services to the websocket. See fetching service actions <https://developers.home-assistant.io/docs/api/websocket#fetching-service-actions>__ for more information.

Parameters:

Name Type Description Default
service str

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

required

Returns:

Type Description
dict | None

Information about the service in a dict with the following keys: name, description, target, and

dict | None

fields.

get_tracker_details(person=True, namespace=None, copy=True)

Returns a list of all device tracker and the associated states.

Parameters:

Name Type Description Default
person boolean

If set to True, use person rather than device_tracker as the device type to query

True
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
copy bool

Whether to return a copy of the state dictionary. This is usually the desired behavior because it prevents accidental modification of the internal AD data structures. Defaults to True.

True

Examples:

>>> trackers = self.get_tracker_details()
>>> for tracker in trackers:
>>>     do something

get_tracker_state(*args, **kwargs)

get_tracker_state(entity_id: str, attribute: str | None = None, default: Any | None = None, namespace: str | None = None, copy: bool = True) -> str

Gets the state of a tracker.

Parameters:

Name Type Description Default
entity_id str

Fully qualified entity id of the device tracker or person to query, e.g., device_tracker.andrew or person.andrew.

required
attribute str

Name of the attribute to return

required
default Any

Default value to return when the attribute isn't found

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.

required
copy bool

Whether to return a copy of the state dictionary. This is usually the desired behavior because it prevents accidental modification of the internal AD data structures. Defaults to True.

required

Returns:

Type Description
str

The values returned depend in part on the

str

configuration and type of device trackers in the system. Simpler tracker

str

types like Locative or NMAP will return one of 2 states:

str
  • home
str
  • not_home
str

Some types of device tracker are in addition able to supply locations

str

that have been configured as Geofences, in which case the name of that

str

location can be returned.

Examples:

>>> state = self.get_tracker_state("device_tracker.andrew")
>>>     self.log(f"state is {state}")
>>> state = self.get_tracker_state("person.andrew")
>>>     self.log(f"state is {state}")

get_trackers(person=True, namespace=None)

Returns a list of all device tracker names.

Parameters:

Name Type Description Default
person boolean

If set to True, use person rather than device_tracker as the device type to query

True
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

Examples:

>>> trackers = self.get_trackers()
>>> for tracker in trackers:
>>>     do something
>>> people = self.get_trackers(person=True)
>>> for person in people:
>>>     do something

integration_entities(integration)

Get a list of entities that are associated with a given integration, such as hue or zwave_js.

See entities for an integration <https://www.home-assistant.io/docs/configuration/templating/#entities-for-an-integration>_ for more information.

is_device_attr(device_or_entity_id, attr_name, attr_value)

Get returns whether the value of attr_name for the given device or entity ID matches attr_value.

See device functions <https://www.home-assistant.io/docs/configuration/templating/#devices>_ for more information.

label_areas(label_name_or_id)

Get the list of area IDs tied to a given label ID or name.

See label functions <https://www.home-assistant.io/docs/configuration/templating/#labels>_ for more information.

label_devices(label_name_or_id)

Get the list of device IDs tied to a given label ID or name.

See label functions <https://www.home-assistant.io/docs/configuration/templating/#labels>_ for more information.

label_entities(label_name_or_id)

Get the list of entity IDs tied to a given label ID or name.

See label functions <https://www.home-assistant.io/docs/configuration/templating/#labels>_ for more information.

label_id(lookup_value)

Get the label ID for a given label name.

See label functions <https://www.home-assistant.io/docs/configuration/templating/#labels>_ for more information.

label_name(lookup_value)

Get the label name for a given label ID.

See label functions <https://www.home-assistant.io/docs/configuration/templating/#labels>_ for more information.

labels()

Get the full list of label IDs, or those for a given area ID, device ID, or entity ID.

See label functions <https://www.home-assistant.io/docs/configuration/templating/#labels>_ for more information.

last_pressed(button_id, namespace=None)

Only works on entities in the input_button domain

noone_home(person=True, namespace=None) async

Determines if the house/apartment is empty.

A convenience function to determine if no people are at home. Use this in preference to getting the state of group.all_devices() as it avoids a race condition when using state change callbacks for device trackers.

Parameters:

Name Type Description Default
person boolean

If set to True, use person rather than device_tracker as the device type to query

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

required

Returns:

Type Description
bool

Returns True if no one is home, False otherwise.

Examples:

>>> if self.noone_home():
>>>     do something
>>> if self.noone_home(person=True):
>>>     do something

notify(message, title=None, name=None, namespace=None, **kwargs) async

Sends a notification.

This is a convenience function for the notify service. It will send a notification to a named notification service. If the name is not specified, it will default to notify/notify.

Parameters:

Name Type Description Default
message str

Message to be sent to the notification service.

required
title str

Title of the notification.

None
name str

Name of the notification service.

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

Result of the notify function if any, see `service call notes

None

`__ for more details.

Examples:

>>> self.notify("Switching mode to Evening")
>>> self.notify("Switching mode to Evening", title = "Some Subject", name = "smtp")
    # will send a message through notify.smtp instead of the default notify.notify

notify_android(device, tag='appdaemon', title=None, message=None, target=None, **kwargs)

Convenience method for quickly creating mobile Android notifications

notify_ios(device, tag='appdaemon', **kwargs)

Convenience method for quickly creating mobile iOS notifications

ping() async

Gets the number of seconds

render_template(template, namespace=None, **kwargs) async

Renders a Home Assistant Template.

See the documentation for the Template Integration <https://www.home-assistant.io/integrations/template> and Templating Configuration <https://www.home-assistant.io/docs/configuration/templating> for more information.

Parameters:

Name Type Description Default
template str

The Home Assistant template to be rendered.

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 that get passed to the template rendering.

{}

Returns:

Type Description
Any

The rendered template in a native Python type.

Examples:

>>> self.render_template("{{ states('sun.sun') }}")
above_horizon
>>> self.render_template("{{ is_state('sun.sun', 'above_horizon') }}")
True
>>> self.render_template("{{ states('sensor.outside_temp') }}")
97.2
>>> self.render_template("hello {{ name }}", variables={"name": "bob"})
hello bob

restore_full(slug, password=None, timeout=30, hass_timeout=10) async

Restore from full backup.

Action hassio.restore_full <https://www.home-assistant.io/integrations/hassio/#action-hassiorestore_full>_

Parameters:

Name Type Description Default
slug str

Slug of backup to restore from.

required
password str

Optional password for backup.

None
timeout str | int | float

Timeout for the app thread to wait for a response from the main thread.

30
hass_timeout str | int | float

Timeout for AppDaemon waiting on a response from Home Assistant to respond to the backup request. Cannot be set lower than the timeout value.

10

restore_partial(slug, homeassistant=None, addons=None, folders=None, password=None, timeout=30, hass_timeout=10) async

Restore from partial backup.

Action hassio.restore_partial <https://www.home-assistant.io/integrations/hassio/#action-hassiorestore_partial>_

Parameters:

Name Type Description Default
slug str

Slug of backup to restore from.

required
homeassistant bool

Whether to restore Home Assistant, true or false. Defaults to False.

None
addons Iterable[str]

List of add-on slugs to restore.

None
folders Iterable[str]

List of directories to restore.

None
password str

Optional password for backup.

None
timeout str | int | float

Timeout for the app thread to wait for a response from the main thread.

30
hass_timeout str | int | float

Timeout for AppDaemon waiting on a response from Home Assistant to respond to the backup request. Cannot be set lower than the timeout value.

10

Returns:

Name Type Description
dict dict

Response from the restore service.

run_script(entity_id, namespace=None, return_immediately=True, **kwargs)

Runs a script in Home Assistant

Parameters:

Name Type Description Default
entity_id str

The entity ID of the script to run, if it doesn't start with script, it will be added.

required
namespace str

The namespace to use. Defaults to the namespace of the calling app.

None
return_immediately bool

Whether to return immediately or wait for the script to complete. Defaults to True. See the Home Assistant documentation for more information. https://www.home-assistant.io/integrations/script/#waiting-for-script-to-complete

True
**kwargs

Additional keyword arguments to pass to the service call.

{}

Returns:

Name Type Description
dict dict

The result of the service call.

select_option(entity_id, option, namespace=None) async

Sets the value of an input_option.

This is a convenience function for the input_select.select_option function. It can set the value of an input_select in Home Assistant.

Parameters:

Name Type Description Default
entity_id str

Fully qualified id of input_select to be changed (e.g., input_select.mode).

required
option str

The new value to set the input_select to.

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 get passed to the service call.

required

Returns:

Type Description
None

Result of the select_option function if any, see service call notes <APPGUIDE.html#some-notes-on-service-calls>__ for more details.

Examples:

>>> self.select_option("input_select.mode", "Day")

set_textvalue(entity_id, value, namespace=None) async

Sets the value of an input_text.

This is a convenience function for the input_text.set_value function. It can set the value of an input_text in Home Assistant.

Parameters:

Name Type Description Default
entity_id str

Fully qualified id of input_text to be changed (e.g., input_text.text1).

required
value str

The new value to set the input_text to.

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

Result of the set_textvalue function if any, see service call notes <APPGUIDE.html#some-notes-on-service-calls>__ for more details.

Examples:

>>> self.set_textvalue("input_text.text1", "hello world")

set_value(entity_id, value, namespace=None) async

Sets the value of an input_number.

This is a convenience function for the input_number.set_value function. It can set the value of an input_number in Home Assistant.

Parameters:

Name Type Description Default
entity_id str

Fully qualified id of input_number to be changed (e.g., input_number.alarm_hour).

required
value int or float

The new value to set the input_number to.

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 get passed to the service call.

required

Returns:

Type Description
None

Result of the set_value function if any, see service call notes <APPGUIDE.html#some-notes-on-service-calls>__ for more details.

Examples:

>>> self.set_value("input_number.alarm_hour", 6)

time_since_last_press(button_id, namespace=None)

Only works on entities in the input_button domain

toggle(entity_id, namespace=None, **kwargs) async

Toggles between on and off for the selected entity.

This is a convenience function for the homeassistant.toggle function. It is able to flip the state of pretty much anything in Home Assistant that can be turned on or off.

Parameters:

Name Type Description Default
entity_id str

Fully qualified id of the thing to be turned off (e.g., light.office_lamp, scene.downstairs_on).

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 get passed to the service call.

{}

Returns:

Type Description
dict

Result of the toggle function if any, see service call notes <APPGUIDE.html#some-notes-on-service-calls>__ for more details.

Examples:

>>> self.toggle("switch.backyard_lights")
>>> self.toggle("light.office_1", color_name="green")

turn_off(entity_id, namespace=None, **kwargs) async

Turns off a Home Assistant entity.

This is a convenience function for the homeassistant.turn_off function. It can turn off pretty much anything in Home Assistant that can be turned off (e.g., Lights, Switches, etc.).

Parameters:

Name Type Description Default
entity_id str

Fully qualified id of the thing to be turned off (e.g., light.office_lamp, scene.downstairs_on).

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 get passed to the service call.

{}

Returns:

Type Description
dict

Result of the turn_off function if any, see `service call notes

dict

`__ for more details.

Examples:

Turn off a switch.

>>> self.turn_off("switch.backyard_lights")

Turn off a scene.

>>> self.turn_off("scene.bedroom_on")

turn_on(entity_id, namespace=None, **kwargs) async

Turns on a Home Assistant entity.

This is a convenience function for the homeassistant.turn_on function. It can turn on pretty much anything in Home Assistant that can be turned on or run (e.g., Lights, Switches, Scenes, Scripts, etc.).

Note that Home Assistant will return a success even if the entity name is invalid.

Parameters:

Name Type Description Default
entity_id str

Fully qualified id of the thing to be turned on (e.g., light.office_lamp, scene.downstairs_on). namespace (str, optional): 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.

required
**kwargs optional

Zero or more keyword arguments that get passed to the service call.

{}

Returns:

Type Description
dict

Result of the turn_on function if any, see service call notes <APPGUIDE.html#some-notes-on-service-calls>__ for more details.

Examples:

Turn on a switch.

>>> self.turn_on("switch.backyard_lights")

Turn on a scene.

>>> self.turn_on("scene.bedroom_on")

Turn on a light and set its color to green.

>>> self.turn_on("light.office_1", color_name = "green")

MQTT

appdaemon.plugins.mqtt.mqttapi

Mqtt

Bases: ADBase, ADAPI

A list of API calls and information specific to the MQTT plugin.

App Creation

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

.. code:: python

import mqttapi as mqtt

class MyApp(mqtt.Mqtt:

    def initialize(self):
Making Calls to MQTT

AD API's call_service() is used to carry out service calls from within an AppDaemon app. This allows the app to carry out one of the following services:

  • Publish
  • Subscribe
  • Unsubscribe

By simply specifying within the function what is to be done. It uses configuration specified in the plugin configuration which simplifies the call within the app significantly. Different brokers can be accessed within an app, as long as they are all declared when the plugins are configured, and using the namespace parameter.

Examples ^^^^^^^^

.. code:: python

# if wanting to publish data to a broker
self.call_service("publish", topic = "homeassistant/bedroom/light", payload = "ON")
# if wanting to unsubscribe a topic from a broker in a different namespace
self.call_service("unsubscribe", topic = "homeassistant/bedroom/light", namespace = "mqtt2")

The MQTT API also provides 3 convenience functions to make calling of specific functions easier an more readable. These are documented in the following section.

is_client_connected(**kwargs) async

Returns TRUE if the MQTT plugin is connected to its broker, FALSE otherwise.

This a helper function used to check or confirm within an app if the plugin is connected to its broker. This can be useful, if it is necessary to be certain the client is connected, so if not the app can internally store the data in a queue, and wait for connection before sending the data.

Different brokers can be accessed within an app, as long as they are all declared when the plugins are configured, and using the namespace parameter.

Parameters:

Name Type Description Default
**kwargs optional

Zero or more keyword arguments.

{}

Other Parameters:

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

Returns:

Type Description
bool

Boolean.

Examples:

Check if client is connected, and send data.

>>> if self.clientConnected():
>>>     self.mqtt_publish(topic, payload)

Check if client is connected in mqtt2 namespace, and send data.

>>> if self.clientConnected(namespace = 'mqtt2'):
>>>     self.mqtt_publish(topic, payload, namespace = 'mqtt2')

listen_event(callback, event=None, **kwargs) async

Listens for changes within the MQTT plugin.

Unlike other plugins, MQTT does not keep state. All MQTT messages will have an event which is set to MQTT_MESSAGE by default. This can be changed to whatever that is required in the plugin configuration.

Parameters:

Name Type Description Default
callback Callable

Function to be invoked when the requested event occurs. It must conform to the standard Event Callback format documented Here <APPGUIDE.html#about-event-callbacks>__.

required
event str

Name of the event to subscribe to. Can be the declared event_name parameter as specified in the plugin configuration. If no event is specified, listen_event() will subscribe to all MQTT events within the app's functional namespace.

None
**kwargs optional

One or more keyword value pairs representing App specific parameters to supply to the callback. If the keywords match values within the event data, they will act as filters, meaning that if they don't match the values, the callback will not fire.

As an example of this, a specific topic or wildcard can be listened to, instead of listening to all topics subscribed to. For example, if data is sent to a subscribed topic, it will generate an event as specified in the config; if we want to listen to a specific topic or wildcard, topic or wildcard can be passed in, and used to filter the callback by supplying them as keyword arguments. If you include keyword values, the values supplied to the listen_event() call must match the values in the event or it will not fire. If the keywords do not match any of the data in the event they are simply ignored.

Filtering will work with any event type, but it will be necessary to figure out the data associated with the event to understand what values can be filtered on. If using wildcard, only those used to subscribe to the broker can be used as wildcards. The plugin supports the use both single and multi-level wildcards.

{}

Other Parameters:

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

binary bool

If wanting the payload to be returned as binary, this should be specified. If not given, AD will return the payload as decoded data. It should be noted that it is not possible to have different apps receive both binary and non-binary data on the same topic

Returns:

Type Description
str

A handle that can be used to cancel the callback.

Examples:

Listen all events.

>>> self.listen_event(self.mqtt_message_received_event, "MQTT_MESSAGE")

Listen events for a specific subscribed topic.

>>> self.listen_event(self.mqtt_message_received_event, "MQTT_MESSAGE", topic='homeassistant/bedroom/light')

Listen events for a specific subscribed high level topic.

>>> self.listen_event(self.mqtt_message_received_event, "MQTT_MESSAGE", wildcard='homeassistant/#')
>>> self.listen_event(self.mqtt_message_received_event, "MQTT_MESSAGE", wildcard='homeassistant/+/motion')

Listen events for binary payload

>>> self.listen_event(self.mqtt_message_received_event, "MQTT_MESSAGE", topic='hermes/audioServer/#', binary=True)

Listen plugin's disconnected events from the broker.

>>> self.listen_event(self.mqtt_message_received_event, "MQTT_MESSAGE", state='Disconnected', topic=None)

Listen plugin's' connected events from the broker.

>>> self.listen_event(self.mqtt_message_received_event, "MQTT_MESSAGE", state='Connected', topic=None)
Notes

At this point, it is not possible to use single level wildcard like using homeassistant/+/light instead of homeassistant/bedroom/light. This could be added later, if need be.

mqtt_publish(topic, payload=None, **kwargs)

Publishes a message to a MQTT broker.

This helper function used for publishing a MQTT message to a broker, from within an AppDaemon app. It uses configuration specified in the plugin configuration which simplifies the call within the App significantly.

Different brokers can be accessed within an app, as long as they are all declared when the plugins are configured, and using the namespace parameter.

Parameters:

Name Type Description Default
topic str

topic the payload is to be sent to on the broker (e.g., homeassistant/bedroom/light).

required
payload Any

data that is to be sent to on the broker (e.g., 'ON').

None
**kwargs optional

Zero or more keyword arguments.

{}

Other Parameters:

Name Type Description
qos int

The Quality of Service (QOS) that is to be used when sending the data to the broker. This is has to be an integer (Default value: 0).

retain bool

This flag is used to specify if the broker is to retain the payload or not (Default value: False).

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.

Returns:

Type Description
None

None.

Examples:

Send data to the default HA broker.

self.mqtt_publish("homeassistant/bedroom/light", "ON")

Send data to a different broker.

self.mqtt_publish("homeassistant/living_room/light", "ON", qos = 0, retain = True, namespace = "mqtt2")

mqtt_subscribe(topic, **kwargs)

Subscribes to a MQTT topic.

This helper function used for subscribing to a topic on a broker, from within an AppDaemon App.

This allows the apps to now access events from that topic, in realtime. So outside the initial configuration at plugin config, this allows access to other topics while the apps runs. It should be noted that if AppDaemon was to reload, the topics subscribed via this function will not be available by default. On those declared at the plugin config will always be available. It uses configuration specified in the plugin configuration which simplifies the call within the app significantly.

Different brokers can be accessed within an app, as long as they are all declared when the plugins are configured, and using the namespace parameter.

Parameters:

Name Type Description Default
topic str | list

The topic to be subscribed to on the broker (e.g., homeassistant/bedroom/light).

required
**kwargs optional

Zero or more keyword arguments.

{}

Other Parameters:

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

Returns:

Type Description
None

None.

Examples:

>>> self.mqtt_subscribe("homeassistant/bedroom/light")
>>> self.mqtt_subscribe(["homeassistant/bedroom/light", "zigbee2mqtt/Living Room Light"])

mqtt_unsubscribe(topic, **kwargs)

Unsubscribes from a MQTT topic.

A helper function used to unsubscribe from a topic on a broker, from within an AppDaemon app.

This denies the Apps access events from that topic, in realtime. It is possible to unsubscribe from topics, even if they were part of the topics in the plugin config; but it is not possible to unsubscribe #. It should also be noted that if AppDaemon was to reload, the topics unsubscribed via this function will be available if they were configured with the plugin by default. It uses configuration specified in the plugin configuration which simplifies the call within the app significantly.

Different brokers can be accessed within an app, as long as they are all declared when the plugins are configured, and using the namespace parameter.

Parameters:

Name Type Description Default
topic str | list

The topic to be unsubscribed from on the broker (e.g., homeassistant/bedroom/light).

required
**kwargs optional

Zero or more keyword arguments.

{}

Other Parameters:

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

Returns:

Type Description
None

None.

Examples:

>>> self.mqtt_unsubscribe("homeassistant/bedroom/light")