Thursday, 1 October 2026

AI Stress Detection and Mental Health Monitoring System

AI Stress Detection & Mental-Health Monitoring System

ESP32 + IoT Sensors + AI Agent + n8n Automation + Telegram Voice Alerts + Google Sheets + ThingSpeak + Web Dashboard

Important: This is an educational IoT/wellness monitoring system, not a medical diagnostic device. “Stress level” should be treated as an experimental indicator derived from sensor patterns—not as a diagnosis of anxiety, depression, or another mental-health condition. Any high-risk or crisis indication should be handled by an appropriate human/professional rather than by an automated agent.


1. Project overview

The proposed system continuously collects physiological and motion information using an ESP32 and sensors such as:

  • Heart rate / pulse

  • SpO₂

  • Skin conductance / GSR

  • Body temperature

  • Motion/activity

  • Optional microphone or button for user interaction

The ESP32 performs basic signal processing and sends the measurements through Wi-Fi to an n8n webhook.

n8n becomes the central automation/agent layer:

                    ┌─────────────────────────┐
                    │       USER/PERSON       │
                    │                         │
                    │ Stress / activity data  │
                    └────────────┬────────────┘
                                 │
                                 ▼
                    ┌─────────────────────────┐
                    │        ESP32             │
                    │                         │
                    │ HR / SpO2               │
                    │ GSR                     │
                    │ Temperature             │
                    │ Motion                  │
                    └────────────┬────────────┘
                                 │ Wi-Fi / JSON
                                 ▼
                    ┌─────────────────────────┐
                    │      n8n WEBHOOK         │
                    │                         │
                    │ Validate / Normalize    │
                    └────────────┬────────────┘
                                 │
                                 ▼
                    ┌─────────────────────────┐
                    │   STRESS ANALYSIS       │
                    │                         │
                    │ Rule engine + AI Agent  │
                    └───────┬────────┬────────┘
                            │        │
              ┌─────────────┘        └─────────────┐
              ▼                                    ▼
     ┌──────────────────┐                 ┌──────────────────┐
     │ Google Sheets    │                 │ ThingSpeak       │
     │ Historical data  │                 │ IoT graphs       │
     └──────────────────┘                 └──────────────────┘
              │
              │
              ▼
     ┌────────────────────────────────────────────┐
     │              ALERT ENGINE                  │
     │                                             │
     │ Normal → no alert                          │
     │ Elevated → text notification               │
     │ High → Telegram notification               │
     │ Sustained high → Telegram voice alert      │
     └───────────────────┬────────────────────────┘
                         │
                         ▼
              ┌──────────────────────┐
              │       TELEGRAM       │
              │                      │
              │ Text + Voice Alert   │
              └──────────────────────┘

n8n's Webhook node is specifically designed to receive external events and start workflows, and it provides separate test and production webhook URLs. GitHub+1


2. Main objectives

The project has six major objectives:

  1. Collect physiological data

  2. Calculate a stress-related score

  3. Send data to the cloud automatically

  4. Use an AI agent to interpret trends

  5. Notify a user/caregiver through Telegram

  6. Store historical information for analysis

The system can additionally provide:

  • Real-time ESP32 webpage

  • ThingSpeak graphs

  • Google Sheets database

  • Daily/weekly summaries

  • Telegram commands

  • Voice notifications

  • AI-generated explanations

  • Device health monitoring

  • Sensor fault detection


3. Recommended hardware

3.1 Core components

Component Purpose
ESP32 DevKit V1 Main controller
MAX30102 Heart rate + SpO₂
GSR sensor Skin conductance
MPU6050 Movement/activity
DS18B20 Temperature
4.7 kΩ resistor DS18B20 pull-up
OLED 0.96" I²C Local display
Push button Manual event/SOS input
Buzzer Local notification
LED Status indication
Breadboard Prototype
Jumper wires Connections
5 V USB supply Power

Optional

  • ESP32-CAM

  • INMP441 microphone

  • MAX4466 microphone

  • Battery

  • Li-ion charging circuit

  • Vibration motor

  • RTC module


4. Hardware architecture

                         ┌─────────────────────┐
                         │       ESP32         │
                         │                     │
                         │ Wi-Fi               │
                         │ Web Server           │
                         │ Sensor Processing    │
                         │ JSON API             │
                         └──────────┬──────────┘
                                    │
             ┌──────────────────────┼─────────────────────┐
             │                      │                     │
             ▼                      ▼                     ▼
       ┌───────────┐          ┌───────────┐        ┌───────────┐
       │ MAX30102  │          │    GSR    │        │ MPU6050   │
       │           │          │           │        │           │
       │ HR        │          │ Skin      │        │ Motion    │
       │ SpO2      │          │ Conduct.  │        │ Activity  │
       └───────────┘          └───────────┘        └───────────┘
             │                      │                     │
             └──────────────────────┼─────────────────────┘
                                    │
                              I²C / ADC
                                    │
                              ┌─────▼─────┐
                              │ DS18B20   │
                              │ Temp      │
                              └───────────┘

                       ESP32 Wi-Fi
                           │
             ┌─────────────┼─────────────┐
             ▼             ▼             ▼
          n8n Cloud    ThingSpeak    ESP32 Web

ESP32 supports Wi-Fi station mode, which is the appropriate mode when the board connects to an Internet access point. Espressif Documentation


5. Schematic / wiring diagram

A practical wiring arrangement is:

                    ESP32 DEVKIT
                ┌─────────────────┐
                │                 │
                │ 3V3 ────────────┼──────── MAX30102 VIN
                │ GND ────────────┼──────── MAX30102 GND
                │ GPIO21 ─────────┼──────── SDA
                │ GPIO22 ─────────┼──────── SCL
                │                 │
                │                 │
                │ GPIO34 ─────────┼──────── GSR OUT
                │                 │
                │ GPIO4 ──────────┼──────── DS18B20 DATA
                │                 │
                │ GPIO18 ─────────┼──────── MPU6050 SDA* 
                │                 │
                │ GPIO19 ─────────┼──────── MPU6050 SCL*
                │                 │
                │ GPIO25 ─────────┼──────── Buzzer
                │ GPIO26 ─────────┼──────── LED
                │ GPIO27 ─────────┼──────── Button
                │                 │
                └─────────────────┘

Important correction

The MAX30102 and MPU6050 are both I²C devices, so they can normally share:

GPIO21 → SDA
GPIO22 → SCL

Therefore the cleaner wiring is:

ESP32 GPIO21 ───── SDA ───── MAX30102
                         └── MPU6050

ESP32 GPIO22 ───── SCL ───── MAX30102
                         └── MPU6050

6. Complete wiring table

MAX30102

MAX30102 ESP32
VIN 3.3 V
GND GND
SDA GPIO21
SCL GPIO22

MPU6050

MPU6050 ESP32
VCC 3.3 V
GND GND
SDA GPIO21
SCL GPIO22

GSR

GSR ESP32
VCC Module-rated supply
GND GND
AO GPIO34

Do not blindly apply 5 V to an ESP32 ADC input. Verify the particular GSR module's output range and use appropriate voltage scaling if necessary.

DS18B20

DS18B20

       ┌────────────┐
       │            │
       │ 1  2  3   │
       └─┬──┬──┬───┘
         │  │  │
        GND DATA VCC
             │
             │
           GPIO4

4.7kΩ resistor:
GPIO4 ───── 4.7kΩ ───── 3.3V

7. Stress detection concept

The project should not simply say:

HR > 100 = stress.

That would produce many false positives.

Instead, create a multidimensional score.

For example:

             ┌─────────────┐
             │ Heart Rate  │
             └──────┬──────┘
                    │
             ┌──────▼──────┐
             │ GSR change  │
             └──────┬──────┘
                    │
             ┌──────▼──────┐
             │ Temperature │
             └──────┬──────┘
                    │
             ┌──────▼──────┐
             │   Motion    │
             └──────┬──────┘
                    │
                    ▼
             NORMALIZATION
                    │
                    ▼
             FEATURE VECTOR
                    │
                    ▼
             STRESS SCORE
                 0–100
                    │
          ┌─────────┼──────────┐
          ▼         ▼          ▼
        LOW      ELEVATED     HIGH

8. Example stress-score algorithm

Use a personal baseline rather than fixed universal thresholds.

Suppose:

Baseline HR = 72 BPM
Current HR = 96 BPM

Baseline GSR = 1800
Current GSR = 2500

Baseline temperature = 36.5°C
Current temperature = 36.8°C

Normalize:

HR deviation
= |96 - 72| / 72

GSR deviation
= |2500 - 1800| / 1800

Temperature deviation
= |36.8 - 36.5| / 36.5

Then combine weighted features:

Stress Score =
    HR contribution
  + GSR contribution
  + temperature contribution
  + motion/context contribution

Example:

HR        = 45%
GSR       = 35%
Motion    = 10%
Temp      = 10%

Then clamp:

0 ≤ StressScore ≤ 100

A prototype classification could be:

0–30     LOW
31–60    ELEVATED
61–80    HIGH
81–100   VERY HIGH

These values are engineering thresholds for the prototype, not medically validated thresholds.


9. Personal baseline

The baseline is extremely important.

When the device starts:

CALIBRATION MODE
       │
       ▼
Collect 60–120 seconds
       │
       ▼
Calculate:
HR average
GSR average
Temperature average
Motion average
       │
       ▼
Store baseline

Then compare future measurements against that baseline.

This is substantially more useful than assuming every person's resting HR or GSR is identical.


10. ESP32 software architecture

The firmware has five jobs:

                ESP32 PROGRAM
                     │
       ┌─────────────┼──────────────┐
       ▼             ▼              ▼
   Sensors       Web Server       Wi-Fi
       │             │              │
       └─────────────┼──────────────┘
                     ▼
               Data Processing
                     │
                     ▼
                JSON Payload
                     │
                     ▼
                 n8n Webhook

11. Required Arduino libraries

Install through Arduino IDE Library Manager:

WiFi
WebServer
HTTPClient
ArduinoJson
Wire
OneWire
DallasTemperature
Adafruit MPU6050
Adafruit Unified Sensor
MAX30105 / MAX3010x library

The ESP32 Arduino environment provides HTTP client functionality for HTTP/HTTPS requests. GitHub+1


12. ESP32 firmware

Below is a prototype firmware framework. Sensor libraries can differ between module/library versions, so you may need to adjust the MAX30102 initialization for your particular breakout.

#include <WiFi.h>
#include <WebServer.h>
#include <HTTPClient.h>
#include <Wire.h>
#include <ArduinoJson.h>

#include <OneWire.h>
#include <DallasTemperature.h>

#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>

#include "MAX30105.h"
#include "heartRate.h"

// =====================================================
// Wi-Fi
// =====================================================

const char* WIFI_SSID = "YOUR_WIFI";
const char* WIFI_PASSWORD = "YOUR_PASSWORD";

// n8n production webhook
const char* N8N_WEBHOOK =
  "https://YOUR-N8N-DOMAIN/webhook/stress-data";

// =====================================================
// Pins
// =====================================================

#define GSR_PIN       34
#define TEMP_PIN       4
#define BUZZER_PIN    25
#define LED_PIN       26
#define BUTTON_PIN    27

// =====================================================
// Objects
// =====================================================

WebServer server(80);

MAX30105 particleSensor;
Adafruit_MPU6050 mpu;

OneWire oneWire(TEMP_PIN);
DallasTemperature tempSensor(&oneWire);

// =====================================================
// Variables
// =====================================================

float heartRate = 0;
float spo2 = 0;
float temperature = 0;
float gsr = 0;

float accelX = 0;
float accelY = 0;
float accelZ = 0;

float baselineHR = 70;
float baselineGSR = 1000;
float baselineTemp = 36.5;

float stressScore = 0;

String stressLevel = "LOW";

unsigned long lastSend = 0;
unsigned long sendInterval = 10000;

// =====================================================
// Web page
// =====================================================

String htmlPage()
{
  String html = R"rawliteral(

<!DOCTYPE html>
<html>

<head>

<meta name="viewport"
content="width=device-width,initial-scale=1">

<title>AI Stress Monitor</title>

<style>

body {
    font-family: Arial;
    background: #101820;
    color: white;
    margin: 0;
    padding: 20px;
}

.container {
    max-width: 900px;
    margin: auto;
}

.card {
    background: #1d2935;
    border-radius: 15px;
    padding: 20px;
    margin: 10px;
    display: inline-block;
    width: 180px;
}

.value {
    font-size: 32px;
    color: #00e5ff;
}

.status {
    font-size: 30px;
    font-weight: bold;
}

button {
    padding: 15px;
    background: #00aaff;
    color: white;
    border: none;
    border-radius: 8px;
}

</style>

</head>

<body>

<div class="container">

<h1>AI Stress Monitoring System</h1>

<div class="card">
<h3>Heart Rate</h3>
<div class="value" id="hr">--</div>
</div>

<div class="card">
<h3>SpO2</h3>
<div class="value" id="spo2">--</div>
</div>

<div class="card">
<h3>GSR</h3>
<div class="value" id="gsr">--</div>
</div>

<div class="card">
<h3>Temperature</h3>
<div class="value" id="temp">--</div>
</div>

<div class="card">
<h3>Stress Score</h3>
<div class="value" id="score">--</div>
</div>

<div class="card">
<h3>Status</h3>
<div class="status" id="status">--</div>
</div>

</div>

<script>

async function updateData()
{
    const response =
      await fetch('/api/data');

    const data =
      await response.json();

    document.getElementById("hr")
      .innerText = data.hr + " BPM";

    document.getElementById("spo2")
      .innerText = data.spo2 + " %";

    document.getElementById("gsr")
      .innerText = data.gsr;

    document.getElementById("temp")
      .innerText = data.temperature + " °C";

    document.getElementById("score")
      .innerText = data.stress_score;

    document.getElementById("status")
      .innerText = data.stress_level;
}

setInterval(updateData, 2000);

updateData();

</script>

</body>

</html>

)rawliteral";

  return html;
}

// =====================================================
// Read sensors
// =====================================================

void readSensors()
{
    // -------------------------------
    // GSR
    // -------------------------------

    gsr = analogRead(GSR_PIN);

    // -------------------------------
    // Temperature
    // -------------------------------

    tempSensor.requestTemperatures();

    temperature =
        tempSensor.getTempCByIndex(0);

    // -------------------------------
    // MPU6050
    // -------------------------------

    sensors_event_t a;
    sensors_event_t g;
    sensors_event_t temp;

    mpu.getEvent(&a, &g, &temp);

    accelX = a.acceleration.x;
    accelY = a.acceleration.y;
    accelZ = a.acceleration.z;

    // -------------------------------
    // MAX30102
    // -------------------------------

    long irValue =
        particleSensor.getIR();

    if (irValue > 50000)
    {
        // Basic pulse detection.
        // Production implementation should
        // calculate HR over a time window.

        if (checkForBeat(irValue))
        {
            static unsigned long lastBeat = 0;

            unsigned long now =
                millis();

            unsigned long delta =
                now - lastBeat;

            lastBeat = now;

            float bpm =
                60.0 /
                (delta / 1000.0);

            if (bpm > 40 && bpm < 180)
            {
                heartRate = bpm;
            }
        }
    }
}

// =====================================================
// Stress calculation
// =====================================================

void calculateStress()
{
    float hrDeviation =
        abs(heartRate - baselineHR)
        / max(baselineHR, 1.0f);

    float gsrDeviation =
        abs(gsr - baselineGSR)
        / max(baselineGSR, 1.0f);

    float tempDeviation =
        abs(temperature - baselineTemp)
        / max(baselineTemp, 1.0f);

    // Convert to approximate 0-100 contributions

    float hrScore =
        constrain(hrDeviation * 100.0, 0, 100);

    float gsrScore =
        constrain(gsrDeviation * 100.0, 0, 100);

    float tempScore =
        constrain(tempDeviation * 300.0, 0, 100);

    // Prototype weighted score

    stressScore =
        (hrScore * 0.45) +
        (gsrScore * 0.40) +
        (tempScore * 0.15);

    stressScore =
        constrain(stressScore, 0, 100);

    if (stressScore < 30)
    {
        stressLevel = "LOW";
    }
    else if (stressScore < 60)
    {
        stressLevel = "ELEVATED";
    }
    else if (stressScore < 80)
    {
        stressLevel = "HIGH";
    }
    else
    {
        stressLevel = "VERY HIGH";
    }
}

// =====================================================
// Send data to n8n
// =====================================================

void sendToN8N()
{
    if (WiFi.status() != WL_CONNECTED)
        return;

    HTTPClient http;

    http.begin(N8N_WEBHOOK);

    http.addHeader(
        "Content-Type",
        "application/json"
    );

    StaticJsonDocument<1024> doc;

    doc["device_id"] = "ESP32_STRESS_001";

    doc["timestamp"] = millis();

    doc["heart_rate"] = heartRate;

    doc["spo2"] = spo2;

    doc["gsr"] = gsr;

    doc["temperature"] = temperature;

    doc["accel_x"] = accelX;
    doc["accel_y"] = accelY;
    doc["accel_z"] = accelZ;

    doc["stress_score"] =
        stressScore;

    doc["stress_level"] =
        stressLevel;

    String payload;

    serializeJson(doc, payload);

    int httpCode =
        http.POST(payload);

    Serial.print("n8n HTTP: ");
    Serial.println(httpCode);

    http.end();
}

// =====================================================
// API
// =====================================================

void handleAPI()
{
    StaticJsonDocument<512> doc;

    doc["hr"] = heartRate;
    doc["spo2"] = spo2;
    doc["gsr"] = gsr;
    doc["temperature"] = temperature;
    doc["stress_score"] = stressScore;
    doc["stress_level"] = stressLevel;

    String response;

    serializeJson(doc, response);

    server.send(
        200,
        "application/json",
        response
    );
}

// =====================================================
// Setup
// =====================================================

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

    pinMode(
        BUZZER_PIN,
        OUTPUT
    );

    pinMode(
        LED_PIN,
        OUTPUT
    );

    pinMode(
        BUTTON_PIN,
        INPUT_PULLUP
    );

    Wire.begin(
        21,
        22
    );

    // -------------------------------
    // Temperature
    // -------------------------------

    tempSensor.begin();

    // -------------------------------
    // MPU6050
    // -------------------------------

    if (!mpu.begin())
    {
        Serial.println(
            "MPU6050 not found"
        );
    }

    // -------------------------------
    // MAX30102
    // -------------------------------

    if (!particleSensor.begin(
            Wire,
            I2C_SPEED_FAST))
    {
        Serial.println(
            "MAX30102 not found"
        );
    }

    particleSensor.setup();

    // -------------------------------
    // Wi-Fi
    // -------------------------------

    WiFi.begin(
        WIFI_SSID,
        WIFI_PASSWORD
    );

    Serial.print("Connecting");

    while (
        WiFi.status() != WL_CONNECTED)
    {
        delay(500);

        Serial.print(".");
    }

    Serial.println();

    Serial.print(
        "ESP32 IP: "
    );

    Serial.println(
        WiFi.localIP()
    );

    // -------------------------------
    // Web server
    // -------------------------------

    server.on(
        "/",
        []()
        {
            server.send(
                200,
                "text/html",
                htmlPage()
            );
        }
    );

    server.on(
        "/api/data",
        handleAPI
    );

    server.begin();
}

// =====================================================
// Loop
// =====================================================

void loop()
{
    server.handleClient();

    readSensors();

    calculateStress();

    if (
        millis() - lastSend
        > sendInterval)
    {
        lastSend = millis();

        sendToN8N();
    }

    delay(50);
}

Important production improvement

The example above demonstrates the architecture. For a serious implementation, HR and SpO₂ should be calculated over appropriate sampling windows, filtered, quality-checked, and accompanied by a signal-quality indicator. Do not treat a single noisy MAX30102 reading as meaningful.


13. JSON data sent by ESP32

Example:

{
  "device_id": "ESP32_STRESS_001",
  "timestamp": 12345678,
  "heart_rate": 94,
  "spo2": 98,
  "gsr": 2450,
  "temperature": 36.8,
  "accel_x": 0.13,
  "accel_y": -0.04,
  "accel_z": 9.71,
  "stress_score": 67,
  "stress_level": "HIGH"
}

This is the main data packet moving through the system.


14. n8n architecture

Create the following workflow:

ESP32
  │
  ▼
Webhook
  │
  ▼
Validate JSON
  │
  ▼
Normalize Data
  │
  ▼
Calculate/Verify Stress
  │
  ├───────────────┐
  │               │
  ▼               ▼
Google Sheets   ThingSpeak
  │
  ▼
AI Agent
  │
  ▼
Decision
  │
  ├── LOW ───────────────► Log only
  │
  ├── ELEVATED ──────────► Telegram text
  │
  ├── HIGH ──────────────► Telegram alert
  │
  └── VERY HIGH/
      SUSTAINED ─────────► Telegram voice + text

n8n's HTTP Request node can make REST API calls and can also be attached to an AI agent as a tool. GitHub


15. n8n workflow — Step 1

Create:

Webhook

Configuration:

HTTP Method:
POST

Path:
stress-data

Authentication:
Header Auth or another appropriate authentication method

During development, use the test webhook. Once the workflow is published, use the production webhook. n8n explicitly distinguishes the two URLs. GitHub


16. n8n workflow — Step 2: validation

Add:

IF

Check:

heart_rate exists
gsr exists
temperature exists
stress_score exists
device_id exists

For example:

IF stress_score >= 0
AND stress_score <= 100

If invalid:

Invalid data
     │
     ▼
Log error
     │
     ▼
Stop

17. n8n workflow — Step 3: data normalization

Use a Code node.

const d = $json;

return [{
  json: {
    device_id: d.device_id || "unknown",

    timestamp: new Date().toISOString(),

    heart_rate: Number(d.heart_rate || 0),

    spo2: Number(d.spo2 || 0),

    gsr: Number(d.gsr || 0),

    temperature: Number(d.temperature || 0),

    accel_x: Number(d.accel_x || 0),

    accel_y: Number(d.accel_y || 0),

    accel_z: Number(d.accel_z || 0),

    stress_score:
      Math.max(
        0,
        Math.min(
          100,
          Number(d.stress_score || 0)
        )
      ),

    stress_level:
      d.stress_level || "UNKNOWN"
  }
}];

18. Google Sheets database

Create a spreadsheet:

AI_Stress_Monitor

Sheet:

SensorData

Columns:

Timestamp
Device ID
Heart Rate
SpO2
GSR
Temperature
Accel X
Accel Y
Accel Z
Stress Score
Stress Level
AI Analysis
Alert Sent

Then n8n:

Normalize
    │
    ▼
Google Sheets
    │
    └── Append Row

Example row:

Timestamp HR SpO₂ GSR Temp Score Level
2026-10-01 22:10 94 98 2450 36.8 67 HIGH

This gives you a simple historical dataset for later machine-learning experimentation.


19. ThingSpeak integration

ThingSpeak is particularly useful for time-series IoT visualization.

Create a channel:

AI Stress Monitor

Use fields such as:

Field 1 = Heart Rate
Field 2 = SpO2
Field 3 = GSR
Field 4 = Temperature
Field 5 = Stress Score
Field 6 = Activity

ThingSpeak supports channel data updates through its API. thingspeak.readthedocs.io+1

The n8n HTTP Request node can send the update.

Conceptually:

GET/POST
https://api.thingspeak.com/update

api_key = YOUR_WRITE_API_KEY

field1 = HR
field2 = SpO2
field3 = GSR
field4 = Temperature
field5 = StressScore

Do not expose the ThingSpeak write API key in a public webpage.


20. ThingSpeak flow

             ESP32
                │
                ▼
               n8n
                │
       ┌────────┴────────┐
       │                 │
       ▼                 ▼
Google Sheets       ThingSpeak
       │                 │
       │                 ▼
       │             Time-series
       │               graphs
       │
       ▼
Historical dataset

21. AI Agent architecture

The AI agent should not directly decide that somebody has a mental-health disorder.

Instead, give the agent a constrained task:

Analyze physiological trends and generate a wellness-oriented interpretation. Do not diagnose medical or psychiatric conditions. Identify whether the sensor pattern is stable, changing, or potentially concerning, and recommend appropriate non-diagnostic actions.

Input:

{
  "heart_rate": 94,
  "spo2": 98,
  "gsr": 2450,
  "temperature": 36.8,
  "stress_score": 67,
  "stress_level": "HIGH",
  "duration_minutes": 12
}

22. AI agent system prompt

Use a prompt along these lines:

You are a wellness-monitoring analysis agent.

Your task is to interpret sensor measurements from an
experimental ESP32 physiological monitoring device.

You must NOT diagnose:
- anxiety
- depression
- panic disorder
- cardiovascular disease
- psychiatric illness
- or any other medical condition.

Treat the stress score as an experimental signal.

Analyze:
1. Current stress score
2. Heart-rate trend
3. GSR trend
4. Temperature
5. Activity
6. Duration of elevated readings
7. Sensor quality

Return JSON only:

{
  "state": "LOW|ELEVATED|HIGH|VERY_HIGH|UNKNOWN",
  "trend": "IMPROVING|STABLE|WORSENING|UNKNOWN",
  "confidence": 0-1,
  "summary": "...",
  "recommended_action": "...",
  "send_alert": true/false,
  "voice_alert": true/false
}

Never claim that sensor data proves a mental-health condition.

If sensor quality is poor, state that the result is unreliable.

23. Why an AI agent is useful

Without AI:

Stress Score = 72
→ Send alert

With an agent:

Stress Score = 72
        │
        ▼
Look at previous readings
        │
        ▼
HR rising?
        │
        ▼
GSR rising?
        │
        ▼
User stationary?
        │
        ▼
Duration > threshold?
        │
        ▼
Sensor quality acceptable?
        │
        ▼
Generate contextual explanation

This helps prevent unnecessary notifications.


24. Example AI result

{
  "state": "HIGH",
  "trend": "WORSENING",
  "confidence": 0.82,
  "summary": "The experimental stress indicator has remained elevated for approximately 10 minutes, with increased heart rate and GSR relative to the user's baseline.",
  "recommended_action": "Consider pausing activity, sitting comfortably, and using a brief breathing or relaxation exercise. If the person feels unwell or has concerning symptoms, seek appropriate human or medical assistance.",
  "send_alert": true,
  "voice_alert": true
}

25. Alert decision system

Do not send a Telegram message every 10 seconds.

Otherwise:

10 sec → Alert
20 sec → Alert
30 sec → Alert
40 sec → Alert
...

The user will quickly ignore the system.

Instead use state transitions.

LOW
 │
 ▼
ELEVATED
 │
 ▼
HIGH
 │
 ▼
VERY HIGH

Alert only when:

HIGH persists for > 2–5 minutes

or:

LOW → VERY HIGH

or:

Repeated high readings

26. Alert state machine

                  ┌─────────────┐
                  │    LOW      │
                  └──────┬──────┘
                         │
                  score > 30
                         │
                         ▼
                  ┌─────────────┐
                  │  ELEVATED   │
                  └──────┬──────┘
                         │
                  score > 60
                         │
                         ▼
                  ┌─────────────┐
                  │    HIGH     │
                  └──────┬──────┘
                         │
                 sustained
                         │
                         ▼
                  ┌─────────────┐
                  │ VERY HIGH   │
                  └──────┬──────┘
                         │
                         ▼
                 Telegram Voice

27. Telegram integration

Create a Telegram bot using BotFather and obtain:

BOT_TOKEN

Then obtain:

CHAT_ID

n8n can use Telegram to send text notifications.

Example:

🚨 Stress Monitoring Alert

Device: ESP32_STRESS_001

Stress indicator: HIGH
Score: 72/100

Heart Rate: 96 BPM
SpO2: 98%
GSR: Elevated

The system has detected a sustained change
relative to the user's baseline.

Please check the user and sensor placement.

28. Telegram voice alerts

The Telegram Bot API supports sendVoice; for a true Telegram voice message, the audio should be OGG/Opus. Blogfork

The workflow becomes:

AI Agent
    │
    ▼
Generate alert text
    │
    ▼
Text-to-Speech
    │
    ▼
OGG/Opus audio
    │
    ▼
Telegram sendVoice
    │
    ▼
User's phone

Example spoken message:

“Stress monitoring alert. The experimental stress indicator has remained elevated. Please check how the person is feeling and verify the sensor placement.”

This is deliberately non-diagnostic.


29. n8n complete workflow

The complete workflow can be designed as:

┌──────────────────────────┐
│ ESP32 POST /stress-data  │
└────────────┬─────────────┘
             │
             ▼
┌──────────────────────────┐
│ Webhook                  │
└────────────┬─────────────┘
             │
             ▼
┌──────────────────────────┐
│ Validate JSON            │
└────────────┬─────────────┘
             │
             ▼
┌──────────────────────────┐
│ Normalize Data           │
└────────────┬─────────────┘
             │
       ┌─────┴──────┐
       │            │
       ▼            ▼
 Google Sheets   ThingSpeak
       │            │
       └─────┬──────┘
             │
             ▼
┌──────────────────────────┐
│ Retrieve recent readings │
└────────────┬─────────────┘
             │
             ▼
┌──────────────────────────┐
│ AI Agent                 │
│                          │
│ Trend analysis           │
│ Context analysis         │
│ Alert decision           │
└────────────┬─────────────┘
             │
             ▼
        ┌───────────┐
        │ IF alert? │
        └─────┬─────┘
              │
        ┌─────┴─────┐
        │           │
       NO          YES
        │           │
        ▼           ▼
      Finish   Telegram Text
                    │
                    ▼
               ┌────────────┐
               │ Voice?     │
               └─────┬──────┘
                     │
                     ▼
                 TTS Engine
                     │
                     ▼
                Telegram
                sendVoice

30. Telegram conversation / chat design

The system can also accept commands.

User

/status

Bot

📊 Current Monitoring Status

Device: ESP32_STRESS_001

❤️ HR: 82 BPM
🫁 SpO2: 98%
⚡ GSR: 1920
🌡 Temperature: 36.6°C

Experimental stress score: 34/100
State: ELEVATED

Trend: Stable

Last update: 22:18

User

/report

Bot

📈 Daily Wellness Report

Monitoring duration: 8h 12m

Average HR: 76 BPM
Average SpO2: 98%
Average stress indicator: 31/100

Elevated periods: 4

Longest elevated period:
18 minutes

Note:
These measurements are experimental physiological
signals and are not a medical diagnosis.

User

/history

Bot:

Recent measurements:

22:01  LOW       21
22:03  LOW       24
22:05  ELEVATED  39
22:07  ELEVATED  45
22:09  HIGH      68
22:11  HIGH      72
22:13  HIGH      75

31. ESP32 web dashboard

The ESP32 itself can host:

http://ESP32_IP_ADDRESS/

Example:

┌───────────────────────────────────────────────┐
│        AI STRESS MONITOR                     │
├───────────────────────────────────────────────┤
│                                               │
│ ❤️ Heart Rate          82 BPM                │
│                                               │
│ 🫁 SpO₂                 98 %                 │
│                                               │
│ ⚡ GSR                 1,920                 │
│                                               │
│ 🌡 Temperature          36.6 °C              │
│                                               │
│ 🧠 Stress Indicator     34 / 100             │
│                                               │
│ STATUS: ELEVATED                             │
│                                               │
├───────────────────────────────────────────────┤
│       LIVE SENSOR DATA                        │
│                                               │
│      HR       /\                              │
│             /    \                            │
│        ____/      \____                       │
│                                               │
└───────────────────────────────────────────────┘

32. Better cloud dashboard architecture

For a more professional version:

                     Internet
                        │
                        ▼
                 ┌─────────────┐
                 │    n8n      │
                 └──────┬──────┘
                        │
              ┌─────────┼─────────┐
              ▼         ▼         ▼
          Sheets    ThingSpeak   Database
              │         │         │
              └─────────┼─────────┘
                        ▼
                  Web Dashboard

The dashboard can show:

  • Current HR

  • Current SpO₂

  • GSR

  • Temperature

  • Stress indicator

  • 1-hour graph

  • 24-hour graph

  • Daily average

  • Alert history

  • Device status


33. Recommended data model

Store every measurement as:

{
  "timestamp": "2026-10-01T22:20:00+05:30",
  "device_id": "ESP32_STRESS_001",

  "physiology": {
    "heart_rate": 82,
    "spo2": 98,
    "temperature": 36.6
  },

  "electrodermal": {
    "gsr": 1920
  },

  "motion": {
    "x": 0.12,
    "y": -0.04,
    "z": 9.72
  },

  "analysis": {
    "stress_score": 34,
    "stress_level": "ELEVATED"
  }
}

This structure makes later AI/ML analysis much easier.


34. Device → cloud communication

ESP32
 │
 │ HTTPS POST
 ▼
n8n
 │
 ├── Google Sheets
 │
 ├── ThingSpeak
 │
 ├── AI Agent
 │
 └── Telegram

For production, prefer HTTPS and authenticated webhooks rather than exposing an unauthenticated endpoint.

n8n supports webhook authentication mechanisms including Basic Auth, Header Auth and JWT, which can be used to protect the endpoint. GitHub


35. Security design

Never hard-code sensitive production credentials into a publicly shared repository.

Avoid:

const char* PASSWORD = "mypassword";
const char* TELEGRAM_TOKEN = "...";
const char* THINGSPEAK_KEY = "...";

in a public GitHub repository.

Instead:

ESP32
 └── n8n webhook secret

n8n
 ├── Telegram credentials
 ├── Google credentials
 ├── ThingSpeak API key
 └── AI API credentials

The ESP32 only needs the minimum information necessary to send telemetry.


36. Recommended n8n credential architecture

n8n Credentials
│
├── Telegram Bot
│
├── Google Sheets
│
├── AI Provider
│
├── TTS Provider
│
└── ThingSpeak API

This keeps secrets away from the ESP32 firmware.


37. Sensor-quality detection

This is an important improvement.

The system should distinguish:

HIGH STRESS

from:

BAD SENSOR CONTACT

For example:

MAX30102 IR signal very low
        │
        ▼
Finger not detected
        │
        ▼
Do NOT generate stress alert

Likewise:

GSR suddenly jumps
        │
        ▼
Movement detected?
        │
        ├── YES → Possible artifact
        │
        └── NO → Potential physiological change

Therefore the AI input should include:

{
  "sensor_quality": {
    "heart_rate": "GOOD",
    "spo2": "GOOD",
    "gsr": "GOOD"
  }
}

38. Motion context

Movement is particularly useful.

Suppose:

HR = 110

If:

Activity = RUNNING

then the reading should not automatically be interpreted as stress.

But:

HR = 110
Activity = RESTING
GSR = rapidly increasing

is a different sensor pattern.

Therefore:

Heart rate
+
GSR
+
Motion
+
Time
+
Baseline

should be considered together.


39. Improved feature vector

For future ML:

Feature 1  = mean HR
Feature 2  = HR standard deviation
Feature 3  = HR change
Feature 4  = mean GSR
Feature 5  = GSR slope
Feature 6  = GSR variance
Feature 7  = temperature
Feature 8  = acceleration
Feature 9  = activity level
Feature 10 = time of day
Feature 11 = sensor quality
Feature 12 = baseline deviation

Then:

Feature Vector
       │
       ▼
Machine Learning Model
       │
       ▼
Stress-related classification

40. Future machine-learning version

Once enough consented, appropriately anonymized data has been collected:

ESP32
  │
  ▼
Google Sheets / Database
  │
  ▼
Data Cleaning
  │
  ▼
Feature Engineering
  │
  ▼
Training Dataset
  │
  ▼
ML Model
  │
  ├── Random Forest
  ├── XGBoost
  ├── SVM
  └── Neural Network
  │
  ▼
Stress-related prediction

Do not label the training data as medical diagnoses unless you have an appropriate validated clinical protocol and expert oversight.


41. Complete project flowchart

                         START
                           │
                           ▼
                   Initialize ESP32
                           │
                           ▼
                    Initialize Wi-Fi
                           │
                           ▼
                    Initialize Sensors
                           │
                           ▼
                 Sensor Calibration
                           │
                           ▼
                    Establish Baseline
                           │
                           ▼
                 ┌──────────────────┐
                 │ Read sensor data │
                 └────────┬─────────┘
                          │
                          ▼
                    Filter signals
                          │
                          ▼
                  Check sensor quality
                          │
                          ▼
                  Calculate features
                          │
                          ▼
                   Calculate score
                          │
                          ▼
                    Classify state
                          │
                          ▼
                    Create JSON
                          │
                          ▼
                  Send HTTPS → n8n
                          │
                          ▼
                    Validate data
                          │
                          ▼
                 Store Google Sheets
                          │
                          ▼
                  Update ThingSpeak
                          │
                          ▼
                    AI Agent analysis
                          │
                          ▼
                    Alert required?
                     /          \
                   NO            YES
                   │              │
                   ▼              ▼
                 Finish       Telegram text
                                  │
                                  ▼
                             Voice required?
                              /          \
                            NO            YES
                            │              │
                            ▼              ▼
                          Finish          TTS
                                           │
                                           ▼
                                      OGG/Opus
                                           │
                                           ▼
                                     Telegram Voice
                                           │
                                           ▼
                                         Finish

42. Physical system diagram

              ┌─────────────────────────┐
              │       HUMAN USER        │
              └────────────┬────────────┘
                           │
              physiological signals
                           │
       ┌───────────────────┼───────────────────┐
       │                   │                   │
       ▼                   ▼                   ▼
   MAX30102              GSR              Temperature
 HR / SpO2            conductance           sensor
       │                   │                   │
       └───────────────────┼───────────────────┘
                           │
                           ▼
                    ┌────────────┐
                    │   ESP32    │
                    │            │
                    │ Processing │
                    │ Web server │
                    │ Wi-Fi      │
                    └─────┬──────┘
                          │
                       HTTPS
                          │
                          ▼
                    ┌────────────┐
                    │    n8n     │
                    └─────┬──────┘
                          │
         ┌────────────────┼────────────────┐
         │                │                │
         ▼                ▼                ▼
    Google Sheets     ThingSpeak       AI Agent
                                           │
                                           ▼
                                       Decision
                                           │
                                           ▼
                                      Telegram
                                       /      \
                                    Text       Voice

43. Example n8n node list

Your workflow can contain approximately:

1. Webhook
2. Validate Data
3. Code – Normalize
4. Google Sheets – Append
5. HTTP Request – ThingSpeak
6. Data Store / database – Recent readings
7. Code – Calculate trend
8. AI Agent
9. IF – Alert required?
10. Telegram – Send Message
11. IF – Voice required?
12. TTS HTTP Request
13. Telegram – Send Voice
14. Respond to Webhook

n8n's HTTP Request node is intended for REST API integrations, while the Webhook node can serve as the external trigger. GitHub+1


44. Example trend calculation in n8n

Suppose recent scores are:

25
29
31
35
42
49
57
65

The trend is:

WORSENING

If:

72
68
61
54
43
37
31

then:

IMPROVING

Simple Code node:

const scores = $json.recent_scores || [];

if (scores.length < 3) {
  return [{
    json: {
      trend: "UNKNOWN"
    }
  }];
}

const first = scores[0];
const last = scores[scores.length - 1];

let trend = "STABLE";

if (last - first > 10) {
  trend = "WORSENING";
}
else if (first - last > 10) {
  trend = "IMPROVING";
}

return [{
  json: {
    trend,
    first_score: first,
    last_score: last
  }
}];

45. Alert suppression

Implement a cooldown:

Alert sent
   │
   ▼
Start 15-minute cooldown
   │
   ▼
Additional high readings
   │
   ▼
No duplicate notification

Then:

After cooldown
      │
      ▼
Is condition still high?
   /          \
 NO            YES
 │              │
 ▼              ▼
Reset       New alert

This makes the system much more usable.


46. Emergency/SOS button

Add a physical button:

ESP32 GPIO27
      │
      ▼
SOS button

When pressed:

Button press
    │
    ▼
ESP32
    │
    ▼
n8n
    │
    ▼
Telegram

Example:

🚨 MANUAL ASSISTANCE REQUEST

The physical assistance button on
ESP32_STRESS_001 was pressed.

Please check on the user directly.

This notification was manually triggered
and is not a medical diagnosis.

This is preferable to having an AI independently declare that someone is in an emergency.


47. Telegram voice architecture

                AI Agent
                   │
                   ▼
        "Generate notification"
                   │
                   ▼
             Text message
                   │
                   ▼
              TTS service
                   │
                   ▼
             OGG/Opus file
                   │
                   ▼
           Telegram sendVoice
                   │
                   ▼
                Phone
                   │
                   ▼
              Voice alert

Telegram documents sendVoice for voice messages and specifies OGG/Opus for that presentation mode. Blogfork


48. Example alert levels

Condition Action
Low Store data
Elevated Store + dashboard
High briefly Store + optional Telegram
High sustained Telegram text
Very high sustained Text + voice
Poor sensor quality Request sensor adjustment
Manual SOS Immediate Telegram
Device offline Device-health alert

49. Device-offline monitoring

Another useful n8n workflow:

Schedule Trigger
       │
       ▼
Check latest ESP32 timestamp
       │
       ▼
Last seen > 5 minutes?
      / \
    NO   YES
    │     │
    ▼     ▼
 Finish  Telegram
          │
          ▼
      "ESP32 offline"

This is important because:

No data ≠ Low stress

A missing sensor must never be interpreted as a normal condition.


50. Daily AI report

Run an n8n Schedule Trigger every evening:

Schedule
   │
   ▼
Retrieve today's data
   │
   ▼
Calculate:
- average HR
- maximum HR
- average GSR
- stress-indicator periods
- sensor quality
- device uptime
   │
   ▼
AI Agent
   │
   ▼
Generate summary
   │
   ▼
Google Sheets
   │
   ▼
Telegram

Example:

📊 Daily Monitoring Summary

Monitoring time: 8h 42m

Average HR: 76 BPM
Average SpO2: 98%
Average temperature: 36.6°C

Experimental stress-indicator average:
32/100

Elevated periods: 3
Longest period: 14 minutes

Overall trend:
Mostly stable with several short elevated periods.

This report is based on sensor measurements and
does not constitute a medical assessment.

51. Project folder structure

I recommend organizing the project like this:

AI-Stress-Monitor/
│
├── ESP32/
│   ├── stress_monitor.ino
│   ├── config.h
│   ├── sensors.h
│   └── web_dashboard.h
│
├── n8n/
│   ├── stress-monitor-workflow.json
│   ├── ai-agent-prompt.txt
│   └── telegram-workflow.json
│
├── dashboard/
│   ├── index.html
│   ├── style.css
│   └── app.js
│
├── documentation/
│   ├── architecture.md
│   ├── wiring.md
│   ├── installation.md
│   └── testing.md
│
├── data/
│   └── sample_sensor_data.csv
│
└── README.md

52. Testing procedure

Test 1 — ESP32

Check serial monitor:

WiFi connected
IP: 192.168.x.x
MAX30102 OK
MPU6050 OK
DS18B20 OK
Web server started

Test 2 — Web dashboard

Open:

http://ESP32-IP/

Verify:

HR
SpO2
GSR
Temperature
Stress score
Stress state

Test 3 — n8n

Send a test JSON:

{
  "device_id": "TEST001",
  "heart_rate": 85,
  "spo2": 98,
  "gsr": 2000,
  "temperature": 36.6,
  "stress_score": 42,
  "stress_level": "ELEVATED"
}

Verify:

Webhook
 ↓
Validation
 ↓
Google Sheets
 ↓
ThingSpeak
 ↓
AI

53. Test Telegram

Use:

/test

Expected:

Telegram Bot → test notification

Then test voice:

/testvoice

Expected:

TTS
 ↓
OGG/Opus
 ↓
Telegram
 ↓
Voice message

54. Test high-stress simulation

Do not intentionally create unsafe physiological conditions to test the system.

Instead, inject simulated JSON:

{
  "device_id": "SIMULATOR",
  "heart_rate": 105,
  "spo2": 98,
  "gsr": 3200,
  "temperature": 36.8,
  "stress_score": 78,
  "stress_level": "HIGH"
}

Then verify:

AI Agent
    ↓
HIGH
    ↓
Telegram
    ↓
Voice

55. Failure-mode testing

Test these conditions:

Wi-Fi disconnected
n8n unavailable
ThingSpeak unavailable
Telegram unavailable
Google Sheets unavailable
MAX30102 disconnected
GSR disconnected
temperature sensor disconnected
bad sensor contact
ESP32 reboot
power interruption

The system should fail safely.

For example:

n8n unavailable
      │
      ▼
ESP32 continues local monitoring
      │
      ▼
Retry later

56. Important privacy considerations

Physiological data is sensitive.

The system should therefore use:

Authentication
HTTPS
Access control
Minimal data collection
Secure API keys
Limited retention
User consent

Avoid putting personally identifying information into ThingSpeak or Google Sheets unless necessary.

Instead of:

Rahul_Employee_12345

use:

DEVICE_001

and maintain identity mapping separately and securely.


57. Recommended final architecture

For the full project, I would use this architecture:

                         HUMAN
                           │
             ┌─────────────┼─────────────┐
             │             │             │
             ▼             ▼             ▼
          MAX30102        GSR         Temperature
             │             │             │
             └─────────────┼─────────────┘
                           │
                        MPU6050
                           │
                           ▼
                    ┌─────────────┐
                    │    ESP32    │
                    │             │
                    │ Filtering   │
                    │ Baseline    │
                    │ Score       │
                    │ Web Server  │
                    └──────┬──────┘
                           │
                         HTTPS
                           │
                           ▼
                    ┌─────────────┐
                    │     n8n     │
                    │             │
                    │ Automation  │
                    │ AI Agent    │
                    └──────┬──────┘
                           │
          ┌────────────────┼─────────────────┐
          │                │                 │
          ▼                ▼                 ▼
     Google Sheets      ThingSpeak      AI Analysis
          │                │                 │
          │                │                 ▼
          │                │            Alert Decision
          │                │                 │
          │                │          ┌──────┴──────┐
          │                │          ▼             ▼
          │                │       Telegram       TTS
          │                │          │             │
          │                │          │             ▼
          │                │          │       OGG/Opus
          │                │          │             │
          │                │          └──────┬──────┘
          │                │                 ▼
          │                │           Telegram Voice
          │                │
          └────────────────┴───────────────┐
                                           ▼
                                    Cloud Dashboard

58. Final project description for documentation

Project title

AI-Powered IoT Stress Monitoring and Mental-Wellness Assistance System Using ESP32, n8n Automation, AI Agent, Telegram Voice Alerts, Google Sheets and ThingSpeak

Abstract

This project presents an IoT-based physiological monitoring system using an ESP32 microcontroller and multiple sensors to collect heart-rate, SpO₂, electrodermal activity, temperature and motion-related data. The collected measurements are processed locally and transmitted through Wi-Fi to an n8n automation server using a secure webhook.

The n8n workflow acts as the central integration and automation layer. Incoming sensor measurements are validated, normalized, stored in Google Sheets and transmitted to ThingSpeak for time-series visualization. An AI agent analyzes current and recent sensor patterns, compares them with the user's established baseline, identifies changes in the experimental stress indicator, and determines whether a notification should be generated.

When configured alert conditions persist, the workflow sends a Telegram notification. An optional text-to-speech stage generates an OGG/Opus voice message that is delivered through Telegram's voice-message interface. The system also provides an ESP32-hosted web dashboard for local real-time monitoring.

The architecture demonstrates the integration of embedded systems, IoT sensing, cloud automation, AI-assisted data interpretation, time-series visualization, spreadsheet storage and messaging automation in a single application.

The system is intended for educational and wellness-monitoring purposes. Sensor-derived stress indicators should not be interpreted as clinical diagnoses or as a replacement for professional assessment.


59. Main technologies

Hardware:
    ESP32
    MAX30102
    GSR
    MPU6050
    DS18B20
    OLED

Firmware:
    Arduino C++
    Wi-Fi
    HTTP/HTTPS
    JSON
    Web Server

Automation:
    n8n
    Webhook
    HTTP Request
    Google Sheets
    Telegram

AI:
    AI Agent
    Trend analysis
    Baseline comparison
    Structured JSON response

Cloud:
    ThingSpeak
    Google Sheets

Communication:
    REST API
    Telegram Bot API

Interface:
    ESP32 Web Dashboard
    ThingSpeak Dashboard
    Telegram

60. What makes this a strong final-year/major project

The project combines several engineering areas:

Embedded Systems
       +
IoT
       +
Biomedical-style sensing
       +
Signal Processing
       +
AI
       +
Agentic Automation
       +
Cloud
       +
Web Dashboard
       +
Messaging
       +
Data Analytics

The most important design principle is that the ESP32 handles sensing and immediate processing, n8n handles integration/automation, the AI agent handles contextual interpretation, and Telegram provides the human notification channel.

n8n's Webhook and HTTP Request architecture is well suited to this separation because external devices can trigger workflows through webhooks while the HTTP Request node handles REST-based cloud services. GitHub+1

Suggested final demonstration

For your project demonstration, show this sequence:

1. Wear/place sensors
        ↓
2. ESP32 begins collecting data
        ↓
3. Local webpage displays readings
        ↓
4. ESP32 sends JSON to n8n
        ↓
5. n8n stores data in Google Sheets
        ↓
6. n8n updates ThingSpeak
        ↓
7. AI agent analyzes the trend
        ↓
8. Alert condition is simulated safely
        ↓
9. Telegram text arrives
        ↓
10. Telegram voice alert arrives
        ↓
11. ThingSpeak graph updates
        ↓
12. Google Sheets contains historical record

This gives you a complete ESP32 → IoT → n8n → AI Agent → Cloud → Telegram Voice Alert → Dashboard demonstration rather than just a sensor-monitoring project.

## Project Summary **AI Stress Detection & Mental-Wellness Monitoring System** is an IoT-based project combining **ESP32, physiological sensors, AI, n8n automation, Telegram voice alerts, Google Sheets, ThingSpeak, and a web dashboard**. ### Core flow ``` Sensors ↓ ESP32 ↓ Wi-Fi / HTTPS ↓ n8n Webhook ↓ Data Validation & Processing ↓ AI Agent ↓ ┌───────────────┬────────────────┬─────────────────┐ │ Google Sheets │ ThingSpeak │ Telegram Alerts │ │ Data storage │ Cloud graphs │ Text + Voice │ └───────────────┴────────────────┴─────────────────┘ ``` ### Hardware - **ESP32** — main controller - **MAX30102** — heart rate / SpO₂ - **GSR sensor** — electrodermal activity - **MPU6050** — motion/activity - **DS18B20** — temperature - Optional OLED, buzzer, LED and SOS button ### Software - Arduino IDE / C++ - ESP32 Wi-Fi and web server - JSON/HTTP or HTTPS - **n8n** automation - AI Agent - Google Sheets - ThingSpeak - Telegram Bot API - Text-to-speech for voice alerts ### Stress-analysis concept The system combines multiple signals instead of relying on a single heart-rate threshold: ``` Heart Rate + GSR + Temperature + Motion + Personal Baseline ↓ Experimental Stress Score: 0–100 ↓ LOW / ELEVATED / HIGH / VERY HIGH ``` The score is an **experimental wellness indicator**, not a medical diagnosis. ### n8n automation ``` ESP32 ↓ Webhook ↓ Validate JSON ↓ Normalize data ├──────────────→ Google Sheets ├──────────────→ ThingSpeak ↓ AI Agent ↓ Alert Decision ├── Normal → Log only ├── Elevated → Optional text ├── High sustained → Telegram text └── Very high / configured condition → Telegram voice ``` ### Telegram The bot can support: ``` /status /report /history /test ``` and automatically send: ``` 🚨 Monitoring Alert Experimental stress indicator: HIGH Score: 72/100 Heart Rate: 96 BPM SpO₂: 98% Please check the person's condition and verify sensor placement. ``` It can additionally send a **voice notification** through Telegram. ### Dashboards The project has two main monitoring interfaces: 1. **ESP32 Web Dashboard** - Live HR - SpO₂ - GSR - Temperature - Stress score - Status 2. **ThingSpeak** - Historical sensor graphs - Stress-score trends - Time-series visualization ### Safety and reliability Important features include: - Personal baseline calibration - Sensor-quality detection - Motion/context awareness - Alert cooldowns - Device-offline detection - HTTPS/authenticated webhooks - Secure API credentials - Privacy protection - Manual SOS button ### Final project architecture ``` ┌──────────────┐ │ HUMAN │ └──────┬───────┘ │ ┌───────────────┼──────────────┐ ▼ ▼ ▼ MAX30102 GSR Temperature │ │ │ └───────────────┼──────────────┘ ▼ MPU6050 │ ▼ ┌─────────────┐ │ ESP32 │ │ Sensors │ │ Processing │ │ Web Server │ └──────┬──────┘ │ HTTPS ▼ ┌─────────────┐ │ n8n │ │ Automation │ │ AI Agent │ └──────┬──────┘ │ ┌─────────────┼─────────────┐ ▼ ▼ ▼ Google Sheets ThingSpeak Telegram │ Text/Voice ``` **In one sentence:** the project is an **AI-assisted ESP32 IoT monitoring platform that collects physiological signals, analyzes changes relative to a personal baseline, automates cloud storage and visualization through n8n, and provides configurable Telegram text/voice notifications.**

🧠 AI Stress Detection & Mental-Wellness Monitoring — Mind Map

                           ┌──────────────────────────────────┐
                           │  AI STRESS DETECTION &            │
                           │  MENTAL-WELLNESS MONITORING      │
                           └───────────────┬──────────────────┘
                                           │
          ┌────────────────────────────────┼────────────────────────────────┐
          │                                │                                │
          ▼                                ▼                                ▼
   ┌─────────────┐                  ┌─────────────┐                  ┌─────────────┐
   │   HARDWARE  │                  │   ESP32     │                  │   SENSORS   │
   └──────┬──────┘                  └──────┬──────┘                  └──────┬──────┘
          │                                │                                │
          ├── ESP32                        ├── Wi-Fi                        ├── MAX30102
          ├── OLED                         ├── Data processing               │   ├─ HR
          ├── Buzzer                       ├── Baseline                      │   └─ SpO₂
          ├── LED                          ├── Stress score                  │
          └── SOS Button                  ├── Web server                    ├── GSR
                                           └── HTTPS/JSON                    │
                                                                            ├── MPU6050
                                                                            │   └─ Motion
                                                                            │
                                                                            └── DS18B20
                                                                                └─ Temperature


          ┌────────────────────────────────┼────────────────────────────────┐
          │                                │                                │
          ▼                                ▼                                ▼
   ┌─────────────┐                  ┌─────────────┐                  ┌─────────────┐
   │   SIGNAL    │                  │   STRESS    │                  │    n8n      │
   │ PROCESSING  │                  │   ENGINE    │                  │ AUTOMATION  │
   └──────┬──────┘                  └──────┬──────┘                  └──────┬──────┘
          │                                │                                │
          ├── Filtering                    ├── Personal baseline             ├── Webhook
          ├── Noise removal                ├── HR deviation                  ├── Validation
          ├── Sensor quality               ├── GSR deviation                 ├── Normalize
          └── Feature extraction           ├── Temperature                   ├── Google Sheets
                                           ├── Motion/context                ├── ThingSpeak
                                           └── Score 0–100                   ├── AI Agent
                                                                            └── Alert logic


                           ┌──────────────────────────────────┐
                           │           AI AGENT               │
                           └───────────────┬──────────────────┘
                                           │
                         ┌─────────────────┼─────────────────┐
                         │                 │                 │
                         ▼                 ▼                 ▼
                    Trend analysis    Context analysis   Sensor quality
                         │                 │                 │
                         └─────────────────┼─────────────────┘
                                           ▼
                                  ┌──────────────────┐
                                  │ Decision Engine  │
                                  └────────┬─────────┘
                                           │
                       ┌───────────────────┼───────────────────┐
                       ▼                   ▼                   ▼
                     LOW               ELEVATED               HIGH
                       │                   │                   │
                       ▼                   ▼                   ▼
                    Log only          Optional text       Telegram alert
                                                               │
                                                               ▼
                                                          Voice Alert


          ┌────────────────────────────────┼────────────────────────────────┐
          │                                │                                │
          ▼                                ▼                                ▼
   ┌─────────────┐                  ┌─────────────┐                  ┌─────────────┐
   │ GOOGLE      │                  │ THINGSPEAK  │                  │  TELEGRAM   │
   │ SHEETS      │                  │             │                  │             │
   └──────┬──────┘                  └──────┬──────┘                  └──────┬──────┘
          │                                │                                │
          ├── Timestamp                    ├── HR graphs                    ├── Text
          ├── Device ID                    ├── SpO₂ graphs                  ├── Voice
          ├── HR                            ├── GSR graphs                   ├── /status
          ├── SpO₂                          ├── Temperature                  ├── /report
          ├── GSR                           └── Stress score                 └── /history
          ├── Temperature
          └── Stress score


                           ┌──────────────────────────────────┐
                           │          WEB DASHBOARD           │
                           └───────────────┬──────────────────┘
                                           │
                              ┌────────────┼────────────┐
                              ▼            ▼            ▼
                           Live data    Graphs       Status
                              │            │            │
                              ├── HR       ├── HR       ├── LOW
                              ├── SpO₂     ├── GSR      ├── ELEVATED
                              ├── GSR      ├── Temp     ├── HIGH
                              ├── Temp     └── Score    └── VERY HIGH
                              └── Score


                           ┌──────────────────────────────────┐
                           │       SECURITY & SAFETY          │
                           └───────────────┬──────────────────┘
                                           │
                           ┌───────────────┼───────────────┐
                           ▼               ▼               ▼
                        HTTPS         API security      Privacy
                           │               │               │
                           ├── Webhook     ├── Secrets     ├── Consent
                           ├── TLS         ├── Tokens      ├── Minimal data
                           └── Auth        └── Credentials └── Access control


                           ┌──────────────────────────────────┐
                           │       FUTURE DEVELOPMENT         │
                           └───────────────┬──────────────────┘
                                           │
                    ┌──────────────────────┼──────────────────────┐
                    ▼                      ▼                      ▼
               ML model               Mobile app             Advanced AI
                    │                      │                      │
                Random Forest          Notifications          Trend prediction
                XGBoost                Dashboard              Personalization
                Neural Network         History                 Voice assistant

Core project chain

Sensors
   ↓
ESP32
   ↓
Signal Processing
   ↓
Personal Baseline
   ↓
Stress Indicator
   ↓
n8n
   ↓
AI Agent
   ↓
Google Sheets + ThingSpeak
   ↓
Telegram
   ↓
Text / Voice Alert

Note: The stress score is an experimental physiological indicator and should not be presented as a diagnosis of a mental-health condition.

 

AI Solar Air Purifier with Air Quality Prediction

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:

  1. What is the current air quality?

  2. Is the air quality getting worse?

  3. Should the purifier fan speed increase?

  4. Is the solar/battery system operating normally?

  5. Should the user receive an alert?

  6. Should the event be recorded?

  7. 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:

  1. Abstract

  2. Introduction

  3. Problem Statement

  4. Objectives

  5. Existing System

  6. Proposed System

  7. System Architecture

  8. Hardware Requirements

  9. Software Requirements

  10. Circuit/Schematic

  11. ESP32 Firmware Design

  12. Sensor Integration

  13. Solar Power Design

  14. Air Purification Design

  15. IoT Communication

  16. n8n Workflow

  17. AI Prediction Methodology

  18. AI Agent Architecture

  19. Telegram Voice Notification

  20. Google Sheets Integration

  21. ThingSpeak Integration

  22. Web Dashboard

  23. Security

  24. Failure Handling

  25. Testing

  26. Prediction Accuracy

  27. Results

  28. Advantages

  29. Limitations

  30. Future Scope

  31. Conclusion

  32. References

  33. 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.