ESP32 + ASI Biont: How an AI Agent Controls Your IoT Devices in Seconds

Introduction

The ESP32 is one of the most popular microcontrollers for IoT projects. With built-in Wi-Fi, Bluetooth, dual-core processing, and rich peripheral support (GPIO, ADC, I2C, SPI, UART), it powers everything from smart home sensors to industrial data loggers. But writing the integration code for every new use case, debugging serial protocols, or setting up MQTT subscriptions can be tedious and time-consuming.

ASI Biont is an AI agent designed to connect to any device — microcontrollers, PLCs, SBCs, and cloud APIs — via natural language conversation. Instead of manually coding, you describe what you need in the chat, and ASI Biont writes the Python code, executes it, and interacts with the device using industry-standard protocols: MQTT, COM port (via Hardware Bridge), HTTP API, Modbus TCP, SSH, and more. This article is a hands‑on guide to connecting an ESP32 to ASI Biont using real integration methods. No fake endpoints, no hypothetical dashboards — just a chat with an AI.

Which Connection Method to Use?

ESP32 can be integrated with ASI Biont through several channels. The choice depends on your scenario:

Method Best for Setup Effort
MQTT (paho‑mqtt) Continuous sensor data streaming, remote control Low – just need broker address
COM port via Hardware Bridge (bridge.py) Direct UART control, flashing, serial debug Medium – local PC with USB cable
HTTP API (aiohttp) REST endpoints on ESP32 Low – if ESP32 runs a web server
CoAP (aiocoap) Constrained IoT devices Medium – needs CoAP library on ESP32
SSH (paramiko) ESP32 with ESP‑OS / MicroPython + SSH Low – if SSH is enabled
Modbus TCP (pymodbus) ESP32 as Modbus slave in industrial setups Medium – need Modbus implementation on ESP32
execute_python (universal) Any custom protocol (e.g., raw TCP, WebSocket) None – AI writes the adapter

In this guide we focus on the two most practical and commonly used methods: MQTT (for cloud‑ready sensor data) and COM port via Hardware Bridge (for direct UART control). Both are fully supported by ASI Biont today.

Scenario 1: ESP32 + DHT22 Temperature/Humidity Sensor → MQTT + ASI Biont

Problem

You have an ESP32 with a DHT22 sensor placed in a greenhouse. You want ASI Biont to read temperature and humidity every minute, detect dangerous trends (e.g., temperature > 35°C), and send you a Telegram alert. You also want to be able to query the latest sensor value via chat.

Hardware Setup

  • ESP32 Dev Board (e.g., ESP32‑WROOM‑32)
  • DHT22 sensor
  • 10 kΩ pull‑up resistor (DHT22 data pin to 3.3V)
  • Breadboard and jumper wires

Wiring:

DHT22 Pin ESP32 Pin
VCC 3.3V
DATA GPIO4
GND GND

Code on ESP32 (Arduino IDE / PlatformIO)

The ESP32 will publish sensor data to an MQTT broker. Here’s a minimal ESP32 sketch (using PubSubClient library):

#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>

#define DHT_PIN 4
#define DHT_TYPE DHT22
DHT dht(DHT_PIN, DHT_TYPE);

const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASS";
const char* mqtt_server = "broker.hivemq.com"; // public broker for demo

WiFiClient espClient;
PubSubClient client(espClient);

void setup_wifi() {
  delay(10);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }
}

void reconnect() {
  while (!client.connected()) {
    if (client.connect("ESP32_DHT22")) { }
    delay(5000);
  }
}

void setup() {
  Serial.begin(115200);
  dht.begin();
  setup_wifi();
  client.setServer(mqtt_server, 1883);
}

void loop() {
  if (!client.connected()) reconnect();
  client.loop();

  float h = dht.readHumidity();
  float t = dht.readTemperature();
  if (isnan(h) || isnan(t)) return;

  char payload[64];
  snprintf(payload, 64, "{\"temp\":%.1f,\"hum\":%.1f}", t, h);
  client.publish("greenhouse/sensor1", payload);

  delay(60000); // every 60 seconds
}

Upload the sketch to your ESP32. Now it publishes JSON to topic greenhouse/sensor1 every minute on the public HiveMQ broker.

ASI Biont Integration via Chat

Open ASI Biont and start a new chat. Describe the device:

“Connect to MQTT broker broker.hivemq.com:1883, subscribe to topic greenhouse/sensor1, parse the JSON with temperature and humidity, and if temperature exceeds 35°C, send me a Telegram alert. Also, if I ask ‘what is the latest sensor value?’, reply with the last value.”

ASI Biont will generate and execute a Python script using paho‑mqtt and requests (for Telegram). Here’s the code the AI might produce:

import paho.mqtt.client as mqtt
import json
import time
import requests

TELEGRAM_BOT_TOKEN = "YOUR_BOT_TOKEN"
TELEGRAM_CHAT_ID = "YOUR_CHAT_ID"

latest_data = {}

def on_connect(client, userdata, flags, rc):
    client.subscribe("greenhouse/sensor1")

def on_message(client, userdata, msg):
    global latest_data
    try:
        data = json.loads(msg.payload.decode())
        temp = data["temp"]
        hum = data["hum"]
        latest_data = {"temp": temp, "hum": hum}
        print(f"Received: T={temp}, H={hum}")
        if temp > 35.0:
            requests.post(
                f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage",
                json={"chat_id": TELEGRAM_CHAT_ID, "text": f"🔥 Alert! Temperature {temp}°C exceeds 35°C!"}
            )
    except Exception as e:
        print("Parse error:", e)

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("broker.hivemq.com", 1883, 60)
client.loop_start()

time.sleep(5)  # wait for first messages
print("MQTT listener started. You can query via chat.")

# Keep running (but note: sandbox timeout 30s; for demo we just sleep)
# In production, ASI Biont keeps the script alive with long-running processes

Because execute_python has a 30‑second timeout, the AI will use the industrial_command tool with MQTT subscription for persistent monitoring. The above is a simplified version; in practice ASI Biont uses the publish command for quick writes and a background subscriber for continuous reading.

Result: Now you can ask in the chat “What is the latest temperature?” and ASI Biont will reply with the stored value. If temperature spikes, you get a Telegram message – all without writing a single line of MQTT code yourself.

Scenario 2: ESP32 as a Serial Controller via Hardware Bridge

Problem

You have an ESP32 running a simple command‑based firmware (e.g., control an LED, read an analog sensor). You want ASI Biont to send commands like LED_ON or ANALOG? over USB‑UART and receive responses – directly from the chat.

Hardware Setup

  • ESP32 Dev Board
  • USB cable connecting ESP32 to your PC where bridge.py runs
  • (Optional) LED on GPIO2 with 220Ω resistor for visual feedback

ESP32 Firmware (Arduino)

void setup() {
  Serial.begin(115200);
  pinMode(2, OUTPUT);
  Serial.println("HELP: LED_ON, LED_OFF, ANALOG?, STATUS");
}

void loop() {
  if (Serial.available()) {
    String cmd = Serial.readStringUntil('\n');
    cmd.trim();
    if (cmd == "LED_ON") {
      digitalWrite(2, HIGH);
      Serial.println("LED ON");
    } else if (cmd == "LED_OFF") {
      digitalWrite(2, LOW);
      Serial.println("LED OFF");
    } else if (cmd == "ANALOG?") {
      Serial.println(analogRead(34));
    } else if (cmd == "STATUS") {
      Serial.println("Running");
    } else {
      Serial.println("Unknown");
    }
  }
}

Upload this to the ESP32. Connect it to your PC. Note the COM port (e.g., COM3 on Windows, /dev/ttyUSB0 on Linux).

Running Hardware Bridge

Download bridge.py from the ASI Biont dashboard (Devices → Create API Key → Download bridge). Install dependencies:

pip install pyserial requests websockets

Run the bridge with your API token and the COM port:

python bridge.py --token=YOUR_API_TOKEN --ports=COM3 --baud=115200

The bridge connects to ASI Biont via WebSocket and listens for commands.

Integration via Chat

In the ASI Biont chat, describe:

“Use Hardware Bridge to connect to COM3 at 115200 baud. Send the command LED_ON and read the response. Then send ANALOG? and give me the analog value.”

ASI Biont will call the industrial_command tool with protocol serial://:

industrial_command(
    protocol='serial://',
    command='serial_write_and_read',
    data='4c45445f4f4e0a',  # hex for "LED_ON\n"
    port='COM3'
)

The bridge sends LED_ON (plus newline) to the ESP32, reads the reply "LED ON", and returns it to the AI. The AI then sends ANALOG? (hex: 414e414c4f473f0a) and gets a numeric value.

Now you can control and query the ESP32 entirely through natural language. No need to open Serial Monitor – just ask the AI.

Scenario 3: ESP32 as an HTTP Server (REST API) + AI Agent

Problem

You have an ESP32 running a simple web server that controls relays and reads sensors. You want ASI Biont to turn on/off a relay and log the state.

ESP32 Code (Arduino)

Use the ESPAsyncWebServer library to expose a minimal REST API:

#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>

const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASS";

AsyncWebServer server(80);
const int relayPin = 5;

void setup() {
  Serial.begin(115200);
  pinMode(relayPin, OUTPUT);
  digitalWrite(relayPin, LOW);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) delay(500);
  Serial.println(WiFi.localIP());

  server.on("/relay", HTTP_GET, [](AsyncWebServerRequest *request){
    String state = request->arg("state");
    if (state == "on") {
      digitalWrite(relayPin, HIGH);
      request->send(200, "text/plain", "Relay ON");
    } else if (state == "off") {
      digitalWrite(relayPin, LOW);
      request->send(200, "text/plain", "Relay OFF");
    } else {
      request->send(400, "text/plain", "Use ?state=on or ?state=off");
    }
  });

  server.on("/temp", HTTP_GET, [](AsyncWebServerRequest *request){
    // read sensor, for demo return dummy
    request->send(200, "application/json", "{\"temp\":23.5}");
  });

  server.begin();
}

void loop() {}

Integration via Chat

In ASI Biont:

“Connect to ESP32 HTTP server at 192.168.1.100. Turn the relay on by sending GET request to /relay?state=on. Then read temperature from /temp.”

ASI Biont will execute a Python script with requests or aiohttp inside the sandbox:

import requests

base = "http://192.168.1.100"
r = requests.get(f"{base}/relay?state=on")
print("Relay response:", r.text)

temp_r = requests.get(f"{base}/temp")
print("Temperature:", temp_r.json())

The output is shown in the chat. You can also ask AI to schedule periodic control or send alerts.

Why Integration via ASI Biont is a Game Changer

  • Zero boilerplate: You don’t need to write MQTT clients, parse protocols, or handle reconnections. The AI does it for you in seconds.
  • Protocol flexibility: Whether your ESP32 speaks raw serial, MQTT, CoAP, Modbus, or HTTP – ASI Biont supports all of them via the industrial_command tool or execute_python.
  • Reactive automation: Set rules like “If temperature > 35°C, turn on fan” – AI will subscribe to the data stream and trigger actions on your ESP32 or other devices.
  • No added bloat: You don’t need to install an SDK on the ESP32. Use your own firmware – the AI adapts.

Conclusion

The ESP32 is a versatile platform, but integrating it with an intelligent agent used to require custom middleware and endless debugging. With ASI Biont, you simply describe the task – and the AI agent writes the code, connects to the device, and executes your commands. From sensor monitoring to actuator control, the possibilities are limited only by your imagination.

Try it yourself today: Go to asibiont.com, create an API key, run bridge.py if you need serial access, and start chatting with your ESP32. No dashboards, no buttons – just pure conversation with your device.


Sources: ESP32 technical reference (Espressif), DHT22 datasheet (Aosong), Paho MQTT client documentation, PubSubClient library by Nick O’Leary, ASI Biont official documentation.

← All posts

Comments