- Python Remote API
- Get configuration
- Get details about services, events, and entitites
- Get the state of an entity
- Set the state of an entity
- Blinking all entities of a domain
- Control a single entity
- Specify a timeout
- Send a notification
- Examples
- List all sensors and their value
- Show difference between last_changed and last_updated
- Development Guide
- Usage
- Services
- Entities
- Using Client with async / await
- Async Services
- Async Entities
- What’s Next?
Python Remote API
See the developer documentation for a full overview of the documentation. The rest of this page will contain examples on how to use it.
In the package homeassistant.remote a Python API on top of the HTTP API can be found. If you are not using the frontend in your setup then you need to add the api component to your configuration.yaml file to use the Python Remote API.
A simple way to get all current entities is to visit the “Set State” page in the “Developer Tools”. For the examples below just choose one from the available entries. Here the sensor sensor.office_temperature and the switch switch.livingroom_pin_2 are used.
First import the module and setup the basics:
import homeassistant.remote as remote api = remote.API('127.0.0.1', 'password') print(remote.validate_api(api))
Get configuration
Get the current configuration of a Home Assistant instance:
import homeassistant.remote as remote api = remote.API('127.0.0.1', 'password') print(remote.get_config(api))
Get details about services, events, and entitites
The output from this is similar to the output you’d find via the frontend, using the Developer Tools.
import homeassistant.remote as remote api = remote.API('127.0.0.1', 'YOUR_PASSWORD') print('-- Available services:') services = remote.get_services(api) for service in services: print(service['services']) print('\n-- Available events:') events = remote.get_event_listeners(api) for event in events: print(event) print('\n-- Available entities:') entities = remote.get_states(api) for entity in entities: print(entity)
Get the state of an entity
To get the details of a single entity, use get_state :
import homeassistant.remote as remote api = remote.API('127.0.0.1', 'YOUR_PASSWORD') office_temp = remote.get_state(api, 'sensor.office_temperature') print('<> is <> <>.'.format( office_temp.name, office_temp.state, office_temp.attributes['unit_of_measurement']) )
This outputs the details which are stored for this entity, ie:
Office Temperature is 19 °C.
Switches work the same way. The only difference is that both entities have different attributes.
import homeassistant.remote as remote api = remote.API('127.0.0.1', 'YOUR_PASSWORD') switch_livingroom = remote.get_state(api, 'switch.livingroom_pin_2') print('<> is <>.'.format( switch_livingroom.name, switch_livingroom.state) )
Set the state of an entity
Of course, it’s possible to set the state as well:
import homeassistant.remote as remote from homeassistant.const import STATE_ON api = remote.API('127.0.0.1', 'YOUR_PASSWORD') remote.set_state(api, 'sensor.office_temperature', new_state=123) remote.set_state(api, 'switch.livingroom_pin_2', new_state=STATE_ON)
The state will be set to the new values until the next update occurs.
Blinking all entities of a domain
If you want to turn on all entities of a domain, retrieve the service via get_services and act on that:
import time import homeassistant.remote as remote api = remote.API('127.0.0.1', 'YOUR_PASSWORD') domain = 'switch' remote.call_service(api, domain, 'turn_on') time.sleep(10) remote.call_service(api, domain, 'turn_off')
Control a single entity
To turn on or off a single switch, pass the ID of the entity:
import time import homeassistant.remote as remote api = remote.API('127.0.0.1', 'YOUR_PASSWORD') domain = 'switch' switch_name = 'switch.livingroom_pin_2' remote.call_service(api, domain, 'turn_on', 'entity_id': '<>'.format(switch_name)>) time.sleep(5) remote.call_service(api, domain, 'turn_off', 'entity_id': '<>'.format(switch_name)>)
Specify a timeout
The default timeout for an API call with call_service is 5 seconds. Services taking longer than this to return will raise homeassistant.exceptions.HomeAssistantError: Timeout , unless provided with a longer timeout.
import homeassistant.remote as remote api = remote.API('host', 'password') domain = 'switch' # Assuming switch.timeout_switch takes 10 seconds to return switch_name = 'switch.timeout_switch' # Raises homeassistant.exceptions.HomeAssistantError: Timeout when talking to remote.call_service(api, domain, 'turn_on', 'entity_id': switch_name>) # Runs withous exception remote.call_service(api, domain, 'turn_on', 'entity_id': switch_name>, timeout=11)
Send a notification
The example uses the Jabber notification platform to send a single message to the given recipient in the configuration.yaml file:
import homeassistant.remote as remote api = remote.API('127.0.0.1', 'YOUR_PASSWORD') domain = 'notify' data = "title":"Test", "message":"A simple test message from HA."> remote.call_service(api, domain, 'jabber', data)
Examples
This section contains a couple of sample scripts.
List all sensors and their value
If you want to see, export or list all sensor states then an easy way to do it, is to get all entities and filter for the one you are looking for.
import homeassistant.remote as remote api = remote.API('127.0.0.1', 'YOUR_PASSWORD') entities = remote.get_states(api) for entity in entities: if entity.entity_id.startswith('sensor'): data = remote.get_state(api, entity.entity_id) print('<>: <>'.format(data.attributes['friendly_name'], data.state))
Show difference between last_changed and last_updated
The documentation about the State Objects describes the last_changed and last_updated fields. This example shows how it works in practice.
import time from prettytable import PrettyTable import homeassistant.remote as remote api = remote.API('127.0.0.1', 'YOUR_PASSWORD') ACTIONS = 'Create sensor': [21, 'Test'], 'No new sensor value': [21, 'Test'], 'New sensor value': [22, 'Test'], 'Update attribute': [22, 'Test1'], > output = PrettyTable(['Action', 'Last changed', 'Last updated']) for key, value in ACTIONS.items(): remote.set_state(api, 'sensor.test', new_state=value[0], attributes='friendly_name': value[1]>) data = remote.get_state(api, 'sensor.test') output.add_row([key, data.last_changed, data.last_updated]) time.sleep(2) print(output)
Development Guide
- Introduction
- Architecture
- Components
- Setting up Environment
- Submit your Work
- Checklist
- Style guidelines
- Testing
- Catching up with Reality
- Validation
- Hass object
- Events
- States
- Services
- Config
- Checklist creating a platform
- Example sensor platform
- Example light platform
- Checklist creating a component
- Loading components
- Requirements & Dependencies
- Handling events
- States
- Visibility
- Loading Platforms
- Component Discovery
- Firing intents
- Handling intents
- Registering sentences
- Introduction to asyncio
- Categorizing Functions
- Working with Async
- Miscellaneous
- Add State Card
- Add More Info Dialog
- Add Custom Panels
- Add Custom UI
- Backend Localization
- Custom Component Localization
- Translation
- Debugging Hass.io
- Tutorial: Making your first add-on
- Configuration
- Communication
- Local Testing
- Publishing
- Presentation
- Repositories
- Python API
- Websocket API
- REST API
- Python REST API
- Server-sent events
- Standards
- Create a new page
- Contributor License Agreement
- Privacy Policy
- Terms of Service
- Code of Conduct
- Credits
- License
Contact us at hello@home-assistant.io (no support!).
Website powered by Jekyll and the Oscalite theme.
Hosted by GitHub and served by CloudFlare.home-assistant.io is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
Usage
This library is centered around the Client class. Once you have have your api base url and Long Lived Access Token from Home Assistant we can start to do stuff. The rest of this guide assumes you have the Client saved to a client variable. Most of these examples require some integrations to be setup inside Home Assistant for the examples to actually work. The most commonly used features of this library include triggering services and getting and modifying entity states.
1import os 2from homeassistant_api import Client 3 4URL = '' 5TOKEN = '' 6 7# Assigns the Client object to a variable and checks if it's running. 8client = Client(URL, TOKEN) 9 10service = client.get_domain("light") # Gets the light service domain from Home Assistant 11 12service.turn_on(entity_id="light.my_living_room_light") 13# Triggers the light.turn_on service on the entity `light.my_living_room_light`
1 from datetime import datetime 2 from homeassistant_api import Client 3 4 # You can also initialize Client before you use it. 5 6 client = Client("https://foobarhomeassistant.duckdns.org:8123/api", "mylongtokenpasswordthingyfoobar") 7 8 # In order to activate the requests session you to use the Client context manager like so. 9 # Using it as a context manager will automatically close the session when you're done with it. 10 # But also will *ping* your Home Assistant instance to make sure it's running. 11 with client: 12 while True: 13 sun = client.get_entity(entity_id="sun.sun") 14 state = sun.get_state() # Because requests are cached we reduce bandwidth usage :D 15 # Cache expires every 30 seconds by default. 16 if state.state == "below_horizon": 17 difference = datetime.now() - state.last_updated 18 print("Sun set", difference.seconds, "seconds ago.") 19 break
Services
light = client.get_domain("light") print(light.services) # changed_states = light.toggle(entity_id="light.light_bulb_1")
Entities
entity_groups = client.get_entities() # , 'zone': , . > door = client.get_entity(entity_id='cover.garage_door') # "> states = client.get_states() # [, . ] state = client.get_state('sun.sun') # new_state = client.set_state( State(state='my ToaTallY Whatever vAlUe 12t87932', entity_id='my_favorite_colors.number_one') ) # # Alternatively you can set state from the entity class itself from homeassistant_api import State # If you are wondering where door came from its about 15 lines up. door.set_state(State(state="My new state", attributes="open_height": "5ft">)) #
Using Client with async / await
Are you wondering if you can use homeassistant_api using Python’s async / await syntax? Good news! You can!
Async Services
import asyncio from homeassistant_api import Client # Initialize client like usual, except with the :code:`use_async` keyword. client = Client(url, token, use_async=True) async def main(): domains = await client.async_get_domains() print(domains) # , 'notify': > cover = await client.async_get_domain("cover") changed_states = await cover.close_cover(entity_id='cover.garage_door') # [] asyncio.get_event_loop().run_until_complete(main())
Async Entities
entity_groups = await client.async_get_entities() # , 'zone': , . > door = await client.async_get_entity(entity_id='cover.garage_door') # "> states = await client.async_get_states() # [, . ] state = await client.async_get_state('sun.sun') # new_state = await client.async_set_state( State( state='my ToaTallY Whatever vAlUe 12t87932', entity_id='my_favorite_colors.number_one' ) ) # # Alternatively you can set state from the entity class itself from homeassistant_api import State # If you are wondering where door came from its about 15 lines up. door.state.state = 'My new state' door.state.attributes.update('open_height': '5ft'>) await door.async_set_state(door.state) #
What’s Next?
Browse below to learn more about what you can do with homeassistant_api .
© Copyright 2023, Nate Larsen. Revision 748d9794 .