AI Solar Air Purifier with Air- Quality Prediction
ESP32 + IoT Web Dashboard + AI Agent + n8n + Telegram Voice Alerts + Google Sheets + ThingSpeak
Below is a complete project architecture and implementation guide. The design uses an ESP32 as the edge controller, air-quality/environment sensors, a solar-powered supply, an air-purification unit, n8n as the automation/orchestration layer, an AI agent for interpreting sensor conditions , Telegram for alerts, Google Sheets for historical logging, and ThingSpeak/web UI for visualization.
1. Project Overview
Project title
AI-Powered Solar Air Purifier with Predictive Air-Quality Monitoring and Agentic IoT Automation using ESP32, n8n, Telegram, Google Sheets and ThingSpeak
Main idea
The system continuously measures:
-
PM2.5
-
PM10
-
CO₂
-
Temperature
-
Humidity
-
VOC/air-quality indicators
-
Optional gas concentrations
-
Solar-panel voltage/current
-
Battery voltage
The ESP32 sends the measurements to the cloud.
The AI/automation layer then determines:
-
What is the current air quality?
-
Is the air quality getting worse?
-
Should the purifier fan speed increase?
-
Is the solar/battery system operating normally?
-
Should the user receive an alert?
-
Should the event be recorded?
-
Does the system need human intervention?
The result is a system that does more than simply display sensor values.
It creates an agentic IoT loop:
SENSE
↓
ANALYZE
↓
PREDICT
↓
DECIDE
↓
ACT
↓
VERIFY
↓
LOG
↓
NOTIFY
↓
LEARN / PREDICT AGAIN
2. High-Level Architecture
☀️ SOLAR PANEL
│
▼
┌─────────────────┐
│ Solar Charge │
│ Controller │
└────────┬────────┘
│
┌─────────▼─────────┐
│ Battery / Power │
│ Management │
└─────────┬─────────┘
│
┌──────────────┴──────────────┐
│ │
▼ ▼
ESP32 SYSTEM AIR PURIFIER
│ FAN / HEPA
│ FILTER
│
┌───────┴────────┐
│ │
▼ ▼
AIR SENSORS POWER SENSORS
│ │
└───────┬────────┘
│
▼
ESP32
│
Wi-Fi / MQTT / HTTP
│
▼
┌─────────────┐
│ n8n │
│ Automation │
└──────┬──────┘
│
┌───────┼─────────┐
│ │ │
▼ ▼ ▼
AI Google Telegram
Agent Sheets Bot
│ │
│ ▼
│ Voice Alert
│
▼
Control Decision
│
▼
ESP32
│
▼
Fan / Purifier Control
┌──────────────────┐
│ ThingSpeak │
│ Cloud Dashboard │
└──────────────────┘
3. Major Hardware Components
3.1 Controller
ESP32
Recommended:
-
ESP32 DevKit V1
-
ESP32-WROOM-32
-
ESP32-S3 if additional processing/interface capability is desired
The ESP32 provides:
-
Wi-Fi
-
GPIO
-
ADC
-
I²C
-
UART
-
PWM
-
sufficient processing power for sensor acquisition and local control
4. Air-Quality Sensors
A practical prototype can use the following combination.
| Parameter | Sensor |
|---|---|
| PM1/PM2.5/PM10 | PMS5003 / PMS7003 |
| CO₂ | MH-Z19B / SCD30 / SCD41 |
| Temperature | BME280 |
| Humidity | BME280 |
| Pressure | BME280 |
| VOC | BME680 / SGP30 |
| Gas | MQ-series, optional |
| Light | LDR/BH1750, optional |
Recommended combination
For a serious prototype:
PMS5003
+
SCD40/SCD41
+
BME280
This provides substantially more useful environmental information than relying on a single MQ sensor.
5. Purification System
The purification section can contain:
Air inlet
↓
Pre-filter
↓
HEPA filter
↓
Activated-carbon filter
↓
Fan
↓
Clean-air outlet
Example:
DIRTY AIR
↓
┌──────────────────┐
│ PRE FILTER │
└────────┬─────────┘
↓
┌──────────────────┐
│ HEPA FILTER │
└────────┬─────────┘
↓
┌──────────────────┐
│ ACTIVATED CARBON │
└────────┬─────────┘
↓
FAN
↓
CLEAN AIR
6. Fan Control
The ESP32 should not directly drive a large DC fan from a GPIO.
Use:
ESP32 GPIO
│
▼
MOSFET driver
│
▼
12/24 V DC fan
Example:
+12V
│
│
FAN +
│
FAN -
│
▼
Drain
┌────────┐
ESP32 ──R───► │ MOSFET │
└────┬───┘
│
GND
Use an appropriate logic-level MOSFET and flyback protection where required by the fan/driver topology.
7. Solar Power System
A typical architecture:
☀️ SOLAR PANEL
│
▼
┌──────────────────┐
│ SOLAR CHARGE │
│ CONTROLLER │
└────────┬─────────┘
│
▼
🔋 BATTERY
│
┌─────┴─────┐
│ │
▼ ▼
DC-DC DC-DC
Converter Converter
│ │
▼ ▼
ESP32 FAN
The exact battery, charge controller, fuse, converter and wiring must be selected for the chosen panel, battery chemistry and fan power.
For a student prototype, keep the high-current power section separate from the ESP32's low-voltage electronics.
8. Electrical Schematic
A simplified complete schematic:
SOLAR PANEL
+---------------+
| |
| SOLAR |
| PANEL |
| |
+-------+-------+
|
▼
+------------------+
| CHARGE CONTROLLER|
+--------+---------+
|
▼
BATTERY
+---------+
| 12 V |
+----+----+
|
+--------------+--------------+
| |
▼ ▼
DC-DC 5V/3.3V FAN SUPPLY
│ │
▼ │
+-------------+ │
| ESP32 | │
+------+------+ │
│ │
┌──────┼─────────────┐ │
│ │ │ │
▼ ▼ ▼ │
PMS5003 BME280 SCD40 │
│ │ │ │
└──────┴──────┬──────┘ │
│ │
▼ │
ESP32 │
│ │
│ PWM │
▼ │
MOSFET ◄─────────────────┘
│
▼
FAN
9. Example ESP32 Pin Configuration
One possible configuration:
| Device | ESP32 |
|---|---|
| BME280 SDA | GPIO 21 |
| BME280 SCL | GPIO 22 |
| PMS5003 TX | GPIO 16 |
| PMS5003 RX | GPIO 17 |
| SCD40 SDA | GPIO 21 |
| SCD40 SCL | GPIO 22 |
| Fan PWM | GPIO 25 |
| Battery ADC | GPIO 34 |
| Solar voltage ADC | GPIO 35 |
| Status LED | GPIO 2 |
The exact pins can be changed depending on your ESP32 board and sensor modules.
10. Important Electrical Protection
Add:
-
Fuse between battery and load
-
Reverse-polarity protection
-
Appropriate voltage regulator
-
TVS/surge protection where appropriate
-
Common ground for low-voltage electronics
-
Capacitors near ESP32 and sensors
-
Separate high-current fan wiring from sensitive sensor wiring
Do not connect a 12 V battery or fan directly to an ESP32 GPIO.
11. ESP32 Software Architecture
The ESP32 firmware has several tasks:
START
│
▼
Initialize sensors
│
Initialize Wi-Fi
│
Initialize cloud connection
│
Initialize fan control
│
┌─────────────────────────┐
│ MAIN LOOP │
└───────────┬─────────────┘
│
Read sensors
│
▼
Validate readings
│
▼
Calculate local AQ
│
▼
Control purifier
│
▼
Send telemetry
│
▼
Check commands
│
▼
Repeat
12. ESP32 Data Structure
The ESP32 can generate JSON such as:
{
"device_id": "AIRPURIFIER_01",
"pm25": 42.5,
"pm10": 65.2,
"co2": 980,
"temperature": 29.4,
"humidity": 61.2,
"voc": 125,
"fan_speed": 70,
"battery_voltage": 12.4,
"solar_voltage": 18.7,
"timestamp": "2026-10-01T16:30:00Z"
}
This becomes the common data format used by n8n, dashboards and cloud services.
13. ESP32 Arduino Code
Below is a starter implementation. The sensor-specific libraries can be replaced according to the exact modules you purchase.
#include <WiFi.h>
#include <HTTPClient.h>
#include <Wire.h>
#include <ArduinoJson.h>
const char* WIFI_SSID = "YOUR_WIFI";
const char* WIFI_PASSWORD = "YOUR_PASSWORD";
const char* N8N_URL =
"https://YOUR-N8N-DOMAIN/webhook/air-quality";
#define FAN_PWM_PIN 25
#define BATTERY_PIN 34
#define SOLAR_PIN 35
const int PWM_CHANNEL = 0;
const int PWM_FREQ = 25000;
const int PWM_RESOLUTION = 8;
unsigned long lastSend = 0;
const unsigned long SEND_INTERVAL = 30000;
float pm25 = 0;
float pm10 = 0;
float co2 = 0;
float temperature = 0;
float humidity = 0;
float voc = 0;
float batteryVoltage = 0;
float solarVoltage = 0;
int fanSpeed = 30;
void setup() {
Serial.begin(115200);
Wire.begin(21, 22);
ledcSetup(PWM_CHANNEL, PWM_FREQ, PWM_RESOLUTION);
ledcAttachPin(FAN_PWM_PIN, PWM_CHANNEL);
setFanSpeed(30);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
// Initialize sensors here.
}
void loop() {
readSensors();
localAirControl();
if (millis() - lastSend >= SEND_INTERVAL) {
lastSend = millis();
sendTelemetry();
}
delay(1000);
}
14. Sensor Reading Function
void readSensors() {
// Replace these demo values with actual sensor readings.
pm25 = 35.0;
pm10 = 52.0;
co2 = 850;
temperature = 29.1;
humidity = 60.5;
voc = 100;
batteryVoltage =
analogRead(BATTERY_PIN) * (3.3 / 4095.0) * 4.0;
solarVoltage =
analogRead(SOLAR_PIN) * (3.3 / 4095.0) * 6.0;
}
The voltage multiplier must be calculated from the actual resistor-divider values used in your hardware.
15. Local Air-Control Algorithm
The ESP32 should have a basic safety/control algorithm that works even if the internet is unavailable.
void localAirControl() {
int requiredSpeed = 30;
if (pm25 > 35)
requiredSpeed = 50;
if (pm25 > 55)
requiredSpeed = 70;
if (pm25 > 100)
requiredSpeed = 100;
if (co2 > 1200)
requiredSpeed += 10;
if (requiredSpeed > 100)
requiredSpeed = 100;
setFanSpeed(requiredSpeed);
}
This is important.
The AI should augment the safety/control system, not be the only mechanism responsible for operating the purifier.
16. Fan-Control Function
void setFanSpeed(int percent) {
percent = constrain(percent, 0, 100);
int pwmValue =
map(percent, 0, 100, 0, 255);
ledcWrite(PWM_CHANNEL, pwmValue);
fanSpeed = percent;
}
17. Sending Data to n8n
void sendTelemetry() {
if (WiFi.status() != WL_CONNECTED)
return;
HTTPClient http;
http.begin(N8N_URL);
http.addHeader(
"Content-Type",
"application/json"
);
StaticJsonDocument<512> doc;
doc["device_id"] = "AIRPURIFIER_01";
doc["pm25"] = pm25;
doc["pm10"] = pm10;
doc["co2"] = co2;
doc["temperature"] = temperature;
doc["humidity"] = humidity;
doc["voc"] = voc;
doc["fan_speed"] = fanSpeed;
doc["battery_voltage"] = batteryVoltage;
doc["solar_voltage"] = solarVoltage;
String json;
serializeJson(doc, json);
int responseCode =
http.POST(json);
Serial.print("n8n response: ");
Serial.println(responseCode);
http.end();
}
18. What Makes This an "Agentic IoT" System?
A conventional IoT system might do this:
Sensor → Cloud → Dashboard
Your proposed project can go further:
Sensor
↓
Context
↓
AI reasoning
↓
Decision
↓
Action
↓
Verification
↓
Notification
For example:
PM2.5 = 42
PM2.5 increasing
CO₂ = 1100
Battery = 75%
Solar = available
↓
AI Agent
↓
"Air quality is deteriorating.
Increase fan to 70%.
Monitor for 5 minutes.
Notify user only if PM2.5
continues increasing."
↓
ESP32
↓
Fan = 70%
↓
5-minute verification
↓
PM2.5 reduced
↓
Log successful intervention
19. n8n Architecture
The n8n workflow can be divided into multiple workflows instead of making one enormous workflow.
Workflow 1 — Telemetry ingestion
ESP32
↓
Webhook
↓
Validate JSON
↓
Normalize data
↓
Google Sheets
↓
ThingSpeak
Workflow 2 — AI analysis
Telemetry
↓
Threshold Check
↓
Historical Data
↓
AI Agent
↓
Decision
Workflow 3 — Alerts
AI Decision
↓
Alert Required?
↙ ↘
YES NO
↓ ↓
Telegram Continue
↓
Voice Alert
Workflow 4 — Device control
AI Agent
↓
Action JSON
↓
Validation
↓
HTTP/MQTT
↓
ESP32
↓
Fan Control
20. n8n Main Workflow
┌──────────────┐
│ ESP32 │
└──────┬───────┘
│
▼
┌──────────────┐
│ Webhook │
└──────┬───────┘
│
▼
┌──────────────┐
│ Validate │
│ Sensor Data │
└──────┬───────┘
│
▼
┌──────────────┐
│ Calculate │
│ Air Quality │
└──────┬───────┘
│
┌───────────┴───────────┐
│ │
▼ ▼
Google Sheets ThingSpeak
│ │
└───────────┬───────────┘
▼
┌──────────────┐
│ AI Agent │
└──────┬───────┘
│
▼
┌──────────────┐
│ Decision │
└──────┬───────┘
│
┌──────────┼───────────┐
│ │ │
▼ ▼ ▼
NORMAL ACTION ALERT
│ │ │
│ ▼ ▼
│ ESP32 Telegram
│ │ │
│ ▼ ▼
│ Fan Control Voice
│
▼
Log
21. n8n Webhook
Create an n8n Webhook node:
HTTP Method:
POST
Path:
air-quality
ESP32 sends:
POST /webhook/air-quality
Content-Type: application/json
Body:
{
"device_id": "AIRPURIFIER_01",
"pm25": 75,
"pm10": 100,
"co2": 1300,
"temperature": 30,
"humidity": 65,
"voc": 200,
"fan_speed": 50,
"battery_voltage": 12.2,
"solar_voltage": 17.8
}
22. Data Validation Node
Use an n8n Code node.
const d = $json;
const required = [
"device_id",
"pm25",
"pm10",
"co2",
"temperature",
"humidity",
"battery_voltage"
];
for (const key of required) {
if (d[key] === undefined || d[key] === null) {
throw new Error(`Missing field: ${key}`);
}
}
if (d.pm25 < 0 || d.pm25 > 1000) {
throw new Error("Invalid PM2.5 value");
}
if (d.humidity < 0 || d.humidity > 100) {
throw new Error("Invalid humidity");
}
return [
{
json: {
...d,
received_at: new Date().toISOString()
}
}
];
23. Air-Quality Classification
A simple rule engine can initially classify the measurements:
const pm25 = Number($json.pm25);
const co2 = Number($json.co2);
let status = "GOOD";
let fan = 30;
if (pm25 >= 35) {
status = "MODERATE";
fan = 50;
}
if (pm25 >= 55) {
status = "POOR";
fan = 70;
}
if (pm25 >= 100) {
status = "VERY_POOR";
fan = 100;
}
if (co2 >= 1500) {
fan = Math.max(fan, 80);
}
return [{
json: {
...$json,
air_status: status,
recommended_fan: fan
}
}];
These thresholds should be treated as project-configurable values, not universal medical or regulatory limits.
24. AI Agent
The AI Agent receives:
Current sensor data
+
Recent historical measurements
+
Solar/battery state
+
Current purifier state
Example AI-agent input:
Device: AIRPURIFIER_01
PM2.5: 78
PM10: 110
CO2: 1380
Temperature: 30.4 C
Humidity: 68%
VOC: 230
Fan: 50%
Battery: 72%
Solar: charging
Recent PM2.5:
55
61
67
72
78
The important information is not merely that PM2.5 is high.
It is increasing over time.
25. Air-Quality Prediction
A simple prediction model can begin with linear regression.
Suppose the last five measurements are:
Time PM2.5
1 45
2 50
3 58
4 66
5 74
The trend is positive.
A simple prediction:
PM2.5(t+1)
can be estimated from the slope.
For a more advanced project, use:
-
Linear regression
-
Random Forest
-
XGBoost
-
LSTM
-
Temporal convolution model
-
Cloud-hosted ML model
For a student/engineering prototype, starting with regression and then adding an AI model makes the development easier to demonstrate.
26. Prediction Pipeline
Historical Data
│
▼
Cleaning
│
▼
Feature Engineering
│
├── PM2.5
├── PM10
├── CO₂
├── Temperature
├── Humidity
├── VOC
├── Fan speed
├── Solar power
└── Time of day
│
▼
Prediction Model
│
▼
Predicted PM2.5
│
▼
Risk Evaluation
│
▼
AI Agent
27. Prediction Example
Current:
PM2.5 = 65
Prediction:
10 minutes = 82
30 minutes = 105
AI agent receives:
Current: 65
Predicted: 105
Trend: increasing
Fan: 50%
Battery: 80%
Solar: available
Potential decision:
{
"action": "INCREASE_FAN",
"fan_speed": 80,
"alert": true,
"reason": "Predicted deterioration"
}
28. AI Agent Output Should Be Structured
Do not allow the AI model to return arbitrary device commands.
Require JSON:
{
"status": "WARNING",
"reason": "PM2.5 is increasing",
"predicted_pm25": 105,
"recommended_fan": 80,
"send_alert": true,
"action": "SET_FAN"
}
Then validate the output before sending anything to the ESP32.
29. Agent Safety Layer
This is extremely important.
Use:
AI Agent
↓
JSON Validator
↓
Range Validator
↓
Safety Rules
↓
ESP32
For example:
let fan = Number($json.recommended_fan);
if (!Number.isFinite(fan)) {
throw new Error("Invalid fan command");
}
fan = Math.max(0, Math.min(100, fan));
return [{
json: {
...$json,
safe_fan_speed: fan
}
}];
The AI should never be allowed to send arbitrary GPIO commands.
30. Telegram Integration
Telegram provides:
-
Text alerts
-
Voice notifications
-
Commands
-
Remote monitoring
Example alert:
🚨 AIR QUALITY ALERT
Device: AIRPURIFIER_01
PM2.5: 82 µg/m³
CO₂: 1380 ppm
Temperature: 30.4°C
Humidity: 68%
Predicted PM2.5 in 30 min: 105
Fan automatically increased:
50% → 80%
Solar charging: YES
Battery: 72%
31. Telegram Voice Alert
The n8n workflow:
AI Agent
↓
Alert Required
↓
Create Alert Text
↓
Text-to-Speech
↓
Audio File
↓
Telegram Bot
↓
Send Voice Message
Voice message could say:
"Air quality warning. PM2.5 is increasing and is predicted to exceed the configured threshold. The purifier fan has automatically increased to eighty percent."
This is particularly useful for a demonstration because the system becomes visibly and audibly autonomous.
32. Telegram Commands
The user can also control the device.
Example:
/status
Response:
AIR PURIFIER STATUS
PM2.5: 32
CO2: 780 ppm
Temperature: 28.4°C
Humidity: 58%
Fan: 40%
Battery: 84%
Solar: Charging
Other commands:
/start
/status
/air
/fan 50
/auto
/predict
/solar
/help
33. Telegram Command Architecture
User
│
▼
Telegram
│
▼
n8n Telegram Trigger
│
▼
Command Parser
│
├── /status ──────► Sensor status
│
├── /predict ─────► AI prediction
│
├── /fan 80 ─────► Validate ───► ESP32
│
└── /auto ───────► Automatic mode
34. Google Sheets Database
Create a spreadsheet:
| Timestamp | Device | PM2.5 | PM10 | CO₂ | Temp | Humidity | VOC | Fan | Battery | Solar | Status |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 10:00 | AIR01 | 32 | 48 | 760 | 28 | 57 | 80 | 30 | 85 | 18 | GOOD |
| 10:01 | AIR01 | 39 | 55 | 820 | 28 | 58 | 95 | 50 | 84 | 18 | MODERATE |
| 10:02 | AIR01 | 55 | 72 | 980 | 29 | 60 | 120 | 70 | 83 | 17 | POOR |
Google Sheets is useful for:
-
historical analysis
-
project demonstrations
-
exporting CSV
-
creating graphs
-
training prediction models
For very high-frequency telemetry, use a proper time-series database rather than Sheets as the primary database.
35. ThingSpeak Integration
ThingSpeak can be used as a time-series IoT visualization layer.
Possible fields:
Field 1 = PM2.5
Field 2 = PM10
Field 3 = CO2
Field 4 = Temperature
Field 5 = Humidity
Field 6 = VOC
Field 7 = Battery
Field 8 = Fan speed
Architecture:
ESP32
│
▼
n8n
│
▼
ThingSpeak
│
▼
Cloud Charts
Alternatively, the ESP32 can publish directly to ThingSpeak while n8n handles AI/ automation.
36. IoT Webpage
The web dashboard should contain:
┌─────────────────────────────────────────────┐
│ ☀️ AI SOLAR AIR PURIFIER │
├─────────────────────────────────────────────┤
│ │
│ AIR QUALITY │
│ │
│ PM2.5 42 µg/m³ 🟡 │
│ PM10 61 µg/m³ │
│ CO₂ 920 ppm │
│ │
├─────────────────────────────────────────────┤
│ ENVIRONMENT │
│ │
│ Temperature 29.4°C │
│ Humidity 61% │
│ VOC 125 │
│ │
├─────────────────────────────────────────────┤
│ PURIFIER │
│ │
│ Fan ███████░░░ 70% │
│ Mode AUTO │
│ │
├─────────────────────────────────────────────┤
│ SOLAR POWER │
│ │
│ Solar 18.7 V │
│ Battery 82% │
│ Charging YES │
│ │
├─────────────────────────────────────────────┤
│ AI PREDICTION │
│ │
│ Current PM2.5 42 │
│ Predicted 30 min 58 │
│ Trend ↗ Increasing │
│ │
└─────────────────────────────────────────────┘
37. Web Dashboard Architecture
ESP32
│
▼
n8n
│
┌──────────┼───────────┐
│ │ │
▼ ▼ ▼
ThingSpeak Database AI Agent
│ │
└──────────┬───────────┘
│
▼
Web Dashboard
38. Simple Webpage
A basic HTML frontend:
<!DOCTYPE html>
<html>
<head>
<title>AI Solar Air Purifier</title>
<style>
body {
font-family: Arial, sans-serif;
background: #0f172a;
color: white;
margin: 0;
padding: 20px;
}
h1 {
color: #38bdf8;
}
.dashboard {
display: grid;
grid-template-columns:
repeat(auto-fit, minmax(220px, 1fr));
gap: 20px;
}
.card {
background: #1e293b;
padding: 20px;
border-radius: 15px;
}
.value {
font-size: 32px;
color: #4ade80;
}
.warning {
color: #facc15;
}
.danger {
color: #ef4444;
}
</style>
</head>
<body>
<h1>☀️ AI Solar Air Purifier</h1>
<div class="dashboard">
<div class="card">
<h3>PM2.5</h3>
<div id="pm25" class="value">--</div>
</div>
<div class="card">
<h3>PM10</h3>
<div id="pm10" class="value">--</div>
</div>
<div class="card">
<h3>CO₂</h3>
<div id="co2" class="value">--</div>
</div>
<div class="card">
<h3>Temperature</h3>
<div id="temperature" class="value">--</div>
</div>
<div class="card">
<h3>Humidity</h3>
<div id="humidity" class="value">--</div>
</div>
<div class="card">
<h3>Fan</h3>
<div id="fan" class="value">--</div>
</div>
</div>
<script>
async function updateDashboard() {
const response =
await fetch("/api/latest");
const data =
await response.json();
document.getElementById("pm25")
.textContent = data.pm25;
document.getElementById("pm10")
.textContent = data.pm10;
document.getElementById("co2")
.textContent = data.co2;
document.getElementById("temperature")
.textContent =
data.temperature + " °C";
document.getElementById("humidity")
.textContent =
data.humidity + " %";
document.getElementById("fan")
.textContent =
data.fan + " %";
}
setInterval(updateDashboard, 5000);
updateDashboard();
</script>
</body>
</html>
39. AI Prediction Dashboard
Add a dedicated prediction card:
┌─────────────────────────────┐
│ 🤖 AI AIR QUALITY FORECAST │
├─────────────────────────────┤
│ │
│ Current PM2.5: 42 │
│ │
│ 10 min: 47 │
│ 30 min: 58 │
│ 60 min: 71 │
│ │
│ Trend: ↗ Increasing │
│ │
│ AI recommendation: │
│ Increase fan to 60% │
│ │
└─────────────────────────────┘
40. Full Agentic Decision Loop
This is the core innovation of the project.
┌───────────────────┐
│ ESP32 │
└─────────┬─────────┘
│
▼
Sensor readings
│
▼
┌───────────────────┐
│ n8n Workflow │
└─────────┬─────────┘
│
▼
Data validation
│
▼
Historical data
│
▼
┌───────────────────┐
│ AI Prediction │
└─────────┬─────────┘
│
▼
Future air quality
│
▼
┌───────────────────┐
│ AI Agent │
└─────────┬─────────┘
│
▼
Decision
│
┌────────────┼─────────────┐
│ │ │
▼ ▼ ▼
No action Fan control Alert
│ │ │
│ ▼ ▼
│ ESP32 Telegram
│ │ │
│ ▼ ▼
│ Fan Voice
│
└────────────┬─────────────┘
│
▼
Verify
│
▼
Log outcome
│
▼
Next cycle
41. Example AI Agent Conversation
Sensor → AI
SYSTEM:
You are the Air Purifier IoT Agent.
DEVICE:
AIRPURIFIER_01
CURRENT:
PM2.5 = 82
PM10 = 108
CO2 = 1320
Temperature = 30.2
Humidity = 67
Fan = 50%
Battery = 76%
Solar = charging
TREND:
PM2.5 has increased from 51 to 82
during the last 10 minutes.
PREDICTION:
PM2.5 after 30 minutes = 105
AI Agent
ANALYSIS:
Air quality is deteriorating.
PM2.5 has a positive trend.
The predicted value is higher than
the configured warning threshold.
Solar power is currently available.
ACTION:
Increase purifier fan to 80%.
NOTIFICATION:
Send Telegram alert.
n8n
AI decision
↓
Validate JSON
↓
Fan = 80%
↓
Send ESP32 command
↓
Send Telegram alert
↓
Write Google Sheets record
42. ESP32 Command Endpoint
The ESP32 can expose a secure command endpoint or poll for commands.
Example command:
{
"command": "SET_FAN",
"value": 80,
"request_id": "abc123"
}
ESP32:
void processCommand(String command,
int value) {
if (command == "SET_FAN") {
value = constrain(value, 0, 100);
setFanSpeed(value);
Serial.print("Fan set to: ");
Serial.println(value);
}
}
For an actual internet-connected installation, use authentication and encrypted transport rather than exposing an unauthenticated ESP32 HTTP endpoint.
43. Solar Intelligence
The system can also become energy-aware.
For example:
Solar power HIGH
↓
Battery charging
↓
Fan may operate aggressively
But:
Solar LOW
+
Battery LOW
↓
Energy saving mode
↓
Reduce fan speed unless air quality
requires higher purification
This creates another agentic decision:
AIR QUALITY
+
SOLAR ENERGY
+
BATTERY STATE
↓
OPTIMIZED PURIFIER OPERATION
44. Energy-Aware AI Logic
Example:
const pm25 = Number($json.pm25);
const battery = Number($json.battery_voltage);
const solar = Number($json.solar_voltage);
let fan = 30;
if (pm25 > 35)
fan = 50;
if (pm25 > 55)
fan = 70;
if (pm25 > 100)
fan = 100;
// Energy-saving condition
if (battery < 11.5 && pm25 < 55) {
fan = Math.min(fan, 40);
}
// Air quality takes priority
if (pm25 > 100) {
fan = 100;
}
return [{
json: {
...$json,
recommended_fan: fan
}
}];
45. System States
The purifier can have these states:
OFF
│
▼
STARTING
│
▼
MONITORING
│
├─────────────┐
│ │
▼ ▼
GOOD DETERIORATING
│ │
│ ▼
│ PURIFYING
│ │
│ ▼
│ VERIFYING
│ │
│ ┌─────┴─────┐
│ ▼ ▼
│ IMPROVED STILL BAD
│ │ │
└───────┴───────────┘
│
▼
MONITORING
46. Failure Handling
The system should continue functioning if:
Wi-Fi fails
Wi-Fi OFF
↓
ESP32 local control
↓
Continue purification
↓
Store recent data locally
↓
Reconnect
↓
Upload buffered data
n8n fails
n8n unavailable
↓
ESP32 detects timeout
↓
Local threshold algorithm
↓
Continue fan control
AI unavailable
AI unavailable
↓
Rule-based fallback
↓
Normal purifier operation
This is much more robust than making the AI cloud service a single point of failure.
47. Local Data Buffer
The ESP32 can maintain a small circular buffer:
struct SensorData {
unsigned long timestamp;
float pm25;
float pm10;
float co2;
float temperature;
float humidity;
float battery;
float solar;
};
Store important events in flash/NVS or an appropriate local storage mechanism if offline persistence is required.
48. Security Architecture
Use:
ESP32
│
│ HTTPS / MQTT TLS
▼
n8n
│
├── Authentication
│
├── Validation
│
└── Rate limiting
│
▼
AI
Never put API keys directly into public JavaScript.
Keep credentials in:
-
ESP32 secrets/configuration
-
n8n credentials
-
environment variables
-
server-side configuration
49. Recommended n8n Workflows
I recommend creating five workflows.
Workflow A — Sensor ingestion
Webhook
↓
Validate
↓
Normalize
↓
Google Sheets
↓
ThingSpeak
Workflow B — AI prediction
Schedule
↓
Get recent data
↓
Calculate features
↓
Prediction
↓
Store forecast
Workflow C — AI Agent
Latest data
↓
Prediction
↓
Energy state
↓
AI Agent
↓
Structured decision
↓
Safety validation
Workflow D — Device controller
AI decision
↓
Validate
↓
HTTP/MQTT
↓
ESP32
↓
Read confirmation
Workflow E — Telegram
Telegram Trigger
↓
Command parser
↓
Status / prediction / control
↓
ESP32 or AI
↓
Telegram response
50. Example n8n AI Prompt
Use a constrained prompt similar to:
You are an AI agent controlling an air-quality monitoring
and purification system.
Your job is to analyze sensor data and recommend safe
purifier actions.
You may recommend only:
SET_FAN
NO_ACTION
SEND_ALERT
Fan speed must be between 0 and 100.
Consider:
1. Current PM2.5
2. PM2.5 trend
3. Predicted PM2.5
4. CO2
5. Battery state
6. Solar availability
7. Current fan speed
Do not invent sensor readings.
Do not issue arbitrary hardware commands.
Return ONLY JSON:
{
"status": "...",
"reason": "...",
"action": "...",
"fan_speed": 0,
"send_alert": false
}
51. Example Complete AI Decision
Input:
{
"pm25": 83,
"pm10": 112,
"co2": 1450,
"temperature": 30.5,
"humidity": 68,
"fan": 50,
"battery": 12.3,
"solar": 18.1,
"predicted_pm25_30min": 108
}
Possible validated output:
{
"status": "WARNING",
"reason": "PM2.5 is elevated and predicted to increase",
"action": "SET_FAN",
"fan_speed": 80,
"send_alert": true
}
52. Telegram Voice Workflow
AI AGENT
│
▼
send_alert=true
│
▼
Create message
│
▼
Text-to-Speech
│
▼
Audio generated
│
▼
Telegram Bot
│
┌─────────┴─────────┐
▼ ▼
Text Alert Voice Alert
53. Example Telegram Conversation
User
/status
Bot
🌱 AIR PURIFIER STATUS
Air Quality: MODERATE
PM2.5: 42
PM10: 61
CO₂: 920 ppm
Temperature: 29.4°C
Humidity: 61%
Fan: 60%
Mode: AUTO
Battery: 82%
Solar: Charging ☀️
User
/predict
Bot
🤖 AI PREDICTION
Current PM2.5: 42
10 minutes: 47
30 minutes: 58
60 minutes: 71
Trend: Increasing ↗
Recommendation:
Maintain automatic purification.
54. Complete Data Flow
☀️
│
▼
Solar Energy
│
▼
Battery
│
▼
ESP32
│
┌──────┼───────┐
│ │ │
▼ ▼ ▼
PM CO₂ Environment
Sensors Sensor Sensors
│ │ │
└──────┼───────┘
│
▼
Sensor Fusion
│
▼
Local Control
│
▼
Wi-Fi
│
▼
n8n
│
┌──────┼────────┐
│ │ │
▼ ▼ ▼
Sheets ThingSpeak AI
│
▼
Prediction
│
▼
AI Agent
│
┌─────────┼─────────┐
│ │ │
▼ ▼ ▼
No Action ESP32 Telegram
│ │
▼ ▼
FAN Voice
│
▼
Air Quality
│
▼
Feedback
55. Project Demonstration Scenario
For a college/project exhibition, demonstrate this sequence.
Stage 1 — Clean air
Display:
PM2.5 = 20
Fan = 30%
Status = GOOD
Stage 2 — Introduce controlled particulate disturbance
Sensor detects:
PM2.5 = 50
System:
AI detects deterioration
↓
Fan → 60%
Stage 3 — Increasing pollution
PM2.5 = 80
PM2.5 trend = ↑
AI:
Prediction:
PM2.5 = 105
System:
Fan → 80%
Telegram → Alert
Google Sheets → Log
ThingSpeak → Update
Dashboard → Warning
Stage 4 — Recovery
PM2.5 = 42
System:
Fan → 50%
Status → Improving
Telegram → Recovery notification
This demonstrates the entire closed loop.
56. Testing Plan
Sensor testing
Test:
-
PM sensor
-
CO₂ sensor
-
temperature
-
humidity
-
VOC
-
battery measurement
-
solar voltage
Communication testing
Test:
ESP32 → Wi-Fi
ESP32 → n8n
n8n → Google Sheets
n8n → ThingSpeak
n8n → Telegram
n8n → ESP32
AI testing
Use recorded datasets:
Normal
Increasing pollution
Sudden pollution
Recovery
Low battery
No solar
Verify the agent produces valid decisions.
57. Failure Test Matrix
| Failure | Expected behaviour |
|---|---|
| Wi-Fi disconnected | Local ESP32 control |
| n8n unavailable | Local control continues |
| AI unavailable | Rule-based fallback |
| Sensor invalid | Ignore/reject measurement |
| Battery low | Energy-saving mode |
| Solar unavailable | Battery operation |
| Telegram unavailable | Continue purification |
| Google Sheets unavailable | Continue system operation |
| ThingSpeak unavailable | Continue system operation |
58. Important AI Evaluation Metrics
For air-quality prediction:
MAE
MAE =
average(|actual - predicted|)
RMSE
RMSE =
sqrt(average((actual - predicted)²))
R²
Measure how much of the variation is explained by the model.
For the project report, show:
Prediction horizon:
10 min
30 min
60 min
MAE:
...
RMSE:
...
R²:
...
Do not claim that the prediction is accurate unless you actually evaluate it against collected measurements.
59. Project Modules
Your final project can be divided into these modules:
MODULE 1
Solar Power System
MODULE 2
ESP32 Controller
MODULE 3
Air Quality Sensors
MODULE 4
Air Purifier
MODULE 5
IoT Communication
MODULE 6
n8n Automation
MODULE 7
AI Prediction
MODULE 8
AI Agent
MODULE 9
Telegram Voice Alert
MODULE 10
Google Sheets Logging
MODULE 11
ThingSpeak Dashboard
MODULE 12
Web Dashboard
MODULE 13
Security
MODULE 14
Testing & Evaluation
60. Novelty / Innovation
The project combines several technologies:
Solar Energy
+
Environmental Sensing
+
ESP32 Edge Computing
+
IoT
+
Time-Series Data
+
AI Prediction
+
Agentic Decision Making
+
n8n Automation
+
Telegram Voice
+
Cloud Dashboard
The strongest architectural concept is:
Predictive and energy-aware autonomous air purification rather than simple threshold-based switching.
61. Final Project Block Diagram
☀️ SOLAR PANEL
│
▼
┌───────────────┐
│ Solar Charger │
└───────┬───────┘
│
▼
🔋 BATTERY
│
┌───────────┴──────────┐
│ │
▼ ▼
DC-DC FAN POWER
│
▼
┌─────────────────┐
│ ESP32 │
└────────┬────────┘
│
┌──────────┼───────────┐
│ │ │
▼ ▼ ▼
PMS5003 SCD40 BME280
│ │ │
└──────────┼───────────┘
│
▼
Sensor Data
│
▼
Wi-Fi
│
▼
┌─────────────────┐
│ n8n │
│ Automation │
└───────┬─────────┘
│
┌────────┼──────────┐
│ │ │
▼ ▼ ▼
Google ThingSpeak AI Agent
Sheets │ │
│ │ ▼
│ │ Prediction
│ │ │
│ └────┬─────┘
│ │
│ ▼
│ Decision Engine
│ │
│ ┌─────┴─────┐
│ │ │
│ ▼ ▼
│ ESP32 Telegram
│ │ │
│ ▼ ▼
│ FAN Voice Alert
│
▼
Historical
Data
┌──────────────────┐
│ WEB DASHBOARD │
└──────────────────┘
62. Suggested Final Hardware BOM
| Component | Qty |
|---|---|
| ESP32 DevKit | 1 |
| PMS5003/PMS7003 | 1 |
| SCD40/SCD41 or equivalent CO₂ sensor | 1 |
| BME280 | 1 |
| VOC sensor | 1 |
| DC blower/fan | 1 |
| HEPA filter | 1 |
| Activated-carbon filter | 1 |
| Solar panel | 1 |
| Solar charge controller | 1 |
| Battery | 1 |
| DC-DC converter | 1–2 |
| MOSFET driver | 1 |
| Fuse/protection | As required |
| Resistors for voltage sensing | As required |
| Enclosure | 1 |
| Wires/connectors | As required |
63. Recommended Software Stack
Firmware:
Arduino IDE / PlatformIO
+
ESP32 Arduino Framework
IoT:
HTTP / MQTT
Automation:
n8n
AI:
LLM + prediction model
Cloud:
ThingSpeak
Database/logging:
Google Sheets
Notification:
Telegram Bot
+
Text-to-Speech
Frontend:
HTML
CSS
JavaScript
Optional backend:
Node.js / Python
64. Complete Project Sequence
When you actually build it, follow this order:
STEP 1
Build solar/battery power system
↓
STEP 2
Power ESP32 safely
↓
STEP 3
Connect BME280
↓
STEP 4
Connect PM sensor
↓
STEP 5
Connect CO₂ sensor
↓
STEP 6
Test each sensor independently
↓
STEP 7
Add fan + MOSFET
↓
STEP 8
Implement local fan control
↓
STEP 9
Connect ESP32 to Wi-Fi
↓
STEP 10
Create n8n webhook
↓
STEP 11
Send ESP32 JSON → n8n
↓
STEP 12
Add Google Sheets logging
↓
STEP 13
Add ThingSpeak
↓
STEP 14
Create web dashboard
↓
STEP 15
Collect historical data
↓
STEP 16
Build prediction model
↓
STEP 17
Add AI Agent
↓
STEP 18
Add safety/command validation
↓
STEP 19
Add Telegram bot
↓
STEP 20
Add Telegram voice alerts
↓
STEP 21
Add remote ESP32 control
↓
STEP 22
Add solar/battery intelligence
↓
STEP 23
Test failure conditions
↓
STEP 24
Run complete demonstration
65. What the Finished System Does
The final system operates approximately like this:
ESP32 measures air
↓
PM2.5 begins increasing
↓
Data reaches n8n
↓
Historical trend analyzed
↓
AI predicts future PM2.5
↓
AI Agent evaluates:
│
├─ Air quality
├─ Trend
├─ Prediction
├─ Fan state
├─ Battery
└─ Solar power
↓
Decision generated
↓
Safety validator
↓
ESP32 receives command
↓
Fan speed increases
↓
Air quality improves
↓
ESP32 reports new data
↓
AI verifies result
↓
Google Sheets logs event
↓
ThingSpeak updates graph
↓
Web dashboard updates
↓
Telegram sends voice notification
That gives you a closed-loop AI/IoT system, rather than merely an ESP32 sensor project.
66. Recommended final report structure
For a college/project/thesis document, use:
-
Abstract
-
Introduction
-
Problem Statement
-
Objectives
-
Existing System
-
Proposed System
-
System Architecture
-
Hardware Requirements
-
Software Requirements
-
Circuit/Schematic
-
ESP32 Firmware Design
-
Sensor Integration
-
Solar Power Design
-
Air Purification Design
-
IoT Communication
-
n8n Workflow
-
AI Prediction Methodology
-
AI Agent Architecture
-
Telegram Voice Notification
-
Google Sheets Integration
-
ThingSpeak Integration
-
Web Dashboard
-
Security
-
Failure Handling
-
Testing
-
Prediction Accuracy
-
Results
-
Advantages
-
Limitations
-
Future Scope
-
Conclusion
-
References
-
Appendix — Source Code
If you build it in this modular order, each subsystem can be tested independently before connecting the complete ESP32 → n8n → AI → Telegram → cloud → ESP32 feedback loop.
## Project Summary **AI Solar Air Purifier with Predictive Air-Quality Monitoring and Agentic IoT Automation** is an intelligent, solar-powered air-purification system built around an **ESP32**. The system continuously monitors **PM2.5, PM10, CO₂, temperature, humidity and optional VOC levels**. The ESP32 processes the sensor readings locally and sends telemetry through Wi-Fi to an **n8n automation platform**. ``` Air Sensors ↓ ESP32 ↓ Wi-Fi ↓ n8n ↓ ┌───┼─────────────┐ ↓ ↓ ↓ AI Google ThingSpeak Sheets ↓ AI Agent ↓ Decision ├──→ ESP32 → Fan └──→ Telegram → Text/Voice Alert ``` ### Main intelligence The AI system analyzes: - Current air quality - Historical sensor readings - PM2.5 trend - Predicted future air quality - Fan speed - Battery level - Solar availability It can then make structured decisions such as: ``` { "action": "SET_FAN", "fan_speed": 80, "send_alert": true, "reason": "PM2.5 is increasing and predicted to deteriorate" } ``` ### Major subsystems 1. **☀️ Solar Power** — solar panel, charge controller, battery and DC-DC conversion. 2. **🧠 ESP32** — sensor acquisition, local control and Wi-Fi communication. 3. **🌫️ Air Sensors** — PMS5003/PMS7003, SCD40/SCD41, BME280 and optional VOC sensor. 4. **🌬️ Purifier** — pre-filter, HEPA filter, activated carbon filter and variable-speed fan. 5. **⚙️ n8n** — receives telemetry, validates data, performs automation and coordinates the AI agent. 6. **🤖 AI Prediction** — predicts future PM2.5/air-quality trends. 7. **🧩 AI Agent** — combines predictions, sensor data and energy status to recommend actions. 8. **📱 Telegram** — text and voice notifications plus remote commands. 9. **📊 Google Sheets** — historical sensor/event logging. 10. **☁️ ThingSpeak** — IoT time-series visualization. 11. **🌐 Web Dashboard** — live air-quality, purifier, solar, battery and AI-prediction display. 12. **🛡️ Safety layer** — validates AI commands and provides rule-based fallback if cloud/AI services fail. ### Agentic IoT feedback loop ``` SENSE ↓ SEND ↓ ANALYZE ↓ PREDICT ↓ DECIDE ↓ ACT ↓ VERIFY ↓ LOG ↓ NOTIFY ↓ REPEAT ``` The key idea is therefore not simply **“ESP32 + air sensor”**, but a **closed-loop predictive IoT system** in which the ESP32 senses the environment, AI predicts deterioration, an agent decides on an appropriate response, the purifier acts, and the result is verified and recorded.

No comments:
Post a Comment