Tuesday, 6 October 2026

AI Fire Protection System for EV Battery Packs

Absolutely . I can build this as a complete engineering-project document covering the EV battery fire-protection hardware, ESP32 firmware, AI/agent layer, n8n automation, Telegram voice alerts, Google Sheets logging, ThingSpeak dashboard, web interface, schematics, flow diagrams, and testing procedure.

One important design point: because this involves EV lithium-ion battery fire detection and suppression, the ESP32/AI system should be treated as a monitoring and secondary protection system, not the sole safety mechanism. A real EV battery pack needs appropriately rated electrical isolation, BMS protection, thermal barriers, pressure/venting provisions, and a professionally engineered suppression strategy.

AI-Powered IoT Fire Protection System for EV Battery Packs

1. Project title

AI-Powered IoT Fire Protection and Early Warning System for EV Battery Packs using ESP32, n8n, AI Agent, Telegram Voice Alerts, Google Sheets and ThingSpeak

Short title

AI Agentic EV Battery Fire Protection System

Technologies

  • ESP32

  • Temperature sensors

  • Smoke/gas detection

  • Flame detection

  • Battery voltage/current monitoring

  • BMS interface

  • Relay/MOSFET control

  • Fire/suppression actuator

  • Wi-Fi

  • MQTT/HTTP

  • n8n

  • AI Agent

  • Telegram Bot

  • Telegram voice notifications

  • Google Sheets

  • ThingSpeak

  • Web dashboard

  • Cloud database/logging

  • Optional camera/thermal camera


2. Abstract

Lithium-ion batteries used in electric vehicles can experience dangerous thermal events when subjected to overcharging, internal short circuits, mechanical damage, excessive temperature, manufacturing defects, or abnormal electrical conditions.

The proposed project develops an AI-assisted IoT monitoring and emergency-response system for an EV battery pack.

An ESP32 continuously monitors parameters such as:

  • Battery temperature

  • Multiple cell/pack temperatures

  • Pack voltage

  • Charging/discharging current

  • Smoke/gas indication

  • Flame indication

  • Battery state

  • BMS fault information

  • Ambient temperature

  • Optional pressure

  • Optional thermal-camera information

The ESP32 sends measurements to an IoT/cloud layer. n8n acts as the automation/orchestration platform.

When an abnormal condition occurs, the system evaluates the severity and automatically:

  1. Detects the abnormal condition.

  2. Classifies the event.

  3. Sends data to the AI Agent.

  4. Determines the appropriate response workflow.

  5. Activates local safety outputs where appropriate.

  6. Sends a Telegram emergency notification.

  7. Generates a voice alert.

  8. Records the event in Google Sheets.

  9. Updates the ThingSpeak dashboard.

  10. Displays the condition on the local/web dashboard.

  11. Maintains an event history for later analysis.

The objective is to create an agentic IoT safety architecture, where the ESP32 performs deterministic real-time sensing and safety logic while the AI/cloud layer provides higher-level interpretation, notification, logging and decision support.


3. Important safety architecture

Do not design the system so that an AI model has unrestricted authority to activate or deactivate critical battery-safety hardware.

The recommended hierarchy is:

                 ┌──────────────────────────┐
                 │      EV BATTERY PACK     │
                 └────────────┬─────────────┘
                              │
                    Physical Sensors
                              │
                              ▼
                 ┌──────────────────────────┐
                 │          ESP32           │
                 │ Real-Time Safety Logic   │
                 └────────────┬─────────────┘
                              │
               ┌──────────────┴──────────────┐
               │                             │
               ▼                             ▼
       LOCAL SAFETY ACTION             IoT/CLOUD DATA
       (deterministic)                       │
                                             ▼
                                      ┌─────────────┐
                                      │    n8n      │
                                      └──────┬──────┘
                                             │
                             ┌───────────────┼───────────────┐
                             ▼               ▼               ▼
                           AI Agent       Telegram       Google Sheets
                             │               │               │
                             ▼               ▼               ▼
                         Analysis       Voice Alert        Logging
                                             │
                                             ▼
                                      ThingSpeak/Web
                                         Dashboard

Critical principle:

AI recommends and coordinates; independent deterministic safety logic protects the battery.


4. Overall system architecture

                    EV BATTERY PACK
                           │
          ┌────────────────┼────────────────┐
          │                │                │
          ▼                ▼                ▼
     Temperature        Voltage/Current   Smoke/Gas
       Sensors             Sensors          Sensor
          │                │                │
          └────────────────┼────────────────┘
                           │
                           ▼
                    ┌────────────┐
                    │   ESP32    │
                    │ Controller │
                    └─────┬──────┘
                          │
             ┌────────────┼────────────┐
             │            │            │
             ▼            ▼            ▼
          Buzzer        Relay       Emergency
          /LEDs        Output       Shutdown*
                          │
                          ▼
                     Suppression*
                          │
                          │
                    Wi-Fi / MQTT
                          │
                          ▼
                    ┌────────────┐
                    │    n8n     │
                    │ Automation │
                    └─────┬──────┘
                          │
            ┌─────────────┼──────────────┐
            │             │              │
            ▼             ▼              ▼
         AI Agent      Telegram      Google Sheets
            │             │              │
            │             ▼              │
            │        Voice Alert         │
            │                            │
            └──────────────┬─────────────┘
                           │
                           ▼
                     ThingSpeak
                           │
                           ▼
                     Web Dashboard

* These functions require appropriate hardware engineering and should not depend solely on cloud connectivity.


5. Hardware architecture

5.1 Main controller

ESP32

Recommended because it provides:

  • Wi-Fi

  • Bluetooth

  • Multiple GPIOs

  • ADC

  • I²C

  • SPI

  • UART

  • Low-cost development

  • Sufficient processing power for sensor processing

  • MQTT/HTTP support

For a prototype, an ESP32 development board is sufficient.

For an actual automotive product , use an appropriately qualified automotive-grade MCU/control architecture rather than a hobby development board.


6. Sensors

A prototype can use several sensing layers.

Temperature

Possible sensors:

  • DS18B20

  • TMP117

  • thermistors

  • thermocouples with appropriate interface

  • battery-module temperature sensors

For a multi-cell battery pack, temperature should ideally be measured at multiple physically important locations, not just once at the pack exterior.

Example:

       Battery Module
 ┌─────────────────────────┐
 │                         │
 │ T1 ●                 ● T2│
 │                         │
 │       Battery Cells      │
 │                         │
 │ T3 ●                 ● T4│
 │                         │
 └─────────────────────────┘

7. Voltage measurement

The ESP32 should not directly connect a high-voltage EV battery pack to an ESP32 ADC.

Use an appropriately engineered:

  • isolated voltage measurement circuit,

  • dedicated battery monitor IC,

  • BMS communication interface,

  • or other suitably rated measurement subsystem.

For a low-voltage laboratory prototype, an appropriately designed voltage divider can be used, but it must be scaled and protected for the actual voltage.


8. Current measurement

Possible approaches:

  • Hall-effect current sensor

  • isolated current transducer

  • dedicated battery monitor IC

  • BMS current data

Conceptually:

Battery + ───── Current Sensor ───── Load/Charger
                    │
                    ▼
                  ESP32

9. Smoke/gas detection

A prototype can use a suitable gas/smoke sensor.

Possible sensors include:

  • MQ-series sensors

  • dedicated VOC sensors

  • particulate sensors

  • electrochemical sensors

  • application-specific battery off-gas sensors

For a serious EV safety system, generic MQ sensors should not be treated as certified fire-detection equipment.


10. Flame detection

A flame sensor can be included as a secondary indication.

Flame Sensor
     │
     ▼
   ESP32
     │
     ├── Local alarm
     ├── Event generation
     └── Cloud notification

Flame detection should never be the only fire-detection mechanism because thermal runaway can develop before visible flame occurs.


11. Optional thermal camera

A much more advanced version can add:

  • MLX90640

  • FLIR-type thermal camera

  • other thermal imaging module

Architecture:

Thermal Camera
      │
      ▼
 Temperature Matrix
      │
      ▼
 ESP32 / Edge Processor
      │
      ▼
 Hotspot Detection
      │
      ▼
 AI Analysis

This can identify localized thermal hotspots rather than simply monitoring average temperature.


12. Optional pressure sensor

Thermal runaway can produce gases and pressure changes.

A pressure sensor can therefore provide another diagnostic signal.

Temperature
     +
Gas
     +
Pressure
     +
Voltage
     +
Current
     +
BMS Fault
     │
     ▼
Multi-parameter risk evaluation

13. Actuator system

Possible outputs include:

  • buzzer

  • warning LEDs

  • contactor-control interface

  • cooling system

  • ventilation system

  • emergency shutdown interface

  • suppression-system interface

For demonstration purposes:

ESP32 GPIO
    │
    ▼
Driver Circuit
    │
    ▼
MOSFET / Relay
    │
    ▼
Actuator

Never drive a high-power actuator directly from an ESP32 GPIO.


14. Suggested prototype pin architecture

An example—not a universal wiring recommendation:

Device ESP32 interface
DS18B20 temperature GPIO
Smoke/gas sensor ADC
Flame sensor GPIO
Current sensor ADC/I²C
Voltage monitor ADC/isolated interface
OLED I²C
Buzzer GPIO → transistor
Red LED GPIO
Green LED GPIO
Relay/driver GPIO → driver
BMS UART/CAN/RS485 interface
Wi-Fi Built-in

The exact GPIO assignments should be selected based on the specific ESP32 board and peripherals.


15. Local safety -state machine

Rather than simply using:

Temperature > X → FIRE

use several states.

                 ┌───────────────┐
                 │     NORMAL    │
                 └───────┬───────┘
                         │
                 abnormal parameter
                         │
                         ▼
                 ┌───────────────┐
                 │    WARNING    │
                 └───────┬───────┘
                         │
                persistent abnormality
                         │
                         ▼
                 ┌───────────────┐
                 │     ALERT     │
                 └───────┬───────┘
                         │
              multiple danger indicators
                         │
                         ▼
                 ┌───────────────┐
                 │    CRITICAL   │
                 └───────┬───────┘
                         │
                         ▼
                 ┌───────────────┐
                 │ EMERGENCY     │
                 │ RESPONSE      │
                 └───────────────┘

This prevents a single noisy sensor reading from unnecessarily triggering the highest response.


16. Sensor fusion

The system can calculate a risk score.

For example:

Risk Score =
 Temperature Risk
 + Temperature Rate-of-Rise Risk
 + Gas Risk
 + Voltage Anomaly
 + Current Anomaly
 + BMS Fault
 + Thermal Hotspot

Example conceptual classification:

0–20       NORMAL
21–40      WATCH
41–60      WARNING
61–80      HIGH RISK
81–100     CRITICAL

These numbers are illustrative software thresholds, not certified EV fire-safety limits. Real thresholds must be determined from the specific battery chemistry, cell manufacturer specifications, BMS limits, test data and safety engineering.


17 . Temperature rate of rise

Temperature alone is not enough.

For example:

T1 = 32°C
T2 = 34°C
T3 = 38°C
T4 = 44°C

The system should also calculate:

dT/dt = temperature change / time

Example:

40°C → 42°C → 46°C → 52°C

A rapidly increasing temperature may be more concerning than a stable elevated temperature.


18. AI layer

The AI Agent receives structured information rather than raw uncontrolled sensor streams.

Example:

{
  "device": "EV_PACK_01",
  "temperature_max": 47.8,
  "temperature_rate": 1.8,
  "pack_voltage": 51.7,
  "current": 31.4,
  "smoke": false,
  "flame": false,
  "bms_fault": true,
  "risk_score": 67,
  "state": "HIGH_RISK"
}

The AI Agent can produce:

{
  "severity": "HIGH",
  "summary": "Rapid temperature increase with BMS fault detected",
  "recommended_action": "Inspect battery and isolate charging system",
  "notify": true,
  "voice_alert": true
}

Again, the AI should not override deterministic safety interlocks.


19. n8n architecture

The n8n workflow becomes the central automation engine.

ESP32
  │
  │ HTTP/MQTT
  ▼
n8n Webhook
  │
  ▼
Validate Data
  │
  ▼
Calculate/Verify Risk
  │
  ▼
AI Agent
  │
  ├──────────────┐
  │              │
  ▼              ▼
Normal         Critical
  │              │
  ▼              ▼
Google Sheets  Telegram
                 │
                 ▼
             Voice Alert
                 │
                 ▼
            ThingSpeak
                 │
                 ▼
             Dashboard

20. n8n workflow

A practical workflow could contain :

[Webhook]
     │
     ▼
[JSON Validation]
     │
     ▼
[Sensor Data Normalization]
     │
     ▼
[Risk Calculation]
     │
     ▼
[IF: Critical?]
     │
 ┌───┴────┐
 │        │
NO       YES
 │        │
 ▼        ▼
Log      AI Agent
 │        │
 │        ▼
 │    Notification
 │        │
 │   ┌────┴─────┐
 │   ▼          ▼
 │Telegram   Google Sheets
 │   │
 │   ▼
 │Voice Alert
 │
 └──────┬───────
        ▼
   ThingSpeak
        │
        ▼
   Web Dashboard

21. Example n8n JSON data

ESP32 sends:

{
  "device_id": "EVPACK001",
  "temperature_1": 35.4,
  "temperature_2": 36.2,
  "temperature_3": 42.7,
  "temperature_4": 44.1,
  "voltage": 52.4,
  "current": 18.6,
  "smoke": false,
  "flame": false,
  "bms_fault": false,
  "timestamp": "2026-10-07T07:00:00+05:30"
}

22. Google Sheets logging

Recommended spreadsheet columns:

Timestamp Device Tmax dT/dt Voltage Current Smoke Flame BMS Risk AI Status Action
07:00 EV001 36.2 0.2 52.4 18.6 No No OK 12 Normal None
07:05 EV001 43.8 1.2 52.1 22.4 No No Warning 55 Warning Inspect
07:07 EV001 58.4 3.4 51.8 28.1 Yes No Fault 89 Critical Emergency

This gives you a useful historical dataset for later AI/ML analysis.


23. Telegram alert architecture

When the risk becomes critical:

ESP32
  ↓
n8n
  ↓
AI Agent
  ↓
Telegram Bot
  ↓
User's Telegram

Example alert:

🚨 EV BATTERY CRITICAL ALERT
Battery ID: EVPACK001
Maximum temperature: 58.4°C
Temperature rise: 3.4°C/min
Smoke: Detected
BMS: Fault
Risk: CRITICAL
Immediate inspection/isolation required.


24. Telegram voice alert

The n8n workflow can generate a spoken message using a text-to-speech service and send the resulting audio through Telegram.

Conceptually:

AI Agent
   │
   ▼
Generate Alert Text
   │
   ▼
Text-to-Speech
   │
   ▼
Audio File
   │
   ▼
Telegram Bot
   │
   ▼
Voice Notification

Example voice message:

"Critical battery safety alert. Battery pack EVPACK001 has detected rapidly increasing temperature, smoke indication and a BMS fault. Follow the emergency battery isolation procedure."

The exact TTS service can be selected based on your deployment requirements.


25. ThingSpeak architecture

ThingSpeak can be used for visualization.

Example fields:

Field 1 → Temperature
Field 2 → Voltage
Field 3 → Current
Field 4 → Smoke
Field 5 → Flame
Field 6 → Risk Score
Field 7 → Battery State
Field 8 → BMS Status

Dashboard:

┌───────────────────────────────────────────┐
│        EV BATTERY SAFETY DASHBOARD        │
├───────────────────────────────────────────┤
│ Temperature       42.6 °C                 │
│ Voltage           52.4 V                  │
│ Current           18.3 A                  │
│ Risk Score        48                      │
│ Battery State     WARNING                 │
│ Smoke             NORMAL                  │
│ Flame             NORMAL                  │
│ BMS               OK                      │
├───────────────────────────────────────────┤
│ Temperature Graph                         │
│     /\                                     │
│    /  \       /\                           │
│ __/    \_____/  \_____                     │
└───────────────────────────────────────────┘

26. Web dashboard

You can also create your own webpage.

Suggested interface:

=================================================
       AI EV BATTERY SAFETY MONITOR
=================================================

Battery: EVPACK001
Connection: ● ONLINE

┌──────────────┐ ┌──────────────┐
│ Temperature  │ │ Risk Score   │
│   42.7 °C    │ │     48       │
└──────────────┘ └──────────────┘

┌──────────────┐ ┌──────────────┐
│ Voltage      │ │ Current      │
│   52.4 V     │ │   18.6 A     │
└──────────────┘ └──────────────┘

Smoke:       NORMAL
Flame:       NORMAL
BMS:         WARNING

AI STATUS
"Temperature increasing faster than normal.
Recommend battery inspection."

-------------------------------------------------
Temperature History
-------------------------------------------------

Alerts:
07:00  NORMAL
07:05  WARNING
07:07  CRITICAL
=================================================

27. ESP32 software architecture

The ESP32 program should be divided into modules.

main.cpp
│
├── sensors.cpp
├── sensors.h
│
├── battery.cpp
├── battery.h
│
├── safety.cpp
├── safety.h
│
├── wifi.cpp
├── wifi.h
│
├── mqtt.cpp
├── mqtt.h
│
├── webserver.cpp
├── webserver.h
│
└── config.h

28. ESP32 firmware flow

START
  │
  ▼
Initialize GPIO
  │
  ▼
Initialize Sensors
  │
  ▼
Connect Wi-Fi
  │
  ▼
Read Sensors
  │
  ▼
Validate Measurements
  │
  ▼
Calculate:
 Tmax
 dT/dt
 Voltage
 Current
 Risk
  │
  ▼
Determine Safety State
  │
 ┌┴───────────────────────┐
 │                        │
NORMAL                  CRITICAL
 │                        │
 ▼                        ▼
Cloud Update        Local Safety Action
 │                        │
 └──────────┬─────────────┘
            ▼
       Send IoT Data
            │
            ▼
         Repeat

29. Example ESP32 Arduino code

Below is a prototype framework rather than production automotive safety firmware.

#include <WiFi.h>
#include <HTTPClient.h>

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

const char* N8N_URL =
  "https://YOUR-N8N-SERVER/webhook/ev-battery";

#define TEMP_SENSOR_PIN 34
#define SMOKE_PIN       35
#define FLAME_PIN       27

#define RED_LED         25
#define GREEN_LED       26
#define BUZZER          14

float temperature = 0.0;
float voltage = 0.0;
float current = 0.0;

bool smokeDetected = false;
bool flameDetected = false;

String safetyState = "NORMAL";
int riskScore = 0;

void setup() {

  Serial.begin(115200);

  pinMode(SMOKE_PIN, INPUT);
  pinMode(FLAME_PIN, INPUT);

  pinMode(RED_LED, OUTPUT);
  pinMode(GREEN_LED, OUTPUT);
  pinMode(BUZZER, OUTPUT);

  digitalWrite(RED_LED, LOW);
  digitalWrite(GREEN_LED, HIGH);
  digitalWrite(BUZZER, LOW);

  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

  Serial.print("Connecting to WiFi");

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println();
  Serial.println("WiFi connected");
}

float readTemperature() {

  int raw = analogRead(TEMP_SENSOR_PIN);

  // Replace with calibration equation
  float temp = map(raw, 0, 4095, 0, 100);

  return temp;
}

void evaluateSafety() {

  riskScore = 0;

  if (temperature > 40)
    riskScore += 20;

  if (temperature > 50)
    riskScore += 25;

  if (smokeDetected)
    riskScore += 30;

  if (flameDetected)
    riskScore += 50;

  if (riskScore >= 80) {

    safetyState = "CRITICAL";

    digitalWrite(RED_LED, HIGH);
    digitalWrite(GREEN_LED, LOW);
    digitalWrite(BUZZER, HIGH);

  }
  else if (riskScore >= 50) {

    safetyState = "WARNING";

    digitalWrite(RED_LED, HIGH);
    digitalWrite(GREEN_LED, LOW);
    digitalWrite(BUZZER, LOW);

  }
  else {

    safetyState = "NORMAL";

    digitalWrite(RED_LED, LOW);
    digitalWrite(GREEN_LED, HIGH);
    digitalWrite(BUZZER, LOW);
  }
}

void sendData() {

  if (WiFi.status() != WL_CONNECTED)
    return;

  HTTPClient http;

  http.begin(N8N_URL);

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

  String json = "{";

  json += "\"device_id\":\"EVPACK001\",";
  json += "\"temperature\":" + String(temperature) + ",";
  json += "\"voltage\":" + String(voltage) + ",";
  json += "\"current\":" + String(current) + ",";
  json += "\"smoke\":" + String(smokeDetected ? "true" : "false") + ",";
  json += "\"flame\":" + String(flameDetected ? "true" : "false") + ",";
  json += "\"risk\":" + String(riskScore) + ",";
  json += "\"state\":\"" + safetyState + "\"";

  json += "}";

  int responseCode = http.POST(json);

  Serial.print("n8n response: ");
  Serial.println(responseCode);

  http.end();
}

void loop() {

  temperature = readTemperature();

  smokeDetected = digitalRead(SMOKE_PIN);

  flameDetected = !digitalRead(FLAME_PIN);

  evaluateSafety();

  sendData();

  delay(5000);
}

30. Important improvement to the firmware

For a real system, replace the simple logic above with:

Sensor acquisition
       ↓
Sensor validation
       ↓
Filtering
       ↓
Calibration
       ↓
Rate-of-rise calculation
       ↓
BMS data
       ↓
Sensor fusion
       ↓
State machine
       ↓
Local safety response
       ↓
Cloud transmission

Also implement:

  • watchdog timer

  • brownout handling

  • Wi-Fi reconnection

  • MQTT reconnection

  • sensor-failure detection

  • invalid-value detection

  • CRC/checksum where applicable

  • timestamping

  • nonvolatile event storage

  • OTA update security

  • authentication

  • TLS

  • fail-safe outputs


31. n8n AI Agent logic

The AI Agent should receive structured data.

Example prompt:

You are an EV battery monitoring assistant.

Analyze the battery telemetry.

Do not override hardware safety controls.

Classify the condition as:

NORMAL
WARNING
HIGH_RISK
CRITICAL

Consider:

- temperature
- rate of temperature increase
- smoke
- flame
- voltage
- current
- BMS fault
- sensor failures

Return JSON only.

Required format:

{
  "severity": "",
  "summary": "",
  "recommended_action": "",
  "telegram_alert": true,
  "voice_alert": true
}

32. Example AI response

{
  "severity": "CRITICAL",
  "summary": "Rapid temperature increase and smoke indication detected.",
  "recommended_action": "Initiate the predefined emergency battery isolation procedure and evacuate the immediate area according to site safety procedures.",
  "telegram_alert": true,
  "voice_alert": true
}

33. Agentic behavior

The project becomes "agentic" because the AI workflow can coordinate multiple actions.

                  Sensor Event
                       │
                       ▼
                 n8n Workflow
                       │
                       ▼
                    AI Agent
                       │
          ┌────────────┼─────────────┐
          │            │             │
          ▼            ▼             ▼
       Analyze       Notify         Log
          │            │             │
          ▼            ▼             ▼
     Determine      Telegram      Google
      severity        Voice         Sheets
          │
          ▼
     Update Dashboard

The agent can decide whether a notification is:

  • informational

  • warning

  • urgent

  • critical

while deterministic hardware protection remains independent.


34. Example complete emergency flow

Temperature begins increasing
              │
              ▼
ESP32 detects abnormal dT/dt
              │
              ▼
Additional sensors checked
              │
              ▼
BMS reports abnormal condition
              │
              ▼
Risk state = HIGH
              │
              ▼
ESP32 sends event
              │
              ▼
             n8n
              │
              ▼
           AI Agent
              │
              ▼
"Potential thermal event"
              │
       ┌──────┼──────────┐
       ▼      ▼          ▼
   Telegram  Sheets   ThingSpeak
       │
       ▼
 Voice Alert

If the local deterministic protection logic identifies a critical hardware condition, it can independently execute the pre-engineered local response without waiting for n8n.


35. Communication architecture

Recommended:

ESP32
 │
 ├── Wi-Fi
 │
 ▼
MQTT / HTTPS
 │
 ▼
n8n
 │
 ├── AI API
 ├── Telegram
 ├── Google Sheets
 └── ThingSpeak

For security:

ESP32
   │
   │ TLS
   ▼
Secure endpoint
   │
   ▼
n8n

Do not expose an unauthenticated ESP32 webhook to the public internet.


36. Local web server

The ESP32 can also host a basic local webpage.

Example:

server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {

  String html = "<html>";

  html += "<h1>EV Battery Monitor</h1>";

  html += "<p>Temperature: ";
  html += temperature;
  html += " C</p>";

  html += "<p>Risk Score: ";
  html += riskScore;
  html += "</p>";

  html += "<p>State: ";
  html += safetyState;
  html += "</p>";

  html += "</html>";

  request->send(200, "text/html", html);
});

For a more advanced dashboard, use a separate web application connected to your backend/cloud data.


37. Hardware schematic – conceptual

                         EV BATTERY PACK
                    ┌───────────────────────┐
                    │                       │
                    │     Li-ion Cells      │
                    │                       │
                    └──────────┬────────────┘
                               │
                       ┌───────▼────────┐
                       │      BMS       │
                       └───────┬────────┘
                               │
                ┌──────────────┼───────────────┐
                │              │               │
                ▼              ▼               ▼
             Voltage         Current       Temperature
             Monitor         Sensor          Sensors
                │              │               │
                └──────────────┼───────────────┘
                               │
                               ▼
                         ┌───────────┐
                         │   ESP32   │
                         └─────┬─────┘
                               │
              ┌────────────────┼─────────────────┐
              │                │                 │
              ▼                ▼                 ▼
           Buzzer             LEDs          Driver Circuit
                                                │
                                                ▼
                                             Actuator
                              
                         Wi-Fi
                           │
                           ▼
                         n8n

38. Power architecture

The ESP32 should not normally be powered directly from the raw EV traction battery.

Use an appropriately rated power architecture:

EV Battery
    │
    ▼
Protected DC/DC
    │
    ▼
Regulated Low Voltage
    │
    ▼
ESP32 + Sensors

Include appropriate:

  • fusing

  • transient protection

  • reverse-polarity protection

  • overvoltage protection

  • isolation where necessary

  • grounding strategy


39. Recommended prototype enclosure

For a demonstration:

┌────────────────────────────────────┐
│        EV BATTERY SAFETY BOX       │
│                                    │
│  [Temperature Sensors]             │
│                                    │
│  [Gas/Smoke Sensor]                │
│                                    │
│  [ESP32]                            │
│                                    │
│  [Buzzer]       [LED Indicators]   │
│                                    │
│  [Display]                          │
│                                    │
│  Wi-Fi → Cloud                      │
└────────────────────────────────────┘

For actual battery testing, the enclosure and test environment need appropriate fire-safety engineering and laboratory controls.


40. State indicators

A simple three-color system:

🟢 GREEN
NORMAL

🟡 YELLOW
WARNING

🔴 RED
CRITICAL

Example:

State Meaning
Green Normal
Yellow Abnormal condition
Orange High risk
Red Critical
Flashing red Emergency event

41. Notification hierarchy

Instead of sending every sensor reading to Telegram:

NORMAL
   │
   └── Dashboard/log only

WARNING
   │
   └── Telegram text

HIGH RISK
   │
   ├── Telegram text
   └── Dashboard warning

CRITICAL
   │
   ├── Telegram text
   ├── Telegram voice
   ├── Google Sheets event
   ├── Dashboard alarm
   └── Local alarm

This prevents notification fatigue.


42. Failure scenario

Suppose:

Temperature = 61°C
dT/dt = rapidly increasing
Smoke = detected
BMS = fault
Flame = not detected

The system should not say:

"No flame, therefore everything is safe."

Instead:

Multiple abnormal indicators
          │
          ▼
Potential thermal event
          │
          ▼
CRITICAL

43. Sensor failure handling

A very important feature is distinguishing:

NORMAL

from:

SENSOR FAILURE

Example:

Temperature sensor = -127°C

should not be interpreted as:

Battery extremely cold

It should become:

TEMPERATURE SENSOR FAULT

Likewise:

No sensor response
Out-of-range value
Frozen value
Impossible voltage
Impossible current

should generate diagnostic faults.


44. Cybersecurity

Because the system is internet-connected, include:

  • HTTPS/TLS

  • authenticated MQTT

  • secure credentials

  • API keys stored securely

  • n8n authentication

  • Telegram bot token protection

  • no hard-coded production secrets

  • OTA firmware authentication

  • firewall/VPN where appropriate

  • rate limiting

  • event audit logs

Never place something like this in published firmware:

const char* PASSWORD = "mypassword";

Use secure configuration mechanisms instead.


45. Complete project flowchart

                 START
                   │
                   ▼
            Initialize ESP32
                   │
                   ▼
             Initialize Sensors
                   │
                   ▼
               Wi-Fi Connect
                   │
                   ▼
             Read Battery Data
                   │
                   ▼
            Validate Sensor Data
                   │
             ┌─────┴──────┐
             │            │
          Invalid        Valid
             │            │
             ▼            ▼
       Sensor Fault    Calculate
                         Risk
                          │
                          ▼
                    Safety State
                          │
          ┌───────────────┼───────────────┐
          │               │               │
        NORMAL          WARNING        CRITICAL
          │               │               │
          ▼               ▼               ▼
       Log Data       Alert User      Local Alarm
          │               │               │
          └───────────────┼───────────────┘
                          │
                          ▼
                         n8n
                          │
                          ▼
                       AI Agent
                          │
             ┌────────────┼─────────────┐
             ▼            ▼             ▼
         Telegram      Sheets       ThingSpeak
             │
             ▼
        Voice Alert
             │
             ▼
          Dashboard
             │
             ▼
           Repeat

46. n8n detailed workflow

A production-style workflow can be organized into subflows:

Workflow 1 – Data ingestion

Webhook
 ↓
Authentication
 ↓
JSON validation
 ↓
Normalize data
 ↓
Store telemetry

Workflow 2 – Risk analysis

Telemetry
 ↓
Threshold check
 ↓
Rate-of-rise check
 ↓
BMS status
 ↓
AI Agent
 ↓
Risk classification

Workflow 3 – Emergency notification

Critical Event
 ↓
Create alert
 ↓
Telegram message
 ↓
Text-to-Speech
 ↓
Telegram audio
 ↓
Log event

Workflow 4 – Dashboard

Telemetry
 ↓
ThingSpeak
 ↓
Web dashboard

47. Example n8n pseudo-workflow

Webhook
   ↓
Set Device ID
   ↓
Validate JSON
   ↓
Code Node
   ↓
Calculate Risk
   ↓
IF Risk > Threshold
   │
   ├── FALSE → Google Sheets → ThingSpeak
   │
   └── TRUE
         ↓
       AI Agent
         ↓
      Switch Node
         │
    ┌────┼─────┐
    ▼    ▼     ▼
 Warning High Critical
    │    │      │
    ▼    ▼      ▼
 Telegram Telegram Telegram
               +
             TTS
               │
               ▼
        Telegram Voice

48. AI Agent conversation example

System

Battery telemetry received.

AI Agent

I detected an abnormal condition.

Maximum temperature is increasing rapidly.
The BMS has also reported a fault.

Current classification:
HIGH RISK

Notification should be sent to the operator.

Telegram

⚠️ EV BATTERY WARNING

Battery: EVPACK001

Temperature: 48.2°C
Rate: 1.7°C/min
Voltage: 51.8V
Current: 27.4A
Smoke: NO
Flame: NO
BMS: FAULT

Risk: HIGH

Recommended action:
Follow the predefined battery inspection/isolation procedure.

Critical example

🚨 CRITICAL EV BATTERY ALERT

Battery: EVPACK001

Temperature: 61.5°C
Rapid temperature increase detected.
Smoke: YES
BMS: FAULT
Risk: CRITICAL

Follow the site's emergency battery safety procedure immediately.

49. Google Sheets automation

The sheet can become your project database for:

  • experiments

  • faults

  • sensor readings

  • AI decisions

  • notifications

  • maintenance

  • test results

Recommended tabs:

Sheet 1 → Live Data
Sheet 2 → Alerts
Sheet 3 → Sensor Faults
Sheet 4 → AI Analysis
Sheet 5 → Maintenance
Sheet 6 → Test Results

50. AI/ML future expansion

Once sufficient historical data is collected, the system can progress from rule-based detection toward predictive analytics.

Historical Data
       │
       ▼
Google Sheets / Database
       │
       ▼
Data Cleaning
       │
       ▼
Feature Engineering
       │
       ▼
ML Model
       │
       ▼
Anomaly Detection
       │
       ▼
Early Warning

Potential features:

  • temperature

  • temperature gradient

  • temperature rate

  • voltage

  • voltage imbalance

  • current

  • charging state

  • ambient temperature

  • BMS faults

  • cycle count

  • gas indication

  • thermal hotspot


51. Digital-twin concept

An advanced version can create a digital representation:

Physical Battery
       │
       │ telemetry
       ▼
Digital Battery Model
       │
       ├── Temperature
       ├── Voltage
       ├── Current
       ├── SOC
       ├── SOH
       └── Risk

The AI Agent can then reason over the battery's historical and current behavior.


52. Project modules

For an academic/engineering project, divide it into these modules:

Module 1

Battery monitoring

Module 2

Temperature monitoring

Module 3

Smoke/gas detection

Module 4

Flame detection

Module 5

BMS integration

Module 6

ESP32 firmware

Module 7

IoT communication

Module 8

n8n automation

Module 9

AI Agent

Module 10

Telegram notifications

Module 11

Voice alert

Module 12

Google Sheets logging

Module 13

ThingSpeak visualization

Module 14

Web dashboard

Module 15

Safety testing


53. Development stages

Stage 1 – Sensor prototype

Get:

ESP32
+
Temperature
+
Smoke
+
Flame

working locally.

Stage 2 – Battery telemetry

Add:

Voltage
Current
BMS

Stage 3 – Local alarm

Implement:

LED
Buzzer
Safety state machine

Stage 4 – Internet

Implement:

ESP32 → Wi-Fi → n8n

Stage 5 – Automation

Implement:

n8n → Google Sheets
n8n → ThingSpeak

Stage 6 – Telegram

Implement:

n8n → Telegram

Stage 7 – Voice

Implement:

AI → TTS → Telegram Voice

Stage 8 – AI Agent

Implement:

Telemetry → AI → Classification

Stage 9 – Web dashboard

Implement:

Live telemetry
+
alerts
+
AI status

54. Testing procedure

Do not test this by intentionally causing thermal runaway in an ordinary lab environment.

Use safe simulated inputs first.

Test 1 – Normal

Normal temperature
No smoke
No flame
Normal voltage/current

Expected:

GREEN
No Telegram alert
Data logged

Test 2 – Temperature warning

Simulate elevated temperature.

Expected:

WARNING
Telegram warning
Google Sheets entry
Dashboard update

Test 3 – Rapid temperature rise

Use simulated sensor data.

Expected:

HIGH RISK
Telegram alert
AI analysis

Test 4 – Smoke indication

Simulate smoke sensor.

Expected:

HIGH/CRITICAL
Telegram
Dashboard
Log

Test 5 – Multiple faults

Simulate:

Temperature ↑
Smoke = YES
BMS = FAULT

Expected:

CRITICAL
Telegram text
Voice notification
Local alarm
Event logging

55. Fault injection testing

A strong engineering project should deliberately test software faults:

Wi-Fi disconnected
       ↓
ESP32 continues local safety monitoring
n8n unavailable
       ↓
ESP32 continues local protection
AI unavailable
       ↓
Deterministic safety logic continues
Temperature sensor failed
       ↓
Sensor fault state
Telegram unavailable
       ↓
Event retained/logged

This is extremely important.


56. Fail-safe philosophy

The system should satisfy:

Cloud failure ≠ safety failure

and:

AI failure ≠ safety failure

and:

Wi-Fi failure ≠ safety failure

The ESP32/local safety subsystem should continue operating independently.


57. Complete data flow

             PHYSICAL WORLD
                   │
                   ▼
          ┌─────────────────┐
          │ EV Battery Pack │
          └────────┬────────┘
                   │
                   ▼
               Sensors
                   │
                   ▼
              ┌────────┐
              │ ESP32  │
              └───┬────┘
                  │
        ┌─────────┴─────────┐
        │                   │
        ▼                   ▼
 Local Safety          Wi-Fi/TLS
        │                   │
        ▼                   ▼
 Alarm/Actuator           n8n
                            │
               ┌────────────┼────────────┐
               │            │            │
               ▼            ▼            ▼
            AI Agent    Google Sheets  ThingSpeak
               │
               ▼
          Decision/Alert
               │
               ▼
            Telegram
               │
               ▼
          Voice Alert
               │
               ▼
         Operator/User

58. Final project block diagram

                           ┌───────────────────────┐
                           │      EV BATTERY       │
                           │       PACK            │
                           └───────────┬───────────┘
                                       │
                ┌──────────────────────┼──────────────────────┐
                │                      │                      │
                ▼                      ▼                      ▼
          Temperature              Voltage                 Current
           Sensors                Monitor                 Sensor
                │                      │                      │
                └──────────────────────┼──────────────────────┘
                                       │
                       ┌───────────────┼───────────────┐
                       ▼               ▼               ▼
                     Smoke          Flame             BMS
                     Sensor         Sensor          Interface
                       │               │               │
                       └───────────────┼───────────────┘
                                       ▼
                                ┌────────────┐
                                │   ESP32    │
                                │ Controller │
                                └──────┬─────┘
                                       │
                   ┌───────────────────┼────────────────────┐
                   │                   │                    │
                   ▼                   ▼                    ▼
                 Buzzer               LEDs              Local Safety
                                                            Logic
                                                            │
                                                            ▼
                                                         Actuator
                                                           
                                       │
                                      Wi-Fi
                                       │
                                       ▼
                                ┌────────────┐
                                │    n8n     │
                                │ Automation │
                                └──────┬─────┘
                                       │
                    ┌──────────────────┼──────────────────┐
                    │                  │                  │
                    ▼                  ▼                  ▼
                 AI Agent          Telegram         Google Sheets
                    │                  │
                    │                  ▼
                    │            Voice Alert
                    │
                    └──────────────┬──────────────────────
                                   │
                                   ▼
                              ThingSpeak
                                   │
                                   ▼
                              Web Dashboard

59. Suggested final project name

A polished academic/project title would be:

“AI-Powered Agentic IoT-Based Early Fire Detection and Safety Monitoring System for EV Battery Packs Using ESP32, n8n Automation, Telegram Voice Alerts, Google Sheets and ThingSpeak Cloud Dashboard”

A shorter product-style name:

EV-SAFE AI — Agentic IoT Fire Detection and Early Warning System for EV Battery Packs


60. What the final demonstration should look like

Your project demonstration can be:

                   ┌───────────────────────┐
                   │      EV BATTERY       │
                   │       MODEL           │
                   └───────────┬───────────┘
                               │
                 ┌─────────────┼─────────────┐
                 │             │             │
                 ▼             ▼             ▼
             Temperature     Smoke         BMS
                │             │             │
                └─────────────┼─────────────┘
                              ▼
                         ESP32 BOARD
                              │
                              ▼
                             Wi-Fi
                              │
                              ▼
                         n8n Workflow
                              │
                    ┌─────────┼──────────┐
                    ▼         ▼          ▼
                  AI Agent Telegram Google Sheets
                              │
                              ▼
                         Voice Alert
                              │
                              ▼
                         ThingSpeak
                              │
                              ▼
                        Web Dashboard

The operator sees the temperature increasing on the dashboard, the ESP32 identifies the abnormal state, n8n receives the event, the AI Agent classifies it, Google Sheets records it, ThingSpeak plots it, and Telegram sends both a text and voice warning.

That gives you a complete ESP32 + IoT + n8n + AI Agent + Telegram Voice + Google Sheets + ThingSpeak + Web Dashboard project rather than just a temperature-monitoring circuit.

 

Project Summary

Project: AI-Powered IoT Fire Protection and Early Warning System for EV Battery Packs

The system uses an ESP32 to continuously monitor an EV battery pack for abnormal conditions such as:

  • 🌡️ High temperature and rapid temperature rise

  • 🔋 Abnormal voltage/current

  • 💨 Smoke/gas detection

  • 🔥 Flame detection

  • ⚠️ BMS faults

  • Optional thermal-camera/pressure information

System flow

EV Battery Pack
      ↓
Sensors + BMS
      ↓
ESP32
      ↓
Local Safety Logic
      ↓
Wi-Fi / HTTPS / MQTT
      ↓
n8n Automation
      ↓
AI Agent
      ↓
┌────────────┬──────────────┬───────────────┐
│ Telegram   │ Google Sheets│ ThingSpeak    │
│ Text/Voice │ Event Log    │ Cloud Graphs  │
└────────────┴──────────────┴───────────────┘
      ↓
Web Dashboard

Safety concept

The project uses two layers:

  1. Local ESP32 safety layer — real-time deterministic monitoring and alarms.

  2. Cloud/AI layer — analysis, automation, logging, dashboards and notifications.

The AI should not be the sole controller of critical battery protection. Cloud, Wi-Fi or AI failure must not disable local safety functions.

Main software

  • ESP32 Arduino/C++ firmware

  • n8n workflow automation

  • AI Agent for event classification

  • Telegram Bot for notifications

  • Text-to-Speech for voice alerts

  • Google Sheets for historical logging

  • ThingSpeak for telemetry visualization

  • Web dashboard for live status

Example emergency sequence

Temperature rises rapidly
        ↓
ESP32 detects abnormal condition
        ↓
Risk score increases
        ↓
Local alarm activated
        ↓
n8n receives telemetry
        ↓
AI Agent analyzes event
        ↓
CRITICAL classification
        ↓
Telegram text + voice alert
        ↓
Google Sheets event logged
        ↓
ThingSpeak dashboard updated
        ↓
Operator follows emergency procedure

Development stages

  1. Build ESP32 sensor prototype.

  2. Add temperature, voltage and current monitoring.

  3. Integrate BMS information.

  4. Implement local safety state machine.

  5. Connect ESP32 to n8n.

  6. Add Google Sheets logging.

  7. Add ThingSpeak dashboard.

  8. Add Telegram notifications.

  9. Add Telegram voice alerts.

  10. Add AI Agent.

  11. Build web dashboard.

  12. Perform simulated fault-injection and reliability testing.

Important: This architecture is suitable as a prototype/academic project. A real EV battery fire-protection product requires professional electrical, thermal, fire-safety, BMS, enclosure, isolation and automotive safety engineering; generic ESP32 sensors and AI should not be treated as certified life-safety protection.

 

IoT-Enabled Real-Time Solar Energy Monitoring and Environmental Parameter Analysis Using ESP8266 and ThingSpeak Cloud

IoT-Enabled Real-Time Solar Energy Monitoring and Environmental Parameter Analysis Using ESP8266 and ThingSpeak Cloud | IoT-Enabled Real-Time Monitoring and Performance Analysis of Solar PV Systems.

************************************************

🛠️   Do  You  Want  to  Purchase  the  Full  Working  Project  KIT?   ðŸ› ️

Mail Us:                svsembedded@gmail.com

Title  Name  Along  With  You-Tube  Video  Link

🔌 CODE   &   CIRCUIT DIAGRAMS FOR SALE 🔧
💡 Reliable – Affordable – Ready to Use

http://svsembedded.com/                              è               http://www.svskit.com/

m1:            +91 9491535690                           è               M2:            +91 7842358459
We Will Send Working Model Project KIT through   DTDC / India Post / Blue Dart
We Will Provide Project Soft Data through Google Drive
1.       Project Abstract / Synopsis
2.       Project Related Datasheets of Each Component
3.       Project Sample Report / Documentation
4.       Project Kit Circuit / Schematic Diagram
5.       Project Kit Working Software Code
6.       Project Related Software Compilers
7.       Project Related Sample PPT’s
8.       Project Kit Photos & Working Video links
Latest Projects with Year Wise YouTube video Links
216 Projects è https://svsembedded.com/ieee_2026.php
218 Projects è https://svsembedded.com/ieee_2025.php
152 Projects è https://svsembedded.com/ieee_2024.php
133 Projects è https://svsembedded.com/ieee_2023.php
157 Projects è https://svsembedded.com/ieee_2022.php
135 Projects è https://svsembedded.com/ieee_2021.php
151 Projects è https://svsembedded.com/ieee_2020.php
103 Projects è https://svsembedded.com/ieee_2019.php
61 Projects   è https://svsembedded.com/ieee_2018.php
171 Projects è https://svsembedded.com/ieee_2017.php
170 Projects è https://svsembedded.com/ieee_2016.php
67 Projects  è  https://svsembedded.com/ieee_2015.php
55 Projects  è  https://svsembedded.com/ieee_2014.php
43 Projects  è  https://svsembedded.com/ieee_2013.php
*************************************************

1.SolarPulse: An IoT-Enabled Real-Time Solar Energy Performance and Environmental Intelligence System.
2.Real-Time Solar Energy Monitoring Using Arduino Nano, ESP8266 & ThingSpeak Cloud.
3.IoT-Based Solar Energy Monitoring and Environmental Parameter Analysis System.
4.Design and Implementation of an IoT-Enabled Real-Time Solar Energy Monitoring and Environmental Parameter Analysis System.
5.SolarSense: Intelligent IoT-Based Solar Energy and Environmental Monitoring System.
6.A Smart IoT Framework for Real-Time Photovoltaic Energy Monitoring, Environmental Sensing, and Cloud Analytics.
7.SolarIQ: Intelligent IoT-Based Solar Energy Performance and Environmental Analytics System.
8.IoT-Based Solar Energy Monitoring System Using Arduino Nano and ESP8266.
9.Smart Solar Energy Monitoring Using Arduino Nano, ESP8266 and ThingSpeak.
10.SolarVision: An Intelligent IoT Platform for Real-Time Solar Power and Environmental Performance Analysis.
11.Real-Time Solar Panel Monitoring System Using Arduino Nano, ESP8266 and ThingSpeak.
12.An IoT-Based Cloud-Connected Framework for Real-Time Solar Energy Performance and Environmental Monitoring.
13.SolarPulse Intelligence: Real-Time Renewable Energy and Environmental Analytics Using IoT.
14.IoT-Enabled Integrated Monitoring of Solar Energy Generation and Environmental Parameters for Smart Renewable Energy Management.
15.SolarNexus: A Cloud-Connected IoT Architecture for Intelligent Solar Energy Monitoring and Analytics.
16.Solar Energy and Environmental Monitoring Using Arduino Nano, ESP8266 and ThingSpeak Cloud.
17.Development of a Smart IoT Architecture for Solar Energy Generation Monitoring and Environmental Parameter Analytics.
18.SolarPredict: IoT-Based Solar Energy Performance Monitoring and Predictive Environmental Analytics.
19.Smart Solar Power Monitoring System with Real-Time IoT Data Visualization Using ThingSpeak.
20.Cloud-Connected Intelligent Monitoring and Environmental Analysis of Solar Energy Systems Using IoT.
21.SolarGuard: Real-Time IoT-Based Monitoring and Performance Assessment of Photovoltaic Systems.
22.IoT-Based Solar Power Monitoring and Environmental Parameter Analysis Using ESP8266.
23.SunTrack: Smart IoT-Based Solar Energy Monitoring with Real-Time Environmental Analytics.
24.Real-Time Photovoltaic Performance Monitoring Using IoT-Based Sensing and Cloud Analytics.
25.SolarScope: Real-Time IoT Visualization and Analytics for Solar Energy and Environmental Monitoring.
26.Smart Solar Energy Monitoring and Environmental Sensing Using Arduino Nano and ESP8266.
27.An IoT-Driven Solar Energy Monitoring Framework with Real-Time Environmental Sensing and Cloud-Based Visualization.
28.EcoVolt: Smart Solar Energy and Environmental Parameter Monitoring Using IoT.
29.Solar Energy Generation Monitoring and Environmental Data Analytics Using IoT and ThingSpeak.
30.SunMetrics: An IoT-Based Real-Time Solar Energy and Environmental Data Intelligence Platform.
31.Design and Development of a Cloud-Connected IoT System for Solar Energy Assessment and Environmental Intelligence.
32.IoT-Based Real-Time Solar Panel Performance Monitoring and Environmental Condition Analysis.
33.SolarBrain: An Intelligent IoT Platform for Solar Energy and Environmental Data Analytics.
34.Smart Renewable Energy Monitoring Platform with Integrated Solar and Environmental Data Fusion.
35.SolarWatch: Real-Time IoT Monitoring of Solar Energy Generation and Environmental Conditions.
36.A Cloud-Connected IoT Framework for Real-Time Photovoltaic Energy Monitoring and Environmental Analytics.
37.SolarFusion: Multivariate IoT Analytics for Solar Energy and Environmental Performance Assessment.
38.IoT Solar Power Monitoring System Using Arduino Nano, ESP8266 and ThingSpeak.
39.Integrated Solar-Environmental Intelligence System for Real-Time Renewable Energy Assessment.
40.SolarNet: A Cloud-Connected IoT Framework for Real-Time Solar Energy and Environmental Monitoring.
41.Real-Time Solar Power and Environmental Monitoring Using ESP8266 and ThingSpeak Cloud.
42.PhotonTrack: Smart IoT-Based Solar Energy Harvesting and Environmental Parameter Analysis.
43.Context-Aware Photovoltaic Performance Monitoring System Using Distributed IoT Sensing.
44.Smart Solar Monitoring with IoT: Arduino Nano, ESP8266 and ThingSpeak-Based Cloud Analytics.
45.SolarXpert: Intelligent Monitoring and Analytics of Solar Energy Generation Using IoT.
46.Real-Time Solar Energy Monitoring and Environmental Analysis Using IoT and Cloud Computing.
47.EcoPhoton: An Intelligent IoT Framework for Solar Energy Monitoring and Environmental Analytics.
48.Distributed IoT Architecture for Real-Time Solar Energy Monitoring and Environmental Condition Analysis.
49.SunSync: IoT-Based Intelligent Solar Energy Monitoring and Environmental Analytics Platform.
50.Complete IoT Solar Energy Monitoring System Using Arduino Nano, ESP8266 and ThingSpeak.
51.SolarPulse: An IoT-Enabled Real-Time Solar Energy Performance and Environmental Intelligence System.
52.Design and Implementation of an IoT-Enabled Real-Time Solar Energy Monitoring and Environmental Parameter Analysis System.
53.SolarSense: Intelligent IoT-Based Solar Energy and Environmental Monitoring System.
54.A Smart IoT Framework for Real-Time Photovoltaic Energy Monitoring, Environmental Sensing, and Cloud Analytics.
55.SolarIQ: Intelligent IoT-Based Solar Energy Performance and Environmental Analytics System.
56.An IoT-Based Cloud-Connected Framework for Real-Time Solar Energy Performance and Environmental Monitoring.
57.SolarVision: An Intelligent IoT Platform for Real-Time Solar Power and Environmental Performance Analysis.
58.IoT-Enabled Integrated Monitoring of Solar Energy Generation and Environmental Parameters for Smart Renewable Energy Management.
59.SolarNexus: A Cloud-Connected IoT Architecture for Intelligent Solar Energy Monitoring and Analytics.
60.Real-Time Photovoltaic Performance Monitoring Using IoT-Based Sensing and Cloud Analytics.

Monday, 5 October 2026

AI Diabetes Prediction System using Machine Learning

Absolutely. I can structure this as a **complete final-year/engineering project documentation package** for: > **AI-Powered Diabetes Prediction & IoT Health Monitoring System using Machine Learning, ESP32, n8n Agentic Automation, Telegram Voice Alerts, Google Sheets, ThingSpeak, and a Web Dashboard** The system can combine **ML-based diabetes-risk prediction**, **ESP32 IoT sensing**, **cloud visualization**, and an **AI agent that automatically interprets readings and triggers Telegram voice/text alerts**. ## 1\. Project Title **AI-Powered Diabetes Prediction and IoT Health Monitoring System using ESP32, Machine Learning, n8n Agentic Automation, Telegram Voice Alerts, Google Sheets and ThingSpeak** ### Short title **Agentic IoT-Based AI Diabetes Prediction System** --- # 2\. Abstract This project proposes an intelligent healthcare monitoring system that combines **Artificial Intelligence, Machine Learning, Internet of Things (IoT), ESP32, cloud dashboards, and workflow automation** to assist with diabetes-risk monitoring. The ESP32 acts as the IoT controller and collects physiological/environmental information from connected sensors. The collected measurements are transmitted through Wi-Fi to an IoT/cloud platform such as ThingSpeak and can also be forwarded to an automation workflow implemented using n8n. A trained Machine Learning model analyzes relevant health parameters and estimates the user's diabetes-risk category. The n8n automation layer functions as an **agentic orchestration layer**, receiving sensor/prediction data, applying decision logic and optionally an AI model, storing records in Google Sheets, updating cloud services, and sending notifications through Telegram. When a potentially abnormal condition or high-risk prediction is detected, the system can automatically generate a Telegram notification and, where configured, a voice alert. The user can also interact with the system through Telegram. The proposed system therefore creates an end-to-end pipeline: **Sensors → ESP32 → Wi-Fi → Cloud/API → n8n → AI/ML Analysis → Decision → Google Sheets/ThingSpeak → Telegram Alert** > **Important:** A diabetes prediction model should be presented as a **screening/research tool, not a medical diagnostic device**. Actual diagnosis requires appropriate clinical testing and professional medical evaluation. --- # 3\. Main Objectives The project has several objectives: 1. Develop a Machine Learning model capable of estimating diabetes risk from health-related input parameters. 2. Build an ESP32-based IoT monitoring device. 3. Collect sensor/user health data automatically. 4. Send data to a cloud platform. 5. Develop a web-based monitoring dashboard. 6. Integrate n8n for workflow automation. 7. Introduce an AI-agent layer for interpreting incoming information. 8. Store historical measurements in Google Sheets. 9. Visualize time-series data using ThingSpeak. 10. Send Telegram notifications when configurable thresholds/risk conditions are reached. 11. Generate Telegram voice notifications where supported by the selected implementation. 12. Provide an extensible architecture for future healthcare/IoT applications. --- # 4\. Proposed System Architecture ``` ┌──────────────────────────┐ │ USER / PATIENT │ │ Age, BMI, Glucose, etc. │ └────────────┬─────────────┘ │ ▼ ┌──────────────────────────┐ │ ESP32 IoT DEVICE │ │ │ │ Sensors / Display / WiFi │ └────────────┬─────────────┘ │ Wi-Fi / HTTP │ ▼ ┌──────────────────────────┐ │ IoT CLOUD │ │ ThingSpeak │ └────────────┬─────────────┘ │ │ API / Webhook ▼ ┌──────────────────────────┐ │ n8n │ │ Automation Workflow │ └────────────┬─────────────┘ │ ┌──────────────┼──────────────┐ │ │ │ ▼ ▼ ▼ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ ML Model │ │ AI Agent │ │ Validation │ │ Prediction │ │ Reasoning │ │ / Rules │ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ └───────────────┼───────────────┘ ▼ ┌──────────────────────────┐ │ DECISION ENGINE │ │ Normal / Warning / High │ └────────────┬─────────────┘ │ ┌──────────────────┼──────────────────┐ ▼ ▼ ▼ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ Google Sheets│ │ ThingSpeak │ │ Telegram │ │ Data Storage │ │ Dashboard │ │ Notification │ └──────────────┘ └──────────────┘ └──────┬───────┘ │ ▼ ┌──────────────┐ │ Voice Alert │ └──────────────┘ ``` --- # 5\. Overall Data Flow The complete data flow is: ``` START │ ▼ Power ON ESP32 │ ▼ Initialize Sensors │ ▼ Connect to Wi-Fi │ ▼ Read Sensor/User Parameters │ ▼ Validate Data │ ├── Invalid ──► Reject / Retry │ ▼ Send Data │ ├──────────────► ThingSpeak │ └──────────────► n8n Webhook │ ▼ Preprocess Data │ ▼ ML Prediction │ ▼ Risk Classification │ ┌───────────┼───────────┐ ▼ ▼ ▼ LOW MODERATE HIGH │ │ │ ▼ ▼ ▼ Record Record Record │ │ │ └───────────┼───────────┘ ▼ AI Agent Analysis │ ▼ Generate Response │ ┌───────────┼────────────┐ ▼ ▼ ▼ Google Sheets ThingSpeak Telegram │ ▼ Voice Notification ``` --- # 6\. Hardware Requirements A practical prototype can contain: | Component | Purpose | | --- | --- | | ESP32 development board | Main IoT controller | | MAX30102 | Heart-rate / SpO₂ sensing\* | | DS18B20 | Temperature measurement | | OLED display | Local information display | | Push button | User interaction | | Buzzer | Local alarm | | LED | Status indication | | Wi-Fi | Internet communication | | 5 V USB supply | Power | \*Sensor measurements such as SpO₂ and heart rate should not automatically be treated as clinically accurate unless the hardware and measurement procedure have been properly validated. For a diabetes-prediction prototype, some model inputs may not actually be measurable by the ESP32. For example: - Age - BMI - Pregnancies - Blood glucose - Blood pressure - Insulin - Diabetes pedigree information can instead be entered through the web interface or Telegram. This gives the system two input paths: ``` ┌───────────────┐ │ ESP32 Sensors │ └───────┬───────┘ │ ▼ IoT Measurements │ │ ┌──────────────┐ │ │ Web Interface│─────┤ └──────────────┘ │ ▼ Combined Patient Data │ ▼ ML Model ``` --- # 7\. ESP32 Hardware Block Diagram ``` ┌─────────────┐ │ ESP32 │ │ │ │ GPIO/I2C │ └──────┬──────┘ │ ┌────────────────┼────────────────┐ │ │ │ ▼ ▼ ▼ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ MAX30102│ │ DS18B20 │ │ OLED │ │ Sensor │ │ Temp. │ │ Display │ └─────────┘ └─────────┘ └─────────┘ │ │ ▼ Health Data ┌─────────────┐ │ Wi-Fi Router│ └──────┬──────┘ │ Internet │ ▼ Cloud / n8n ``` --- # 8\. Suggested ESP32 Pin Configuration Example configuration: ``` ESP32 │ ├── GPIO 21 → I2C SDA ├── GPIO 22 → I2C SCL │ ├── I2C → MAX30102 ├── I2C → OLED │ ├── GPIO 4 → DS18B20 DATA ├── GPIO 25 → Buzzer ├── GPIO 26 → Status LED └── GPIO 27 → Push Button ``` ### Important I²C devices can share SDA/SCL as long as their I²C addresses do not conflict. Also verify the voltage requirements of every module before connecting it to the ESP32. --- # 9\. Schematic-Level Connection ``` ESP32 ┌───────────────┐ │ │ │ GPIO21 ───────┼──── SDA ─────┐ │ GPIO22 ───────┼──── SCL ─────┤ │ │ │ │ 3V3 ──────────┼──────────────┼───┐ │ GND ──────────┼──────────────┼───┤ │ │ │ │ └───────────────┘ │ │ │ │ ┌────────▼───▼──────┐ │ MAX30102 │ │ │ │ SDA SCL VCC GND │ └───────────────────┘ GPIO4 ───────────── DATA 3V3 ────────────── VCC GND ────────────── GND ┌─────────┐ │ DS18B20 │ └─────────┘ GPIO21 ───────── SDA GPIO22 ───────── SCL 3V3 ──────────── VCC GND ──────────── GND ┌───────┐ │ OLED │ └───────┘ GPIO25 ───────── Buzzer GPIO26 ───────── LED GPIO27 ───────── Push Button ``` For a physical build, include appropriate resistors, decoupling, pull-ups and transistor/driver stages where required by the specific modules. --- # 10\. Software Architecture ``` ┌───────────────────────────────────────────────┐ │ USER INTERFACE │ │ HTML / CSS / JavaScript Web App │ └───────────────────────┬───────────────────────┘ │ ▼ ┌───────────────────────────────────────────────┐ │ API / BACKEND │ │ Python Flask / FastAPI / Node.js │ └───────────────────────┬───────────────────────┘ │ ┌──────────┴──────────┐ ▼ ▼ ┌──────────────┐ ┌──────────────┐ │ ML Prediction│ │ n8n Webhook │ └──────────────┘ └──────┬───────┘ │ ▼ ┌──────────────┐ │ AI Agent │ └──────┬───────┘ │ ┌────────────────┼───────────────┐ ▼ ▼ ▼ Google Sheets ThingSpeak Telegram ``` --- # 11\. Machine Learning Component A commonly used academic dataset for demonstrating diabetes prediction is the **Pima Indians Diabetes Database**. Typical features include: ``` Pregnancies Glucose BloodPressure SkinThickness Insulin BMI DiabetesPedigreeFunction Age ``` Target: ``` Outcome 0 = lower predicted diabetes-risk class 1 = higher predicted diabetes-risk class ``` For an academic project, compare several algorithms rather than assuming one is automatically best: - Logistic Regression - Decision Tree - Random Forest - Support Vector Machine - K-Nearest Neighbors - Gradient Boosting Useful evaluation metrics: ``` Accuracy Precision Recall F1-score ROC-AUC Confusion Matrix ``` For health-related screening, **recall/sensitivity and false-negative behavior are especially important**, so reporting only accuracy would be inadequate. --- # 12\. ML Training Code Example Python implementation: ``` import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.pipeline import Pipeline from sklearn.linear_model import LogisticRegression from sklearn.metrics import ( accuracy_score, precision_score, recall_score, f1_score, roc_auc_score, confusion_matrix ) # Load dataset df = pd.read_csv("diabetes.csv") # Input features X = df.drop("Outcome", axis=1) # Target y = df["Outcome"] # Train/test split X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.20, random_state=42, stratify=y ) # Pipeline model = Pipeline([ ("scaler", StandardScaler()), ("classifier", LogisticRegression(max_iter=1000)) ]) # Train model.fit(X_train, y_train) # Prediction y_pred = model.predict(X_test) y_prob = model.predict_proba(X_test)[:, 1] # Metrics print("Accuracy:", accuracy_score(y_test, y_pred)) print("Precision:", precision_score(y_test, y_pred)) print("Recall:", recall_score(y_test, y_pred)) print("F1:", f1_score(y_test, y_pred)) print("ROC-AUC:", roc_auc_score(y_test, y_prob)) print("Confusion Matrix:") print(confusion_matrix(y_test, y_pred)) ``` --- # 13\. Saving the ML Model ``` import joblib joblib.dump(model, "diabetes_model.pkl") print("Model saved successfully.") ``` The resulting model: ``` diabetes_model.pkl ``` can be loaded by the backend. --- # 14\. Prediction API A simple FastAPI implementation: ``` from fastapi import FastAPI import joblib app = FastAPI() model = joblib.load("diabetes_model.pkl") @app.get("/") def home(): return { "status": "online", "service": "AI Diabetes Prediction API" } @app.post("/predict") def predict(data: dict): features = [[ data["Pregnancies"], data["Glucose"], data["BloodPressure"], data["SkinThickness"], data["Insulin"], data["BMI"], data["DiabetesPedigreeFunction"], data["Age"] ]] prediction = int(model.predict(features)[0]) probability = float( model.predict_proba(features)[0][1] ) if prediction == 1: risk = "HIGH" else: risk = "LOW" return { "prediction": prediction, "risk": risk, "probability": probability } ``` --- # 15\. Webpage The webpage can provide: ``` +--------------------------------------------------+ | AI DIABETES & IoT MONITORING SYSTEM | +--------------------------------------------------+ | | | Patient Information | | | | Age: [ 45 ] | | Glucose: [ 145 ] | | Blood Pressure: [ 85 ] | | BMI: [ 28.5 ] | | | | [ PREDICT DIABETES RISK ] | | | +--------------------------------------------------+ | LIVE IoT DATA | +--------------------------------------------------+ | Heart Rate: 78 BPM | | SpO2: 97 % | | Temperature: 36.7 °C | +--------------------------------------------------+ | AI RESULT | | | | Risk: MODERATE/HIGH | | Probability: XX % | | | +--------------------------------------------------+ | ThingSpeak Graph | | | | /\/\/\/\__/\/\/\/\ | | | +--------------------------------------------------+ ``` --- # 16\. Example HTML ``` AI Diabetes Monitoring

AI Diabetes Prediction



ESP32 Live Monitoring

Heart Rate: --

SpO2: --

Temperature: --

``` --- # 17\. ESP32 Firmware Arduino-style ESP32 example: ``` #include #include const char* ssid = "YOUR_WIFI"; const char* password = "YOUR_PASSWORD"; const char* serverURL = "https://YOUR_SERVER/api/iot"; void setup() { Serial.begin(115200); WiFi.begin(ssid, password); Serial.print("Connecting"); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(); Serial.println("WiFi connected"); } void loop() { float heartRate = 78.0; float spo2 = 97.0; float temperature = 36.7; if (WiFi.status() == WL_CONNECTED) { HTTPClient http; http.begin(serverURL); http.addHeader( "Content-Type", "application/json" ); String json = "{"; json += "\"heartRate\":" + String(heartRate) + ","; json += "\"spo2\":" + String(spo2) + ","; json += "\"temperature\":" + String(temperature); json += "}"; int responseCode = http.POST(json); Serial.print("HTTP Response: "); Serial.println(responseCode); http.end(); } delay(30000); } ``` Replace the example sensor values with actual sensor-library readings after integrating the hardware. --- # 18\. ThingSpeak Integration A useful ThingSpeak channel structure could be: ``` Field 1 → Heart Rate Field 2 → SpO2 Field 3 → Temperature Field 4 → Glucose Field 5 → BMI Field 6 → ML Risk Probability Field 7 → Risk Class ``` Conceptually: ``` ESP32 │ ▼ ThingSpeak API │ ├── Field 1 ── Heart Rate ├── Field 2 ── SpO2 ├── Field 3 ── Temperature ├── Field 4 ── Glucose ├── Field 5 ── BMI ├── Field 6 ── ML Probability └── Field 7 ── Risk ``` The ThingSpeak graph then provides a historical view of measurements. --- # 19\. n8n Automation Architecture The n8n workflow is the central automation layer. ``` ┌─────────────────┐ │ Webhook Trigger │ └────────┬────────┘ │ ▼ ┌─────────────────┐ │ Validate Input │ └────────┬────────┘ │ ▼ ┌─────────────────┐ │ Data Processing │ └────────┬────────┘ │ ▼ ┌─────────────────┐ │ ML Prediction │ └────────┬────────┘ │ ▼ ┌─────────────────┐ │ AI Agent │ │ Interpretation │ └────────┬────────┘ │ ▼ ┌─────────────┐ │ IF / Switch │ └──────┬──────┘ │ ┌──────────┼───────────┐ ▼ ▼ ▼ NORMAL WARNING HIGH │ │ │ ▼ ▼ ▼ Store Store Store │ │ │ └──────────┼───────────┘ ▼ Google Sheets │ ▼ Telegram │ ▼ Voice Alert ``` --- # 20\. Example n8n Workflow Recommended nodes: ``` Webhook ↓ Set / Edit Fields ↓ Code ↓ HTTP Request ↓ AI Agent ↓ Switch ├── LOW ├── MODERATE └── HIGH ↓ Google Sheets ↓ Telegram ↓ Voice generation / audio delivery ``` ### Webhook JSON ESP32/backend can send: ``` { "device_id": "ESP32_001", "heart_rate": 82, "spo2": 97, "temperature": 36.8, "glucose": 142, "bmi": 28.4, "age": 45 } ``` --- # 21\. n8n Code Node Example: ``` const data = $json; const glucose = Number(data.glucose); const bmi = Number(data.bmi); const age = Number(data.age); let status = "NORMAL"; if (glucose >= 200) { status = "HIGH"; } else if (glucose >= 140) { status = "WARNING"; } return [{ json: { ...data, preliminary_status: status, timestamp: new Date().toISOString() } }]; ``` This should be treated as **workflow demonstration logic**, not as a clinical diagnostic threshold engine. --- # 22\. AI Agent Role The AI agent should **not replace the ML model**. Instead: ``` ML Model │ │ numerical prediction ▼ AI Agent │ ├── Interpret result ├── Generate explanation ├── Decide notification wording ├── Summarize recent readings └── Trigger appropriate workflow action ``` This separation is important. ### ML model Answers: > "What does the trained statistical model predict?" ### AI agent Answers: > "How should this information be interpreted and communicated within the automation workflow?" --- # 23\. Example AI Agent Prompt ``` You are an IoT health-monitoring workflow assistant. Your task is to interpret incoming device data and the output of a diabetes-risk machine-learning model. Do not diagnose disease. Do not invent medical measurements. Use only the information supplied by the workflow. Return: 1. Risk category 2. Short explanation 3. Whether a notification should be generated 4. Concise Telegram message If the data appears incomplete or invalid, report that instead of making assumptions. If the ML system reports elevated risk, advise the user to consider appropriate professional medical evaluation rather than claiming that the user has diabetes. ``` --- # 24\. Google Sheets Database Create columns such as: ``` Timestamp Device_ID Age Glucose BloodPressure BMI HeartRate SpO2 Temperature ML_Probability Risk_Class AI_Message Alert_Status ``` Example: | Timestamp | Glucose | BMI | HR | Temp | ML Probability | Risk | | --- | --- | --- | --- | --- | --- | --- | | 08:00 | 120 | 24.5 | 76 | 36.6 | 0.21 | LOW | | 09:00 | 145 | 28.1 | 81 | 36.8 | 0.58 | MODERATE | | 10:00 | 165 | 30.2 | 88 | 37.0 | 0.76 | HIGH | --- # 25\. Telegram Notification Example normal message: ``` 🟢 HEALTH MONITORING UPDATE Device: ESP32_001 Heart Rate: 76 BPM SpO2: 98% Temperature: 36.6°C ML Risk Probability: 21% Status: LOW No automated alert is required. ``` Warning: ``` 🟠 HEALTH MONITORING ALERT The latest measurements produced an elevated ML risk estimate. Please review the recorded measurements and consider appropriate medical follow-up. This system is a screening/monitoring aid and is not a medical diagnosis. ``` High-risk workflow: ``` 🔴 ATTENTION REQUIRED The latest data has produced a high-risk prediction from the configured ML model. Please review the measurements and seek appropriate professional medical advice. This automated message does not constitute a diagnosis. ``` --- # 26\. Telegram Voice Alert The workflow can be: ``` ML Prediction ↓ Risk = HIGH ↓ AI Agent creates message ↓ Text-to-Speech service ↓ Audio file ↓ Telegram Bot ↓ Voice message ``` Example: ``` "Attention. The latest health measurements have produced an elevated risk prediction. Please review your measurements and consider contacting a qualified healthcare professional." ``` The exact text-to-speech implementation can be selected according to the services available in your deployment. --- # 27\. Complete Agentic IoT Workflow ``` ┌──────────────┐ │ ESP32 │ └──────┬───────┘ │ Sensor Measurements │ ▼ ┌──────────────┐ │ Wi-Fi │ └──────┬───────┘ │ ▼ ┌──────────────┐ │ n8n │ │ Webhook │ └──────┬───────┘ │ ▼ ┌──────────────┐ │ Data Validate │ └──────┬───────┘ │ ▼ ┌──────────────┐ │ ML Prediction │ └──────┬───────┘ │ ▼ ┌──────────────┐ │ AI Agent │ └──────┬───────┘ │ ┌────────┴────────┐ │ │ ▼ ▼ Normal/Low Elevated │ │ ▼ ▼ Log Information Generate Alert │ ┌──────────┼──────────┐ ▼ ▼ ▼ Sheet Telegram Voice │ │ │ └──────────┴──────────┘ │ ▼ User Response ``` --- # 28\. Telegram Chat Interface The system can also accept commands: ``` USER /start BOT Welcome to AI Health Monitor. Commands: /status /latest /prediction /history /help ``` ### Example ``` USER: /status BOT: ESP32_001 Heart Rate: 78 BPM SpO2: 97% Temperature: 36.7°C Latest ML Risk: LOW Last update: 10:42 AM ``` Another example: ``` USER: /prediction BOT: Latest prediction: Risk probability: 0.32 Classification: LOW This is an automated ML screening result and is not a medical diagnosis. ``` --- # 29\. Bidirectional Agentic Architecture The more advanced version allows the user to communicate back to the system. ``` ┌──────────────┐ │ USER │ └──────┬───────┘ │ Telegram │ ▼ ┌──────────────┐ │ Telegram Bot │ └──────┬───────┘ │ ▼ ┌──────────────┐ │ n8n │ └──────┬───────┘ │ ▼ ┌───────────┐ │ AI Agent │ └─────┬─────┘ │ ┌──────────┼──────────┐ ▼ ▼ ▼ Status Prediction History │ │ │ └──────────┼──────────┘ ▼ Response │ ▼ Telegram ``` This is what makes the project more **agentic** rather than simply a sensor + alert system. --- # 30\. Data Security Because this involves health-related information, security should be included in the project. Recommended measures: - HTTPS for API communication. - Do not hard-code Telegram bot tokens into publicly shared code. - Store credentials in environment variables or n8n credentials. - Authenticate API requests. - Use device IDs and authentication tokens. - Avoid exposing Google Sheets publicly. - Restrict access to dashboards. - Do not transmit unnecessary personally identifiable information. - Keep logs protected. - Use encrypted communication wherever possible. Example: ``` ESP32 │ │ HTTPS ▼ Authenticated API │ ▼ n8n │ ├── secured credentials ├── ML service ├── Google Sheets └── Telegram ``` --- # 31\. Failure Handling A professional project should demonstrate what happens when something fails. ### Wi-Fi failure ``` ESP32 ↓ Wi-Fi disconnected ↓ Retry connection ↓ Store temporary reading ↓ Reconnect ↓ Upload buffered data ``` ### n8n failure ``` ESP32 ↓ API unavailable ↓ Retry ↓ Log error ↓ Continue local monitoring ``` ### Invalid sensor data ``` Sensor ↓ Invalid reading ↓ Validation ↓ Reject value ↓ Retry sensor ``` ### AI service unavailable ``` ML result available ↓ AI service unavailable ↓ Use predefined safe notification template ↓ Continue logging ``` This is particularly important because **an AI agent should not become a single point of failure**. --- # 32\. Complete Project Flowchart ``` START │ ▼ Initialize ESP32 │ ▼ Initialize Sensors │ ▼ Connect Wi-Fi │ ┌─────┴─────┐ │ Connected?│ └─────┬─────┘ No │ Yes │ │ └───┘ Retry │ ▼ Read Sensors │ ▼ Validate Values │ ┌──────┴──────┐ │ Valid Data? │ └──────┬───────┘ │ Yes │ No │ │ │ Retry ▼ Send IoT Data │ ▼ n8n Webhook │ ▼ Preprocess Data │ ▼ ML Prediction │ ▼ AI Agent │ ▼ Decision Engine │ ┌─────────┼─────────┐ ▼ ▼ ▼ LOW MODERATE HIGH │ │ │ └─────────┼─────────┘ ▼ Google Sheets │ ▼ ThingSpeak │ ▼ Telegram Alert │ ▼ Voice Notification │ ▼ Repeat ``` --- # 33. Recommended Project Folder Structure ``` AI-Diabetes-IoT/ │ ├── README.md │ ├── esp32/ │ ├── esp32_main.ino │ ├── sensors.h │ └── config.h │ ├── ml/ │ ├── diabetes.csv │ ├── train_model.py │ ├── evaluate_model.py │ └── diabetes_model.pkl │ ├── backend/ │ ├── main.py │ ├── requirements.txt │ └── models/ │ ├── web/ │ ├── index.html │ ├── style.css │ └── app.js │ ├── n8n/ │ └── diabetes_iot_workflow.json │ ├── telegram/ │ └── bot_logic.md │ ├── docs/ │ ├── architecture.md │ ├── hardware.md │ ├── software.md │ ├── testing.md │ └── project_report.md │ └── diagrams/ ├── system_architecture.png ├── flowchart.png └── circuit.png ``` --- # 34\. Testing Plan | Test | Input | Expected Result | | --- | --- | --- | | ESP32 boot | Power ON | Device starts | | Wi-Fi | Correct credentials | Connected | | Sensor | Valid measurement | Reading displayed | | API | Valid JSON | HTTP success | | ML | Valid features | Prediction generated | | Invalid input | Missing feature | Validation error | | n8n | Webhook data | Workflow executes | | Google Sheets | Valid record | Row inserted | | ThingSpeak | Valid fields | Graph updated | | Telegram | Alert condition | Message delivered | | Voice | High-risk workflow | Audio notification | | Network loss | Disconnect Wi-Fi | Retry/recovery | --- # 35\. Performance Metrics ### Machine Learning Report: ``` Accuracy Precision Recall F1-score ROC-AUC Confusion Matrix ``` ### IoT Measure: ``` Sensor sampling interval API latency n8n workflow execution time Telegram notification latency Packet loss Wi-Fi reconnection time ``` ### System Measure: ``` End-to-end latency Sensor reading ↓ Cloud ↓ n8n ↓ ML ↓ AI Agent ↓ Telegram Total response time = ______ seconds ``` --- # 36\. Advantages - Combines AI, ML and IoT. - ESP32 provides a low-cost IoT platform. - Automated workflow reduces manual monitoring. - Historical data can be stored automatically. - ThingSpeak provides visualization. - Google Sheets provides simple data analysis/export. - Telegram enables remote notifications. - Voice alerts improve accessibility. - AI-agent architecture allows natural-language interaction. - Modular design allows additional sensors and models. --- # 37\. Limitations A good academic report should explicitly acknowledge: 1. The system is not a medical diagnostic device. 2. ML performance depends heavily on the training dataset. 3. Dataset bias can affect predictions. 4. Consumer sensors may not provide clinically validated measurements. 5. Internet connectivity is required for cloud automation. 6. AI-generated explanations may be imperfect. 7. Threshold-based alerts are not equivalent to clinical decision-making. 8. Personal health data requires careful security and privacy management. --- # 38\. Future Enhancements The system can later be extended with: ``` Continuous glucose monitoring integration ↓ Mobile application ↓ Wearable device ↓ Federated learning ↓ Personalized ML models ↓ Anomaly detection ↓ Long-term trend analysis ↓ Voice-based AI assistant ↓ Multilingual Telegram assistant ↓ Doctor/caregiver dashboard ``` An advanced version could use: ``` ESP32 ↓ MQTT ↓ IoT Broker ↓ n8n ↓ AI Agent ↓ Tool Calling ├── ML prediction ├── Database ├── Google Sheets ├── ThingSpeak └── Telegram ``` --- # 39\. Final System Architecture The strongest version of the project can therefore be presented as: ``` ┌───────────────────┐ │ USER │ └─────────┬─────────┘ │ ┌─────────────┴─────────────┐ │ │ ▼ ▼ Web Dashboard Telegram │ │ │ │ └─────────────┬─────────────┘ ▼ ┌──────────────────┐ │ n8n │ │ Automation Layer │ └────────┬─────────┘ │ ┌─────────────┼──────────────┐ │ │ │ ▼ ▼ ▼ ESP32 IoT ML Model AI Agent │ │ │ │ └──────┬───────┘ │ │ ▼ ▼ Sensor Data Decision │ │ └──────────┬─────────┘ ▼ ┌──────────────┐ │ Cloud Storage│ └──────┬───────┘ │ ┌───────────┴───────────┐ ▼ ▼ Google Sheets ThingSpeak │ ▼ Cloud Dashboard AI Agent │ ┌────────────┴────────────┐ ▼ ▼ Telegram Text Voice Alert ``` ## 40\. Suggested Final Project Name For your **project report, PPT, GitHub repository and viva**, I recommend using one consistent title: > **“AI-Powered IoT-Based Diabetes Risk Prediction and Health Monitoring System Using ESP32, Machine Learning and n8n Agentic Automation with Telegram Voice Alerts”** This title captures the complete project without making the stronger—and medically inappropriate—claim that the system itself diagnoses diabetes. If you are building this as a **college/final-year project**, the documentation can be organized into **Chapter 1: Introduction, Chapter 2: Literature Survey, Chapter 3: Requirements, Chapter 4: System Design, Chapter 5: Hardware Design, Chapter 6: ML Model, Chapter 7: ESP32 Programming, Chapter 8: n8n/AI Agent, Chapter 9: Telegram/Cloud Integration, Chapter 10: Implementation, Chapter 11: Testing & Results, Chapter 12: Conclusion and Future Scope**, followed by references and appendices.

Project Summary

AI-Powered IoT-Based Diabetes Risk Prediction and Health Monitoring System combines Machine Learning, ESP32 IoT, n8n automation, an AI agent, Telegram alerts, Google Sheets, ThingSpeak, and a web dashboard into one automated healthcare-monitoring prototype.

Core workflow

ESP32 Sensors / Web Input
          ↓
       Wi-Fi
          ↓
    ThingSpeak / API
          ↓
        n8n
          ↓
   Data Validation
          ↓
   ML Diabetes-Risk Model
          ↓
       AI Agent
          ↓
   Decision / Risk Level
     ↙      ↓       ↘
  Normal  Warning    High
     ↓      ↓         ↓
     └──────┼─────────┘
            ↓
      Google Sheets
            +
       ThingSpeak
            +
        Telegram
            ↓
       Voice Alert

Main components

  • ESP32: collects IoT measurements and communicates over Wi-Fi.

  • Machine Learning: predicts diabetes risk from features such as glucose, BMI, age, blood pressure, etc.

  • Web application: allows users to enter patient/model inputs and view IoT data.

  • n8n: coordinates the complete automation workflow.

  • AI Agent: interprets ML results and generates appropriate responses/notifications.

  • ThingSpeak: provides cloud-based IoT visualization and historical graphs.

  • Google Sheets: maintains a simple historical database.

  • Telegram: delivers text and voice notifications.

  • Sensors: examples include MAX30102, DS18B20, OLED, buzzer and status LED.

ML component

A dataset such as the Pima Indians Diabetes Database can be used for academic model development. Candidate algorithms include:

  • Logistic Regression

  • Random Forest

  • Decision Tree

  • SVM

  • KNN

  • Gradient Boosting

Evaluate the model using accuracy, precision, recall, F1-score, ROC-AUC and a confusion matrix.

Important design principle

The ML model should make the statistical prediction, while the AI agent interprets and communicates the result. The AI agent should not independently diagnose diabetes.

Final project outcome

The completed system demonstrates an end-to-end Agentic IoT architecture:

Sense → Transmit → Predict → Reason → Automate → Store → Visualize → Alert

For an academic project, describe it as a diabetes-risk screening/monitoring prototype, not as a clinically validated diagnostic system.