How to Connect Zigbee Devices (ZHA, Zigbee2MQTT) to an AI Agent: A Practical Guide with ASI Biont

Introduction

If you're running a smart home with Zigbee devices—temperature sensors, smart plugs, or light bulbs—you've probably hit the same wall: getting them to talk to an AI that actually understands context. Most automation platforms are rule-based ("if temperature > 30°C, turn on fan"), but what if you want the AI to analyze trends, predict when your room will get too warm, or send a Telegram warning before the AC fails?

That's where ASI Biont comes in. It's an AI agent that connects directly to your Zigbee network via MQTT (using Zigbee2MQTT or ZHA) and lets you control everything through a chat conversation. No coding required—you just describe what you want, and the AI writes the integration code on the fly.

In this guide, I'll walk through a real-world setup: a Zigbee temperature/humidity sensor (like Aqara or Sonoff) and a smart plug, connected to ASI Biont via Zigbee2MQTT. You'll see how to read sensor data, log it, and create automations that alert you in Telegram when thresholds are exceeded—all without writing a single line of Python yourself.

How ASI Biont Connects to Zigbee Devices

Zigbee devices don't talk directly to the internet—they communicate through a coordinator (like a Conbee II or Sonoff ZBDongle) that bridges to your network. Most hobbyists run Zigbee2MQTT or ZHA (Zigbee Home Automation) inside Home Assistant. Both expose device data via an MQTT broker (usually Mosquitto).

ASI Biont supports MQTT out of the box. The AI agent uses the execute_python feature, which runs a Python script in a sandbox on the ASI Biont cloud server (Railway). That script uses the paho-mqtt library to subscribe to MQTT topics published by Zigbee2MQTT, parse the JSON payloads, and react accordingly.

Why MQTT?

Feature Why It Works for Zigbee
Lightweight Zigbee2MQTT sends sensor updates as small JSON messages (e.g., {"temperature": 22.5, "humidity": 45})
Bidirectional Subscribe to sensor topics for reads; publish to command topics to control switches, lights, etc.
Standard Works with any MQTT broker (Mosquitto, HiveMQ) and any coordinator

Connection flow:
1. Zigbee sensor sends data to coordinator → Zigbee2MQTT publishes to zigbee2mqtt/0x00158d0003c12345
2. ASI Biont's Python script subscribes to that topic (or a wildcard zigbee2mqtt/#)
3. AI parses the JSON, logs it, and triggers actions (e.g., send Telegram message, save to database)
4. To control a smart plug, AI publishes to zigbee2mqtt/0x00158d0003c54321/set with payload {"state": "ON"}

Real Example: Temperature Sensor + Smart Plug + Telegram Alerts

Hardware Used

  • Zigbee coordinator: Sonoff ZBDongle-E (Zigbee 3.0 USB dongle, flashed with Z-Stack firmware)
  • Sensor: Aqara WSDCGQ11LM (temperature, humidity, pressure)
  • Smart plug: Sonoff S31 Lite ZB (with power monitoring)
  • MQTT broker: Mosquitto running on a Raspberry Pi 4 (also running Zigbee2MQTT)

Step 1: User Describes the Task to ASI Biont

In the chat, the user writes:

"Connect to my MQTT broker at 192.168.1.100:1883 with no authentication. Subscribe to all topics under zigbee2mqtt/0x00158d0003c12345 (my Aqara sensor). When temperature exceeds 30°C, turn on the smart plug at zigbee2mqtt/0x00158d0003c54321/set and send me a Telegram alert with the current temperature and humidity."

Step 2: AI Writes the Integration Code

ASI Biont's AI generates a Python script using paho-mqtt and runs it inside the execute_python sandbox. Here's the exact code it produces:

import paho.mqtt.client as mqtt
import json
import asyncio
from datetime import datetime

# Configuration (provided by user in chat)
MQTT_BROKER = "192.168.1.100"
MQTT_PORT = 1883
SENSOR_TOPIC = "zigbee2mqtt/0x00158d0003c12345"
PLUG_COMMAND_TOPIC = "zigbee2mqtt/0x00158d0003c54321/set"
TELEGRAM_BOT_TOKEN = "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"
TELEGRAM_CHAT_ID = "987654321"

TEMPERATURE_THRESHOLD = 30.0  # Celsius

def on_connect(client, userdata, flags, rc):
    print(f"Connected to MQTT broker with result code {rc}")
    client.subscribe(SENSOR_TOPIC)

def on_message(client, userdata, msg):
    payload = json.loads(msg.payload.decode())
    temperature = payload.get("temperature")
    humidity = payload.get("humidity")

    print(f"Received: temp={temperature}°C, humidity={humidity}%")

    if temperature is not None and temperature > TEMPERATURE_THRESHOLD:
        # Turn on smart plug
        client.publish(PLUG_COMMAND_TOPIC, json.dumps({"state": "ON"}))
        print("Plug turned ON due to high temperature")

        # Send Telegram alert
        message = f"⚠️ *Temperature Alert!*\nTemp: {temperature}°C\nHumidity: {humidity}%\nTime: {datetime.now().isoformat()}"
        send_telegram(message)

def send_telegram(text):
    import requests
    url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
    requests.post(url, json={"chat_id": TELEGRAM_CHAT_ID, "text": text, "parse_mode": "Markdown"})

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(MQTT_BROKER, MQTT_PORT, 60)
client.loop_forever()  # Runs for up to 30 seconds (sandbox limit)

Important: The sandbox has a 30-second timeout. For long-running automation, you'd use ASI Biont's industrial_command tool with MQTT protocol, which runs continuously on the bridge. But for testing and one-off tasks, execute_python works perfectly.

Step 3: AI Runs the Script and Monitors

ASI Biont executes the script. Within seconds, it starts receiving temperature updates. When the temperature hits 31°C, it:
- Publishes {"state": "ON"} to the smart plug topic → the plug turns on
- Sends a Telegram message with the alert

The user can then ask the AI: "Now turn off the plug after 30 minutes" or "Log all temperature readings to a Google Sheet"—and the AI will modify the script accordingly.

Beyond Basic Automation: Predictive Alerts

You can ask the AI to do more sophisticated things without writing extra code:

"Analyze the last 50 temperature readings and predict when the room will exceed 35°C. If the trend shows a rise of more than 2°C per hour, send a warning to Telegram."

ASI Biont will generate a new script that:
- Collects 50 messages (or reads from a local database if you set one up)
- Uses numpy to fit a linear regression
- Calculates the slope and predicts time to threshold
- Sends an early warning

This is where ASI Biont shines—it's not just a rule engine; it's a real AI that can reason about data.

No Coding? Yes, Really.

The entire integration happens through the chat. You don't:
- Write a single line of Python
- Install libraries manually (the sandbox has everything)
- Create dashboards or click "add device" buttons
- Wait for developers to add Zigbee support

ASI Biont connects to any device that can speak MQTT, Modbus, SSH, HTTP, OPC-UA, or serial. For Zigbee, the only prerequisite is a running Zigbee2MQTT or ZHA instance publishing to an MQTT broker.

Potential Pitfalls

  1. MQTT topic structure: Zigbee2MQTT uses device IEEE addresses by default. Make sure you know the exact topic your sensor publishes to. You can check by subscribing to zigbee2mqtt/# with an MQTT client like mosquitto_sub.
  2. Sandbox timeout: execute_python scripts have a 30-second limit. For persistent subscriptions, use industrial_command with the MQTT protocol (it runs on the bridge and is always on).
  3. JSON keys: Different Zigbee devices report different keys. The Aqara sensor sends temperature, humidity, pressure. A Sonoff TH sensor might send temperature, humidity. Always check the payload first.
  4. Security: If your MQTT broker uses authentication, include username/password in the chat. ASI Biont will add them to the script.

Conclusion

Connecting Zigbee devices to an AI agent is not only possible—it's incredibly simple. By bridging Zigbee2MQTT with ASI Biont's MQTT integration, you get an AI that can monitor, analyze, and control your smart home based on natural language instructions. No dashboard, no coding, no waiting.

Try it yourself: https://asibiont.com. Start a chat, describe your Zigbee setup, and watch the AI take control in seconds.

← All posts

Comments