### Basic Python Example Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/index.rst This snippet demonstrates basic usage of the Homeassistant API library in Python. It requires the library to be installed. ```python from homeassistant_api import HomeAssistantAPI async def main(): async with HomeAssistantAPI(url="http://localhost:8123", token="YOUR_LONG_LIVED_ACCESS_TOKEN") as hass: # Example: Get all lights lights = await hass.lights.get_all() print(f"Found {len(lights)} lights.") # Example: Turn on a light if lights: await hass.lights.turn_on(lights[0].entity_id) print(f"Turned on {lights[0].entity_id}") if __name__ == "__main__": import asyncio asyncio.run(main()) ``` -------------------------------- ### Install Development Version with Git and Uv Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/quickstart.rst Clone the repository and use 'uv sync' to install the latest development version and its dependencies. Ensure you have Git and Uv installed. ```bash git clone https://github.com/HomeAssistant-API/HomeAssistantAPI cd HomeAssistantAPI python -m pip install uv uv sync ``` -------------------------------- ### Example Environment Variables for Docker Setup Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/CONTRIBUTING.rst These environment variables are required when using the repository's Docker setup for Home Assistant. Ensure these are set in your environment before running the Docker Compose command. ```bash HOMEASSISTANTAPI_URL=http://localhost:8123/api HOMEASSISTANTAPI_WS_URL=ws://localhost:8123/api/websocket HOMEASSISTANTAPI_TOKEN=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJkMDE4YjQ4YzMyZTE0ODNhYjY2ZWQzOTZmYzg3ZDAyNiIsImlhdCI6MTY3ODU3NDUwMSwiZXhwIjoxOTkzOTM0NTAxfQ.fyhnfwpont4uE0gn46_Ut_pPmyn4QWv0MDaVAei2PPk ``` -------------------------------- ### Install Latest Stable Version with Pip Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/quickstart.rst Use this command to install the latest stable version of the library from PyPI. This is the recommended installation method. ```bash pip install homeassistant_api ``` -------------------------------- ### Install Latest Development Version with Pip Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/quickstart.rst Install the latest development version directly from GitHub using pip. This is useful for testing the newest features. ```bash pip install git+https://github.com/HomeAssistant-API/HomeAssistantAPI ``` -------------------------------- ### Get and Trigger Light Services Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Demonstrates how to retrieve available services for a domain (e.g., 'light') and trigger a service like 'toggle'. ```python light = client.get_domain("light") print(light.services) # {'turn_on': Service(service_id='turn_on', name='Turn on', description='Turn on one or more lights and adjust properties of the light, even when they are turned on already. ', ...) changed_states = light.toggle(entity_id="light.light_bulb_1") ``` -------------------------------- ### Async Get Domains Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Asynchronously retrieve a list of available domains in Home Assistant. Requires an AsyncClient instance. ```python import asyncio from homeassistant_api import AsyncClient async def main(): async with AsyncClient(url, token) as client: domains = await client.get_domains() print(domains) ``` -------------------------------- ### Get and Set Climate Temperature via WebSocket Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Shows how to access services for a 'climate' domain using a WebSocket client and set the temperature for a thermostat. ```python climate = ws_client.get_domain("climate") print(climate.services) # {'set_temperature': Service(service_id='set_temperature', name='Set temperature', description='Set the target temperature for a climate entity. ', ...) changed_states = climate.set_temperature(entity_id="climate.my_thermostat", temperature=72) ``` -------------------------------- ### AsyncWebsocketClient Get Rendered Template Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Render a Jinja2 template using the AsyncWebsocketClient. ```APIDOC ## AsyncWebsocketClient Get Rendered Template ### Description Render a Jinja2 template string on the Home Assistant server. ### Method `await ws_client.get_rendered_template(template_string)` ### Parameters - **template_string** (string, required) - The Jinja2 template to render. ### Response - **rendered_template** (string) - The result of the template rendering. ``` -------------------------------- ### Retrieve and Manage Entities Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Provides examples for fetching entity groups, specific entities, all states, and individual states. It also shows how to set an entity's state directly or by updating its local state object. ```python entity_groups = client.get_entities() # {'person': , '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 update state from the entity class itself. # Modify the entity's local state object, then push it to Home Assistant. door.state.state = 'My new state' door.state.attributes.update({'open_height': '5ft'}) door.update_state() # # All of these methods work with the WebsocketClient as well. ``` -------------------------------- ### AsyncClient Get Entities Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Retrieve a dictionary of all entities grouped by their domain using the AsyncClient. ```APIDOC ## AsyncClient Get Entities ### Description Get a dictionary of all entities, grouped by their domain. ### Method `await client.get_entities()` ### Response - **entity_groups** (dict) - A dictionary where keys are domain names and values are group objects containing entities. ``` -------------------------------- ### AsyncClient Get Domains Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Retrieve a list of available domains in Home Assistant using the AsyncClient. ```APIDOC ## AsyncClient Get Domains ### Description Get a dictionary of all available domains in Home Assistant. ### Method `await client.get_domains()` ### Response - **domains** (dict) - A dictionary where keys are domain names and values are domain objects. ``` -------------------------------- ### AsyncClient Get Domain Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Retrieve a specific domain object using the AsyncClient. ```APIDOC ## AsyncClient Get Domain ### Description Get a specific domain object by its name. ### Method `await client.get_domain(domain_name)` ### Parameters - **domain_name** (string, required) - The name of the domain to retrieve. ### Response - **domain** (object) - The domain object. ``` -------------------------------- ### Async Get All States Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Asynchronously retrieve the states of all entities. Requires an AsyncClient instance. ```python states = await client.get_states() ``` -------------------------------- ### Run Home Assistant Server with Docker Compose Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/CONTRIBUTING.rst Use Docker Compose to spin up a Home Assistant development environment. This command starts a container running Home Assistant with port 8123 exposed. ```bash $ docker compose up server ``` -------------------------------- ### Synchronous Client with Persistent File Cache Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/advanced.rst Implement persistent caching using CachedSession by specifying a cache_name. This example uses a file path for the cache, defaulting to SQLite. ```python from pathlib import Path from homeassistant_api import Client from niquests_cache.session import CachedSession client = Client( "", "", session=CachedSession(cache_name=Path('.cache') / 'http'), # by default uses sqlite backend ) with client: # Grab and update some cool entities and services inside your installation. ... ``` -------------------------------- ### AsyncClient Get States Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Retrieve a list of all current states for all entities using the AsyncClient. ```APIDOC ## AsyncClient Get States ### Description Get a list of the current states for all entities in Home Assistant. ### Method `await client.get_states()` ### Response - **states** (tuple) - A tuple of State objects, each representing the current state of an entity. ``` -------------------------------- ### AsyncClient Get Entity Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Retrieve a specific entity by its entity ID using the AsyncClient. ```APIDOC ## AsyncClient Get Entity ### Description Get a specific entity by its unique entity ID. ### Method `await client.get_entity(entity_id)` ### Parameters - **entity_id** (string, required) - The unique ID of the entity. ### Response - **entity** (object) - The entity object, including its current state. ``` -------------------------------- ### Async Get Entity Groups Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Asynchronously retrieve groups of entities. Requires an AsyncClient instance. ```python entity_groups = await client.get_entities() ``` -------------------------------- ### AsyncClient Get State Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Retrieve the current state of a specific entity by its entity ID using the AsyncClient. ```APIDOC ## AsyncClient Get State ### Description Get the current state of a specific entity. ### Method `await client.get_state(entity_id)` ### Parameters - **entity_id** (string, required) - The unique ID of the entity. ### Response - **state** (object) - The State object for the specified entity. ``` -------------------------------- ### Async Get Specific Entity Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Asynchronously retrieve a specific entity by its entity ID. Requires an AsyncClient instance. ```python door = await client.get_entity(entity_id='cover.garage_door') ``` -------------------------------- ### Async Get Specific State Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Asynchronously retrieve the state of a single entity by its entity ID. Requires an AsyncClient instance. ```python state = await client.get_state('sun.sun') ``` -------------------------------- ### Initialize WebSocket Client for Event Handling Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Demonstrates the initialization of the WebSocket client, which is necessary for listening to and firing events within Home Assistant. ```python from homeassistant_api import WebsocketClient WS_URL = '' # Example: 'ws://homeassistant.local:8123/api/websocket' TOKEN = '' ``` -------------------------------- ### Initialize Sync REST Client with Context Manager Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Illustrates initializing the synchronous REST API client and using it within a context manager. The context manager ensures the session is closed and pings the Home Assistant instance to verify it's running. ```python from datetime import datetime from homeassistant_api import Client # You can also initialize Client before you use it. client = Client("http://homeassistant.local:8123/api", "mylongtokenpasswordthingyfoobar") # In order to activate the requests session you need to use the Client context manager like so. # Using it as a context manager will automatically close the session when you're done with it. # But also will *ping* your Home Assistant instance to make sure it's running. with client: while True: sun = client.get_entity(entity_id="sun.sun") state = sun.get_state() # Because requests are cached we reduce bandwidth usage :D # Cache expires every 30 seconds by default. if state.state == "below_horizon": difference = datetime.now() - state.last_updated print("Sun set", difference.seconds, "seconds ago.") break ``` -------------------------------- ### Initialize Sync WebSocket Client and Render Template Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Shows how to initialize the synchronous WebSocket client to execute a rendered template. This is useful for retrieving dynamic information from Home Assistant. ```python from homeassistant_api import WebsocketClient WS_URL = '' # Example: 'ws://homeassistant.local:8123/api/websocket' TOKEN = '' with WebsocketClient(WS_URL, TOKEN) as ws_client: # opens a websocket connection to Home Assistant print(ws_client.get_rendered_template("{{ states('sensor.my_sensor') }}")) ``` -------------------------------- ### Initialize Sync REST Client and Trigger Service Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Demonstrates initializing the synchronous REST API client and triggering a service call. Ensure you have your API base URL and a Long Lived Access Token. ```python import os from homeassistant_api import Client URL = '' # Example: 'http://homeassistant.local:8123/api' TOKEN = '' # Assigns the Client object to a variable and checks if it's running. client = Client(URL, TOKEN) service = client.get_domain("light") # Gets the light service domain from Home Assistant service.turn_on(entity_id="light.my_living_room_light") # Triggers the light.turn_on service on the entity `light.my_living_room_light` ``` -------------------------------- ### Clone the HomeAssistantAPI Repository Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/CONTRIBUTING.rst Clone the official HomeAssistantAPI repository to your local machine to begin development. Replace '' with your actual GitHub username. ```bash $ git clone https://github.com//HomeAssistantAPI ``` -------------------------------- ### homeassistant_api.Client Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/api.rst Reference for the synchronous client class. Lists all public members available for direct use. ```APIDOC ## Class: homeassistant_api.Client ### Description Provides a synchronous interface for interacting with the Home Assistant API. ### Members This class exposes various methods for API interaction. Refer to the full documentation for individual method signatures and usage. ``` -------------------------------- ### homeassistant_api.AsyncClient Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/api.rst Reference for the asynchronous client class. Lists all public members available for direct use. ```APIDOC ## Class: homeassistant_api.AsyncClient ### Description Provides an asynchronous interface for interacting with the Home Assistant API. ### Members This class exposes various methods for API interaction. Refer to the full documentation for individual method signatures and usage. ``` -------------------------------- ### WebsocketClient Event Listening Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Demonstrates how to listen for all events, specific event types, or a limited number of events using the WebsocketClient. ```APIDOC ## WebsocketClient Event Listening ### Description Listen for events using the `WebsocketClient`. You can listen for all events, specific event types, or a limited number of events. ### Method `ws_client.listen_events(event_type=None)` ### Parameters - **event_type** (string, optional) - The type of event to listen for. If not provided, all events are listened to. ### Request Example ```python from homeassistant_api import WebsocketClient with WebsocketClient(WS_URL, TOKEN) as ws_client: # Listen for all events with ws_client.listen_events() as events: for event in events: print(event) # Listen for a specific event type with ws_client.listen_events('state_changed') as events: for event in events: print(event) # Listen for a limited number of events with ws_client.listen_events("my_event") as events: for _, event in zip(range(10), events): print(event) # Listen for just one event with ws_client.listen_events("my_event") as events: event = next(events) print(event) ``` ### Response Events are yielded as they occur. ``` -------------------------------- ### Async Render Template via WebSocket Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Asynchronously render a template using the AsyncWebsocketClient. Requires an AsyncWebsocketClient instance. ```python import asyncio from homeassistant_api import AsyncWebsocketClient async def main(): async with AsyncWebsocketClient(ws_url, token) as ws_client: template = await ws_client.get_rendered_template("{{ states('sensor.my_sensor') }}") print(template) ``` -------------------------------- ### Run the Test Suite with uv and pytest Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/CONTRIBUTING.rst Execute the project's test suite using 'uv' to manage environments and 'pytest' to run the tests. This command ensures tests are run in a consistent environment. ```bash $ uv run pytest ``` -------------------------------- ### homeassistant_api.AsyncWebsocketClient Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/api.rst Reference for the asynchronous websocket client class. Lists all public members available for direct use. ```APIDOC ## Class: homeassistant_api.AsyncWebsocketClient ### Description Provides an asynchronous interface for real-time communication via WebSockets with Home Assistant. ### Members This class exposes various methods for WebSocket communication. Refer to the full documentation for individual method signatures and usage. ``` -------------------------------- ### homeassistant_api.WebsocketClient Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/api.rst Reference for the synchronous websocket client class. Lists all public members available for direct use. ```APIDOC ## Class: homeassistant_api.WebsocketClient ### Description Provides a synchronous interface for real-time communication via WebSockets with Home Assistant. ### Members This class exposes various methods for WebSocket communication. Refer to the full documentation for individual method signatures and usage. ``` -------------------------------- ### Set Environment Variables for Home Assistant API Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/CONTRIBUTING.rst Set these environment variables before running tests or interacting with the Home Assistant API. Replace placeholders with your actual Home Assistant host, port, and API token. ```bash $ export HOMEASSISTANTAPI_URL="http://:8123/api" $ export HOMEASSISTANTAPI_WS_URL="ws://:8123/api/websocket" $ export HOMEASSISTANTAPI_TOKEN="" ``` -------------------------------- ### Run Pytest with Cassette Recording Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/CONTRIBUTING.rst Execute pytest with the --record flag to generate .json cassettes for API interactions. Commit these cassettes with your tests for CI replay. ```bash $ uv run pytest --record ``` -------------------------------- ### WebsocketClient Listen Trigger Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Demonstrates how to listen for various types of triggers using the WebsocketClient. ```APIDOC ## WebsocketClient Listen Trigger ### Description Listen for triggers from Home Assistant. This can include event triggers, time triggers, etc. ### Method `ws_client.listen_trigger(trigger_type, **kwargs)` ### Parameters - **trigger_type** (string, required) - The type of trigger to listen for (e.g., 'event', 'time'). - **kwargs** - Additional parameters specific to the trigger type (e.g., `event_type`, `at`). ### Request Example ```python from homeassistant_api import WebsocketClient with WebsocketClient(WS_URL, TOKEN) as ws_client: # Listen for any trigger with ws_client.listen_trigger() as triggers: for trigger in triggers: print(trigger) # Listen for event triggers with ws_client.listen_trigger("event", event_type="my_event") as triggers: ws_client.fire_event("my_event", my_arg="my_value") for trigger in triggers: print(trigger.variables.my_arg) # Listen for time triggers future = ws_client.get_rendered_template( "{{ (now() + timedelta(seconds=1)).strftime('%H:%M:%S') }}" ) with ws_client.listen_trigger("time", at=future) as triggers: print(next(triggers)) ``` ### Response Triggers are yielded as they occur. ``` -------------------------------- ### Listen to All WebSocket Events Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Use this snippet to listen for all events on the WebSocket. Requires a WebsocketClient instance. ```python with WebsocketClient(WS_URL, TOKEN) as ws_client: with ws_client.listen_events() as events: for event in events: print(event) ``` -------------------------------- ### Asynchronous Client with Persistent File Cache Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/advanced.rst Configure an asynchronous client with persistent caching using AsyncCachedSession and a specified cache file path. The cache will persist across runs. ```python # Or an example for async import asyncio from pathlib import Path from homeassistant_api import AsyncClient from niquests_cache.session import AsyncCachedSession client = AsyncClient( "", "", session=AsyncCachedSession( cache_name=Path('.cache') / 'http', ), ) async def main(): async with client: # Grab and update some cool entities and services inside your installation. ... asyncio.run(main()) ``` -------------------------------- ### Listen for Time Triggers Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Listen for triggers at a specific time, calculated using templates. Requires a WebsocketClient instance. ```python future = ws_client.get_rendered_template( "{{ (now() + timedelta(seconds=1)).strftime('%H:%M:%S') }}" ) with ws_client.listen_trigger("time", at=future) as triggers: print(next(triggers)) ``` -------------------------------- ### Synchronous Client with In-Memory Cache Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/advanced.rst Use CachedSession for in-memory caching with a specified expiration time. Requires importing CachedSession and MemoryBackend from niquests_cache. ```python from homeassistant_api import Client from niquests_cache.session import CachedSession from niquests_cache.backend import MemoryBackend client = Client("", "", session=CachedSession(backend=MemoryBackend(), expire_after=300)) ``` -------------------------------- ### WebsocketClient Fire Event Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Shows how to fire a custom event using the WebsocketClient. ```APIDOC ## WebsocketClient Fire Event ### Description Fire a custom event through the WebSocket connection. ### Method `ws_client.fire_event(event_type, **kwargs)` ### Parameters - **event_type** (string, required) - The type of event to fire. - **kwargs** - Additional arguments to pass with the event. ### Request Example ```python ws_client.fire_event("my_event", my_arg="my_value") ``` ``` -------------------------------- ### Listen for All Triggers Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Listen for all types of triggers using the WebsocketClient. Requires a WebsocketClient instance. ```python from homeassistant_api import WebsocketClient with WebsocketClient(WS_URL, TOKEN) as ws_client: with ws_client.listen_trigger() as triggers: for trigger in triggers: print(trigger) ``` -------------------------------- ### Fire a WebSocket Event Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Fire a custom event with arguments using a WebsocketClient instance. ```python ws_client.fire_event("my_event", my_arg="my_value") ``` -------------------------------- ### Listen for a Single WebSocket Event Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Listen for and retrieve only the first event of a specific type. Requires a WebsocketClient instance. ```python with ws_client.listen_events("my_event") as events: event = next(events) print(event) ``` -------------------------------- ### Trigger Service with REST API (Synchronous) Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/README.md Use the synchronous Client to trigger a service call via the REST API. Ensure you provide the correct API server URL and a long-lived access token. ```python from homeassistant_api import Client with Client( '', # i.e. 'http://homeassistant.local:8123/api/' '' ) as client: client.trigger_service('light', 'turn_on', entity_id="light.living_room") ``` -------------------------------- ### Listen for a Limited Number of WebSocket Events Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Listen for a specific number of events of a given type. Requires a WebsocketClient instance. ```python with ws_client.listen_events("my_event") as events: for _, event in zip(range(10), events): print(event) ``` -------------------------------- ### Trigger Service with REST API (Asynchronous) Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/README.md Use the asynchronous AsyncClient to trigger a service call via the REST API. This requires an asyncio event loop and `await` for the client methods. Provide the correct REST API Server URL and a long-lived access token. ```python import asyncio from homeassistant_api import AsyncClient async def main(): async with AsyncClient( '', # i.e. 'http://homeassistant.local:8123/api/' '', ) as client: await client.trigger_service('light', 'turn_on', entity_id="light.living_room") asyncio.run(main()) ``` -------------------------------- ### Async Call Service to Close Cover Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Asynchronously call the 'close_cover' service on a specific entity. Requires an AsyncClient instance. ```python cover = await client.get_domain("cover") changed_states = await cover.close_cover(entity_id='cover.garage_door') ``` -------------------------------- ### Asynchronous Client with In-Memory Cache Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/advanced.rst Utilize AsyncCachedSession for asynchronous operations with in-memory caching. Configure the expiration duration using expire_after. ```python from homeassistant_api import AsyncClient from niquests_cache.session import AsyncCachedSession from niquests_cache.backend import MemoryBackend client = AsyncClient("", "", session=AsyncCachedSession(backend=MemoryBackend(), expire_after=300)) ``` -------------------------------- ### Async Set Entity State Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Asynchronously set the state of an entity using a State object. Requires an AsyncClient instance. ```python new_state = await client.set_state( State( state='my ToaTallY Whatever vAlUe 12t87932', entity_id='my_favorite_colors.number_one' ) ) ``` -------------------------------- ### Listen for Specific WebSocket Event Type Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Listen for a specific event type, like 'state_changed', and break the loop based on event data. Requires a WebsocketClient instance. ```python with ws_client.listen_events('state_changed') as events: for event in events: print(event) if event.data.entity_id == 'myalarmclock.dinner_time' and event.data.new_state.state == 'now': break ``` -------------------------------- ### Listen for Specific Event Triggers Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Listen for triggers related to a specific event type and access trigger variables. Requires a WebsocketClient instance. ```python with ws_client.listen_trigger("event", event_type="my_event") as triggers: ws_client.fire_event("my_event", my_arg="my_value") for trigger in triggers: print(trigger.variables.my_arg) ``` -------------------------------- ### AsyncClient Set State Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Set the state of an entity using the AsyncClient. ```APIDOC ## AsyncClient Set State ### Description Set the state of an entity. This can be used to manually change an entity's state. ### Method `await client.set_state(state_object)` ### Parameters - **state_object** (State object, required) - A State object representing the desired new state. ### Request Example ```python from homeassistant_api import State new_state = await client.set_state( State( state='my ToaTallY Whatever vAlUe 12t87932', entity_id='my_favorite_colors.number_one' ) ) ``` ### Response - **new_state** (State object) - The updated State object after the change. ``` -------------------------------- ### AsyncClient Call Service Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Call a service within a specific domain using the AsyncClient. ```APIDOC ## AsyncClient Call Service ### Description Call a service within a specific domain. This is a generic method that can be used to call any available service. ### Method `await domain.call_service(service_name, **kwargs)` ### Parameters - **service_name** (string, required) - The name of the service to call. - **kwargs** - Arguments for the service call. ### Request Example ```python # Assuming 'cover' is a retrieved domain object changed_states = await cover.close_cover(entity_id='cover.garage_door') ``` ### Response - **changed_states** (tuple) - A tuple of states that were changed by the service call. ``` -------------------------------- ### Trigger Service with Websocket API Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/README.md Use the WebsocketClient to trigger a service call via the Websocket API. Provide the correct WS API Server URL and a long-lived access token. ```python from homeassistant_api import WebsocketClient with WebsocketClient( '', # i.e. 'ws://homeassistant.local:8123/api/websocket' '' ) as ws_client: ws_client.trigger_service('light', 'turn_on', entity_id="light.living_room") ``` -------------------------------- ### Async Update Entity State Directly Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Asynchronously update an entity's state and attributes directly from the entity object. Requires an AsyncClient instance. ```python door.state.state = 'My new state' door.state.attributes.update({'open_height': '5ft'}) await door.update_state() ``` -------------------------------- ### AsyncEntity Update State Source: https://github.com/homeassistant-api/homeassistantapi/blob/main/docs/usage.rst Update an entity's state and attributes directly from the entity object using the AsyncClient. ```APIDOC ## AsyncEntity Update State ### Description Update an entity's state and attributes by modifying the entity object directly and then calling the update method. ### Method `await entity.update_state()` ### Usage Modify the `state` and `attributes` of the entity object first, then call `update_state()`. ### Request Example ```python # Assuming 'door' is an AsyncEntity object door.state.state = 'My new state' door.state.attributes.update({'open_height': '5ft'}) await door.update_state() ``` ### Response - **updated_state** (State object) - The updated State object for the entity. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.