Home Assistant Guide

Simple tutorials for powerful automations

Deep Dive: Using the Hass API in AppDaemon

AppDaemon's hass API layer empowers you to interact with Home Assistant with a rich set of features - far beyond simple state listening or service calls. Let's explore what's possible and how to use it!

1. What the Hass API Provides

  • WebSocket + REST connectivity for reliable two-way interaction .
  • Convenience helpers: turn_on, turn_off, toggle, wrapping Home Assistant services.
  • Generic service calls via call_service(), allowing full flexibility.
  • State handling: manage state with get_state() and set_state().
  • Event scheduling: timer-based callbacks via run_in, run_every, run_daily.
  • Service return values support: use return_response=True to get call results.

2. Common Hass API Methods & Examples

a) Calling Services

self.call_service("light/turn_on", entity_id="light.kitchen", brightness=200)
self.turn_off("switch.garden")           # convenience method
self.toggle("scene.movie_time")          # convenience toggle

Use return_response=True to capture results:

result = self.call_service("notify/telegram", message="Hi", return_response=True)
self.log(f"Service result: {result['success']}")

b) Getting & Setting State

temp = self.get_state("sensor.living_room_temp")
all_lights = self.get_state("light")
self.set_state("sensor.test_sensor", state="42", attributes={"unit_of_measurement":"°C"})

set_state() is useful for testing, creating virtual sensors, or simulating changes .

c) Listening to State Changes

self.listen_state(self.motion_detected, "binary_sensor.motion")
def motion_detected(self, entity, attribute, old, new, kwargs):
    self.log(f"Motion changed from {old} to {new}")

Control filtering via attribute, new=, old=, duration=, immediate=, and oneshot= .

d) Scheduling Callbacks

# After 60s:
self.run_in(self.turn_off_light, 60, entity="light.hall")

# Every day at 07:00:
self.run_daily(self.good_morning, "07:00:00")

# Every 15 mins:
self.run_every(self.poll_temp, "now", 900)

These avoid blocking your app and integrate with AppDaemon's scheduler .

e) Entity Object Interface

self.kitchen = self.get_entity("light.kitchen")
self.kitchen.listen_state(self.handler, attribute="brightness")

This wraps get_state() and listen_state() at the object level .

f) Advanced Features

  • Service registration: create custom services with register_service().
  • Admin services: control AppDaemon apps themselves (start, stop, reload) via namespaced calls.
  • Web endpoints: add REST endpoints inside your app with register_endpoint() or register_route() and integrate with external services.
  • Namespaces: control isolation and persistence of entities across app lifetimes .
  • Startup control: delay app initialization until HS conditions (e.g., Home Assistant fully booted) are met.

3. Putting It All Together: Example App

import appdaemon.plugins.hass.hassapi as hass

class SmartMorning(hass.Hass):

    def initialize(self):
        # Wait for Home Assistant to start fully
        self.listen_event(self.startup_complete, "homeassistant_start")

    def startup_complete(self, event_name, data, kwargs):
        # Schedule morning routine
        self.run_daily(self.morning_routine, "07:00:00")

    def morning_routine(self, kwargs):
        # Get today's weather
        weather = self.get_state("weather.home")
        self.log(f"Today's forecast: {weather}")

        # Gradually turn on lights
        self.call_service("light/turn_on", entity_id="light.bedroom", brightness=1)
        self.run_in(self.brighten, 60, entity="light.bedroom", step=100)

    def brighten(self, kwargs):
        entity = kwargs["entity"]
        brightness = int(self.get_state(entity, attribute="brightness") or 0)
        brightness = min(255, brightness + kwargs.get("step",50))
        self.turn_on(entity, brightness=brightness)

        if brightness < 255:
            self.run_in(self.brighten, 60, entity=entity, step=50)

This example demonstrates startup waiting, state reading, scheduling, looping logic, and service calls - all coordinated through the Hass API.

4. Why Use the Hass API?

  • Extensive coverage: nearly everything you can do in the UI or via WebSocket is available here.
  • Pythonic syntax: helpers make coding easier and more readable.
  • Event-driven + scheduled logic: mix reactive and time-based behavior seamlessly.
  • Dynamic and reusable: classes, namespaces, and scheduling support clean, maintainable code.

5. Learn More & Resources

With this deeper knowledge of the Hass API, you're ready to build robust and intelligent Home Assistant automations in full Python. Experiment, extend, and create!