Smart City Sensors + ASI Biont: AI-Powered Air Quality Monitoring and Automation Guide

From Static Data to AI-Driven Urban Intelligence

Smart city sensors are the nervous system of modern urban environments — CO₂ monitors in classrooms, temperature/humidity nodes in parks, light sensors on smart lampposts. But raw sensor data without intelligent processing is just noise. Connecting these sensors to an AI agent like ASI Biont transforms them into autonomous decision-makers: ventilation kicks in when CO₂ exceeds 800 ppm, streetlights dim when ambient light is sufficient, and facility managers receive Telegram alerts before thresholds are breached.

This guide walks you through a real-world integration: ESP32 + MH-Z19B CO₂ sensor + DHT22 temperature/humidity sensor → ASI Biont via MQTT. You’ll learn how to set up the hardware, configure the MQTT bridge, and let the AI agent handle data parsing, alerting, and actuator control — all through natural language chat.

Why MQTT for Smart City Sensors?

MQTT (Message Queuing Telemetry Transport) is the de facto protocol for IoT sensor networks. It’s lightweight, supports publish/subscribe messaging, and works over unreliable networks. ASI Biont supports MQTT natively via the paho-mqtt library in its sandbox environment. When you describe your setup in chat — broker IP, topics, sensor data format — the AI writes a Python script that subscribes to your sensor topics, parses the payload (JSON, binary, or plain text), and reacts with commands back to actuators or external services (Telegram, Slack, database).

Why not HTTP? HTTP is request/response — polling sensors every few seconds wastes bandwidth and battery. MQTT keeps a persistent connection, pushing data only when it changes. For a city-wide deployment with hundreds of nodes, MQTT saves 80–90% of data transfer compared to HTTP polling (source: HiveMQ IoT Benchmark Report, 2025).

Step-by-Step: ESP32 + CO₂ Sensor → ASI Biont

Hardware Setup

Component Model Purpose
Microcontroller ESP32 DevKit V1 WiFi + MQTT client
CO₂ sensor MH-Z19B (NDIR) Measures 400–5000 ppm CO₂
Temp/Humidity DHT22 ±0.5°C, ±2% RH accuracy
Power 5V USB-C adapter 2A minimum

Connect the MH-Z19B to ESP32 UART2 (TX→GPIO17, RX→GPIO16, VIN→5V, GND→GND). DHT22 data pin to GPIO4 with a 10kΩ pull-up resistor.

ESP32 Firmware (Arduino IDE)

Upload the following sketch to your ESP32. It reads CO₂ via serial command, reads DHT22, and publishes JSON to the MQTT topic city/sensor/balcony.

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

#define DHTPIN 4
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

const char* ssid = "YourWiFi";
const char* password = "YourPass";
const char* mqtt_server = "192.168.1.100";

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
  Serial.begin(115200);
  Serial2.begin(9600, SERIAL_8N1, 16, 17); // MH-Z19B
  dht.begin();
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) delay(500);
  client.setServer(mqtt_server, 1883);
}

int readCO2() {
  uint8_t cmd[9] = {0xFF, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79};
  Serial2.write(cmd, 9);
  delay(100);
  if (Serial2.available() >= 9) {
    uint8_t resp[9];
    Serial2.readBytes(resp, 9);
    return (resp[2] << 8) | resp[3];
  }
  return -1;
}

void loop() {
  if (!client.connected()) client.connect("ESP32_Balcony");
  client.loop();

  int co2 = readCO2();
  float h = dht.readHumidity();
  float t = dht.readTemperature();

  if (co2 > 0 && !isnan(h) && !isnan(t)) {
    char payload[256];
    snprintf(payload, sizeof(payload),
      "{\"co2\":%d,\"temp\":%.1f,\"humidity\":%.1f,\"device\":\"balcony\"}",
      co2, t, h);
    client.publish("city/sensor/balcony", payload);
  }
  delay(60000); // every minute
}

Connecting to ASI Biont via Chat

Once the ESP32 is publishing, open a chat with ASI Biont. You don’t need to write any integration code yourself — just describe what you want:

“Connect to MQTT broker at 192.168.1.100 port 1883, subscribe to city/sensor/balcony. Parse the JSON payload. If CO₂ > 800 ppm, send a Telegram alert to chat ID -1001234567890 with message ‘🚨 High CO₂ on balcony: {co2} ppm’. Also log all readings to a PostgreSQL table called sensor_log.”

The AI agent will write and execute a Python script using paho-mqtt, requests (for Telegram), and psycopg2 (for PostgreSQL). The script runs in the sandbox environment with a 30-second timeout per execution — but because MQTT subscriptions are callback-driven, the AI sets up a persistent listener that processes each incoming message instantly.

What the AI script does (simplified):

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

def on_message(client, userdata, msg):
    data = json.loads(msg.payload)
    co2 = data["co2"]
    if co2 > 800:
        requests.post(f"https://api.telegram.org/bot{TOKEN}/sendMessage",
                      json={"chat_id": CHAT_ID, "text": f"🚨 High CO₂: {co2} ppm"})
    # Log to database
    conn = psycopg2.connect(DB_URL)
    cur = conn.cursor()
    cur.execute("INSERT INTO sensor_log (co2, temp, humidity, ts) VALUES (%s,%s,%s,NOW())",
                (co2, data["temp"], data["humidity"]))
    conn.commit()
    cur.close()
    conn.close()

client = mqtt.Client()
client.on_message = on_message
client.connect("192.168.1.100", 1883)
client.subscribe("city/sensor/balcony")
client.loop_forever()  # runs until sandbox timeout (30s), but messages are processed

Important: The sandbox enforces a 30-second timeout. For long-running MQTT listeners, the AI can instead use the industrial_command tool with protocol MQTT — this keeps the connection alive beyond the sandbox limit. The AI will automatically choose the best method based on your use case.

Advanced Automation: Actuators and Triggers

Smart city isn’t just about monitoring — it’s about acting. With ASI Biont, you can chain sensor data to physical outputs. For example:

  • CO₂-triggered ventilation: When CO₂ > 1000 ppm, AI publishes {"cmd":"fan_on"} to city/actuator/ventilation. An ESP32 subscribed to that topic turns on a relay.
  • Light-based dimming: A lux sensor publishes city/sensor/light. If value > 500 lux, AI writes a command to city/actuator/lamp/dim with brightness=30%.
  • Predictive maintenance: AI collects temperature trends over 24 hours. If rate of change > 5°C/hour, it alerts the facility manager before equipment failure.

All of this is configured through chat — no dashboard, no drag-and-drop. You say: “When CO₂ stays above 700 ppm for 10 minutes, turn on the exhaust fan via MQTT topic city/actuator/fan with payload ON.” The AI creates the logic, subscribes to historical data, and implements the state machine.

Real-World Pitfalls and How to Avoid Them

  1. MQTT QoS mismatch: ESP32 publishes at QoS 0 (fire-and-forget). If your broker or network drops packets, you miss data. Use QoS 1 (at-least-once) for critical alerts. In the AI script, set client.publish(topic, payload, qos=1).
  2. CO₂ sensor warm-up: NDIR sensors like MH-Z19B need 3 minutes to stabilize after power-on. Don’t act on first readings. The AI can skip the first 3 messages by checking a timestamp counter.
  3. Telegram rate limits: If CO₂ spikes every minute, Telegram will block your bot after 20 messages/minute. Add a cooldown: “Only alert if last alert was more than 5 minutes ago.” The AI implements this with a simple last_alert_time variable.
  4. Database connection exhaustion: Opening a new PostgreSQL connection per MQTT message will crash the DB. The AI should use a connection pool (psycopg2.pool.ThreadedConnectionPool) or batch inserts every 10 messages.

Why This Beats Traditional Dashboards

Traditional smart city platforms (ThingsBoard, Losant) require you to:
- Build a dashboard with widgets
- Write Node-RED flows for logic
- Set up alert rules in a UI
- Deploy separate services for Telegram integration

With ASI Biont, you describe the entire system in plain English. The AI generates production-grade Python code, connects to your broker, and runs the logic — all in under 30 seconds. If you need to change the alert threshold, just say: “Change CO₂ alert to 900 ppm and add a Slack notification.” The AI rewrites the script on the fly.

Try It Yourself

Ready to turn your smart city sensor network from a data silo into an intelligent, autonomous system? Visit asibiont.com, start a chat, and describe your sensor setup. No coding required — the AI does the integration. Connect any device: ESP32, Raspberry Pi, industrial PLC, or GPS tracker. ASI Biont supports MQTT, Modbus, OPC-UA, BACnet, SSH, and 10+ other protocols. Your city’s data deserves an AI brain.

Example prompt to get started: “Connect to my Mosquitto MQTT broker at 10.0.0.5:1883. Subscribe to city/+/+. Parse all JSON payloads. If any CO₂ value exceeds 800 ppm, send a Telegram alert and log to InfluxDB.”

← All posts

Comments