### ReconnectLogic.start Example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/utilities.md Example usage of the start method for ReconnectLogic. ```python reconnect = ReconnectLogic(api) await reconnect.start() ``` -------------------------------- ### Quick Start Example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/README.md A basic example demonstrating how to connect to an ESPHome device, retrieve information, subscribe to state changes, and send commands using the aioesphomeapi library. ```python import asyncio from aioesphomeapi import APIClient async def main(): # Create client api = APIClient( address="device.local", port=6053, noise_psk="YOUR_ENCRYPTION_KEY" # from openssl rand -base64 32 ) # Connect and authenticate await api.connect(login=True) # Get device info info = await api.device_info() print(f"Device: {info.name} ({info.esphome_version})") # List entities entities, services = await api.list_entities_services() for entity in entities: print(f" {entity.name}: {entity.object_id}") # Subscribe to state changes def on_state(state): print(f"State change: {state}") api.subscribe_states(on_state) # Send commands api.switch_command(key=1, state=True) # Turn on switch with key 1 # Disconnect await api.disconnect() asyncio.run(main()) ``` -------------------------------- ### Development setup Source: https://github.com/esphome/aioesphomeapi/blob/main/README.rst Install aioesphomeapi and development dependencies in a virtual environment. ```bash # Setup virtualenv (optional) $ python3 -m venv . $ source bin/activate # Install aioesphomeapi and development depenencies $ pip3 install -e . $ pip3 install -r requirements/test.txt # Run linters & test $ script/lint # Update protobuf _pb2.py definitions (requires docker or podman) $ docker run --rm -v $PWD:/aioesphomeapi ghcr.io/esphome/aioesphomeapi-proto-builder:latest # Or with podman: $ podman run --rm -v $PWD:/aioesphomeapi --userns=keep-id ghcr.io/esphome/aioesphomeapi-proto-builder:latest ``` -------------------------------- ### Reconnection Logic Example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/configuration.md Example of setting up and starting the ReconnectLogic for automatic reconnection with exponential backoff. ```python from aioesphomeapi import APIClient, ReconnectLogic async def on_stop(expected_disconnect: bool): print(f"Disconnected (expected={expected_disconnect})") client = APIClient("device.local", 6053, noise_psk="YOUR_KEY") reconnect = ReconnectLogic( client=client, on_disconnect=on_stop, on_connect=None, ) # Start background reconnection loop await reconnect.start() # Later await reconnect.stop() ``` -------------------------------- ### device_info Method Example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md Example of fetching device information. ```python info = await api.device_info() print(info.name, info.mac_address) ``` -------------------------------- ### connect Method Example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md Example of connecting to an APIClient with a noise_psk. ```python api = APIClient("device.local", 6053, noise_psk="YOUR_KEY") await api.connect(login=True) ``` -------------------------------- ### Execute Service Example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md Example of how to call a user-defined service on a device. ```python response = await api.execute_service( key=1, service=user_service, data={"param1": "value", "param2": 42} ) ``` -------------------------------- ### list_entities_services Method Example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md Example of listing entities and services. ```python entities, services = await api.list_entities_services() for entity in entities: print(f"{entity.name} ({entity.object_id})") ``` -------------------------------- ### Installation Source: https://github.com/esphome/aioesphomeapi/blob/main/README.rst Install the aioesphomeapi library using pip. ```bash pip3 install aioesphomeapi ``` -------------------------------- ### CLI Tool for Device Logging Example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/utilities.md Examples of using the aioesphomeapi-logs command-line tool. ```bash aioesphomeapi-logs living_room.local aioesphomeapi-logs 192.168.1.100 --config esphome/ ``` -------------------------------- ### asyncio_timeout example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/utilities.md Example of using the asyncio_timeout context manager. ```python from aioesphomeapi.util import asyncio_timeout try: async with asyncio_timeout(10.0): await api.device_info() except TimeoutError: print("Timed out") ``` -------------------------------- ### discover_mdns Example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/utilities.md Example usage of the discover_mdns method to find ESPHome devices. ```python from aioesphomeapi.discover import discover_mdns devices = await discover_mdns() for hostname, ip in devices.items(): print(f"{hostname}: {ip}") # Output: living_room.local: 192.168.1.100 ``` -------------------------------- ### Connect to Bluetooth Device Example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md Example of how to connect to a Bluetooth device using its MAC address as an integer. ```python # Connect to device with MAC AA:BB:CC:DD:EE:FF mac_int = 0xAABBCCDDEEFF await api.bluetooth_device_connect(mac_int) ``` -------------------------------- ### send_message Example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/connection.md Example of sending a protobuf message to the device using send_message. ```python from aioesphomeapi.api_pb2 import PingRequest connection.send_message(PingRequest()) ``` -------------------------------- ### send_message_await_response Example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/connection.md Example of sending a message and awaiting a specific response, with a timeout. ```python from aioesphomeapi.api_pb2 import DeviceInfoRequest, DeviceInfoResponse response = await connection.send_message_await_response( DeviceInfoRequest(), DeviceInfoResponse, timeout=10.0 ) ``` -------------------------------- ### Reading Configuration from Environment Variables (Home Assistant Example) Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/configuration.md Example of reading ESPHome API configuration from environment variables, suitable for integration with systems like Home Assistant. ```python import os device_host = os.getenv("ESPHOME_HOST", "device.local") device_psk = os.getenv("ESPHOME_PSK") device_port = int(os.getenv("ESPHOME_PORT", "6053")) api = APIClient( address=device_host, port=device_port, noise_psk=device_psk, ) await api.connect() ``` -------------------------------- ### Example Usage for BadMACAddressAPIError Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/errors.md Example of how to catch BadMACAddressAPIError. ```python try: api = APIClient("192.168.1.100", 6053, expected_mac="aabbccddeeff") await api.connect() except BadMACAddressAPIError as e: print(f"MAC mismatch: {e.received_mac}") ``` -------------------------------- ### Invalid Configuration Example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/configuration.md Example demonstrating how invalid configuration parameters raise a ValueError during APIClient initialization. ```python try: api = APIClient("device.local", port=999999) except ValueError as e: print(f"Invalid port: {e}") ``` -------------------------------- ### build_log_name example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/utilities.md Example usage of build_log_name for creating connection identifiers. ```python from aioesphomeapi.util import build_log_name name = build_log_name("192.168.1.100", 6053) # => "192.168.1.100:6053" name = build_log_name("device.local", 6053) # => "device.local:6053" ``` -------------------------------- ### APIVersion Example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/types.md Example usage of APIVersion for checking protocol compatibility. ```python if api.api_version >= APIVersion(1, 5): # Use features added in API 1.5+ pass ``` -------------------------------- ### Version Negotiation Example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/protocol.md Example of how client and server versions are negotiated. ```text Client supports: 1.14 Server supports: 1.10 Negotiated: min(1.14, 1.10) = 1.10 ``` -------------------------------- ### get_timezone example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/utilities.md Example of retrieving the system's IANA timezone name. ```python from aioesphomeapi.timezone import get_timezone tz = get_timezone() # => "America/Chicago" or similar ``` -------------------------------- ### GATT Error Code Mapping Example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/errors.md Example demonstrating how to use ESPHOME_GATT_ERRORS to get a human-readable description for a GATT error code. ```python from aioesphomeapi.core import ESPHOME_GATT_ERRORS, to_human_readable_gatt_error error_code = 2 description = ESPHOME_GATT_ERRORS.get(error_code, "Unknown") # => "Read not permitted" ``` -------------------------------- ### parse_posix_tz example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/utilities.md Example of parsing a POSIX TZ string into a ParsedTimezone object. ```python from aioesphomeapi.posix_tz import parse_posix_tz tz = parse_posix_tz("EST5EDT,M3.2.0,M11.1.0") # => ParsedTimezone with DST rules ``` -------------------------------- ### Custom Zeroconf Instance Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/configuration.md Example of reusing an existing Zeroconf instance for multiple devices or integration. ```python from aiozeroconf import Zeroconf # Reuse existing Zeroconf instance (for multiple devices or integration) zconf = Zeroconf() api = APIClient( address="device.local", port=6053, zeroconf_instance=zconf, ) await api.connect() # Later: clean up shared instance await zconf.async_close() ``` -------------------------------- ### Entity Key System Example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/protocol.md Example demonstrating how entity keys are assigned and used in commands. ```text ListEntitiesRequest ← ListEntitiesBinarySensorResponse(key=1, object_id="door_sensor") ← ListEntitiesSwitchResponse(key=2, object_id="light_1") ← ListEntitiesCoverResponse(key=3, object_id="garage_door") To control: SwitchCommandRequest(key=2, state=True) // Control entity key 2 ``` -------------------------------- ### Example Usage for ResolveAPIError Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/errors.md Example of how to catch ResolveAPIError. ```python try: await api.connect() except ResolveAPIError as e: print(f"Failed to resolve hostname: {e}") ``` -------------------------------- ### ReconnectLogic.stop Example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/utilities.md Example usage of the stop method for ReconnectLogic. ```python await reconnect.stop() ``` -------------------------------- ### Example Usage for BadNameAPIError Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/errors.md Example of how to catch BadNameAPIError. ```python try: api = APIClient("192.168.1.100", 6053, expected_name="kitchen_sensor") await api.connect() except BadNameAPIError as e: print(f"Wrong device! Expected 'kitchen_sensor', got '{e.received_name}'") ``` -------------------------------- ### send_messages_await_response_complex Example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/connection.md Example of sending multiple messages and collecting multiple responses with flexible matching and stop conditions. ```python from aioesphomeapi.api_pb2 import ListEntitiesRequest, ListEntitiesDoneResponse messages = await connection.send_messages_await_response_complex( (ListEntitiesRequest(),), lambda msg: True, # Accept all messages lambda msg: type(msg) is ListEntitiesDoneResponse, # Stop when done timeout=60.0 ) ``` -------------------------------- ### Programmatic Access to Device Logging Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/utilities.md Example of programmatically subscribing to device logs using APIClient and LogLevel. ```python from aioesphomeapi.log_parser import parse_log_message, LogParser from aioesphomeapi import LogLevel def on_log(msg): # msg is a SubscribeLogsResponse parsed = parse_log_message(msg) if parsed: timestamp, level_str, message = parsed print(f"[{timestamp}] {level_str}: {message}") api = APIClient("device.local", 6053, noise_psk="KEY") await api.connect() # Subscribe to device logs unsubscribe = api.subscribe_logs( on_log, log_level=LogLevel.LOG_LEVEL_INFO, ) # Wait for logs... unsubscribe() ``` -------------------------------- ### Example Usage for InvalidAuthAPIError Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/errors.md Example of how to catch InvalidAuthAPIError. ```python try: await api.connect(login=True) except InvalidAuthAPIError: print("Authentication failed - check noise_psk") ``` -------------------------------- ### MESSAGE_TYPE_TO_PROTO example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/utilities.md Example of retrieving a protobuf message type using its numeric ID. ```python from aioesphomeapi.core import MESSAGE_TYPE_TO_PROTO # Get protobuf type for message ID 10 (DeviceInfoResponse) msg_type = MESSAGE_TYPE_TO_PROTO[10] # => DeviceInfoResponse ``` -------------------------------- ### BluetoothGATTAPIError Example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/errors.md Example demonstrating how to catch BluetoothGATTAPIError and inspect the underlying GATT error code. ```python try: data = await api.bluetooth_gatt_read(address, handle) except BluetoothGATTAPIError as e: print(f"GATT error: {e.error.error} - {e}") ``` -------------------------------- ### ReconnectLogic.start Method Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/utilities.md Method to start the background reconnection loop for ReconnectLogic. ```python async def start() -> None ``` -------------------------------- ### Example Usage for ResolveTimeoutAPIError Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/errors.md Example of how to catch ResolveTimeoutAPIError. ```python try: await api.connect() except ResolveTimeoutAPIError: print("mDNS lookup timed out") ``` -------------------------------- ### Protocol Version Negotiation Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/configuration.md Example of checking the negotiated API version after connecting and conditionally using features. ```python await api.connect() # After connect, api_version is available if api.api_version and api.api_version >= APIVersion(1, 9): # Use features added in API 1.9+ pass ``` -------------------------------- ### Operation Timeouts Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/configuration.md Examples of setting timeouts for individual API operations using asyncio.wait_for. ```python # Device info with 10 second timeout info = await asyncio.wait_for( api.device_info(), timeout=10.0 ) # List entities with 60 second timeout entities, services = await asyncio.wait_for( api.list_entities_services(), timeout=60.0 ) # BLE operation with 30 second timeout await api.bluetooth_gatt_read(address, handle, timeout=30.0) ``` -------------------------------- ### ReconnectLogic Usage Pattern Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/utilities.md A comprehensive example demonstrating the usage pattern of ReconnectLogic with APIClient. ```python from aioesphomeapi import APIClient, ReconnectLogic api = APIClient("device.local", 6053, noise_psk="KEY") async def on_connect(): print("Connected!") info = await api.device_info() print(f"Device: {info.name}") async def on_disconnect(expected: bool): if expected: print("Graceful disconnect") else: print("Unexpected disconnect - will reconnect") async def on_error(error): print(f"Connection error: {error}") reconnect = ReconnectLogic( client=api, on_connect=on_connect, on_disconnect=on_disconnect, on_connect_error=on_error, login=False, ) await reconnect.start() # Now api is automatically reconnected on failure # ... use api for requests ... await reconnect.stop() ``` -------------------------------- ### Example Usage for APIConnectionCancelledError Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/errors.md Example of how to catch APIConnectionCancelledError. ```python try: await api.connect() except APIConnectionCancelledError: print("Connection was cancelled") ``` -------------------------------- ### Plaintext Frame Example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/protocol.md An example of a plaintext frame with type 0x00 and a 10-byte payload. ```plaintext [0x00] [0x0A] [10-byte protobuf payload] ``` -------------------------------- ### State Update Stream Example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/protocol.md Example sequence of state update messages received from the device. ```plaintext [Subscribe sent: SubscribeStatesRequest] [Device streaming...] ← CoverStateResponse ← SwitchStateResponse ← BinarySensorStateResponse ← SensorStateResponse ← LightStateResponse [repeat as states change] ``` -------------------------------- ### Enable Native API component Source: https://github.com/esphome/aioesphomeapi/blob/main/README.rst Example configuration entry for enabling the Native API component in ESPHome. ```yaml api: ``` -------------------------------- ### BluetoothConnectionParamsAPIError Example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/errors.md Example showing how to catch BluetoothConnectionParamsAPIError when setting BLE connection parameters. ```python try: await api.bluetooth_device_set_connection_params( address, min_interval=6, max_interval=3200, latency=0, timeout=300, ) except BluetoothConnectionParamsAPIError as e: print(f"BLE params rejected: {e.error_code}") ``` -------------------------------- ### Entity Control Examples Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/README.md Illustrates how to send commands to various types of entities like switches, buttons, numbers, lights, climate devices, and covers. ```python # Binary controls api.switch_command(key=1, state=True) api.button_command(key=2) # Numeric api.number_command(key=3, state=42.5) api.select_command(key=4, state="mode_a") # Complex api.light_command( key=5, state=True, brightness=200, rgb=(255, 0, 0), transition_length=500, ) api.climate_command( key=6, mode=ClimateMode.HEAT, target_temperature=22.5, fan_mode=ClimateFanMode.AUTO, ) api.cover_command(key=7, position=0.5, stop=False) ``` -------------------------------- ### UpdateCommand Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/types.md Defines the possible commands for an update: INSTALL or SKIP. ```python class UpdateCommand(APIIntEnum): INSTALL = 0 SKIP = 1 ``` -------------------------------- ### API Version Check Example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/README.md Demonstrates how to check the API version to conditionally use features. ```python if api.api_version and api.api_version >= APIVersion(1, 9): # Use Bluetooth proxy v5+ features pass else: # Use legacy features or skip pass ``` -------------------------------- ### Parse raw protobuf frames for debugging Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/protocol.md This example demonstrates how to parse raw protobuf frames using the generated Python classes, useful for debugging. ```python from aioesphomeapi.api_pb2 import HelloResponse # Hex frame payload payload_hex = "08011204657370323332" payload_bytes = bytes.fromhex(payload_hex) msg = HelloResponse() msg.ParseFromString(payload_bytes) print(f"Major: {msg.api_version_major}") ``` -------------------------------- ### Enable Native API component with encryption Source: https://github.com/esphome/aioesphomeapi/blob/main/README.rst Example configuration entry for enabling the Native API component with encryption. ```yaml api: encryption: key: !secret api_encryption_key ``` -------------------------------- ### VoiceAssistantCommand Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/types.md Voice assistant control command (start listening, stop, abort). ```python @dataclass(frozen=True) class VoiceAssistantCommand: start: bool = False stop: bool = False abort: bool = False ``` -------------------------------- ### Catching Connection Errors Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/errors.md Example demonstrating a comprehensive try-except block for catching various API connection errors. ```python try: await api.connect() except ResolveAPIError: # Hostname not found pass except SocketAPIError: # Device offline or firewall blocking pass except HandshakeAPIError: # Protocol or encryption error pass except APIConnectionError: # Any other connection error pass ``` -------------------------------- ### Message Flow Example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/README.md Illustrates the typical message exchange sequence between the client and an ESPHome device during an API session. ```text Client Server (ESPHome Device) |-------- HelloRequest -------->| |<------ HelloResponse ---------| |---- AuthenticationRequest --->| (if login=True) |<--- AuthenticationResponse ---| | |---- DeviceInfoRequest ------->| |<----- DeviceInfoResponse -----| | |---- ListEntitiesRequest ----->| |<----- Entity Responses -------| |<--- ListEntitiesDoneResponse -| | |---- SubscribeStatesRequest -->| |<------ State Updates ---------| (streaming, repeats) | |---- Command Requests -------->| (fire-and-forget) | |---- DisconnectRequest ------->| |<---- DisconnectResponse ------| ``` -------------------------------- ### Plaintext Hello Response Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/protocol.md Example of a raw bytes representation for a HelloResponse frame. ```text Raw bytes: 02 0A 08 01 12 04 ... Frame type: 0x02 (type ID 2 = HelloResponse) Payload length: 0x0A (10 bytes) Payload: 08 01 12 04 ... (protobuf-encoded HelloResponse) ``` -------------------------------- ### Device Info + List Entities Combined Request Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/protocol.md Example of combining DeviceInfoRequest and ListEntitiesRequest in a single packet. ```text Requests: DeviceInfoRequest, ListEntitiesRequest (in one packet) Response stream: ← DeviceInfoResponse ← ListEntitiesX Response(s) ← ListEntitiesDoneResponse // Signals end of entities ``` -------------------------------- ### CLI Tool for Device Discovery Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/utilities.md Command-line interface tool for discovering ESPHome devices. ```bash aioesphomeapi-discover ``` -------------------------------- ### Bluetooth Error Handling Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/errors.md Example illustrating how to handle Bluetooth-specific errors like connection drops and GATT errors. ```python try: data = await api.bluetooth_gatt_read(address, handle) except BluetoothConnectionDroppedError: print("Device disconnected") except BluetoothGATTAPIError as e: if e.error.error == 2: # Read not permitted print("Characteristic not readable") else: print(f"GATT error: {e.error.error}") except APIConnectionError as e: print(f"Connection error: {e}") ``` -------------------------------- ### aioesphomeapi-discover --help Source: https://github.com/esphome/aioesphomeapi/blob/main/README.rst CLI tool to discover devices. ```bash aioesphomeapi-discover --help ``` -------------------------------- ### CLI Tool for Device Logging Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/utilities.md Command-line utility for viewing device logs. ```bash aioesphomeapi-logs HOSTNAME [--config /path/to/config] ``` -------------------------------- ### start_connection Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/connection.md Asynchronously open a TCP socket and connect to the resolved address. ```python async def start_connection() -> None ``` -------------------------------- ### Running Benchmarks Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/README.md Instructions on how to run the library's CodSpeed benchmarks. ```bash pytest tests/benchmarks/ --codspeed ``` -------------------------------- ### start_resolve_host Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/connection.md Asynchronously resolve the hostname to IP address(es) using DNS or mDNS lookup. ```python async def start_resolve_host() -> None ``` -------------------------------- ### TimeoutAPIError Example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/errors.md Example demonstrating how to catch asyncio.TimeoutError and TimeoutAPIError when waiting for an API response. ```python try: services = await asyncio.wait_for( api.list_entities_services(), timeout=30.0 ) except asyncio.TimeoutError: print("Device not responding") except TimeoutAPIError: print("API timeout") ``` -------------------------------- ### Custom User Agent Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/configuration.md Using a custom user agent string. ```python api = APIClient( address="device.local", port=6053, client_info="my_app/1.0", # Custom UA sent to device ) await api.connect() ``` -------------------------------- ### connect Method Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md Establish connection, resolve host, complete handshake, and authenticate. ```python async def connect( on_stop: Callable[[bool], Coroutine[Any, Any, None]] | None = None, login: bool = False, log_errors: bool = True, ) -> None ``` -------------------------------- ### BluetoothConnectionDroppedError Example Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/errors.md Example showing how to catch BluetoothConnectionDroppedError when performing a Bluetooth GATT read operation. ```python try: await api.bluetooth_gatt_read(address, handle) except BluetoothConnectionDroppedError: print("BLE device disconnected") ``` -------------------------------- ### discover_mdns Method Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/utilities.md Method to discover ESPHome devices advertising via mDNS. ```python async def discover_mdns( zeroconf_instance: Zeroconf | None = None, ) -> dict[str, str] ``` -------------------------------- ### device_info Method Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md Fetch device information (name, MAC, hardware version, etc.). ```python async def device_info() -> DeviceInfo ``` -------------------------------- ### APIClient Constructor Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/configuration.md Constructor options and connection configuration for APIClient. ```python APIClient( address: str, port: int, password: str | None = None, *, client_info: str = "aioesphomeapi", keepalive: float = 20.0, zeroconf_instance: ZeroconfInstanceType | None = None, noise_psk: str | None = None, expected_name: str | None = None, addresses: list[str] | None = None, expected_mac: str | None = None, timezone: str | None = None, provide_time: bool = True, ) ``` -------------------------------- ### start_resolve_host Method Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md Resolve the host address (DNS or mDNS lookup). Called as part of connect(). ```python async def start_resolve_host( on_stop: Callable[[bool], Coroutine[Any, Any, None]] | None = None, log_errors: bool = True, ) -> None ``` -------------------------------- ### get_timezone function signature Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/utilities.md Gets the system timezone as an IANA timezone name. ```python def get_timezone() -> str ``` -------------------------------- ### Catching Operation Timeouts Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/errors.md Example showing how to differentiate between asyncio.TimeoutError and aioesphomeapi's TimeoutAPIError. ```python try: await asyncio.wait_for(api.device_info(), timeout=10.0) except asyncio.TimeoutError: # Timeout from asyncio pass except TimeoutAPIError: # Timeout from aioesphomeapi pass ``` -------------------------------- ### cover_command Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md Control cover/blind position and tilt. ```python def cover_command( key: int, position: float | None = None, tilt: float | None = None, stop: bool = False, device_id: int = 0, ) -> None ``` -------------------------------- ### IPv4 and IPv6 Dual Stack Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/configuration.md Connection configuration for IPv4 and IPv6 dual-stack devices. ```python api = APIClient( addresses=["2001:db8::1", "192.168.1.100"], port=6053, noise_psk="YOUR_KEY", ) await api.connect() ``` -------------------------------- ### Basic Connection (No Encryption) Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/configuration.md Basic connection without encryption. ```python api = APIClient( address="device.local", port=6053, ) await api.connect() ``` -------------------------------- ### light_command Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md Send light control command with color, brightness, effects, etc. ```python def light_command( key: int, state: bool | None = None, brightness: int | None = None, rgb: tuple[int, int, int] | None = None, white: int | None = None, color_temperature: float | None = None, transition_length: float | None = None, flash_length: float | None = None, effect: str | None = None, device_id: int = 0, ) -> None ``` ```python # Turn on and set color api.light_command(key=5, state=True, rgb=(255, 0, 0), brightness=200) ``` -------------------------------- ### ListEntitiesRequest Response Stream Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/protocol.md Example of a multipart response stream for ListEntitiesRequest. ```text Request: ListEntitiesRequest() Response stream: ← ListEntitiesBinarySensorResponse ← ListEntitiesSwitchResponse ← ListEntitiesLightResponse [... more entities ...] ← ListEntitiesDoneResponse // Signals end of list ``` -------------------------------- ### Run Test Suite Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/README.md Commands to run the test suite, including coverage, type checking, linting, and benchmarks. ```bash # All tests pytest tests/ # With coverage pytest tests/ --cov=aioesphomeapi # Type checking mypy aioesphomeapi/ # Linting ruff check aioesphomeapi/ # Benchmarks pytest tests/benchmarks/ --codspeed ``` -------------------------------- ### aioesphomeapi-logs --help Source: https://github.com/esphome/aioesphomeapi/blob/main/README.rst CLI tool to view logs. ```bash aioesphomeapi-logs --help ``` -------------------------------- ### Error Recovery Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/README.md Provides examples of how to catch and handle various API-specific errors during connection and operation. ```python from aioesphomeapi import ( APIConnectionError, ResolveAPIError, SocketAPIError, InvalidEncryptionKeyAPIError, TimeoutAPIError, ) try: await api.connect() except ResolveAPIError: print("Host not found - check hostname/IP") except SocketAPIError: print("Device offline or firewall blocking - check network") except InvalidEncryptionKeyAPIError: print("Wrong encryption key - check noise_psk") except TimeoutAPIError: print("Device slow to respond - check network/device logs") except APIConnectionError as e: print(f"Connection error: {e}") ``` -------------------------------- ### SubscribeStatesRequest Response Stream Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/protocol.md Example of an ongoing multipart response stream for SubscribeStatesRequest. ```text Request: SubscribeStatesRequest() Response stream (ongoing): ← BinarySensorStateResponse ← SwitchStateResponse ← SensorStateResponse [... repeats as values change ...] [Never ends until disconnect] ``` -------------------------------- ### Regenerate Protobuf Files with Docker Source: https://github.com/esphome/aioesphomeapi/blob/main/CLAUDE.md Command to regenerate protobuf bindings using the official aioesphomeapi-proto-builder Docker image. ```bash docker run --rm -v $PWD:/aioesphomeapi \ ghcr.io/esphome/aioesphomeapi-proto-builder:latest ``` -------------------------------- ### Regenerate Protobuf Files with Podman Source: https://github.com/esphome/aioesphomeapi/blob/main/CLAUDE.md Command to regenerate protobuf bindings using the official aioesphomeapi-proto-builder Podman image. ```bash podman run --rm -v $PWD:/aioesphomeapi --userns=keep-id \ ghcr.io/esphome/aioesphomeapi-proto-builder:latest ``` -------------------------------- ### Verify Device Identity Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/configuration.md Verify device identity using expected name and MAC address. ```python api = APIClient( address="192.168.1.100", port=6053, noise_psk="YOUR_KEY", expected_name="living_room_sensor", # Fail if wrong device expected_mac="aabbccddeeff", # Also check MAC ) await api.connect() ``` -------------------------------- ### send_home_assistant_state Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md Publish Home Assistant entity state to device. ```python def send_home_assistant_state( entity_id: str, attribute: str | None = None, state: str | None = None, ) -> None Publish Home Assistant entity state to device. **Parameters**: - `entity_id`: Home Assistant entity_id (e.g., "light.living_room") - `attribute`: Specific attribute (or None for state) - `state`: State/attribute value string ``` -------------------------------- ### list_entities_services Method Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md List all entities (sensors, switches, etc.) and user services defined on device. ```python async def list_entities_services() -> tuple[list[EntityInfo], list[UserService]] ``` -------------------------------- ### Noise Encrypted Frame Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/protocol.md Example of a raw bytes representation for a Noise encrypted frame. ```text Raw bytes: 01 00 42 <42-byte encrypted+tag> ... Frame type: 0x01 (Noise encrypted) Length: 0x0042 (66 bytes = 50 payload + 16 tag) Encrypted: ChaCha20-Poly1305(plaintext, key, nonce) ``` -------------------------------- ### button_command Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md Press a button. ```python def button_command(key: int, device_id: int = 0) -> None Press a button. **Parameters**: - `key`: Entity key - `device_id`: Device identifier ``` -------------------------------- ### Bluetooth GATT Operations Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/README.md Provides examples for performing Bluetooth GATT operations such as discovering services, reading, writing, and subscribing to notifications on characteristics. ```python # Discover services services = await api.bluetooth_gatt_get_services(mac_address) # Read characteristic data = await api.bluetooth_gatt_read(mac_address, handle) # Write characteristic await api.bluetooth_gatt_write(mac_address, handle, data) # Subscribe to notifications def on_notify(handle, data): print(f"Notify {handle}: {data.hex()}") await api.bluetooth_gatt_start_notify(mac_address, handle, on_notify) # Stop notifications api.bluetooth_gatt_stop_notify(mac_address, handle) ``` -------------------------------- ### Running tests Source: https://github.com/esphome/aioesphomeapi/blob/main/CLAUDE.md Command to run pytest tests. ```bash ./venv/bin/python -m pytest tests/ -v ``` -------------------------------- ### Local Cython build command Source: https://github.com/esphome/aioesphomeapi/blob/main/CLAUDE.md Command to build Cython extensions locally for testing performance-sensitive code changes before pushing. ```sh REQUIRE_CYTHON=1 python setup.py build_ext --inplace ``` -------------------------------- ### water_heater_command Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md Control water heater. ```python def water_heater_command( key: int, mode: int | None = None, target_temperature: float | None = None, away: bool | None = None, device_id: int = 0, ) -> None Control water heater. **Parameters**: - `key`: Entity key - `mode`: Mode identifier - `target_temperature`: Setpoint temperature - `away`: Away mode preset - `device_id`: Device identifier ``` -------------------------------- ### Custom Keepalive Timing Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/configuration.md Customizing keepalive timing for connection monitoring. ```python # Check connection every 30 seconds instead of default 20 api = APIClient( address="device.local", port=6053, keepalive=30.0, ) await api.connect() # Disable keepalive (not recommended) api = APIClient( address="device.local", port=6053, keepalive=0.0, # No ping/pong ) await api.connect() ``` -------------------------------- ### climate_command Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md Control thermostat/climate device. ```python def climate_command( key: int, mode: ClimateMode | None = None, target_temperature: float | None = None, target_temperature_low: float | None = None, target_temperature_high: float | None = None, away: bool | None = None, fan_mode: ClimateFanMode | None = None, swing_mode: ClimateSwingMode | None = None, preset: ClimatePreset | None = None, device_id: int = 0, ) -> None ``` -------------------------------- ### alarm_control_panel_command Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md Arm/disarm alarm panel. ```python def alarm_control_panel_command( key: int, command: AlarmControlPanelCommand, code: str = "", device_id: int = 0, ) -> None Arm/disarm alarm panel. **Parameters**: - `key`: Entity key - `command`: AlarmControlPanelCommand enum (arm_away, arm_home, disarm) - `code`: PIN code - `device_id`: Device identifier ``` -------------------------------- ### subscribe_home_assistant_states_and_services Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md Subscribe to both Home Assistant states and service calls. ```python def subscribe_home_assistant_states_and_services( on_state: Callable[[str, str | None], None], on_service_call: Callable[[HomeassistantServiceCall], None], on_state_request: Callable[[str, str | None], None] | None = None, ) -> None ``` -------------------------------- ### Basic Connection with Automatic Reconnection Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/README.md Demonstrates how to establish a basic connection to an ESPHome device with automatic reconnection logic. ```python from aioesphomeapi import APIClient, ReconnectLogic api = APIClient("device.local", 6053, noise_psk="KEY") reconnect = ReconnectLogic( client=api, on_connect=lambda: print("Connected"), on_disconnect=lambda expected: print(f"Disconnected (expected={expected})"), ) await reconnect.start() # Now use api; it auto-reconnects on failure # ... await reconnect.stop() ``` -------------------------------- ### bluetooth_gatt_start_notify Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md Enable notifications for characteristic. Callback fires on value changes. ```python async def bluetooth_gatt_start_notify( address: int, handle: int, on_notify: Callable[[int, bytearray], None], timeout: float = 30.0, ) -> None ``` ```python def on_notify(handle: int, data: bytearray): print(f"Characteristic {handle}: {data.hex()}") await api.bluetooth_gatt_start_notify(mac_int, char_handle, on_notify) ``` -------------------------------- ### BluetoothGATTServices Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/types.md A container for discovered Bluetooth GATT services. ```python @dataclass(frozen=True) class BluetoothGATTServices: services: list[BluetoothGATTService] = [] ``` -------------------------------- ### media_player_command Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md Control media player (play, pause, volume, etc.). ```python def media_player_command( key: int, command: MediaPlayerCommand | None = None, volume: float | None = None, media_url: str | None = None, device_id: int = 0, ) -> None Control media player (play, pause, volume, etc.). **Parameters**: - `key`: Entity key - `command`: MediaPlayerCommand enum - `volume`: 0.0-1.0 - `media_url`: URL to play - `device_id`: Device identifier ``` -------------------------------- ### ZeroconfManager Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/utilities.md Manages Zeroconf instance lifecycle. Wrapper around Zeroconf for safe instance management. Automatically creates/closes Zeroconf if not provided to APIClient. ```python class ZeroconfManager: """Manages Zeroconf instance lifecycle.""" ``` -------------------------------- ### BadMACAddressAPIError Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/errors.md Device MAC address doesn't match expected_mac parameter. ```python class BadMACAddressAPIError(APIConnectionError): def __init__(self, msg: str, received_name: str, received_mac: str) -> None: self.received_name = received_name self.received_mac = received_mac ``` -------------------------------- ### APIClient Constructor Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md Constructor for the APIClient class. ```python APIClient( address: str, port: int, password: str | None = None, *, client_info: str = "aioesphomeapi", keepalive: float = 20.0, zeroconf_instance: ZeroconfInstanceType | None = None, noise_psk: str | None = None, expected_name: str | None = None, addresses: list[str] | None = None, expected_mac: str | None = None, timezone: str | None = None, provide_time: bool = True, ) -> APIClient ``` -------------------------------- ### ESP_CONNECTION_ERROR_DESCRIPTION Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/utilities.md Mapping of ESP-specific BLE error codes to descriptions. ```python ESP_CONNECTION_ERROR_DESCRIPTION: dict[int, str] ``` -------------------------------- ### Timezone Synchronization Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/configuration.md Configuring timezone synchronization with the device. ```python import zoneinfo # Send device a specific timezone api = APIClient( address="device.local", port=6053, timezone="America/New_York", ) await api.connect() ``` ```python # provide_time=True (default) + no timezone parameter # Device receives system timezone automatically ``` -------------------------------- ### get_voice_assistant_configuration Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md Query voice assistant configuration with a specified timeout. ```python async def get_voice_assistant_configuration( timeout: float = 10.0, ) -> VoiceAssistantConfigurationResponse ``` -------------------------------- ### BluetoothConnectionsFree Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/types.md BLE connection pool availability. ```python @dataclass(frozen=True) class BluetoothConnectionsFree: free: int = 0 limit: int = 0 allocated: list[int] = [] ``` -------------------------------- ### switch_command Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md Send a switch on/off command. ```python def switch_command(key: int, state: bool, device_id: int = 0) -> None ``` -------------------------------- ### device_info_and_list_entities Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md Optimized combined call for device info and entities in a single network packet. ```python async def device_info_and_list_entities() -> tuple[DeviceInfo, list[EntityInfo], list[UserService]] ``` -------------------------------- ### Encrypted Connection with Noise PSK Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/configuration.md Encrypted connection using a Noise PSK. ```python api = APIClient( address="device.local", port=6053, noise_psk="YOUR_BASE64_ENCODED_32_BYTE_KEY", ) await api.connect() ``` -------------------------------- ### update_command Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md Trigger OTA update or skip. ```python def update_command(key: int, command: UpdateCommand, device_id: int = 0) -> None Trigger OTA update or skip. **Parameters**: - `key`: Entity key - `command`: UpdateCommand enum (install, skip) - `device_id`: Device identifier ``` -------------------------------- ### text_command Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md Set text value. ```python def text_command(key: int, state: str, device_id: int = 0) -> None Set text value. **Parameters**: - `key`: Entity key - `state`: Text string - `device_id`: Device identifier ``` -------------------------------- ### LegacyCoverCommand Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/types.md Legacy cover control (pre-position API). ```python class LegacyCoverCommand(APIIntEnum): OPEN = 0 CLOSE = 1 STOP = 2 ``` -------------------------------- ### LIST_ENTITIES_SERVICES_RESPONSE_TYPES mapping Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/utilities.md Maps protobuf message types to model entity info classes. ```python LIST_ENTITIES_SERVICES_RESPONSE_TYPES: dict[type, type] ``` -------------------------------- ### Subscribing to Multiple Event Types Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/README.md Shows how to subscribe to various event streams from the ESPHome device, including state changes, logs, BLE advertisements, and Home Assistant states. ```python # State changes def on_state(state): print(f"State: {state}") api.subscribe_states(on_state) # Device logs def on_log(msg): print(f"[{msg.level}] {msg.message}") api.subscribe_logs(on_log, log_level=LogLevel.LOG_LEVEL_INFO) # Bluetooth advertisements def on_ble_adv(adv): print(f"BLE: {adv.address:012X} RSSI={adv.rssi}") api.subscribe_bluetooth_le_advertisements(on_ble_adv) # Home Assistant state def on_ha_state(entity_id, attribute): print(f"HA: {entity_id}.{attribute} changed") api.subscribe_home_assistant_states(on_ha_state) ``` -------------------------------- ### Legacy Password Authentication Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/configuration.md Legacy password authentication (deprecated). ```python api = APIClient( address="device.local", port=6053, password="your_password", ) await api.connect(login=True) ``` -------------------------------- ### valve_command Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md Control valve position. ```python def valve_command( key: int, position: float | None = None, stop: bool = False, device_id: int = 0, ) -> None Control valve position. **Parameters**: - `key`: Entity key - `position`: 0.0 (closed) to 1.0 (open) - `stop`: If True, halt current movement - `device_id`: Device identifier ``` -------------------------------- ### CoverInfo Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/types.md Cover capabilities. ```python @dataclass(frozen=True) class CoverInfo(EntityInfo): assumed_state: bool = False supports_stop: bool = False supports_position: bool = False supports_tilt: bool = False device_class: str = "" ``` -------------------------------- ### BluetoothDevicePairing Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/types.md BLE pairing result. ```python @dataclass(frozen=True) class BluetoothDevicePairing: address: int = 0 success: bool = False error: int = 0 ``` -------------------------------- ### Connect to older devices with password authentication Source: https://github.com/esphome/aioesphomeapi/blob/main/README.rst Connect to older ESPHome devices still using password authentication. ```python api = aioesphomeapi.APIClient("device.local", 6053, password="MyPassword") ``` -------------------------------- ### asyncio_timeout context manager Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/utilities.md An asyncio timeout context manager, similar to Python 3.11+'s asyncio.timeout. ```python @contextmanager def asyncio_timeout(timeout: float) -> AsyncGenerator[None, None]: """Context manager for asyncio timeout.""" ``` -------------------------------- ### HelloResponse Message Details Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/protocol.md Fields for the HelloResponse protobuf message. ```plaintext api_version_major: uint32 // Device API major api_version_minor: uint32 // Device API minor server_info: string // Device firmware string ``` -------------------------------- ### Connect to device and retrieve details Source: https://github.com/esphome/aioesphomeapi/blob/main/README.rst Connect to an ESPHome device and retrieve its API version, device information, and entity list. ```python import aioesphomeapi import asyncio async def main(): """Connect to an ESPHome device and get details.""" # Establish connection api = aioesphomeapi.APIClient( "api_test.local", 6053, noise_psk="YOUR_ENCRYPTION_KEY", # Remove if not using encryption ) await api.connect(login=True) # Get API version of the device's firmware print(api.api_version) # Show device details device_info = await api.device_info() print(device_info) # List all entities of the device entities = await api.list_entities_services() print(entities) loop = asyncio.get_event_loop() loop.run_until_complete(main()) ``` -------------------------------- ### ResolveTimeoutAPIError Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/errors.md Host resolution timed out (mDNS took too long). ```python class ResolveTimeoutAPIError(ResolveAPIError, asyncio.TimeoutError): """Raised when a resolve timeout occurs.""" ``` -------------------------------- ### select_command Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md Select option from dropdown/enum entity. ```python def select_command(key: int, state: str, device_id: int = 0) -> None Select option from dropdown/enum entity. **Parameters**: - `key`: Entity key - `state`: Option string value - `device_id`: Device identifier ``` -------------------------------- ### ResolveAPIError Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/errors.md Host resolution failed (DNS or mDNS lookup error). ```python class ResolveAPIError(APIConnectionError): """Raised when a resolve error occurs.""" ``` -------------------------------- ### lock_command Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md Lock/unlock or open door lock. ```python def lock_command(key: int, command: LockCommand, device_id: int = 0) -> None Lock/unlock or open door lock. **Parameters**: - `key`: Entity key - `command`: LockCommand enum (lock, unlock, open) - `device_id`: Device identifier ``` -------------------------------- ### HelloRequest Message Details Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/protocol.md Fields for the HelloRequest protobuf message. ```plaintext client_info: string // User agent (e.g., "aioesphomeapi") api_version_major: uint32 // Supported API major (1) api_version_minor: uint32 // Supported API minor (14) ``` -------------------------------- ### UserService Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/types.md Metadata for a user-defined service, including its key, name, description, arguments, and response behavior. ```python @dataclass(frozen=True) class UserService: key: int = 0 name: str = "" description: str = "" args: list[UserServiceArg] = [] returns_response: bool = False supports_response_type: SupportsResponseType = SupportsResponseType.NONE ``` -------------------------------- ### time_command Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md Set time value. ```python def time_command(key: int, hour: int, minute: int, second: int, device_id: int = 0) -> None Set time value. **Parameters**: - `key`: Entity key - `hour`, `minute`, `second`: Time components - `device_id`: Device identifier ``` -------------------------------- ### fan_command Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md Control fan power, speed, oscillation, direction. ```python def fan_command( key: int, state: bool | None = None, speed: FanSpeed | None = None, speed_level: int | None = None, oscillating: bool | None = None, direction: FanDirection | None = None, device_id: int = 0, ) -> None ``` -------------------------------- ### send_voice_assistant_audio Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md Send encoded audio to voice assistant. ```python def send_voice_assistant_audio(data: bytes) -> None ``` -------------------------------- ### Timeout Handling Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/README.md Shows how to handle timeouts for individual API operations and connection attempts. ```python import asyncio # Per-operation timeout try: info = await asyncio.wait_for( api.device_info(), timeout=10.0 ) except asyncio.TimeoutError: print("Device not responding") # Connection timeout (part of connect()) try: await api.connect() except TimeoutAPIError: print("Connection timeout") except SocketAPIError: print("Device offline") ``` -------------------------------- ### send_voice_assistant_event Source: https://github.com/esphome/aioesphomeapi/blob/main/_autodocs/api-client.md Send voice assistant command/event. ```python def send_voice_assistant_event( event: VoiceAssistantCommand, ) -> None ```