Saturday, 3 October 2026

SolarPulse AI: An IoT-Enabled Intelligent Framework for Real-Time Solar PV Performance Monitoring and Multi-Channel AI Alerting

SolarPulse AI: An IoT-Enabled Intelligent Framework for Real-Time Solar PV Performance Monitoring and Multi-Channel AI Alerting

Yes . I can structure this as a complete engineering/project document covering the SolarPulse AI architecture, ESP32 firmware , IoT webpage/dashboard, n8n workflow, AI agent, Telegram voice alerts, Google Sheets logging, ThingSpeak integration, circuit/schematic, data flow, and testing.

A good final project title would be :

SolarPulse AI

An IoT-Enabled Intelligent Framework for Real-Time Solar PV Performance Monitoring and Multi-Channel AI Alerting

1. Project concept

SolarPulse AI is an intelligent IoT-based solar photovoltaic monitoring system in which an ESP32 continuously measures the electrical and environmental parameters of a solar PV system and sends the data to cloud services.

The system combines:

  • ESP32 — sensor acquisition and local intelligence

  • Solar PV sensors — voltage, current, temperature and irradiance

  • IoT webpage/dashboard — real-time visualization

  • ThingSpeak — cloud IoT data storage/visualization

  • n8n — workflow automation

  • AI Agent — interprets abnormal operating conditions

  • Google Sheets — historical data/event logging

  • Telegram — instant text notifications

  • Telegram voice alerts — spoken warning notifications

  • Webhooks/API — communication between the different layers

The overall concept is:

                    ┌─────────────────────┐
                    │     SOLAR PV        │
                    │       PANEL         │
                    └──────────┬──────────┘
                               │
                 ┌─────────────┴─────────────┐
                 │       SENSOR LAYER        │
                 │                           │
                 │ Voltage │ Current         │
                 │ Temp.   │ Irradiance      │
                 └─────────────┬─────────────┘
                               │
                               ▼
                    ┌─────────────────────┐
                    │       ESP32         │
                    │                     │
                    │ ADC + Sensors       │
                    │ Data Processing      │
                    │ Wi-Fi Communication  │
                    └──────────┬──────────┘
                               │
                         Wi-Fi / HTTP
                               │
              ┌────────────────┼────────────────┐
              │                │                │
              ▼                ▼                ▼
       ┌────────────┐   ┌─────────────┐  ┌──────────────┐
       │ ThingSpeak │   │ IoT Webpage │  │ n8n Webhook  │
       │ Cloud      │   │ Dashboard   │  │              │
       └────────────┘   └─────────────┘  └──────┬───────┘
                                                │
                                                ▼
                                      ┌──────────────────┐
                                      │    AI AGENT      │
                                      │                  │
                                      │ Analyze PV Data  │
                                      │ Detect Anomaly   │
                                      │ Generate Reason  │
                                      └────────┬─────────┘
                                               │
                              ┌────────────────┼─────────────────┐
                              │                │                 │
                              ▼                ▼                 ▼
                       ┌────────────┐   ┌────────────┐   ┌─────────────┐
                       │ Telegram   │   │ Voice      │   │ Google      │
                       │ Message    │   │ Alert      │   │ Sheets      │
                       └────────────┘   └────────────┘   └─────────────┘

2. Main objectives

The project has six primary objectives.

Objective 1 — Real-time monitoring

Measure PV parameters continuously:

  • PV voltage

  • PV current

  • PV power

  • panel temperature

  • ambient temperature

  • solar irradiance

  • energy generation

PV power is calculated as:

PPV=VPV×IPVP_{PV}=V_{PV}\times I_{PV}

where:

  • PPVP_{PV} = PV power in watts

  • VPVV_{PV} = PV voltage in volts

  • IPVI_{PV} = PV current in amperes

Energy can be estimated using:

E=∫P(t)dtE=\int P(t)dt

For discrete measurements:

E≈∑PiΔtE \approx \sum P_i\Delta t


3. Proposed hardware

A practical prototype can use:

Component Function
ESP32 DevKit Main IoT controller
Solar panel PV energy source
Voltage sensor/divider PV voltage measurement
Current sensor PV current measurement
DS18B20 Panel/environment temperature
BH1750 / irradiance sensor Light measurement
OLED display Local status display
Wi-Fi Internet communication
5 V/USB supply ESP32 power
Resistors Voltage scaling/protection
Breadboard/PCB Prototype assembly
Optional relay Protection/control
Optional buzzer Local alarm

For an actual PV installation, the voltage/current sensing circuitry must be selected according to the maximum PV voltage and current. The ESP32 ADC must never be exposed directly to a voltage beyond its permitted input range.


4. Hardware block diagram

             SOLAR PANEL
                  │
        ┌─────────┴─────────┐
        │                   │
        ▼                   ▼
 Voltage Measurement    Current Measurement
        │                   │
        │                   │
        └─────────┬─────────┘
                  │
                  ▼
             ┌─────────┐
             │  ESP32  │
             │         │
             │ ADC     │
             │ GPIO    │
             │ I2C     │
             │ Wi-Fi   │
             └────┬────┘
                  │
       ┌──────────┼──────────┐
       │          │          │
       ▼          ▼          ▼
     OLED      Temp.       Wi-Fi
    Display    Sensor        │
                              ▼
                          Internet

5. Suggested ESP32 pin configuration

One possible prototype configuration:

ESP32
────────────────────────────
GPIO 34  → PV Voltage ADC
GPIO 35  → PV Current ADC
GPIO 21  → I2C SDA
GPIO 22  → I2C SCL
GPIO 4   → DS18B20
GPIO 2   → Status LED
GPIO 25  → Buzzer
3.3 V    → Sensors
GND      → Common GND

Example:

                 ESP32
          ┌────────────────┐
          │                │
PV Voltage ───────► GPIO34 │
PV Current ───────► GPIO35 │
          │                │
DS18B20 ──────────► GPIO4  │
          │                │
OLED SDA ─────────► GPIO21 │
OLED SCL ─────────► GPIO22 │
          │                │
Buzzer ◄────────── GPIO25  │
LED    ◄────────── GPIO2   │
          │                │
          └────────────────┘

6. Voltage measurement circuit

The ESP32 ADC cannot directly measure typical PV-panel voltages.

Therefore, a voltage divider is required.

             PV+
              │
             R1
              │
              ├────────────► ESP32 ADC
              │
             R2
              │
             GND

The ADC voltage is:

VADC=VPVR2R1+R2V_{ADC}=V_{PV}\frac{R_2}{R_1+R_2}

Therefore:

VPV=VADCR1+R2R2V_{PV}=V_{ADC}\frac{R_1+R_2}{R_2}

For example, the resistor values must be calculated from the maximum expected PV voltage, with suitable margin and appropriate resistor power ratings.

For a real installation, add suitable:

  • fuse/protection

  • filtering

  • overvoltage protection

  • isolation where required


7. Current measurement

A Hall-effect current sensor can be used.

Conceptually:

PV+ ───────► CURRENT SENSOR ───────► LOAD/CHARGE CONTROLLER
                    │
                    │ Analog output
                    ▼
                 ESP32 ADC

The firmware converts the sensor output into current according to the selected sensor's calibration equation.

For example:

I=Vsensor−VoffsetSensitivityI=\frac{V_{sensor}-V_{offset}}{Sensitivity}

The actual offset and sensitivity must come from the selected current sensor and be calibrated experimentally.


8. Temperature measurement

A DS18B20 can be attached to the rear of the solar panel.

Panel
──────────────────────
│                    │
│      PV CELLS      │
│                    │
──────────────────────
          │
          │ thermal contact
          ▼
      DS18B20
          │
          ▼
        ESP32

Temperature is important because PV output generally changes with cell temperature.

The AI layer can therefore compare:

Solar irradiance
       +
Panel temperature
       +
PV voltage
       +
PV current
       ↓
Expected PV behavior
       ↓
Actual PV behavior
       ↓
Anomaly detection

9. IoT data structure

The ESP32 can transmit a JSON payload such as:

{
  "device_id": "SOLARPULSE_001",
  "voltage": 18.72,
  "current": 2.84,
  "power": 53.16,
  "temperature": 42.6,
  "irradiance": 815,
  "energy": 1.284,
  "status": "NORMAL"
}

The important advantage of JSON is that the same payload can be consumed by:

  • n8n

  • web application

  • cloud APIs

  • database

  • AI agent


10. Complete software architecture

┌───────────────────────────────────────────────────────┐
│                    SOLARPULSE AI                      │
└───────────────────────────────────────────────────────┘

       HARDWARE
           │
           ▼
┌──────────────────────┐
│        ESP32         │
│                      │
│ Sensor acquisition   │
│ Filtering            │
│ Power calculation    │
│ Wi-Fi                │
└──────────┬───────────┘
           │
           │ JSON / HTTP
           ▼
┌──────────────────────┐
│    IoT Cloud Layer   │
│                      │
│ ThingSpeak           │
│ Web API              │
└──────────┬───────────┘
           │
           ├─────────────────┐
           │                 │
           ▼                 ▼
     ┌───────────┐    ┌─────────────┐
     │ Webpage   │    │     n8n     │
     │ Dashboard │    │ Automation  │
     └───────────┘    └──────┬──────┘
                             │
                             ▼
                       ┌────────────┐
                       │ AI Agent   │
                       └─────┬──────┘
                             │
                  ┌──────────┼──────────┐
                  ▼          ▼          ▼
             Telegram     Voice     Google Sheets
             Message      Alert       Logging

11. IoT webpage

The webpage is the user-facing monitoring interface.

A dashboard could contain:

╔══════════════════════════════════════════════════╗
║                 SOLARPULSE AI                    ║
║              Solar PV Dashboard                  ║
╠══════════════════════════════════════════════════╣
║                                                  ║
║  Voltage       Current        Power              ║
║  18.72 V       2.84 A         53.16 W            ║
║                                                  ║
║  Temperature   Irradiance     Energy             ║
║  42.6 °C       815 W/m²       1.284 kWh           ║
║                                                  ║
╠══════════════════════════════════════════════════╣
║              SYSTEM STATUS                      ║
║                                                  ║
║                 🟢 NORMAL                       ║
║                                                  ║
╠══════════════════════════════════════════════════╣
║                 PV POWER GRAPH                  ║
║                                                  ║
║       ╭──╮                                      ║
║   ╭───╯  ╰──╮                                   ║
║ ──╯         ╰────────                           ║
║                                                  ║
╠══════════════════════════════════════════════════╣
║ AI ANALYSIS                                     ║
║                                                  ║
║ "PV generation is operating within the expected ║
║ range for the measured irradiance."             ║
╚══════════════════════════════════════════════════╝

12. n8n automation architecture

n8n becomes the central orchestration layer.

                 ESP32
                   │
                   ▼
              HTTP Request
                   │
                   ▼
             ┌───────────┐
             │ Webhook   │
             └─────┬─────┘
                   │
                   ▼
             Parse JSON
                   │
                   ▼
          Validate Sensor Data
                   │
                   ▼
          Calculate/Check Rules
                   │
          ┌────────┴────────┐
          │                 │
       NORMAL             ABNORMAL
          │                 │
          ▼                 ▼
   Google Sheets        AI Agent
          │                 │
          │           ┌─────┴─────┐
          │           │           │
          │           ▼           ▼
          │        Diagnosis   Recommendation
          │           │
          │           ▼
          │       Telegram
          │           │
          │           ▼
          │      Voice Message
          │
          ▼
       Dashboard

13. n8n workflow nodes

A complete workflow can be organized as:

[Webhook]
    ↓
[Set / Normalize Data]
    ↓
[Function: Calculate Power]
    ↓
[IF: Sensor Valid?]
    ↓
[Store Data]
    ↓
[Rule Evaluation]
    ↓
[AI Agent]
    ↓
[Decision]
   / \
  /   \
Normal  Alert
 |       |
 ▼       ▼
Sheets  Telegram
         |
         ▼
     Text-to-Speech
         |
         ▼
   Telegram Voice

14. AI Agent responsibilities

The AI Agent should not simply say "high" or "low."

It should interpret several parameters together.

For example:

PV Voltage       = 17.1 V
PV Current       = 0.4 A
Irradiance       = 850 W/m²
Temperature      = 39 °C

The AI agent could determine that the current output is unusually low relative to the available irradiance and report a possible performance issue.

Potential anomaly categories:

  • low power

  • sudden power drop

  • abnormal voltage

  • abnormal current

  • overheating

  • sensor failure

  • communication failure

  • nighttime/low-light condition

  • prolonged underperformance

The AI should distinguish actual faults from expected environmental changes.

For example:

Irradiance = 50 W/m²
Power      = 2 W

should not automatically be treated as a PV fault.


15. AI Agent input

A useful AI-agent prompt can be structured around machine-readable input:

You are SolarPulse AI, an assistant responsible for
interpreting solar PV monitoring data.

Analyze:

PV voltage
PV current
PV power
panel temperature
solar irradiance
historical values
previous alerts

Determine:

1. Current operating condition
2. Whether an anomaly exists
3. Severity
4. Possible cause
5. Recommended action

Do not declare a hardware failure unless the available
measurements provide sufficient evidence.

Return JSON:

{
  "status": "NORMAL|WARNING|CRITICAL",
  "anomaly": true,
  "reason": "...",
  "recommendation": "...",
  "voice_message": "..."
}

16. AI agent decision example

Suppose:

Voltage = 18.4 V
Current = 2.9 A
Power = 53.36 W
Temperature = 41 °C
Irradiance = 820 W/m²

AI output:

{
  "status": "NORMAL",
  "anomaly": false,
  "reason": "PV output is consistent with the measured operating conditions.",
  "recommendation": "Continue monitoring.",
  "voice_message": "Solar PV system is operating normally."
}

For an abnormal case:

{
  "status": "WARNING",
  "anomaly": true,
  "reason": "PV current has decreased significantly while irradiance remains high.",
  "recommendation": "Inspect panel shading, connections and PV-side equipment.",
  "voice_message": "Warning. Solar PV output has dropped unexpectedly. Please inspect the system."
}

17. Telegram text alert

Example workflow:

ESP32
  ↓
n8n
  ↓
AI Agent
  ↓
Telegram Bot
  ↓
Mobile Phone

Example message:

⚠️ SOLARPULSE AI ALERT

Device: SOLARPULSE_001

Status: WARNING

PV Voltage: 18.1 V
PV Current: 0.72 A
PV Power: 13.0 W
Irradiance: 830 W/m²
Temperature: 44.2 °C

AI Analysis:
PV output is significantly below the expected level
for the measured irradiance.

Recommended Action:
Inspect the PV panel for shading, contamination or
connection problems.

18. Telegram voice alert

The voice-alert pipeline is:

AI Agent
   │
   ▼
Voice message text
   │
   ▼
Text-to-Speech service
   │
   ▼
Audio file
   │
   ▼
Telegram Bot
   │
   ▼
User's smartphone

Example spoken message:

"SolarPulse warning. PV output has dropped unexpectedly while solar irradiance remains high. Please inspect the solar panel and electrical connections."

This is particularly useful when the operator is not continuously looking at the dashboard.


19. Google Sheets integration

Google Sheets can act as a simple historical event/data repository.

Example:

Timestamp Device Voltage Current Power Temp Irradiance AI Status Alert
10:01 SP001 18.7 2.8 52.4 41.2 810 NORMAL No
10:02 SP001 18.5 2.7 49.9 41.5 825 NORMAL No
10:03 SP001 18.1 0.8 14.5 42.1 830 WARNING Yes

This makes it possible to perform later analysis such as:

  • daily energy

  • maximum power

  • minimum voltage

  • abnormal-event frequency

  • temperature/output relationship

  • historical performance


20. ThingSpeak architecture

ThingSpeak can provide a cloud IoT channel .

Example field assignment:

Field 1 → Voltage
Field 2 → Current
Field 3 → Power
Field 4 → Temperature
Field 5 → Irradiance
Field 6 → Energy
Field 7 → Status

Conceptually:

ESP32
  │
  │ HTTP/MQTT
  ▼
ThingSpeak
  │
  ├────► Charts
  ├────► Historical data
  └────► API

The webpage can either retrieve data from the cloud API or receive data through the project's backend architecture.


21. End-to-end communication

The complete sequence is:

1. Solar panel produces electricity
              ↓
2. Sensors measure PV parameters
              ↓
3. ESP32 reads sensors
              ↓
4. ESP32 filters/calculates measurements
              ↓
5. ESP32 calculates PV power
              ↓
6. ESP32 creates JSON packet
              ↓
7. Data transmitted over Wi-Fi
              ↓
8. Cloud/dashboard receives data
              ↓
9. n8n receives event
              ↓
10. n8n validates data
              ↓
11. AI Agent analyzes operating condition
              ↓
12. AI returns structured diagnosis
              ↓
13. n8n stores record in Google Sheets
              ↓
14. If abnormal:
              ↓
15. Telegram text alert
              ↓
16. Text converted to speech
              ↓
17. Telegram voice alert

22. ESP32 firmware architecture

The firmware should be divided into logical modules.

main()
 │
 ├── initializeSensors()
 │
 ├── initializeDisplay()
 │
 ├── connectWiFi()
 │
 ├── synchronizeTime()
 │
 └── loop()
       │
       ├── readVoltage()
       ├── readCurrent()
       ├── readTemperature()
       ├── readIrradiance()
       ├── calculatePower()
       ├── calculateEnergy()
       ├── validateMeasurements()
       ├── updateDisplay()
       └── sendCloudData()

23. Example ESP32 Arduino code

Below is a prototype/reference implementation. The voltage/current calibration values must be changed for the actual sensors used.

#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <OneWire.h>
#include <DallasTemperature.h>

// ---------------------------
// Wi-Fi configuration
// ---------------------------
const char* WIFI_SSID = "YOUR_WIFI";
const char* WIFI_PASSWORD = "YOUR_PASSWORD";

// n8n webhook
const char* WEBHOOK_URL =
  "https://YOUR-N8N-DOMAIN/webhook/solarpulse";

// ---------------------------
// ESP32 pins
// ---------------------------
#define PV_VOLTAGE_PIN 34
#define PV_CURRENT_PIN 35
#define TEMP_PIN       4
#define STATUS_LED      2

// ---------------------------
// Temperature sensor
// ---------------------------
OneWire oneWire(TEMP_PIN);
DallasTemperature tempSensor(&oneWire);

// ---------------------------
// Calibration
// IMPORTANT:
// Replace these with values
// determined for your hardware.
// ---------------------------
float voltageScale = 6.0;
float currentOffset = 1.65;
float currentSensitivity = 0.066;

// ---------------------------
// Energy calculation
// ---------------------------
float energyWh = 0.0;

unsigned long previousMillis = 0;
const unsigned long sampleInterval = 10000;

// ---------------------------
// Read PV voltage
// ---------------------------
float readPVVoltage()
{
    int raw = analogRead(PV_VOLTAGE_PIN);

    float adcVoltage =
        (raw / 4095.0) * 3.3;

    return adcVoltage * voltageScale;
}

// ---------------------------
// Read PV current
// ---------------------------
float readPVCurrent()
{
    int raw = analogRead(PV_CURRENT_PIN);

    float sensorVoltage =
        (raw / 4095.0) * 3.3;

    float current =
        (sensorVoltage - currentOffset)
        / currentSensitivity;

    if (current < 0)
        current = 0;

    return current;
}

// ---------------------------
// Send JSON data
// ---------------------------
void sendData(
    float voltage,
    float current,
    float power,
    float temperature)
{
    if (WiFi.status() != WL_CONNECTED)
        return;

    HTTPClient http;

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

    StaticJsonDocument<512> doc;

    doc["device_id"] = "SOLARPULSE_001";
    doc["voltage"] = voltage;
    doc["current"] = current;
    doc["power"] = power;
    doc["temperature"] = temperature;
    doc["energy_wh"] = energyWh;

    String payload;

    serializeJson(doc, payload);

    int responseCode =
        http.POST(payload);

    Serial.print("HTTP Response: ");
    Serial.println(responseCode);

    http.end();
}

// ---------------------------
// Setup
// ---------------------------
void setup()
{
    Serial.begin(115200);

    pinMode(STATUS_LED, OUTPUT);

    tempSensor.begin();

    WiFi.begin(
        WIFI_SSID,
        WIFI_PASSWORD
    );

    Serial.print("Connecting");

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

    Serial.println();
    Serial.println("Wi-Fi connected");
    Serial.println(WiFi.localIP());
}

// ---------------------------
// Main loop
// ---------------------------
void loop()
{
    unsigned long currentMillis =
        millis();

    if (currentMillis - previousMillis
        >= sampleInterval)
    {
        previousMillis =
            currentMillis;

        float voltage =
            readPVVoltage();

        float current =
            readPVCurrent();

        tempSensor.requestTemperatures();

        float temperature =
            tempSensor.getTempCByIndex(0);

        float power =
            voltage * current;

        // Energy in Wh
        float hours =
            sampleInterval / 3600000.0;

        energyWh +=
            power * hours;

        Serial.println("-------------------");

        Serial.print("Voltage: ");
        Serial.println(voltage);

        Serial.print("Current: ");
        Serial.println(current);

        Serial.print("Power: ");
        Serial.println(power);

        Serial.print("Temperature: ");
        Serial.println(temperature);

        Serial.print("Energy: ");
        Serial.println(energyWh);

        sendData(
            voltage,
            current,
            power,
            temperature
        );
    }
}

24. Improved ESP32 architecture

For the final version, I would recommend adding:

Sensor
   ↓
Moving Average Filter
   ↓
Outlier Rejection
   ↓
Calibration
   ↓
Range Validation
   ↓
Power Calculation
   ↓
Energy Calculation
   ↓
Local Fault Detection
   ↓
Cloud Transmission

This prevents noisy sensor values from triggering unnecessary AI alerts.


25. Local fault detection

Some faults can be identified without AI.

For example:

if (voltage < 1.0 && current < 0.1)
{
    status = "LOW_OUTPUT";
}

or:

if (temperature > 75)
{
    status = "OVER_TEMPERATURE";
}

But thresholds should be configurable according to the actual PV system.

A useful architecture is:

               Sensor Data
                    │
           ┌────────┴────────┐
           │                 │
           ▼                 ▼
      Rule Engine         AI Agent
           │                 │
           └────────┬────────┘
                    ▼
             Final Decision

This reduces unnecessary AI calls.


26. n8n workflow pseudo-configuration

Node 1 — Webhook

POST /solarpulse

Receives:

{
  "device_id": "SOLARPULSE_001",
  "voltage": 18.7,
  "current": 2.8,
  "power": 52.36,
  "temperature": 42.1,
  "irradiance": 815
}

Node 2 — Code/Function

Calculate derived values:

const d = $json;

const power =
  Number(d.voltage) *
  Number(d.current);

return [{
  json: {
    ...d,
    calculated_power: power
  }
}];

Node 3 — Validation

Voltage valid?
       │
       ├── NO → Error workflow
       │
       └── YES
              ↓
Current valid?
       │
       ├── NO → Error workflow
       │
       └── YES

Node 4 — AI Agent

Send the validated sensor information.

Node 5 — Google Sheets

Append:

timestamp
device
voltage
current
power
temperature
irradiance
AI status
AI explanation

Node 6 — IF

AI status == WARNING
OR
AI status == CRITICAL

Node 7 — Telegram

Send notification.

Node 8 — Text-to-Speech

Generate audio.

Node 9 — Telegram Voice

Send audio message.


27. AI-agent conversation example

The project can document the AI Agent interaction as follows:

SYSTEM
You are SolarPulse AI.

USER
Device: SP001
Voltage: 18.2 V
Current: 0.71 A
Power: 12.9 W
Temperature: 43.7 °C
Irradiance: 840 W/m²

Analyze the PV operating condition.

AI AGENT
Status: WARNING

The measured power is substantially lower than
expected for the reported irradiance.

Possible causes include:
1. Panel shading
2. Surface contamination
3. Electrical connection problem
4. PV-side equipment issue

Recommended action:
Inspect the panel and electrical connections.

Then n8n converts the AI response into:

Telegram Text
       +
Telegram Voice
       +
Google Sheets Event

28. Multi-channel alert architecture

One of the major contributions of the project is that an event does not depend on a single notification channel.

                    AI DETECTS EVENT
                           │
             ┌─────────────┼─────────────┐
             │             │             │
             ▼             ▼             ▼
         Webpage       Telegram      Google Sheets
          Alert          Text           Log
                           │
                           ▼
                      Text-to-Speech
                           │
                           ▼
                     Voice Alert

Therefore:

  • dashboard = visual monitoring

  • Telegram = immediate textual notification

  • voice = hands-free notification

  • Sheets = historical record


29. Webpage software structure

A simple web application can have:

/frontend
    index.html
    style.css
    dashboard.js

/backend
    server.js
    api.js

/data
    sensor-data

/assets
    logo
    icons

Dashboard components:

Header
  │
  ├── Device status
  ├── Last update
  └── Connection status

Metrics
  │
  ├── Voltage
  ├── Current
  ├── Power
  ├── Temperature
  ├── Irradiance
  └── Energy

Charts
  │
  ├── Power vs Time
  ├── Voltage vs Time
  ├── Current vs Time
  └── Temperature vs Time

AI
  │
  ├── Status
  ├── Explanation
  └── Recommendation

Alerts
  │
  ├── Recent alerts
  └── Alert history

30. Dashboard HTML prototype

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>SolarPulse AI</title>

    <style>
        body {
            margin: 0;
            font-family: Arial, sans-serif;
            background: #101820;
            color: white;
        }

        header {
            padding: 20px;
            background: #17232c;
        }

        .dashboard {
            display: grid;
            grid-template-columns:
                repeat(auto-fit, minmax(220px, 1fr));
            gap: 20px;
            padding: 20px;
        }

        .card {
            background: #1d2d38;
            padding: 20px;
            border-radius: 15px;
        }

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

        .normal {
            color: #00e676;
        }

        .warning {
            color: #ffb300;
        }

        .critical {
            color: #ff5252;
        }
    </style>
</head>

<body>

<header>
    <h1>☀ SolarPulse AI</h1>
    <p>Intelligent Solar PV Monitoring System</p>
</header>

<div class="dashboard">

    <div class="card">
        <h3>Voltage</h3>
        <div id="voltage"
             class="value">-- V</div>
    </div>

    <div class="card">
        <h3>Current</h3>
        <div id="current"
             class="value">-- A</div>
    </div>

    <div class="card">
        <h3>Power</h3>
        <div id="power"
             class="value">-- W</div>
    </div>

    <div class="card">
        <h3>Temperature</h3>
        <div id="temperature"
             class="value">-- °C</div>
    </div>

    <div class="card">
        <h3>Irradiance</h3>
        <div id="irradiance"
             class="value">-- W/m²</div>
    </div>

    <div class="card">
        <h3>AI Status</h3>
        <div id="status"
             class="value normal">
             NORMAL
        </div>
    </div>

</div>

<script>

async function updateDashboard()
{
    try
    {
        const response =
            await fetch("/api/latest");

        const data =
            await response.json();

        document.getElementById("voltage")
            .innerText =
            data.voltage + " V";

        document.getElementById("current")
            .innerText =
            data.current + " A";

        document.getElementById("power")
            .innerText =
            data.power + " W";

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

        document.getElementById("irradiance")
            .innerText =
            data.irradiance + " W/m²";

        document.getElementById("status")
            .innerText =
            data.status;
    }
    catch(error)
    {
        console.error(error);
    }
}

setInterval(updateDashboard, 10000);

updateDashboard();

</script>

</body>
</html>

31. Complete project workflow

The complete SolarPulse AI system can therefore be represented as:

                         ☀ SUN
                           │
                           ▼
                     ┌───────────┐
                     │ SOLAR PV  │
                     │  PANEL    │
                     └─────┬─────┘
                           │
             ┌─────────────┼─────────────┐
             │             │             │
             ▼             ▼             ▼
          Voltage        Current      Temperature
          Sensor         Sensor          Sensor
             │             │             │
             └─────────────┼─────────────┘
                           ▼
                     ┌───────────┐
                     │   ESP32   │
                     │           │
                     │ Sampling  │
                     │ Filtering │
                     │ Compute   │
                     └─────┬─────┘
                           │
                         Wi-Fi
                           │
                           ▼
              ┌────────────────────────┐
              │     IoT CLOUD/API      │
              └───────────┬────────────┘
                          │
              ┌───────────┴────────────┐
              │                        │
              ▼                        ▼
        ┌───────────┐            ┌───────────┐
        │ ThingSpeak│            │    n8n    │
        └─────┬─────┘            └─────┬─────┘
              │                        │
              ▼                        ▼
        Cloud Charts             Data Validation
                                       │
                                       ▼
                                  Rule Engine
                                       │
                                       ▼
                                  AI AGENT
                                       │
                              ┌────────┼────────┐
                              │        │        │
                              ▼        ▼        ▼
                         Telegram    Voice    Sheets
                           Text      Alert      Log
                              │
                              ▼
                           USER
                              │
                              ▼
                       Corrective Action

32. Fault-detection logic

A useful rule hierarchy is:

Level 0 — Normal

All sensor readings valid
+
PV output consistent with conditions

Level 1 — Warning

Moderate deviation
OR
temperature approaching limit
OR
unexpected output reduction

Level 2 — Critical

Severe abnormal condition
OR
dangerous temperature
OR
sensor/system failure

Example:

                    Sensor Data
                         │
                         ▼
                ┌─────────────────┐
                │ Data Validation  │
                └────────┬────────┘
                         │
                   Valid data?
                    /          \
                  NO            YES
                  │              │
                  ▼              ▼
               SENSOR        AI ANALYSIS
               ERROR              │
                                  ▼
                            Severity Level
                          /       |        \
                       NORMAL   WARNING   CRITICAL
                         │         │          │
                         ▼         ▼          ▼
                       Log       Telegram   Telegram
                                  Voice      Voice

33. Security architecture

The final system should not expose credentials in ESP32 source code.

Avoid:

const char* API_KEY = "actual-secret";

for production repositories.

Instead use:

ESP32
  │
  └── HTTPS
       │
       ▼
Secure API/Webhook
       │
       ▼
n8n credentials
       │
       ├── Telegram credential
       ├── Google credential
       ├── AI API credential
       └── ThingSpeak credential

Recommended protections include:

  • HTTPS

  • authenticated webhook

  • API keys

  • secret/environment variables

  • n8n credential management

  • rate limiting

  • input validation

  • device identification

  • timestamp validation


34. Failure scenarios

The documentation should explicitly test:

Failure Expected response
Wi-Fi disconnected ESP32 retries connection
Internet unavailable Local buffering/retry
Sensor disconnected Sensor error
Abnormal voltage Warning/critical event
Current suddenly drops AI analysis
High temperature Temperature warning
n8n unavailable Retry transmission
Telegram unavailable Log event/retry
AI service unavailable Rule-based fallback
ThingSpeak unavailable Continue local/cloud retry
Invalid JSON Reject request

35. Important design principle: AI is not the only protection

The system should not depend exclusively on an AI model for electrical safety.

Use deterministic protection for hard limits:

Hardware protection
        ↓
Local ESP32 safety/range checks
        ↓
n8n rule engine
        ↓
AI interpretation
        ↓
Human notification

AI is particularly useful for contextual interpretation, rather than replacing electrical protection circuitry.


36. Project methodology

The project can be implemented in these stages.

Phase 1 — Hardware

  1. Assemble ESP32.

  2. Connect voltage sensor.

  3. Connect current sensor.

  4. Connect temperature sensor.

  5. Verify each sensor independently.

  6. Calibrate measurements.

  7. Test under controlled PV conditions.

Phase 2 — Firmware

  1. Configure ADC.

  2. Read voltage.

  3. Read current.

  4. Read temperature.

  5. Calculate power.

  6. Calculate energy.

  7. Add filtering.

  8. Add Wi-Fi.

  9. Create JSON payload.

  10. Send test data.

Phase 3 — Cloud

  1. Create ThingSpeak channel.

  2. Configure fields.

  3. Test cloud transmission.

  4. Verify charts.

  5. Configure API access.

Phase 4 — n8n

  1. Create webhook.

  2. Receive ESP32 JSON.

  3. Validate data.

  4. Calculate derived values.

  5. Add rule engine.

  6. Connect AI Agent.

  7. Add Google Sheets.

  8. Add Telegram.

  9. Add voice generation.

  10. Test complete workflow.

Phase 5 — Web application

  1. Create dashboard.

  2. Add metric cards.

  3. Add charts.

  4. Add status indicator.

  5. Add AI explanation.

  6. Add alert history.

  7. Connect backend/API.

Phase 6 — Testing

  1. Normal operation.

  2. Low irradiance.

  3. High temperature.

  4. Artificial current reduction.

  5. Sensor disconnection.

  6. Wi-Fi failure.

  7. n8n failure.

  8. Telegram failure.

  9. Recovery testing.


37. Suggested final project directory

SolarPulse-AI/
│
├── README.md
│
├── documentation/
│   ├── project-description.md
│   ├── system-architecture.md
│   ├── hardware-design.md
│   ├── software-design.md
│   ├── n8n-workflow.md
│   ├── ai-agent.md
│   ├── testing.md
│   └── user-manual.md
│
├── esp32/
│   ├── SolarPulse.ino
│   ├── sensors.h
│   ├── sensors.cpp
│   ├── config.h
│   └── calibration.h
│
├── web/
│   ├── index.html
│   ├── style.css
│   └── dashboard.js
│
├── n8n/
│   ├── solarpulse-workflow.json
│   └── ai-agent-prompt.txt
│
├── diagrams/
│   ├── system-block-diagram.png
│   ├── circuit-schematic.png
│   ├── data-flow.png
│   └── n8n-flow.png
│
└── tests/
    ├── sensor-test
    ├── api-test
    └── alert-test

38. Proposed research contribution

For an academic/project report, the novelty can be framed around the integration of multiple layers, rather than claiming that each individual technology is novel.

The proposed framework combines:

IoT sensing
     +
Edge processing
     +
Cloud monitoring
     +
Workflow automation
     +
AI-based contextual analysis
     +
Multi-channel notification

into one solar PV monitoring architecture.

A suitable research contribution statement is:

SolarPulse AI proposes an integrated IoT-agentic architecture for real-time photovoltaic performance monitoring in which edge-based ESP32 sensing, cloud telemetry, workflow automation, AI-assisted anomaly interpretation, historical logging, and multi-channel human notification operate as a unified monitoring pipeline.


39. Recommended final report structure

For a B.Tech/M.Tech/project thesis/paper, I would structure the documentation as:

CHAPTER 1
Introduction

CHAPTER 2
Literature Review

CHAPTER 3
Problem Statement

CHAPTER 4
Objectives and Scope

CHAPTER 5
Proposed SolarPulse AI Architecture

CHAPTER 6
Hardware Design

CHAPTER 7
ESP32 Firmware Design

CHAPTER 8
IoT and Cloud Architecture

CHAPTER 9
n8n Automation Architecture

CHAPTER 10
AI Agent Design

CHAPTER 11
Telegram Voice Alert System

CHAPTER 12
Google Sheets and ThingSpeak Integration

CHAPTER 13
Web Dashboard

CHAPTER 14
System Implementation

CHAPTER 15
Flowcharts and Algorithms

CHAPTER 16
Experimental Setup

CHAPTER 17
Results and Discussion

CHAPTER 18
Fault/Anomaly Detection

CHAPTER 19
Limitations

CHAPTER 20
Future Scope

CHAPTER 21
Conclusion

REFERENCES

APPENDIX
ESP32 Code
n8n Workflow
Circuit
API Configuration
Test Results

40. Final system in one diagram

                         ┌───────────────┐
                         │   SOLAR PV    │
                         │    PANEL      │
                         └───────┬───────┘
                                 │
                  ┌──────────────┼──────────────┐
                  │              │              │
                  ▼              ▼              ▼
             Voltage          Current       Temperature
              Sensor           Sensor          Sensor
                  │              │              │
                  └──────────────┼──────────────┘
                                 │
                                 ▼
                         ┌───────────────┐
                         │     ESP32     │
                         │               │
                         │ Sensor Read   │
                         │ Filtering     │
                         │ P = V × I     │
                         │ Energy        │
                         │ Wi-Fi         │
                         └───────┬───────┘
                                 │
                              HTTPS
                                 │
                  ┌──────────────┼──────────────┐
                  │                             │
                  ▼                             ▼
          ┌───────────────┐              ┌───────────────┐
          │  ThingSpeak   │              │  n8n Webhook  │
          │ Cloud Storage │              │   Automation  │
          └───────┬───────┘              └───────┬───────┘
                  │                              │
                  ▼                              ▼
          ┌───────────────┐              ┌───────────────┐
          │ IoT Dashboard │              │ Data Validate │
          └───────────────┘              └───────┬───────┘
                                                  │
                                                  ▼
                                          ┌───────────────┐
                                          │ Rule Engine   │
                                          └───────┬───────┘
                                                  │
                                                  ▼
                                          ┌───────────────┐
                                          │   AI AGENT    │
                                          │               │
                                          │ Analyze       │
                                          │ Explain       │
                                          │ Recommend     │
                                          └───────┬───────┘
                                                  │
                           ┌──────────────────────┼──────────────────────┐
                           │                      │                      │
                           ▼                      ▼                      ▼
                    ┌────────────┐        ┌──────────────┐       ┌────────────┐
                    │  Telegram  │        │ Text-to-     │       │  Google    │
                    │   Alert    │        │ Speech       │       │  Sheets    │
                    └────────────┘        └──────┬───────┘       └────────────┘
                                                  │
                                                  ▼
                                           ┌────────────┐
                                           │ Telegram   │
                                           │ Voice      │
                                           │ Alert      │
                                           └─────┬──────┘
                                                 │
                                                 ▼
                                             👤 USER

This gives you the complete conceptual and implementation foundation for SolarPulse AI. The next practical step is to turn this into a fully buildable version with the exact sensor modules you intend to use: a complete circuit/schematic, calibrated ESP32 firmware, n8n workflow JSON, AI-agent prompt, Telegram bot configuration, Google Sheets structure, ThingSpeak configuration, and a polished responsive web dashboard.

 

## SolarPulse AI — Project Summary **SolarPulse AI** is an IoT-enabled intelligent solar PV monitoring system that combines **ESP32 sensing, cloud monitoring, n8n automation, AI-based anomaly analysis, Telegram notifications/voice alerts, Google Sheets logging, ThingSpeak, and a web dashboard**. ### Core workflow ``` Solar PV Panel ↓ Voltage / Current / Temperature / Irradiance Sensors ↓ ESP32 ↓ Wi-Fi + JSON ↓ ┌───────────────┬────────────────┐ │ │ │ ▼ ▼ ▼ ThingSpeak Web Dashboard n8n ↓ Data Validation ↓ Rule Evaluation ↓ AI Agent ↓ ┌───────────────────┼─────────────────┐ ↓ ↓ ↓ Telegram Text Voice Alert Google Sheets ``` ### Main functions - **Real-time PV monitoring** - Voltage - Current - Power - Temperature - Irradiance - Energy generation - **ESP32 edge processing** - Sensor acquisition - Filtering/calibration - Power calculation - Energy calculation - Wi-Fi communication - **Cloud/IoT** - ThingSpeak data storage and visualization - Web dashboard for live monitoring - **n8n automation** - Receives ESP32 data - Validates measurements - Runs rules - Calls the AI agent - Logs events - Triggers notifications - **AI Agent** - Interprets PV operating conditions - Detects potential anomalies - Determines severity - Explains possible causes - Provides recommended actions - **Multi-channel alerts** - Telegram text - Telegram voice notification - Dashboard warning - Google Sheets event history ### Example AI scenario ``` Irradiance: 830 W/m² PV Voltage: 18.1 V PV Current: 0.72 A PV Power: 13 W Temperature: 44 °C ↓ AI Agent ↓ WARNING: PV output is significantly lower than expected for the measured irradiance. Possible causes: - Shading - Panel contamination - Electrical connection problem - PV equipment issue ↓ Telegram Text + Voice Alert + Google Sheets Log ``` ### Hardware Typical prototype: ``` ESP32 ├── PV Voltage Sensor ├── PV Current Sensor ├── DS18B20 Temperature Sensor ├── Irradiance/Light Sensor ├── OLED Display ├── Status LED └── Buzzer ``` ### Software stack ``` ESP32 / Arduino + Web Dashboard + ThingSpeak + n8n + AI Agent + Telegram Bot + Text-to-Speech + Google Sheets ``` ### Academic contribution The project integrates **IoT sensing + edge computing + cloud monitoring + workflow automation + AI-based anomaly interpretation + multi-channel alerting** into a unified solar PV monitoring framework. ### Suggested report title **“SolarPulse AI: An IoT-Enabled Intelligent Framework for Real-Time Solar PV Performance Monitoring and Multi-Channel AI Alerting”** The complete implementation can be organized into **hardware design → ESP32 firmware → IoT/cloud → n8n workflow → AI agent → Telegram voice alerts → Google Sheets → web dashboard → testing and results**.

Friday, 2 October 2026

AI Women Safety Bag with Face Capture & Threat Detection

AI Women Safety Bag — Complete IoT + AI Agent Project

This project can be built as an AI-assisted personal safety bag using an ESP32 camera, GPS, panic button, optional microphone/IMU, n8n automation, an AI vision/agent layer, Telegram voice alerts, Google Sheets logging, ThingSpeak dashboard, and a web dashboard.

A practical architecture is to let the ESP32 handle immediate sensing and evidence capture, while n8n handles cloud orchestration and heavier AI analysis. Current Espressif ESP-WHO documentation supports human-face detection/recognition on ESP32-family AI boards, including the ESP32-S3-EYE; the S3-EYE integrates a 2-MP camera, microphone, PSRAM and flash. GitHub+1

Important: This should be treated as an emergency-assistance prototype, not a guaranteed threat detector. AI can miss threats or produce false alarms. The physical SOS button should always trigger an alert without waiting for AI.


1. Project Title

AI Women Safety Bag with Face Capture, Threat Assessment & Agentic IoT

Technologies

  • ESP32 / ESP32-CAM

  • OV2640 camera

  • GPS

  • SOS/panic button

  • Buzzer/vibration motor

  • Optional microphone

  • Optional accelerometer

  • Wi-Fi

  • n8n automation

  • AI vision model

  • AI Agent

  • Telegram Bot

  • Telegram voice notifications

  • Google Sheets

  • ThingSpeak

  • Web dashboard

  • Cloud webhook/API

  • Optional cloud image storage


2. Project Abstract

The AI Women Safety Bag is an IoT-enabled personal safety system designed to provide rapid assistance during potentially dangerous situations.

When the user presses an emergency button, the ESP32 immediately:

  1. Activates the local alarm.

  2. Captures an image using the camera.

  3. Obtains the latest GPS coordinates.

  4. Sends an emergency event to an n8n webhook.

  5. n8n receives the image and sensor information.

  6. An AI vision system analyzes the captured scene.

  7. An AI agent evaluates the event context.

  8. Google Sheets records the incident.

  9. ThingSpeak receives telemetry.

  10. Telegram sends an emergency text alert.

  11. Telegram sends the location.

  12. A voice notification can be generated and sent through Telegram.

  13. A web dashboard displays the latest safety status.

The architecture is deliberately event-driven rather than continuously uploading images.


3. Main Features

Feature Description
SOS button Immediate manual emergency trigger
Camera Captures evidence image
Face detection Detects faces in captured scene
Threat assessment AI analyzes scene/context
GPS Obtains location
Local alarm Buzzer/vibration
Telegram Emergency notification
Telegram voice Spoken emergency alert
Google Sheets Incident history
ThingSpeak IoT telemetry/dashboard
n8n Central automation
AI Agent Decides which actions should occur
Web dashboard Live status
Battery monitoring Optional
Accelerometer Optional fall/struggle detection
Microphone Optional voice/SOS detection

n8n currently provides built-in Telegram, Google Sheets, AI Agent, OpenAI and other integration nodes, making this architecture practical without writing a complete backend from scratch. n8n Docs


4. Overall Architecture

                    ┌──────────────────────────┐
                    │       SAFETY BAG         │
                    │                          │
                    │ ESP32 / ESP32-CAM        │
                    │                          │
                    │  ┌──────────────┐        │
                    │  │ OV2640       │        │
                    │  │ Camera       │        │
                    │  └──────┬───────┘        │
                    │         │                │
                    │  ┌──────▼───────┐        │
                    │  │ SOS Button   │        │
                    │  └──────────────┘        │
                    │                          │
                    │  GPS                     │
                    │  Buzzer                  │
                    │  Vibration               │
                    │  Battery                 │
                    │  Optional MIC/IMU        │
                    └────────────┬─────────────┘
                                 │
                              Wi-Fi
                                 │
                                 ▼
                    ┌──────────────────────────┐
                    │       n8n WEBHOOK         │
                    └────────────┬─────────────┘
                                 │
                 ┌───────────────┼────────────────┐
                 │               │                │
                 ▼               ▼                ▼
           ┌──────────┐   ┌────────────┐   ┌─────────────┐
           │ AI Vision│   │ AI Agent   │   │ Data Parser │
           └────┬─────┘   └─────┬──────┘   └─────────────┘
                │               │
                └───────┬───────┘
                        │
              ┌─────────┼───────────┐
              │         │           │
              ▼         ▼           ▼
        ┌─────────┐ ┌──────────┐ ┌────────────┐
        │Telegram │ │Google    │ │ThingSpeak  │
        │Alerts   │ │Sheets    │ │Dashboard   │
        └────┬────┘ └──────────┘ └────────────┘
             │
             ▼
       ┌─────────────┐
       │ Guardian /  │
       │ Emergency   │
       │ Contact     │
       └─────────────┘

5. Emergency Event Flow

              USER PRESSES SOS
                     │
                     ▼
             ESP32 detects button
                     │
          ┌──────────┴──────────┐
          │                     │
          ▼                     ▼
     Local alarm            Capture image
          │                     │
          │                     ▼
          │                 Read GPS
          │                     │
          └──────────┬──────────┘
                     ▼
               Wi-Fi available?
                /          \
              YES           NO
               │             │
               ▼             ▼
         Send to n8n     Local alarm +
               │         store event
               ▼
          n8n Webhook
               │
               ▼
          Validate event
               │
               ▼
          AI Vision
               │
               ▼
          AI Agent
               │
      ┌────────┼───────────────┐
      │        │               │
      ▼        ▼               ▼
   Telegram  Sheets       ThingSpeak
      │
      ├── Text
      ├── Photo
      ├── Location
      └── Voice alert

6. Hardware Design

Recommended prototype hardware

Core

  • ESP32-CAM AI Thinker or

  • ESP32-S3-EYE / ESP32-S3 camera board

For a new AI-oriented design, an ESP32-S3 camera board is attractive because Espressif's ESP32-S3-EYE integrates the camera, microphone, display, PSRAM and flash. GitHub

For the easiest Arduino prototype, however, the AI Thinker ESP32-CAM + external sensors is straightforward.

Sensors

  • OV2640 camera

  • NEO-6M GPS

  • Push-button SOS

  • Cancel button

  • Buzzer

  • Vibration motor

  • Optional INMP441 I2S microphone

  • Optional MPU6050 accelerometer/gyroscope

  • Optional battery voltage divider


7. Bill of Materials

Component Quantity Purpose
ESP32-CAM 1 Main controller
OV2640 1 Image capture
NEO-6M GPS 1 Location
SOS push button 1 Emergency trigger
Cancel button 1 False-alarm cancellation
Active buzzer 1 Local alarm
Vibration motor 1 Silent feedback
NPN transistor 1 Motor driver
1 kΩ resistor 1 Transistor base
10 kΩ resistor 1 Optional pull-down
Li-ion battery 1 Portable power
TP4056/protected charging circuit 1 Charging
5 V boost/buck regulator 1 ESP32 power
MPU6050 Optional Fall/motion detection
INMP441 Optional Voice detection
microSD Optional Local evidence storage

8. Recommended Hardware Block Diagram

                 ┌───────────────────┐
                 │   Li-Ion Battery  │
                 └─────────┬─────────┘
                           │
                     Power Management
                           │
                           ▼
                 ┌───────────────────┐
                 │      ESP32        │
                 │                   │
                 │ Wi-Fi             │
                 │ Camera Interface  │
                 │ UART              │
                 │ GPIO              │
                 └─────┬───┬───┬─────┘
                       │   │   │
             ┌─────────┘   │   └─────────┐
             ▼             ▼             ▼
          Camera          GPS          SOS
          OV2640         NEO-6M        Button
             │
             ▼
       Evidence Image

                       │
              ┌────────┴────────┐
              ▼                 ▼
           Buzzer          Vibration

9. ESP32-CAM AI Thinker Schematic

The following is a reference schematic. Verify the exact board revision before building the final PCB.

                  ESP32-CAM AI Thinker
             ┌────────────────────────────┐
             │                            │
             │             OV2640         │
             │              CAMERA        │
             │                            │
             │ GPIO16 <──── GPS TX        │
             │ GPIO17 ────> GPS RX        │
             │                            │
             │ GPIO13 <──── SOS BUTTON    │
             │ GPIO14 <──── CANCEL        │
             │ GPIO15 ────> BUZZER        │
             │                            │
             │ GPIO4  ────> Flash LED     │
             │                            │
             │ 5V <──────── Power         │
             │ GND ──────── GND          │
             └────────────────────────────┘

GPS NEO-6M
──────────
GPS VCC → 5V/3.3V according to module
GPS GND → GND
GPS TX  → ESP32 GPIO16
GPS RX  → ESP32 GPIO17


SOS BUTTON
──────────
GPIO13 ────────┐
               │
             BUTTON
               │
              GND

Use INPUT_PULLUP.


CANCEL BUTTON
─────────────
GPIO14 ────────┐
               │
             BUTTON
               │
              GND


BUZZER
──────
GPIO15 ──1kΩ──> NPN base
             NPN collector ── Buzzer -
             Buzzer + ─────── +5V
             NPN emitter ─── GND

10. Vibration Motor Circuit

Do not drive a vibration motor directly from an ESP32 GPIO.

Use:

ESP32 GPIO
    │
   1kΩ
    │
    ▼
   Base
    │
  2N2222
    │
 Collector
    │──────── Motor ───── +5V
    │
 Emitter
    │
   GND

Add a flyback diode across a DC motor:

        +5V
         │
       Motor
         │
         ├────|<|────┐
         │   diode   │
         │           │
         └──Collector

11. SOS Button Logic

The physical SOS button should be the highest-priority trigger.

SOS pressed
     │
     ▼
GPIO interrupt/event
     │
     ├── Turn buzzer ON
     ├── Vibrate
     ├── Capture photo
     ├── Read GPS
     ├── Create event ID
     └── Send event
              │
              ▼
             n8n

Do not make:

SOS → AI → decide whether it is dangerous → alert

because an AI failure could prevent an emergency alert.

Instead:

SOS → immediate alert
       +
       AI analysis for additional context

12. Threat Assessment Design

Avoid defining the AI as a perfect "threat detector."

Use:

AI-assisted risk assessment

The model can inspect:

  • number of visible people

  • whether a face/person is visible

  • unusual crowding

  • visible confrontation

  • apparent physical struggle

  • running/chasing context

  • visible dangerous objects

  • person lying on ground

  • unusual scene

  • whether image is unclear

But the output should be:

{
  "scene_summary": "Two people visible near the user",
  "faces_detected": 2,
  "risk_level": "HIGH",
  "confidence": 0.78,
  "reason": "Visible physical confrontation indicators",
  "recommended_action": "ESCALATE"
}

This is an AI assessment, not proof that a crime or threat has occurred.


13. Risk-State Model

Use four states:

NORMAL
   │
   ▼
WATCH
   │
   ▼
ALERT
   │
   ▼
EMERGENCY

Example:

State Meaning Action
NORMAL No event Log periodically
WATCH Sensor anomaly Monitor
ALERT Possible concern Notify user/guardian
EMERGENCY SOS / strong event Immediate alert

However, physical SOS always produces EMERGENCY, regardless of AI classification.


14. Event JSON

The ESP32/n8n interface should use a consistent data model.

{
  "device_id": "SAFETY-BAG-001",
  "event_id": "EVT-20261003-100501",
  "event_type": "SOS",
  "latitude": 17.3850,
  "longitude": 78.4867,
  "gps_accuracy": 8.4,
  "battery": 78,
  "wifi_rssi": -61,
  "timestamp": "2026-10-03T10:05:01+05:30"
}

The JPEG is transmitted separately as binary data.


15. ESP32 Firmware

Below is a reference Arduino firmware for an AI Thinker ESP32-CAM.

It:

  • connects to Wi-Fi

  • monitors SOS

  • reads GPS

  • captures JPEG

  • posts JPEG to n8n

  • activates buzzer

  • supports cancel

  • sends GPS metadata through URL parameters

Install:

  • ESP32 Arduino board package

  • TinyGPSPlus


ESP32 Code

#include "esp_camera.h"
#include <WiFi.h>
#include <HTTPClient.h>
#include <TinyGPSPlus.h>

// ----------------------------------------------------
// WiFi
// ----------------------------------------------------

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

// n8n webhook
const char* N8N_WEBHOOK =
  "https://YOUR-N8N-DOMAIN/webhook/safety-bag";

// Device identity
const char* DEVICE_ID = "SAFETY-BAG-001";

// ----------------------------------------------------
// GPIO
// ----------------------------------------------------

#define SOS_PIN       13
#define CANCEL_PIN    14
#define BUZZER_PIN    15

// GPS UART
#define GPS_RX_PIN    16
#define GPS_TX_PIN    17

HardwareSerial GPSserial(2);
TinyGPSPlus gps;

// ----------------------------------------------------
// AI Thinker ESP32-CAM camera pins
// ----------------------------------------------------

#define PWDN_GPIO_NUM     32
#define RESET_GPIO_NUM    -1
#define XCLK_GPIO_NUM      0
#define SIOD_GPIO_NUM     26
#define SIOC_GPIO_NUM     27

#define Y9_GPIO_NUM       35
#define Y8_GPIO_NUM       34
#define Y7_GPIO_NUM       39
#define Y6_GPIO_NUM       36
#define Y5_GPIO_NUM       21
#define Y4_GPIO_NUM       19
#define Y3_GPIO_NUM       18
#define Y2_GPIO_NUM        5
#define VSYNC_GPIO_NUM    25
#define HREF_GPIO_NUM     23
#define PCLK_GPIO_NUM     22

// ----------------------------------------------------

bool emergencyActive = false;
unsigned long lastTrigger = 0;

const unsigned long DEBOUNCE_TIME = 3000;

// ----------------------------------------------------

void connectWiFi()
{
  Serial.println("Connecting WiFi...");

  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

  unsigned long start = millis();

  while (WiFi.status() != WL_CONNECTED &&
         millis() - start < 20000)
  {
    delay(500);
    Serial.print(".");
  }

  Serial.println();

  if (WiFi.status() == WL_CONNECTED)
  {
    Serial.println("WiFi connected");
    Serial.println(WiFi.localIP());
  }
  else
  {
    Serial.println("WiFi connection failed");
  }
}

// ----------------------------------------------------

bool initCamera()
{
  camera_config_t config;

  config.ledc_channel = LEDC_CHANNEL_0;
  config.ledc_timer = LEDC_TIMER_0;

  config.pin_d0 = Y2_GPIO_NUM;
  config.pin_d1 = Y3_GPIO_NUM;
  config.pin_d2 = Y4_GPIO_NUM;
  config.pin_d3 = Y5_GPIO_NUM;
  config.pin_d4 = Y6_GPIO_NUM;
  config.pin_d5 = Y7_GPIO_NUM;
  config.pin_d6 = Y8_GPIO_NUM;
  config.pin_d7 = Y9_GPIO_NUM;

  config.pin_xclk = XCLK_GPIO_NUM;
  config.pin_pclk = PCLK_GPIO_NUM;
  config.pin_vsync = VSYNC_GPIO_NUM;
  config.pin_href = HREF_GPIO_NUM;

  config.pin_sccb_sda = SIOD_GPIO_NUM;
  config.pin_sccb_scl = SIOC_GPIO_NUM;

  config.pin_pwdn = PWDN_GPIO_NUM;
  config.pin_reset = RESET_GPIO_NUM;

  config.xclk_freq_hz = 20000000;

  config.pixel_format = PIXFORMAT_JPEG;

  if (psramFound())
  {
    config.frame_size = FRAMESIZE_VGA;
    config.jpeg_quality = 10;
    config.fb_count = 2;
  }
  else
  {
    config.frame_size = FRAMESIZE_QVGA;
    config.jpeg_quality = 12;
    config.fb_count = 1;
  }

  esp_err_t result = esp_camera_init(&config);

  if (result != ESP_OK)
  {
    Serial.printf(
      "Camera initialization failed: 0x%x\n",
      result
    );

    return false;
  }

  Serial.println("Camera initialized");

  return true;
}

// ----------------------------------------------------

void readGPS()
{
  unsigned long start = millis();

  while (millis() - start < 1000)
  {
    while (GPSserial.available())
    {
      gps.encode(GPSserial.read());
    }
  }
}

// ----------------------------------------------------

String gpsLatitude()
{
  if (gps.location.isValid())
    return String(gps.location.lat(), 6);

  return "0";
}

// ----------------------------------------------------

String gpsLongitude()
{
  if (gps.location.isValid())
    return String(gps.location.lng(), 6);

  return "0";
}

// ----------------------------------------------------

void localAlarm()
{
  digitalWrite(BUZZER_PIN, HIGH);

  delay(500);

  digitalWrite(BUZZER_PIN, LOW);
}

// ----------------------------------------------------

bool uploadPhoto()
{
  if (WiFi.status() != WL_CONNECTED)
  {
    Serial.println("WiFi unavailable");
    return false;
  }

  camera_fb_t* fb = esp_camera_fb_get();

  if (!fb)
  {
    Serial.println("Camera capture failed");
    return false;
  }

  String url = String(N8N_WEBHOOK);

  url += "?device_id=";
  url += DEVICE_ID;

  url += "&event_type=SOS";

  url += "&latitude=";
  url += gpsLatitude();

  url += "&longitude=";
  url += gpsLongitude();

  url += "&wifi_rssi=";
  url += WiFi.RSSI();

  Serial.println("Uploading emergency image...");
  Serial.println(url);

  HTTPClient http;

  http.begin(url);

  http.addHeader(
    "Content-Type",
    "image/jpeg"
  );

  http.addHeader(
    "X-Device-ID",
    DEVICE_ID
  );

  http.addHeader(
    "X-Event-Type",
    "SOS"
  );

  int responseCode =
    http.POST(
      fb->buf,
      fb->len
    );

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

  if (responseCode > 0)
  {
    String response = http.getString();

    Serial.println(response);
  }

  http.end();

  esp_camera_fb_return(fb);

  return responseCode >= 200 &&
         responseCode < 300;
}

// ----------------------------------------------------

void triggerEmergency()
{
  if (millis() - lastTrigger < DEBOUNCE_TIME)
    return;

  lastTrigger = millis();

  emergencyActive = true;

  Serial.println();
  Serial.println("==============================");
  Serial.println("       EMERGENCY EVENT");
  Serial.println("==============================");

  // Immediate local feedback
  localAlarm();

  // Get GPS
  readGPS();

  Serial.print("Latitude: ");
  Serial.println(gpsLatitude());

  Serial.print("Longitude: ");
  Serial.println(gpsLongitude());

  // Upload image
  bool success = uploadPhoto();

  if (success)
  {
    Serial.println("Emergency event uploaded");
  }
  else
  {
    Serial.println("Upload failed");
  }
}

// ----------------------------------------------------

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

  pinMode(SOS_PIN, INPUT_PULLUP);
  pinMode(CANCEL_PIN, INPUT_PULLUP);

  pinMode(BUZZER_PIN, OUTPUT);

  digitalWrite(BUZZER_PIN, LOW);

  GPSserial.begin(
    9600,
    SERIAL_8N1,
    GPS_RX_PIN,
    GPS_TX_PIN
  );

  Serial.println();
  Serial.println("AI Safety Bag Starting...");

  if (!initCamera())
  {
    Serial.println("Camera error");
  }

  connectWiFi();
}

// ----------------------------------------------------

void loop()
{
  // Keep GPS parser alive
  while (GPSserial.available())
  {
    gps.encode(GPSserial.read());
  }

  // SOS pressed
  if (digitalRead(SOS_PIN) == LOW)
  {
    triggerEmergency();

    delay(1000);
  }

  // Cancel
  if (digitalRead(CANCEL_PIN) == LOW)
  {
    emergencyActive = false;

    digitalWrite(BUZZER_PIN, LOW);

    Serial.println("Emergency cancelled");

    delay(1000);
  }

  // Reconnect WiFi
  if (WiFi.status() != WL_CONNECTED)
  {
    connectWiFi();
  }

  delay(20);
}

16. Important Firmware Improvement

For the final product, don't rely exclusively on:

Wi-Fi → n8n

If Wi-Fi fails, the device should still:

  • sound/vibrate

  • capture the image

  • save the image locally

  • store GPS

  • queue the event

  • retry transmission later

Use:

SOS
 │
 ├── Local alarm
 ├── Capture image
 ├── Save SD
 ├── Save GPS
 └── Try cloud upload
          │
          ├── Success → delete queued copy
          │
          └── Failure → retry later

17. n8n Architecture

Create an n8n workflow:

Webhook
   │
   ▼
Validate Event
   │
   ▼
Extract Metadata
   │
   ├───────────────┐
   │               │
   ▼               ▼
AI Vision       Google Sheets
   │
   ▼
AI Agent
   │
   ▼
Risk Router
   │
   ├──────────── NORMAL
   │
   ├──────────── ALERT
   │
   └──────────── EMERGENCY
                         │
            ┌────────────┼─────────────┐
            ▼            ▼             ▼
        Telegram      Location      Voice
        Message        Alert         Alert
            │
            ▼
        ThingSpeak

n8n's Telegram integration supports sending messages, photos, locations and other Telegram operations. n8n Docs


18. n8n Workflow 1 — Emergency Webhook

Create:

Node 1 — Webhook

Method:

POST

Path:

safety-bag

The ESP32 sends:

POST /webhook/safety-bag
Content-Type: image/jpeg
X-Device-ID: SAFETY-BAG-001
X-Event-Type: SOS

Query parameters:

device_id
event_type
latitude
longitude
wifi_rssi

The binary JPEG becomes the image input for subsequent processing.


19. n8n Workflow Nodes

Use approximately:

01 Webhook
       ↓
02 Set / Edit Fields
       ↓
03 Validate Event
       ↓
04 AI Vision
       ↓
05 AI Agent
       ↓
06 IF / Switch
       ↓
 ┌─────┼─────────┐
 ▼     ▼         ▼
07    08        09
Telegram Sheets ThingSpeak
       │
       ▼
     Voice

20. Metadata Node

Create normalized data:

{
  "device_id": "{{$json.query.device_id}}",
  "event_type": "{{$json.query.event_type}}",
  "latitude": "{{$json.query.latitude}}",
  "longitude": "{{$json.query.longitude}}",
  "timestamp": "{{$now}}"
}

21. AI Vision Prompt

The vision model should receive:

  • captured image

  • GPS context

  • event type

  • device information

Use a prompt similar to:

You are the visual assessment component of a personal safety IoT system.

Analyze the supplied image conservatively.

Do not claim that a crime has occurred.

Determine only observable characteristics.

Return JSON:

{
  "faces_detected": integer,
  "people_detected": integer,
  "scene_summary": string,
  "visible_concerning_activity": boolean,
  "image_quality": "GOOD|POOR",
  "risk_indicators": [],
  "confidence": number
}

Important:

- Do not identify people by identity.
- Do not infer protected characteristics.
- Do not infer intent from appearance.
- Do not claim certainty about danger.
- Describe only visible evidence.

22. AI Agent

The AI Agent receives:

{
  "event_type": "SOS",
  "gps": {
    "latitude": 17.385,
    "longitude": 78.4867
  },
  "vision": {
    "faces_detected": 2,
    "people_detected": 2,
    "visible_concerning_activity": true,
    "confidence": 0.78
  }
}

Agent prompt:

You are the emergency-event orchestration agent.

Your job is to transform sensor and AI-analysis information
into a safe notification decision.

Rules:

1. A physical SOS button is always an emergency event.
2. Never cancel an SOS because the image appears normal.
3. Never claim that AI has proved that someone is dangerous.
4. Clearly distinguish sensor facts from AI assessment.
5. If GPS is available, prepare a location alert.
6. If GPS is unavailable, explicitly state that location is unavailable.
7. Keep emergency messages short.
8. Return structured JSON only.

Output:

{
  "priority": "EMERGENCY|ALERT|NORMAL",
  "message": "",
  "voice_message": "",
  "send_photo": true,
  "send_location": true,
  "log_event": true
}

23. Example AI Agent Output

{
  "priority": "EMERGENCY",
  "message": "SOS activated from Safety Bag 001. GPS location is available. An image was captured for context. Please check the user's location immediately.",
  "voice_message": "Emergency SOS activated. The safety bag has reported an emergency. Please check the user's location immediately.",
  "send_photo": true,
  "send_location": true,
  "log_event": true
}

Notice that it doesn't say:

"A criminal is attacking her."

Instead it reports:

"SOS activated."

That distinction is important.


24. Telegram Alert

Telegram supports bot HTTP requests and file uploads; its current Bot API supports sendVoice, and voice messages can use OGG/Opus, MP3 or M4A formats. Telegram

A typical alert:

🚨 SAFETY BAG EMERGENCY

Device:
SAFETY-BAG-001

Event:
SOS BUTTON ACTIVATED

Time:
10:05:01

Location:
17.385000, 78.486700

AI visual assessment:
2 people detected.
Possible concerning activity detected.

⚠️ AI assessment is contextual and may be incorrect.

Please check the user immediately.

25. Telegram Location

Send:

Latitude:
17.385000

Longitude:
78.486700

Telegram Bot API provides location-sending functionality, and n8n exposes Telegram message operations including location. n8n Docs+1


26. Telegram Voice Alert

Recommended flow:

AI Agent
    │
    ▼
voice_message
    │
    ▼
Text-to-Speech
    │
    ▼
OGG/Opus or compatible audio
    │
    ▼
Telegram sendVoice
    │
    ▼
Guardian phone

Example:

"Emergency SOS activated.
The safety bag has reported an emergency.
Please check the user's location immediately."

For Telegram voice messages, use the Bot API's sendVoice operation rather than treating the file as ordinary music/audio. Telegram


27. Google Sheets Database

Create a spreadsheet:

Sheet: Emergency_Events

Column Value
timestamp Event timestamp
device_id Safety Bag ID
event_id Unique ID
event_type SOS
latitude GPS
longitude GPS
battery Battery %
faces AI count
people AI count
risk AI assessment
confidence AI confidence
image_url Evidence URL
notification SENT/FAILED
status OPEN/CLOSED

n8n has a built-in Google Sheets integration, so the event can be appended directly into the spreadsheet rather than requiring a custom Google API backend. n8n Docs


28. Example Google Sheets Record

2026-10-03 10:05:01
SAFETY-BAG-001
EVT-000123
SOS
17.385000
78.486700
78
2
2
EMERGENCY
0.78
https://storage.example/event123.jpg
SENT
OPEN

29. ThingSpeak Integration

ThingSpeak is useful for numeric telemetry, rather than storing sensitive images.

Suggested fields:

Field Data
Field 1 Battery
Field 2 Wi-Fi RSSI
Field 3 SOS
Field 4 GPS latitude
Field 5 GPS longitude
Field 6 Face count
Field 7 Risk score
Field 8 Device status

ThingSpeak provides REST and MQTT mechanisms for updating channel data. Its current REST API supports POST/GET updates through api.thingspeak.com/update. MathWorks+1


30. ThingSpeak Example

n8n HTTP Request:

POST

https://api.thingspeak.com/update.json

Parameters:

api_key = YOUR_WRITE_API_KEY
field1 = 78
field2 = -61
field3 = 1
field4 = 17.385000
field5 = 78.486700
field6 = 2
field7 = 0.78
field8 = 1

ThingSpeak documents the Write API Key as the credential used to update a channel. MathWorks+1


31. ThingSpeak Update Rate

Do not continuously transmit at a very high rate.

For a free ThingSpeak license, the documented channel update interval is 15 seconds; paid plans can support faster updates. MathWorks

For this safety-bag project, a good strategy is:

Normal telemetry:
30–60 seconds

Emergency:
Immediate

Post-emergency:
Every 15–30 seconds for a limited period

32. Web Dashboard

Create a webpage containing:

┌─────────────────────────────────────────────┐
│       AI SAFETY BAG DASHBOARD              │
├─────────────────────────────────────────────┤
│                                             │
│ Device: SAFETY-BAG-001                     │
│ Status: 🔴 EMERGENCY                        │
│                                             │
│ Battery: 78%                               │
│ Wi-Fi: -61 dBm                             │
│ GPS: FIX                                    │
│                                             │
│ Latitude: 17.385000                         │
│ Longitude: 78.486700                       │
│                                             │
│ [ OPEN LOCATION ]                           │
│                                             │
├─────────────────────────────────────────────┤
│ Latest Event                                │
│                                             │
│ SOS BUTTON ACTIVATED                        │
│                                             │
│ AI Assessment                               │
│ 2 people detected                           │
│ Concerning activity: possible              │
│ Confidence: 78%                              │
│                                             │
├─────────────────────────────────────────────┤
│ Recent Events                               │
│                                             │
│ 10:05 SOS                                   │
│ 09:50 NORMAL                                │
│ 09:35 NORMAL                                │
└─────────────────────────────────────────────┘

33. Dashboard Architecture

                    ESP32
                      │
                      ▼
                    n8n
                      │
             ┌────────┴─────────┐
             │                  │
             ▼                  ▼
        Google Sheets       ThingSpeak
             │                  │
             └────────┬─────────┘
                      ▼
                 Web Dashboard

For a simple academic project, ThingSpeak can provide the graphs while a separate HTML page shows the latest emergency state.

ThingSpeak supports reading channel feeds through its REST API, including JSON responses, which can be consumed by a webpage or server. MathWorks


34. Simple Dashboard HTML

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>AI Safety Bag</title>

  <style>
    body {
      font-family: Arial, sans-serif;
      background: #111827;
      color: white;
      margin: 0;
      padding: 20px;
    }

    .card {
      background: #1f2937;
      padding: 20px;
      margin-bottom: 15px;
      border-radius: 15px;
    }

    .status {
      font-size: 30px;
      font-weight: bold;
      color: #22c55e;
    }

    .emergency {
      color: #ef4444;
    }

    button {
      padding: 12px 20px;
      border: 0;
      border-radius: 8px;
      background: #3b82f6;
      color: white;
    }
  </style>
</head>

<body>

<h1>🚨 AI Safety Bag Dashboard</h1>

<div class="card">

  <h2>Device</h2>

  <p>
    ID:
    <span id="device">SAFETY-BAG-001</span>
  </p>

  <p>
    Status:
    <span id="status" class="status">
      NORMAL
    </span>
  </p>

</div>

<div class="card">

  <h2>GPS</h2>

  <p>
    Latitude:
    <span id="lat">--</span>
  </p>

  <p>
    Longitude:
    <span id="lon">--</span>
  </p>

  <button onclick="openLocation()">
    Open Location
  </button>

</div>

<div class="card">

  <h2>Telemetry</h2>

  <p>
    Battery:
    <span id="battery">--</span>%
  </p>

  <p>
    Wi-Fi RSSI:
    <span id="rssi">--</span>
  </p>

</div>

<script>

let latitude = 0;
let longitude = 0;

function updateDashboard(data) {

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

  document.getElementById("lat")
    .innerText = data.latitude;

  document.getElementById("lon")
    .innerText = data.longitude;

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

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

  latitude = data.latitude;
  longitude = data.longitude;

  if (data.status === "EMERGENCY") {

    document
      .getElementById("status")
      .classList.add("emergency");

  }
}

function openLocation() {

  if (!latitude || !longitude)
    return;

  const url =
    "https://www.google.com/maps?q="
    + latitude
    + ","
    + longitude;

  window.open(url, "_blank");
}

</script>

</body>
</html>

35. n8n Workflow — Complete Logical Design

┌──────────────────┐
│ ESP32-CAM        │
│ SOS + GPS + JPEG │
└────────┬─────────┘
         │
         │ HTTPS POST
         ▼
┌──────────────────┐
│ Webhook          │
│ /safety-bag      │
└────────┬─────────┘
         │
         ▼
┌──────────────────┐
│ Validate Request │
└────────┬─────────┘
         │
         ▼
┌──────────────────┐
│ Normalize Data   │
└────────┬─────────┘
         │
         ├──────────────────────┐
         │                      │
         ▼                      ▼
┌──────────────────┐     ┌────────────────┐
│ Vision Analysis  │     │ Google Sheets  │
└────────┬─────────┘     └────────────────┘
         │
         ▼
┌──────────────────┐
│ AI Agent         │
└────────┬─────────┘
         │
         ▼
┌──────────────────┐
│ Switch           │
│ EMERGENCY/ALERT  │
└───────┬──────────┘
        │
        ├───────────────┐
        │               │
        ▼               ▼
┌──────────────┐  ┌──────────────┐
│ Telegram     │  │ ThingSpeak   │
│ Text/Photo   │  │ Telemetry    │
└──────┬───────┘  └──────────────┘
       │
       ▼
┌──────────────┐
│ TTS          │
└──────┬───────┘
       │
       ▼
┌──────────────┐
│ Telegram     │
│ Voice        │
└──────────────┘

36. n8n Error Workflow

You should also build a second workflow:

n8n Error Trigger
       │
       ▼
Identify failed workflow
       │
       ▼
Send Telegram admin alert
       │
       ▼
Log failure

Example:

⚠️ SAFETY SYSTEM ERROR

Workflow:
Emergency Processing

Device:
SAFETY-BAG-001

Failure:
Telegram notification failed

Action:
Check n8n execution.

37. Offline Safety Architecture

This is especially important.

                SOS
                 │
        ┌────────┼─────────┐
        │        │         │
        ▼        ▼         ▼
      Alarm     Photo     GPS
        │        │         │
        └────────┼─────────┘
                 ▼
            Local Storage
                 │
                 ▼
             Wi-Fi?
             /     \
           YES      NO
           │         │
           ▼         ▼
          n8n      Queue
                     │
                     ▼
                 Retry later

If the cloud system is unavailable, the device must not silently fail.


38. Optional Voice Trigger

A microphone can be added for phrases such as:

"HELP"
"SOS"
"CALL HELP"

Architecture:

Microphone
    │
    ▼
ESP32 audio capture
    │
    ▼
Keyword detection
    │
    ▼
Emergency state

For the first prototype, I recommend using the physical button as the primary trigger and adding voice activation later.


39. Optional Fall Detection

Add MPU6050:

MPU6050
   │
   ├── Accelerometer
   └── Gyroscope
          │
          ▼
       ESP32
          │
          ▼
  Motion anomaly algorithm
          │
          ▼
      Possible fall

Example:

Acceleration > threshold
        +
orientation change
        +
no movement afterward
        ↓
Possible fall
        ↓
3-second cancellation window
        ↓
No cancellation
        ↓
Emergency event

This should be treated as an additional trigger, not definitive evidence.


40. Three-Stage Emergency Confirmation

For accidental triggers, use:

Stage 1

SOS button pressed

Immediately:

Vibration + LED

Stage 2

3-second cancellation window

Stage 3

If not cancelled:

Cloud emergency notification

However, if your goal is maximum emergency reliability, don't delay the initial notification. Instead send:

SOS activated — awaiting cancellation

then escalate if not cancelled.


41. Telegram Conversation Example

System → Guardian

🚨 SAFETY BAG ALERT

Device: SAFETY-BAG-001

SOS button activated.

Location:
17.385000, 78.486700

Photo captured.

AI visual assessment:
2 people detected.
Possible concerning activity observed.

Confidence: 78%

Please check the user's location.

Voice message

"Emergency SOS activated.
Please check the user's location immediately."

Guardian → Bot

/status

Bot

SAFETY BAG STATUS

Device: SAFETY-BAG-001

Battery: 78%
GPS: Available
Wi-Fi: Connected
Last event: SOS
Last update: 10:05:04

42. Telegram Commands

Implement:

/start
/status
/location
/last
/arm
/disarm
/test
/help

Example:

/status

→ Device online
→ Battery 78%
→ GPS available
→ Last event: NORMAL

43. AI Agent Chat Example

The internal n8n AI Agent can receive:

EVENT:
SOS

GPS:
Available

CAMERA:
Image available

VISION:
2 people detected.
Possible physical confrontation indicators.
Confidence 0.78.

Agent:

ACTION:
EMERGENCY

SEND:
✓ Telegram text
✓ Telegram location
✓ Telegram photo
✓ Telegram voice
✓ Google Sheets
✓ ThingSpeak

44. Face Capture

There are two different concepts:

Face detection

Is there a human face?

Face recognition

Does this face match a previously enrolled identity?

For a safety device, face detection is safer and simpler.

The system can report:

Faces detected: 2

rather than:

Person X is dangerous.

Espressif's ESP-WHO framework supports face detection and recognition examples on supported ESP32-family hardware. GitHub+1


45. Privacy Architecture

Do not continuously upload camera frames.

Recommended:

Normal:
Camera OFF / local processing

SOS:
Capture image

Emergency:
Upload evidence

After event:
Delete temporary image according to retention policy

Also:

  • encrypt communications with HTTPS

  • don't expose ThingSpeak write keys in frontend JavaScript

  • don't expose Telegram bot token

  • don't store unnecessary face identities

  • restrict Google Sheet sharing

  • protect n8n webhook

  • use a random device authentication token

  • rotate credentials if leaked


46. Security Improvement

Don't use:

https://n8n.example/webhook/safety-bag

alone.

Use an authentication header:

X-Device-Token:
YOUR_SECRET_DEVICE_TOKEN

n8n validates:

IF X-Device-Token == configured secret
       │
       ├── YES → process
       │
       └── NO → reject

Better still, use per-device credentials and HTTPS.


47. Device Authentication

ESP32:

http.addHeader(
  "X-Device-Token",
  "YOUR_SECRET_TOKEN"
);

n8n:

Webhook
   ↓
Check Authentication
   ↓
Valid?
 /    \
No     Yes
│       │
Reject   Process

48. Event ID Generation

Every emergency should have a unique ID.

Example:

EVT-20261003-100501-001

Use it in:

  • Google Sheets

  • Telegram

  • ThingSpeak status

  • image filename

  • dashboard

  • n8n execution metadata

This makes debugging much easier.


49. Image Filename

Example:

SAFETY-BAG-001/
    2026/
      10/
        03/
          EVT-20261003-100501.jpg

Avoid publicly accessible image URLs unless the user explicitly chooses that storage model.


50. Testing Plan

Test 1 — Camera

Expected:

Capture successful
JPEG generated

Test 2 — GPS

Expected:

GPS FIX
Latitude
Longitude

Test 3 — SOS

Press button.

Expected:

Buzzer ON
Photo captured
GPS read
n8n receives event

Test 4 — n8n

Expected:

Webhook
 → AI
 → Telegram
 → Google Sheets
 → ThingSpeak

Test 5 — Telegram

Expected:

Text ✓
Photo ✓
Location ✓
Voice ✓

Test 6 — Wi-Fi failure

Turn off Wi-Fi.

Expected:

Alarm continues
Photo saved
Event queued

Test 7 — AI failure

Disable AI API.

Expected:

SOS still produces Telegram emergency notification.

This is a very important acceptance test.


51. System Test Matrix

Test Expected
SOS pressed Emergency event
Camera disconnected Alert still generated
GPS unavailable Alert without location
Wi-Fi unavailable Local alarm + queue
AI unavailable SOS still sent
Telegram unavailable Error logged
Google Sheets unavailable Alert still sent
ThingSpeak unavailable Alert still sent
Low battery Warning
Cancel pressed Event cancelled only according to configured policy

52. Failure Priority

The system should prioritize:

1. Local SOS
2. Emergency notification
3. GPS
4. Evidence capture
5. Telegram
6. Logging
7. Dashboard
8. Analytics

Never allow:

Google Sheets failure

to prevent:

SOS alert

53. Complete Data Flow

                    USER
                     │
                     │ SOS
                     ▼
              ┌─────────────┐
              │ ESP32       │
              │ Controller  │
              └──────┬──────┘
                     │
       ┌─────────────┼──────────────┐
       │             │              │
       ▼             ▼              ▼
     Camera         GPS           Sensors
       │             │              │
       └─────────────┼──────────────┘
                     │
                     ▼
                  Wi-Fi
                     │
                     ▼
               ┌───────────┐
               │    n8n    │
               └─────┬─────┘
                     │
              ┌──────┴───────┐
              ▼              ▼
         AI Vision        Database
              │
              ▼
          AI Agent
              │
        ┌─────┼─────┬──────────┐
        ▼     ▼     ▼          ▼
    Telegram  Voice Sheets  ThingSpeak
        │
        ▼
    Guardian
        │
        ▼
   Emergency response

54. Agentic IoT Concept

The project becomes "agentic" when the AI component isn't merely generating text but orchestrates actions.

Instead of:

ESP32 → AI → text

use:

ESP32
  ↓
Event
  ↓
AI Agent
  ↓
Decide actions
  ├── send Telegram
  ├── send location
  ├── send image
  ├── generate voice
  ├── log event
  ├── update dashboard
  └── request follow-up status

n8n currently documents AI Agents and tools/workflows that can be connected to agentic workflows. n8n Docs


55. Recommended Final Project Structure

AI-WOMEN-SAFETY-BAG/
│
├── firmware/
│   ├── safety_bag.ino
│   ├── camera.cpp
│   ├── gps.cpp
│   └── config.h
│
├── n8n/
│   ├── emergency-workflow.json
│   ├── telemetry-workflow.json
│   └── error-workflow.json
│
├── dashboard/
│   ├── index.html
│   ├── style.css
│   └── dashboard.js
│
├── documentation/
│   ├── architecture.md
│   ├── hardware.md
│   ├── software.md
│   ├── testing.md
│   └── api.md
│
└── README.md

56. Project Modules for a College/Final-Year Project

Divide the project into seven modules.

Module 1 — Embedded System

ESP32
Camera
GPS
SOS
Buzzer
Battery

Module 2 — IoT Communication

Wi-Fi
HTTPS
Webhook
JSON

Module 3 — AI Vision

Image
   ↓
Face/person detection
   ↓
Scene assessment

Module 4 — AI Agent

Sensor data
+
Vision result
+
SOS state
      ↓
AI Agent
      ↓
Action plan

Module 5 — Automation

n8n
 ↓
Telegram
Google Sheets
ThingSpeak
TTS

Module 6 — Dashboard

Live status
GPS
battery
events
risk state

Module 7 — Safety & Reliability

offline mode
retry
authentication
logging
privacy

57. Proposed Project Objectives

You can put these directly into your project report:

  1. To design a portable IoT-enabled personal safety device.

  2. To implement emergency activation using an ESP32 controller.

  3. To capture photographic evidence during an emergency.

  4. To acquire the user's geographical location using GPS.

  5. To implement AI-assisted visual scene assessment.

  6. To develop an agentic automation layer using n8n.

  7. To provide emergency notifications through Telegram.

  8. To generate voice-based emergency notifications.

  9. To maintain an event history using Google Sheets.

  10. To visualize IoT telemetry using ThingSpeak.

  11. To develop a web-based monitoring dashboard.

  12. To provide local operation when cloud connectivity is unavailable.

  13. To implement basic authentication and privacy controls.

  14. To evaluate the system using controlled emergency scenarios.


58. Expected Output

When the user presses SOS:

              SOS
               │
               ▼
        🔊 LOCAL ALARM
               │
               ▼
          📷 PHOTO
               │
               ▼
          📍 GPS
               │
               ▼
           ☁️ n8n
               │
       ┌───────┼─────────┐
       ▼       ▼         ▼
      🤖 AI   📊 LOG    📈 IoT
       │
       ▼
   🚨 TELEGRAM
       │
   ┌───┼──────────┐
   ▼   ▼          ▼
 TEXT PHOTO     LOCATION
       │
       ▼
      🔊
   VOICE ALERT

59. Final Recommended Architecture

For a strong prototype, I would use:

ESP32-S3 Camera Board
        +
GPS
        +
SOS Button
        +
Buzzer
        +
Vibration
        +
Optional MPU6050
        +
Optional microphone
        │
        ▼
       Wi-Fi
        │
        ▼
      n8n
        │
   ┌────┴─────────────┐
   │                  │
   ▼                  ▼
AI Vision          AI Agent
   │                  │
   └────────┬─────────┘
            │
      ┌─────┼─────────────┐
      ▼     ▼             ▼
  Telegram Sheets      ThingSpeak
      │
      ▼
Voice Alert
      │
      ▼
Guardian

The ESP32-S3-EYE is particularly suitable if you want a more integrated AI prototype because Espressif documents its 2-MP camera, digital microphone, 8 MB PSRAM and ESP-WHO-based AI capabilities. GitHub


60. Documentation Chapter Structure

For a complete 50–80 page academic/project report, use this structure:

CHAPTER 1
Introduction

1.1 Background
1.2 Problem Statement
1.3 Motivation
1.4 Objectives
1.5 Scope
1.6 Limitations

CHAPTER 2
Literature / Existing System

2.1 Existing Safety Devices
2.2 IoT Safety Systems
2.3 AI Vision
2.4 Agentic Automation
2.5 Limitations of Existing Systems

CHAPTER 3
Proposed System

3.1 Architecture
3.2 Hardware
3.3 Software
3.4 Communication
3.5 AI Layer
3.6 Automation Layer

CHAPTER 4
Hardware Design

4.1 ESP32
4.2 Camera
4.3 GPS
4.4 SOS Button
4.5 Buzzer
4.6 Vibration
4.7 Battery
4.8 Circuit Diagram

CHAPTER 5
Software Design

5.1 ESP32 Firmware
5.2 Wi-Fi
5.3 HTTP
5.4 n8n
5.5 AI Vision
5.6 AI Agent
5.7 Telegram
5.8 Google Sheets
5.9 ThingSpeak
5.10 Web Dashboard

CHAPTER 6
Implementation

6.1 Hardware Assembly
6.2 Firmware
6.3 n8n Workflow
6.4 AI Configuration
6.5 Telegram Configuration
6.6 Dashboard

CHAPTER 7
Testing

7.1 Unit Testing
7.2 Integration Testing
7.3 Emergency Testing
7.4 Network Failure Testing
7.5 AI Failure Testing
7.6 Performance Testing

CHAPTER 8
Results

8.1 Response Time
8.2 GPS Accuracy
8.3 Image Capture
8.4 Notification Reliability
8.5 Dashboard
8.6 AI Assessment

CHAPTER 9
Security and Privacy

9.1 Authentication
9.2 HTTPS
9.3 Data Retention
9.4 Image Privacy
9.5 API Key Security

CHAPTER 10
Conclusion and Future Scope

Key implementation note

For the first working prototype, I recommend not trying to make the ESP32 itself decide whether someone is a threat. Make the ESP32 a reliable emergency sensor/camera, and let the AI layer provide contextual assessment. That separation gives you a much more defensible engineering design:

ESP32 = "Something happened."
AI     = "Here is what the available evidence appears to show."
n8n   = "Here are the automated actions."
Human = "Makes the real-world emergency decision."

That architecture also means an AI mistake cannot suppress a physical SOS.

For the cloud pieces, the official documentation confirms the current capabilities used here: n8n has Telegram/Google Sheets/AI Agent integrations, Telegram supports bot HTTP APIs and voice messages, and ThingSpeak supports REST/MQTT channel telemetry. n8n Docs+3

Useful official documentation

  • Espressif ESP-WHO

  • n8n Telegram integration

  • Telegram Bot API

  • ThingSpeak REST API

  • ThingSpeak Write Data API

If you implement this as a final-year project, the next practical stage is to turn the above into three concrete deliverables: (1) an exact ESP32-S3/ESP32-CAM circuit with pin-by-pin wiring, (2) importable n8n workflow JSON with the AI/Telegram/Sheets/ThingSpeak nodes, and (3) a complete responsive HTML/CSS/JavaScript dashboard plus the finalized ESP32 firmware.

Project Summary

AI Women Safety Bag is a portable IoT safety system built around an ESP32 camera controller, GPS, SOS button, local alarm, n8n automation, AI vision/agent processing, Telegram alerts, Google Sheets, ThingSpeak, and a web dashboard.

Core flow

SOS Button
    ↓
ESP32
 ├─ Capture photo
 ├─ Read GPS
 ├─ Activate buzzer/vibration
 └─ Send emergency event
          ↓
        n8n
          ↓
     AI Vision
          ↓
      AI Agent
          ↓
 ┌────────┼─────────┐
 ↓        ↓         ↓
Telegram  Sheets   ThingSpeak
 ↓
Text + Photo + GPS
 ↓
Voice Alert
 ↓
Guardian

Main hardware

  • ESP32-CAM or ESP32-S3 camera board

  • OV2640 camera

  • GPS module such as NEO-6M

  • Physical SOS button

  • Cancel button

  • Buzzer

  • Vibration motor

  • Battery and charging circuit

  • Optional MPU6050 for fall/motion detection

  • Optional microphone

  • Optional microSD for offline evidence

Software stack

  • ESP32 Arduino firmware

  • Wi-Fi + HTTPS

  • n8n workflow automation

  • AI vision model

  • AI Agent

  • Telegram Bot

  • Text-to-speech → Telegram voice

  • Google Sheets incident database

  • ThingSpeak IoT telemetry

  • HTML/CSS/JavaScript web dashboard

Most important design principle

The AI should assist, not control the emergency trigger:

Physical SOS → immediate emergency alert
                    +
              AI assessment
                    +
             automated actions

So an AI error, network failure, or incorrect image interpretation should not prevent an SOS alert.

Expected emergency notification

🚨 SAFETY BAG EMERGENCY

Device: SAFETY-BAG-001
Event: SOS ACTIVATED

GPS: 17.385000, 78.486700

Photo: Captured

AI assessment:
2 people detected.
Possible concerning activity observed.

Please check the user's location immediately.

Then the system can send:

  • 📱 Telegram text

  • 📷 Captured image

  • 📍 GPS location

  • 🔊 Telegram voice alert

  • 📊 Google Sheets record

  • 📈 ThingSpeak telemetry

  • 🖥️ Dashboard update

Project modules

  1. Embedded system — ESP32, camera, GPS, SOS, alarm.

  2. IoT communication — Wi-Fi, HTTPS, webhook.

  3. AI vision — scene/face/person assessment.

  4. AI Agent — determines notification actions.

  5. n8n automation — coordinates services.

  6. Emergency communication — Telegram + voice.

  7. Cloud monitoring — Google Sheets + ThingSpeak.

  8. Web dashboard — live status and event history.

  9. Reliability/security — offline queue, authentication, HTTPS and privacy.

Final-year project title

“AI-Powered Women Safety Bag Using ESP32, Agentic IoT, n8n Automation, Computer Vision and Telegram Voice Alerts”

The complete implementation should ultimately contain ESP32 source code + circuit/schematic + n8n workflow JSON + AI prompts + Telegram bot configuration + Google Sheets structure + ThingSpeak configuration + dashboard source + testing documentation.

 

AI Women Safety Bag — Mind Map

                         ┌──────────────────────────────┐
                         │  AI WOMEN SAFETY BAG         │
                         │  ESP32 + AI + IoT + n8n      │
                         └──────────────┬───────────────┘
                                        │
        ┌───────────────────────────────┼───────────────────────────────┐
        │                               │                               │
        ▼                               ▼                               ▼
 ┌───────────────┐              ┌───────────────┐              ┌───────────────┐
 │   HARDWARE    │              │   SOFTWARE    │              │   AI SYSTEM   │
 └───────┬───────┘              └───────┬───────┘              └───────┬───────┘
         │                              │                              │
    ┌────┼────┐                    ┌────┼─────┐                   ┌────┼────┐
    │    │    │                    │    │     │                   │    │    │
    ▼    ▼    ▼                    ▼    ▼     ▼                   ▼    ▼    ▼
 ESP32 Camera GPS                 Arduino n8n Dashboard          Vision Agent Risk
    │    │    │                      │    │     │                 │     │    │
    │    │    │                      │    │     │                 │     │    │
    ├────┼────┤                      │    │     │                 │     │    │
    │    │    │                      │    │     │                 │     │    │
    ▼    ▼    ▼                      ▼    ▼     ▼                 ▼     ▼    ▼
 SOS  Buzzer Vibration             WiFi HTTPS HTML             Face  Scene Decision
 Button                              │                           Detection Analysis
    │                                │
    ├───────────────┐                │
    ▼               ▼                ▼
 MPU6050        Microphone       Webhook/API
 Optional        Optional            │
                                    ▼
                              ┌───────────────┐
                              │     n8n       │
                              │ AUTOMATION    │
                              └───────┬───────┘
                                      │
                 ┌────────────────────┼─────────────────────┐
                 │                    │                     │
                 ▼                    ▼                     ▼
            ┌──────────┐        ┌──────────┐         ┌───────────┐
            │ Telegram │        │  Google  │         │ ThingSpeak│
            │          │        │  Sheets  │         │           │
            └────┬─────┘        └──────────┘         └─────┬─────┘
                 │                                          │
       ┌─────────┼──────────┐                               ▼
       │         │          │                         IoT Dashboard
       ▼         ▼          ▼
     Text      Photo      GPS
       │
       ▼
  Voice Alert
       │
       ▼
    Guardian


                         ┌──────────────────────────┐
                         │     EMERGENCY FLOW       │
                         └────────────┬─────────────┘
                                      │
                                      ▼
                                SOS PRESSED
                                      │
                          ┌───────────┼───────────┐
                          │           │           │
                          ▼           ▼           ▼
                       Alarm       Camera       GPS
                          │        Capture        │
                          │           │           │
                          └───────────┼───────────┘
                                      ▼
                                    Wi-Fi
                                      │
                                      ▼
                                    n8n
                                      │
                                      ▼
                                 AI Vision
                                      │
                                      ▼
                                  AI Agent
                                      │
                         ┌────────────┼────────────┐
                         ▼            ▼            ▼
                      Telegram     Sheets      ThingSpeak
                         │
                 ┌───────┼────────┐
                 ▼       ▼        ▼
               Text    Photo    Location
                         │
                         ▼
                    Voice Alert
                         │
                         ▼
                      Guardian


                         ┌──────────────────────────┐
                         │       RELIABILITY        │
                         └────────────┬─────────────┘
                                      │
                 ┌────────────────────┼───────────────────┐
                 ▼                    ▼                   ▼
             Wi-Fi Loss           AI Failure         Cloud Failure
                 │                    │                   │
                 ▼                    ▼                   ▼
             Local Save          SOS Still Works       Retry Queue
                 │
                 ▼
             Retry Upload


                         ┌──────────────────────────┐
                         │    SECURITY & PRIVACY    │
                         └────────────┬─────────────┘
                                      │
              ┌───────────────────────┼──────────────────────┐
              ▼                       ▼                      ▼
          HTTPS/TLS             Device Token           Data Privacy
              │                       │                      │
              ▼                       ▼                      ▼
         Secure API             n8n Authentication     Image Retention

One-line architecture

ESP32 → Sensors/Camera → Wi-Fi → n8n → AI Vision → AI Agent → Telegram + Voice + Google Sheets + ThingSpeak → Guardian/Dashboard

Core principle

ESP32 detects and captures → AI interprets → n8n orchestrates → Telegram alerts → cloud services record → human responds.