How to Integrate MQTT (Mosquitto, EMQX) with ASI Biont AI Agent: A Step-by-Step Guide for IoT Automation

Introduction

The Internet of Things (IoT) has revolutionized how we monitor and control physical devices—from smart home sensors to industrial machinery. At the heart of many IoT deployments lies MQTT (Message Queuing Telemetry Transport), a lightweight publish-subscribe protocol designed for low-bandwidth, high-latency networks. Brokers like Mosquitto (open-source) and EMQX (enterprise-grade) handle millions of messages daily, enabling real-time data flow between sensors, actuators, and cloud platforms.

But managing MQTT-based IoT systems often requires constant human oversight: setting up dashboards, writing scripts to analyze telemetry, and manually triggering actions. Enter ASI Biont—an AI agent that can connect to any MQTT broker, subscribe to topics, analyze incoming data, and publish commands automatically. Instead of coding a custom MQTT client from scratch, you simply describe your goal in natural language, and ASI Biont writes and executes the integration code in seconds. This article walks you through a real-world use case: monitoring temperature and humidity from an ESP32 sensor and sending Telegram alerts when thresholds are exceeded.

Why MQTT and ASI Biont?

MQTT is the de facto standard for IoT messaging due to its minimal overhead, support for Quality of Service (QoS) levels, and ability to bridge devices behind NAT. Mosquitto is lightweight and perfect for local networks; EMQX adds clustering, authentication, and rule engines for large-scale deployments. However, extracting value from MQTT data typically involves writing Python scripts with paho-mqtt, setting up databases, and configuring alerting logic. ASI Biont eliminates this friction by acting as an intelligent MQTT client that can interpret natural language instructions, generate code on the fly, and execute it in a secure sandbox.

Connection Method: paho-mqtt via execute_python

ASI Biont connects to MQTT brokers using the paho-mqtt library inside the execute_python environment. This is a universal method: the AI writes a complete Python script that runs on the ASI Biont cloud server (Railway). The script can subscribe to topics, process messages, and publish commands. For quick one-off publishes, the AI also uses the industrial_command tool with the publish command, but for continuous monitoring, execute_python is the right choice.

Important: The execute_python sandbox has a 30-second timeout. Therefore, scripts should avoid infinite loops. Instead, they connect, subscribe, process a batch of messages, and exit gracefully. For long-running subscriptions, you can use the industrial_command tool to publish commands, or run a persistent script on your own server that communicates with ASI Biont via HTTP API.

Real-World Use Case: ESP32 Temperature/Humidity Monitoring with Telegram Alerts

Problem

You have an ESP32 microcontroller with a DHT22 sensor publishing temperature and humidity data to a Mosquitto broker running on a Raspberry Pi. You want to:
- Continuously monitor the data.
- Send a Telegram message when temperature exceeds 30°C or humidity drops below 20%.
- Log all readings to a CSV file for later analysis.

Manually, you would need to write a Python script using paho-mqtt, set up a Telegram bot, and handle reconnections. With ASI Biont, you describe the task in chat, and the AI generates the integration code instantly.

Step 1: Describe Your Setup in Chat

You start a conversation with ASI Biont and provide the broker details:

“Connect to MQTT broker at 192.168.1.100:1883, subscribe to topic esp32/dht22. Parse JSON messages with fields temperature and humidity. If temperature > 30°C or humidity < 20%, send a Telegram alert to chat ID 123456789 using bot token ABC:XYZ. Log all readings to sensor_log.csv.”

Step 2: AI Generates and Executes the Code

ASI Biont writes the following Python script (using paho-mqtt, requests for Telegram, and csv for logging) and runs it in the sandbox:

import paho.mqtt.client as mqtt
import json
import csv
from datetime import datetime
import requests

BROKER = "192.168.1.100"
PORT = 1883
TOPIC = "esp32/dht22"
TELEGRAM_TOKEN = "ABC:XYZ"
CHAT_ID = "123456789"
LOG_FILE = "sensor_log.csv"

# Telegram alert function
def send_alert(message):
    url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage"
    payload = {"chat_id": CHAT_ID, "text": message}
    try:
        requests.post(url, json=payload, timeout=5)
    except Exception as e:
        print(f"Telegram error: {e}")

# Callback when message is received
def on_message(client, userdata, msg):
    try:
        data = json.loads(msg.payload.decode())
        temp = data["temperature"]
        hum = data["humidity"]
        timestamp = datetime.now().isoformat()

        # Log to CSV
        with open(LOG_FILE, "a", newline="") as f:
            writer = csv.writer(f)
            writer.writerow([timestamp, temp, hum])

        # Check thresholds
        alerts = []
        if temp > 30:
            alerts.append(f"Temperature {temp}°C exceeds 30°C")
        if hum < 20:
            alerts.append(f"Humidity {hum}% is below 20%")
        if alerts:
            send_alert(" | ".join(alerts))

    except Exception as e:
        print(f"Error processing message: {e}")

# Connect and subscribe
client = mqtt.Client()
client.on_message = on_message
client.connect(BROKER, PORT, 60)
client.subscribe(TOPIC)

# Process 10 messages then exit (avoids timeout)
import time
for _ in range(10):
    client.loop(timeout=1.0)
time.sleep(1)
print("Completed monitoring cycle.")

What happens: The script connects to the Mosquitto broker, subscribes to esp32/dht22, and processes up to 10 messages. For each message, it parses the JSON, logs to CSV, and sends a Telegram alert if thresholds are breached. The sandbox timeout is respected by limiting the loop.

Step 3: Verify Results

After execution, ASI Biont reports back and shows the log entries and any alerts sent. You can ask the AI to:
- Adjust thresholds.
- Change the Telegram bot.
- Switch to an EMQX broker with TLS.
- Publish a command back (e.g., turn on a relay via esp32/relay1).

All modifications happen through natural language—no manual code changes.

Why This Integration Is Powerful

Traditional IoT monitoring requires:
- Setting up a database or cloud platform.
- Writing and debugging Python scripts.
- Managing MQTT reconnections and error handling.
- Integrating third-party APIs (Telegram, email, etc.).

With ASI Biont, you skip all that. The AI agent:
- Writes production-ready Python code using paho-mqtt.
- Handles JSON parsing, CSV logging, and API calls.
- Allows instant changes via chat.
- Connects to any MQTT broker (Mosquitto, EMQX, HiveMQ, AWS IoT Core).

The same approach works for any MQTT-enabled device: smart plugs, industrial sensors, solar inverters, or weather stations. Just describe the topic structure and what you want to do.

Connecting to Any Device, Not Just MQTT

While this article focuses on MQTT, ASI Biont can connect to virtually any hardware using the same execute_python method. The AI has access to a rich set of libraries:

Protocol/Library Example Device Use Case
pyserial Arduino, ESP32 via USB Read sensor data, control servos
paramiko Raspberry Pi, Linux server Run scripts, GPIO control
pymodbus PLC, Modbus TCP devices Read registers, write coils
aiohttp Smart plugs, cameras (HTTP API) Turn on/off, fetch snapshots
opcua-asyncio Factory OPC UA servers Read tags, predict failures
paho.mqtt MQTT brokers (Mosquitto, EMQX) Subscribe, publish, alert

You simply tell the AI: “Connect to my PLC at 10.0.0.5 via Modbus TCP, read holding registers 0-10, and log to a file if any value exceeds 100.” The AI generates the code and executes it. No need to wait for vendor SDKs or dashboard plugins.

Conclusion

MQTT is the backbone of modern IoT, but extracting actionable insights from its data streams often requires significant development effort. ASI Biont changes the game by acting as an intelligent MQTT client that understands natural language. Whether you run a Mosquitto broker in your home lab or EMQX in a factory, you can now monitor, alert, and control your devices by simply chatting with an AI.

The ESP32 temperature monitoring example shows how a task that would take hours to code and debug can be completed in seconds. And because ASI Biont connects to any device via execute_python—without pre-built integrations—you are not limited to MQTT. The same AI can talk to PLCs, Arduino boards, Raspberry Pis, and cloud APIs.

Ready to automate your IoT infrastructure? Try the integration on asibiont.com today. Open a chat, describe your MQTT broker and what you want to achieve, and let the AI take care of the rest.

← All posts

Comments