aioesphomeapi

44.13.3 · active · verified Sun Apr 12

aioesphomeapi is an asynchronous Python API client designed for interacting with devices running ESPHome firmware. It provides a way for Python applications, notably Home Assistant, to communicate with ESPHome devices using their native API for real-time control and monitoring. The library is actively maintained with frequent updates, often aligning with ESPHome and Home Assistant releases. The current version is 44.13.3.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to an ESPHome device, retrieve its API version, device information, and a list of available entities. It prioritizes using `noise_psk` for secure connections, falling back to an optional password (now deprecated). Ensure the ESPHome device has the Native API enabled in its configuration and provide the correct host, port, and authentication details via environment variables.

import aioesphomeapi
import asyncio
import os

async def main():
    host = os.environ.get('ESPHOME_HOST', 'device.local')
    port = int(os.environ.get('ESPHOME_PORT', 6053))
    noise_psk = os.environ.get('ESPHOME_NOISE_PSK', '') # Recommended for secure communication
    password = os.environ.get('ESPHOME_PASSWORD', '') # Deprecated, use noise_psk

    if not noise_psk and not password:
        print("Warning: No encryption key or password provided. Connection might fail or be insecure.")

    # Establish connection
    api = aioesphomeapi.APIClient(
        host,
        port,
        noise_psk=noise_psk if noise_psk else None,
        password=password if password else None
    )
    
    try:
        await api.connect(login=True)
        print(f"Successfully connected to {host}:{port}")

        # Get API version of the device's firmware
        print(f"API Version: {api.api_version}")

        # Show device details
        device_info = await api.device_info()
        print(f"Device Info: {device_info.name} ({device_info.mac_address})")

        # List all entities of the device
        entities = await api.list_entities_services()
        print(f"Number of entities: {len(entities.entities)}")
        # for entity in entities.entities:
        #     print(f" - {entity.name} ({entity.key})")

    except aioesphomeapi.APIConnectionError as e:
        print(f"Connection error: {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
    finally:
        if api.is_connected:
            await api.disconnect()
            print("Disconnected.")

if __name__ == "__main__":
    asyncio.run(main())

view raw JSON →