How to Integrate ESP32 with ASI Biont AI Agent: Smart Greenhouse Automation via MQTT

How to Integrate ESP32 with ASI Biont AI Agent: Smart Greenhouse Automation via MQTT

Introduction

The ESP32 is a powerful, low-cost microcontroller with built-in Wi-Fi and Bluetooth, making it a favorite for IoT projects. However, managing sensor data and automating actions based on that data often requires custom firmware, cloud dashboards, and manual scripting. ASI Biont changes the game: it's an AI agent that can connect to any device—including an ESP32—through natural language conversation. You simply describe your setup, and the AI writes the integration code, handles data parsing, and triggers actions. In this article, we'll explore a real-world use case: automating a greenhouse's ventilation system using an ESP32 with a DHT22 temperature/humidity sensor, connected to ASI Biont via MQTT.

Why Connect an ESP32 to an AI Agent?

In a typical greenhouse, temperature fluctuations can ruin crops. A sudden heat spike without ventilation can cause wilting, yield loss, and increased disease risk. Manual monitoring is labor-intensive and error-prone. With an ESP32 and a DHT22 sensor, you can measure temperature every few seconds. But who watches the data 24/7? An AI agent like ASI Biont can subscribe to MQTT topics, analyze trends, and automatically control ventilation—without you writing a single line of boilerplate code. The result: reduced crop loss, energy savings, and peace of mind.

How ASI Biont Connects to ESP32

ASI Biont supports multiple connection methods. For the ESP32, the most practical is MQTT (Message Queuing Telemetry Transport). MQTT is a lightweight publish/subscribe protocol ideal for low-power IoT devices. The ESP32 publishes sensor readings to a broker (e.g., Mosquitto running on a Raspberry Pi or a cloud service like HiveMQ Cloud). ASI Biont, running in its cloud sandbox, uses a Python script with the paho-mqtt library to subscribe to that topic, analyze the data, and publish commands back to the ESP32 (e.g., "turn on vent fan").

Alternatively, you can use Hardware Bridge (bridge.py) if the ESP32 is connected via USB serial. The bridge runs on your local PC, connects to ASI Biont via WebSocket, and allows serial communication. However, MQTT is more flexible for remote monitoring.

Real-World Use Case: Smart Greenhouse Ventilation

Problem: A small organic farm in California uses a greenhouse to grow tomatoes. The farmer manually checks temperature three times a day. During a heatwave, temperatures exceeded 40°C (104°F) for two hours, causing 25% crop loss. The farmer needed automated ventilation triggered by real-time data.

Solution: The farmer installed an ESP32 with a DHT22 sensor connected to a relay controlling a 12V exhaust fan. The ESP32 publishes temperature readings every 10 seconds to MQTT topic greenhouse/temperature. ASI Biont subscribes to the topic, runs a Python script that checks if temperature exceeds 35°C (95°F). If yes, it publishes a command to greenhouse/fan to turn the fan on. If temperature drops below 30°C (86°F), it turns the fan off. The farmer also receives a Telegram alert when the fan activates.

Results:
- Crop loss reduced by 25% (from 25% to near 0% in subsequent heatwaves)
- Energy consumption for ventilation decreased by 40% (fan runs only when needed)
- Farmer saved 3 hours per week previously spent on manual checks

Metrics:

Metric Before After
Crop loss during heatwaves 25% <2%
Daily manual checks 3 0
Fan runtime per day 12 hours 4 hours
Response time to heat spike up to 4 hours <10 seconds

Step-by-Step Integration Code

1. ESP32 Firmware (Arduino IDE)

The ESP32 reads DHT22 and publishes via MQTT. Install libraries: PubSubClient, DHT sensor library.

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

#define DHTPIN 4
#define DHTTYPE DHT22
#define RELAY_PIN 5

const char* ssid = "YourWiFi";
const char* password = "YourPass";
const char* mqtt_server = "broker.hivemq.com"; // or your broker

WiFiClient espClient;
PubSubClient client(espClient);
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(115200);
  pinMode(RELAY_PIN, OUTPUT);
  digitalWrite(RELAY_PIN, LOW);
  dht.begin();
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) { delay(500); }
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  client.connect("ESP32Greenhouse");
  client.subscribe("greenhouse/fan");
}

void callback(char* topic, byte* payload, unsigned int length) {
  String msg = "";
  for (int i = 0; i < length; i++) msg += (char)payload[i];
  if (msg == "ON") digitalWrite(RELAY_PIN, HIGH);
  else if (msg == "OFF") digitalWrite(RELAY_PIN, LOW);
}

void loop() {
  if (!client.connected()) { client.connect("ESP32Greenhouse"); client.subscribe("greenhouse/fan"); }
  client.loop();
  float t = dht.readTemperature();
  if (!isnan(t)) {
    client.publish("greenhouse/temperature", String(t).c_str());
  }
  delay(10000);
}

2. ASI Biont Integration via Chat

In the ASI Biont chat, the user types:

"Connect to my greenhouse ESP32 via MQTT. Broker: broker.hivemq.com. Subscribe to topic greenhouse/temperature. If temperature > 35°C, publish ON to greenhouse/fan. If temperature < 30°C, publish OFF. Also send me a Telegram alert when fan turns on. My Telegram chat ID is 123456789."

ASI Biont generates and executes this Python script in its sandbox:

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

TELEGRAM_TOKEN = "your_bot_token"
CHAT_ID = "123456789"
THRESHOLD_HIGH = 35.0
THRESHOLD_LOW = 30.0
fan_state = False

def on_message(client, userdata, msg):
    global fan_state
    try:
        temp = float(msg.payload.decode())
        print(f"Temperature: {temp}°C")
        if temp > THRESHOLD_HIGH and not fan_state:
            mqtt_client.publish("greenhouse/fan", "ON")
            fan_state = True
            requests.post(f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage",
                          json={"chat_id": CHAT_ID, "text": "Fan ON - temp {temp}°C"})
        elif temp < THRESHOLD_LOW and fan_state:
            mqtt_client.publish("greenhouse/fan", "OFF")
            fan_state = False
    except Exception as e:
        print(f"Error: {e}")

mqtt_client = mqtt.Client()
mqtt_client.on_message = on_message
mqtt_client.connect("broker.hivemq.com", 1883, 60)
mqtt_client.subscribe("greenhouse/temperature")
mqtt_client.loop_forever(timeout=1)

Note: The sandbox has a 30-second timeout. For long-running tasks, the script uses loop_forever with a timeout, and ASI Biont restarts it as needed.

Why ASI Biont Instead of Custom Code?

Writing a full MQTT integration requires understanding of pub/sub patterns, error handling, reconnection logic, and secure credential storage. With ASI Biont, you just describe your requirement in plain English. The AI handles:
- Library selection (paho-mqtt, requests for Telegram)
- Connection setup and reconnection
- Data parsing and conditional logic
- Alerting via external APIs

No dashboard configuration, no "add device" buttons—everything is conversational.

Advanced: Using Hardware Bridge for Serial ESP32

If your ESP32 is connected via USB (e.g., during prototyping), you can use the Hardware Bridge. Download bridge.py from the ASI Biont dashboard (Devices → Create API Key → Download bridge). Run:

pip install pyserial requests websockets
python bridge.py --token=YOUR_API_KEY --ports=COM3 --baud 115200

Then in chat, type:

"Read temperature from ESP32 on COM3 at 115200 baud. The device sends temperature as a line like 'T:25.4'. If temperature > 35, send 'FAN_ON' command."

ASI Biont uses the industrial_command(protocol='serial://', command='serial_write_and_read', data='...') tool to communicate via the bridge.

Conclusion

Integrating an ESP32 with ASI Biont turns a simple microcontroller into a smart, AI-driven automation system. Whether you're managing a greenhouse, monitoring a server room, or controlling a home aquarium, the process is the same: describe your device and desired logic in natural language, and the AI does the rest. No coding skills required. The greenhouse case study shows a 25% reduction in crop loss and 40% energy savings—real, measurable results.

Ready to automate your ESP32? Visit asibiont.com, create an account, and start a chat. Tell the AI about your device and watch it connect instantly.

← All posts

Comments