A Python helper library to manage Home Assistant entities over MQTT.
Updated for device based MQTT discovery.
Features:
- MQTT client based on paho-mqtt
- Retrieve MQTT service info from the Home Assistant Supervisor
- Manage MQTT discovery info (adding/removing entities)
- MQTTDevice class to manage devices
- Availability management (client-wide and optional per-device
availability_topics) - Manage entities per device
- Availability management (client-wide and optional per-device
- Home Assistant Entities modelled as dataclasses:
- Read-only: Sensor, BinarySensor, DeviceTracker
- Read & write: Select, Switch, Number, Text, Light
- MQTT device events
- Asyncio based
- Helpers for Home Assistant add-ons (optional)
- Add-on configuration modeled as dataclasses
- Load from environment variables, HA's options.yaml or options.json
- Load MQTT connection settings from the Supervisor
- Enable add-on logging (incl colors & debug by config)
- Add-on configuration modeled as dataclasses
Device discovery (homeassistant/device/.../config) is published when Home Assistant signals online on homeassistant/status (after a short debounce).
By default it is not retained (MQTTClient(discovery_retain=False)).
That way the broker does not keep configs after the publisher stops, and removing a device does not require publishing an empty discovery payload.
Set discovery_retain=True on the client if you want the broker to replay discovery on subscribe—clearing removed devices is then your responsibility.
Entity state should be retained so Home Assistant gets the latest value when it subscribes to each state_topic after discovery.
send_state and the tracker/light state helpers default to retain=True; pass retain=False when a value must not be replayed.
JSON attributes and availability are retained by default.
Do not retain device-trigger events.
This MQTT code was included in several of my home Assistant addons (SMA-EM / Sunsynk). It is easier to update a single library & add new features, like discovery removal.
Alternative options (not based on asyncio)
@Ivan-L contributed some of the writable entities to the Sunsynk addon project
Semantic versioning is used for release.
To create a new release, include a commit with a 🐬 emoji as a prefix in the commit message. This will trigger a release on the master branch.
# Patch
git commit -m ":dolphin: Release 0.0.x"
# Minor - any commitTo run the tests, you need to have Python 3.12+ installed.
The --mqtt connects to a live Home Assistant instance using the MQTT broker.
uv run pytest --mqtt