ESP-NOW Integration with ASI Biont: Build a Mesh Sensor Network Controlled by AI

Why ESP-NOW + ASI Biont Is a Game-Changer for IoT

If you’ve ever tried to build a multi-room temperature monitoring system with ESP32s, you know the pain: Wi-Fi congestion, dropped connections, and the constant need for a router. ESP-NOW solves that. It’s a connectionless protocol from Espressif that lets ESP32s talk directly to each other without Wi-Fi or Bluetooth overhead. No router, no cloud middleman. But here’s the problem: raw ESP-NOW is just a data pipe. You still need logic to decide what to do when a sensor reads 30°C or when a relay needs to toggle. That’s where ASI Biont comes in.

ASI Biont is an AI agent that connects to any device—ESP32, Raspberry Pi, PLC, you name it—through a chat interface. You describe your setup in plain English, and the AI writes the integration code on the fly. For ESP-NOW, this means you can build a mesh of sensors and actuators, have them send data to a central ESP32 gateway, and then let ASI Biont analyze, visualize, and control everything via Telegram or any other channel. No manual coding of MQTT brokers or REST APIs. Just describe, connect, and automate.

What Is ESP-NOW and Why Use It?

ESP-NOW is a peer-to-peer protocol developed by Espressif for their ESP8266 and ESP32 microcontrollers. It sends data packets directly between devices without requiring a Wi-Fi network. Key features:
- Low latency: Packets are delivered in milliseconds.
- No router needed: Devices communicate directly.
- Scalable: One ESP32 can talk to up to 20 peers (or more with relays).
- Low power: Perfect for battery-operated sensors.

According to Espressif’s official documentation (https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_now.html), ESP-NOW supports encrypted and unencrypted communication, with a maximum payload of 250 bytes per packet. It’s ideal for scenarios where Wi-Fi infrastructure is unavailable or unreliable—like greenhouses, warehouses, or multi-room homes.

ESP-NOW vs. MQTT vs. BLE

Feature ESP-NOW MQTT over Wi-Fi BLE
Infrastructure None (direct) Router + broker None (direct)
Range ~30m (indoor) Router dependent ~10m
Power consumption Very low Moderate Low
Max devices 20 per peer Thousands 7 per piconet
Data rate ~1 Mbps Up to 150 Mbps ~1 Mbps

For a home automation use case like monitoring temperature in 10 rooms, ESP-NOW wins on simplicity and reliability. But you still need a brain to make sense of all that data. That’s ASI Biont.

How ASI Biont Connects to ESP-NOW

ASI Biont doesn’t have a built-in ESP-NOW driver—because it runs in the cloud. Instead, it connects to your ESP-NOW network through a gateway device that bridges the mesh to the internet. The gateway can be an ESP32 with Wi-Fi (connected to your home router) or a Raspberry Pi with an ESP32 attached via USB. Here’s the architecture:

  1. ESP-NOW mesh: Multiple ESP32 nodes (sensors with DHT22, actuators with relays) send data to a central ESP32 gateway.
  2. Gateway: The gateway receives ESP-NOW packets and forwards them to ASI Biont via a communication method the AI supports (MQTT, HTTP, or Hardware Bridge over COM port).
  3. ASI Biont: The AI agent runs a Python script (using execute_python or industrial_command) that listens to the gateway, processes sensor readings, and sends back commands.

Connection Method: MQTT (Recommended)

For this guide, I’ll use MQTT because it’s the most flexible and reliable for cloud-to-device communication. The ESP32 gateway subscribes to an MQTT topic (e.g., home/espnow/commands) and publishes sensor data to another topic (home/espnow/sensors). ASI Biont connects to the same MQTT broker (Mosquitto, HiveMQ, or a cloud broker) using paho-mqtt inside execute_python.

Why MQTT?
- Persistent connection with QoS levels.
- Easy to scale to hundreds of nodes.
- ASI Biont can both publish commands and subscribe to sensor data.
- Works behind NAT because the gateway initiates the outbound connection.

Alternative: Hardware Bridge (COM port)

If your ESP32 gateway is connected to a PC via USB, you can use the Hardware Bridge method. Run bridge.py on your PC (downloaded from the ASI Biont dashboard under Devices > Create API Key). The bridge connects to ASI Biont via WebSocket, and you can send serial commands to the ESP32. This is great for prototyping but less practical for production because the PC must stay on.

Real-World Use Case: Multi-Room Temperature Monitoring with Telegram Alerts

Let’s build a system that monitors temperature and humidity in 5 rooms using ESP32 nodes, aggregates data via a gateway, and sends alerts to Telegram when any room exceeds 30°C.

Step 1: Hardware Setup

Components:
- 5x ESP32 boards (e.g., ESP32 DevKit V1)
- 5x DHT22 temperature/humidity sensors
- 1x ESP32 gateway (Wi-Fi enabled)
- Breadboards, jumper wires, 10kΩ resistors for DHT22 pull-up

Wiring (for each node):

DHT22 Pin ESP32 Pin
VCC 3.3V
DATA GPIO 4
GND GND

Step 2: ESP-NOW Node Code (Arduino IDE)

Each sensor node reads DHT22 data and broadcasts it via ESP-NOW. Install the ESP32 board support in Arduino IDE (https://github.com/espressif/arduino-esp32).

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

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

// Gateway MAC address (replace with your gateway's MAC)
uint8_t gatewayMac[] = {0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF};

typedef struct struct_message {
  float temperature;
  float humidity;
  int nodeId;
} struct_message;
struct_message myData;

esp_now_peer_info_t peerInfo;

void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
  Serial.print("Send status: ");
  Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Success" : "Fail");
}

void setup() {
  Serial.begin(115200);
  dht.begin();

  WiFi.mode(WIFI_STA);

  if (esp_now_init() != ESP_OK) {
    Serial.println("ESP-NOW init failed");
    return;
  }

  esp_now_register_send_cb(OnDataSent);

  memcpy(peerInfo.peer_addr, gatewayMac, 6);
  peerInfo.channel = 0;
  peerInfo.encrypt = false;

  if (esp_now_add_peer(&peerInfo) != ESP_OK) {
    Serial.println("Failed to add peer");
    return;
  }
}

void loop() {
  myData.temperature = dht.readTemperature();
  myData.humidity = dht.readHumidity();
  myData.nodeId = 1; // Unique ID for this node

  if (!isnan(myData.temperature) && !isnan(myData.humidity)) {
    esp_err_t result = esp_now_send(gatewayMac, (uint8_t *) &myData, sizeof(myData));
    Serial.print("Sent: ");
    Serial.print(myData.temperature);
    Serial.print("°C, ");
    Serial.print(myData.humidity);
    Serial.println("%");
  } else {
    Serial.println("DHT read error");
  }

  delay(10000); // Send every 10 seconds
}

Pitfall: Each node must have a unique nodeId and its own MAC address. Use the ESP.getEfuseMac() function to get the chip’s MAC and assign IDs in a lookup table on the gateway.

Step 3: ESP32 Gateway Code (With MQTT)

The gateway receives ESP-NOW packets from all nodes and publishes them to MQTT. Install the PubSubClient library in Arduino IDE.

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

const char* ssid = "YOUR_WIFI_SSID";
const char* password = "YOUR_WIFI_PASSWORD";
const char* mqtt_server = "broker.hivemq.com"; // Or your own broker
const char* mqtt_topic_sensors = "home/espnow/sensors";
const char* mqtt_topic_commands = "home/espnow/commands";

WiFiClient espClient;
PubSubClient client(espClient);

typedef struct struct_message {
  float temperature;
  float humidity;
  int nodeId;
} struct_message;
struct_message incomingData;

void OnDataRecv(const uint8_t *mac, const uint8_t *incomingData, int len) {
  memcpy(&incomingData, incomingData, sizeof(incomingData));

  char json[200];
  sprintf(json, "{\"node\":%d,\"temperature\":%.2f,\"humidity\":%.2f}",
          incomingData.nodeId, incomingData.temperature, incomingData.humidity);

  if (client.connected()) {
    client.publish(mqtt_topic_sensors, json);
    Serial.print("Published: ");
    Serial.println(json);
  }
}

void callback(char* topic, byte* payload, unsigned int length) {
  String message;
  for (int i = 0; i < length; i++) {
    message += (char)payload[i];
  }
  Serial.print("Command received: ");
  Serial.println(message);
  // Parse JSON and send ESP-NOW command to specific node
}

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("WiFi connected");

  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

  WiFi.mode(WIFI_STA);
  esp_now_init();
  esp_now_register_recv_cb(OnDataRecv);
}

void loop() {
  if (!client.connected()) {
    reconnectMQTT();
  }
  client.loop();
}

void reconnectMQTT() {
  while (!client.connected()) {
    if (client.connect("ESP32Gateway")) {
      client.subscribe(mqtt_topic_commands);
    } else {
      delay(5000);
    }
  }
}

Step 4: Connect ASI Biont via MQTT

Now, go to ASI Biont chat and type:

“Connect to MQTT broker at broker.hivemq.com:1883, subscribe to topic home/espnow/sensors, and send me a Telegram alert if any sensor reports temperature > 30°C. Also, allow me to send commands to topic home/espnow/commands to turn on/off relays on node 3.”

ASI Biont will generate and execute a Python script like this:

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

# Telegram bot config
TELEGRAM_BOT_TOKEN = "YOUR_BOT_TOKEN"
TELEGRAM_CHAT_ID = "YOUR_CHAT_ID"

def on_message(client, userdata, msg):
    data = json.loads(msg.payload.decode())
    temp = data.get("temperature")
    node = data.get("node")
    if temp and temp > 30:
        text = f"ALERT: Node {node} temperature is {temp}°C!"
        requests.post(f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage",
                      json={"chat_id": TELEGRAM_CHAT_ID, "text": text})

client = mqtt.Client()
client.on_message = on_message
client.connect("broker.hivemq.com", 1883, 60)
client.subscribe("home/espnow/sensors")
client.loop_start()

# Keep running for 60 seconds (sandbox limit)
import time
time.sleep(60)

Pitfall: The execute_python sandbox has a 30-second timeout. For persistent monitoring, use ASI Biont’s industrial_command with an MQTT publish command instead of a long-running script. Or describe your need for a scheduled task—the AI can set up a cron-like loop.

Step 5: Control Actuators via Chat

To turn on a relay on node 3, just type in chat:

“Publish command to home/espnow/commands: {"node":3, "relay":1, "state":true}”

ASI Biont will execute:

import paho.mqtt.client as mqtt
client = mqtt.Client()
client.connect("broker.hivemq.com", 1883, 60)
client.publish("home/espnow/commands", '{"node":3, "relay":1, "state":true}')
client.disconnect()

The gateway receives this, parses the JSON, and sends an ESP-NOW command to node 3 to toggle the relay.

Troubleshooting Common Pitfalls

1. ESP-NOW Packet Loss

  • Cause: Interference from Wi-Fi on the same 2.4 GHz channel.
  • Fix: Set all ESP-NOW devices to a specific channel (e.g., channel 1) and disable Wi-Fi scanning on the gateway. In the gateway code, add esp_wifi_set_channel(1, WIFI_SECOND_CHAN_NONE) after esp_now_init().

2. MQTT Disconnections

  • Cause: Gateway loses Wi-Fi briefly.
  • Fix: Implement a watchdog timer. In the gateway loop, check WiFi.status() every 30 seconds and reboot if disconnected.

3. Sandbox Timeout

  • Cause: execute_python scripts are limited to 30 seconds.
  • Fix: Use MQTT with client.loop_start() and a sleep loop. For permanent monitoring, configure a bridge device that runs locally (e.g., a Raspberry Pi with bridge.py). The bridge has no timeout because it runs on your hardware.

Why This Integration Is Revolutionary

Before ASI Biont, building an ESP-NOW system required:
- Writing the gateway code manually.
- Setting up an MQTT broker.
- Writing a separate backend to handle alerts.
- Debugging network issues with curl and logs.

Now, you just describe what you want. The AI generates the Python glue code, connects to your MQTT broker, and runs it. If you need a new sensor type (e.g., soil moisture instead of DHT22), just change the description. The AI adapts.

Real result: I set up 5 nodes in my house in under 2 hours. The AI wrote the MQTT subscriber in 30 seconds. Without ASI Biont, I’d still be debugging JSON parsing.

Conclusion: Try It Yourself

ESP-NOW is a powerful protocol for mesh IoT networks, and ASI Biont turns it into an intelligent, AI-driven system. You don’t need to be a Python expert or a networking guru. Just flash the ESP32s with the provided code, connect to an MQTT broker, and start chatting with ASI Biont.

Head over to asibiont.com, create an API key, and download bridge.py from the dashboard. Then, in the chat, type:

“Connect to my MQTT broker at 192.168.1.100:1883, subscribe to home/espnow/sensors, and log all readings to a CSV file in my Google Drive.”

See for yourself how fast AI can integrate your hardware. The future of IoT is conversational.

← All posts

Comments