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.

 

AI Web Controlled Spy Robot with Real-Time Object Detection

Yes . I can structure this as a complete final-year/major IoT project documentation package covering the ESP32 robot, AI object detection, web control, n8n agentic automation, Telegram voice alerts, Google Sheets, ThingSpeak, schematics, flowcharts, and source code.

Proposed project architecture

                         ┌──────────────────────────┐
                         │        WEB PAGE           │
                         │  Live video + Robot Ctrl │
                         │  Sensors + AI detections  │
                         └────────────┬─────────────┘
                                      │ Wi-Fi / HTTP
                                      ▼
┌──────────────┐              ┌──────────────────┐
│ ESP32-CAM /  │◄────────────►│ Wi-Fi / Internet │
│ ESP32 Robot  │              └────────┬─────────┘
│              │                       │
│ Motors       │                       │
│ Servo        │                       ▼
│ Sensors      │              ┌──────────────────┐
│ Camera       │              │       n8n        │
└──────┬───────┘              │ Automation/Agent│
       │                      └────────┬─────────┘
       │                               │
       │                    ┌──────────┼──────────┐
       │                    ▼          ▼          ▼
       │                Telegram   Google      ThingSpeak
       │                Bot/Voice   Sheets       Cloud
       │                    │          │           │
       │                    ▼          ▼           ▼
       │                 Alerts      Logs       Dashboard
       │
       ▼
┌──────────────────────────────────────────────────┐
│              AI OBJECT DETECTION                 │
│  Person / Vehicle / Animal / Object / Intruder   │
└──────────────────────────────────────────────────┘

Documentation chapters

I would document it in this order:

  1. Project title and abstract

  2. Introduction

  3. Problem statement

  4. Objectives

  5. Existing system

  6. Proposed system

  7. Applications

  8. System requirements

    • ESP32/ESP32-CAM

    • Motor driver

    • DC motors

    • Servo

    • Ultrasonic/IR sensors

    • Battery

    • Computer/server for AI inference

    • Wi-Fi

  9. Hardware architecture

  10. Complete circuit/schematic

  11. ESP32 pin configuration

  12. Robot chassis and motor wiring

  13. Camera/video streaming

  14. Web-based robot controller

  15. Real-time AI object detection

  16. ESP32 ↔ web server communication

  17. n8n workflow architecture

  18. AI-agent decision workflow

  19. Telegram bot integration

  20. Telegram voice notification generation

  21. Google Sheets data logging

  22. ThingSpeak cloud dashboard

  23. End-to-end data flow

  24. Security and authentication

  25. Complete ESP32 firmware

  26. Web HTML/CSS/JavaScript

  27. AI detection code

  28. n8n workflow configuration

  29. Telegram integration code/configuration

  30. Google Sheets integration

  31. ThingSpeak integration

  32. Testing procedure

  33. Test cases and expected results

  34. Troubleshooting

  35. Advantages and limitations

  36. Future enhancements

  37. Conclusion

  38. Bill of materials

  39. Project folder structure

  40. Viva/interview questions and answers

End-to-end operation

For example, when the camera detects a person:

Camera
  ↓
Video frame
  ↓
AI Object Detection
  ↓
"PERSON DETECTED"
  ↓
ESP32 / Web Application
  ↓
n8n Webhook
  ↓
AI Agent
  ↓
Check event + confidence + sensor data
  ↓
┌───────────────┬───────────────┬────────────────┐
│               │               │                │
▼               ▼               ▼                ▼
Telegram       Google Sheets   ThingSpeak     Robot action
alert          event log       telemetry      if required
│
▼
Text-to-Speech
│
▼
Telegram Voice Alert

A Telegram notification could conceptually be:

🤖 SPY ROBOT ALERT

Object: Person
Confidence: 94%
Location: Zone A
Time: 10:42:18
Distance: 2.1 m

AI Agent Action:
Person detected — monitoring activated.

The project can also support commands such as:

USER → Telegram Bot

"Move forward"
      ↓
Telegram
      ↓
n8n
      ↓
AI Agent / Command Parser
      ↓
ESP32 API
      ↓
Motor Driver
      ↓
Robot moves forward

Recommended software structure

AI-ESP32-SPY-ROBOT/
│
├── esp32/
│   ├── robot_controller.ino
│   ├── camera_server.ino
│   ├── motor_control.h
│   ├── sensors.h
│   └── config.h
│
├── web/
│   ├── index.html
│   ├── style.css
│   └── app.js
│
├── ai/
│   ├── detector.py
│   ├── camera.py
│   └── requirements.txt
│
├── n8n/
│   └── robot_agent_workflow.json
│
├── telegram/
│   └── bot_config.md
│
├── cloud/
│   ├── google_sheets.md
│   └── thingspeak.md
│
├── hardware/
│   ├── circuit_diagram
│   ├── pin_configuration.md
│   └── BOM.md
│
└── documentation/
    └── project_report.md

Important design choice: for a practical ESP32 implementation, I would separate robot control/IoT from computationally heavier real-time object detection where necessary. The ESP32 can handle camera capture, motors, sensors and networking, while a PC/Raspberry Pi/edge AI device can perform models such as YOLO; the resulting detection events are sent to n8n. This avoids pretending that a normal ESP32 can comfortably run a large object-detection model.

If you want, I can next produce the complete documentation as a single project report, including the actual ESP32 Arduino code, HTML/JavaScript web controller, Python AI detection code, n8n workflow JSON, Telegram integration, Google Sheets/ThingSpeak configuration, detailed circuit/pin diagram, flowcharts, and testing tables.

 

Absolutely. I ’ll use exactly this chapter structure and turn it into a formal, detailed project document. The code and circuit will be designed as one coherent system rather than disconnected examples.

Complete Project Documentation Structure

1. Project Title and Abstract

Project Title:

AI Web-Controlled Spy Robot with Real-Time Object Detection, Agentic IoT Automation, Telegram Voice Alerts, Google Sheets Logging and ThingSpeak Cloud Dashboard using ESP32 and n8n

Abstract

This project presents an IoT-enabled mobile surveillance robot based on the ESP32/ESP32-CAM platform. The robot combines wireless web-based control, live camera streaming, sensor monitoring, artificial-int elligence-based object detection, cloud data logging, and automated notifications.

The robot can be remotely controlled through a web interface while its camera provides live visual information. An AI detection module analyzes camera frames and identifies predefined objects such as people, vehicles, animals, or other relevant objects. Detection events are transmitted to an automation layer based on n8n.

The n8n workflow acts as the central automation and agentic-IoT layer. Depending on the incoming event, sensor information, detection confidence, and configured rules, the workflow can record information in Google Sheets, update a ThingSpeak dashboard, and send notifications through Telegram. Telegram can additionally be used to provide voice-based alerts and receive commands.

The proposed system demonstrates how low-cost embedded hardware, computer vision, cloud services, workflow automation, and conversational interfaces can be integrated into a single IoT platform.


2. Introduction

The rapid development of IoT, embedded systems, computer vision, and AI has made it possible to build intelligent robotic systems using relatively inexpensive hardware.

Traditional remotely controlled robots generally provide only basic movement:

User → Remote Control → Robot

An intelligent IoT robot can extend this architecture:

User
  ↓
Web / Telegram
  ↓
Internet
  ↓
n8n Automation
  ↓
ESP32 Robot
  ↓
Camera + Sensors
  ↓
AI Analysis
  ↓
Automation
  ↓
Alerts + Cloud Logging

The proposed robot therefore does not simply respond to movement commands. It can also collect information, identify objects, generate events, communicate with external services, and perform predefined automated actions.


3. Problem Statement

Conventional surveillance robots have several limitations:

  • They often require dedicated remote controllers.

  • Camera monitoring and robot control may be separate systems.

  • Sensor information may not be stored systematically.

  • Notifications may require continuous human monitoring.

  • Traditional robots generally do not understand detected objects.

  • IoT data may not be integrated with automation workflows.

  • There may be no centralized event history.

  • Users may have limited remote access.

The proposed system addresses these limitations by integrating:

Robot
+
Camera
+
Sensors
+
AI
+
Web Control
+
n8n
+
Telegram
+
Google Sheets
+
ThingSpeak

4. Objectives

The primary objectives are:

  1. Develop a Wi-Fi-controlled mobile robot.

  2. Provide browser-based robot control.

  3. Provide live camera streaming.

  4. Integrate object detection.

  5. Detect predefined objects in real time.

  6. Monitor distance/sensor information.

  7. Send detection events to n8n.

  8. Automate responses using n8n.

  9. Send Telegram notifications.

  10. Generate Telegram voice alerts.

  11. Record events in Google Sheets.

  12. Display telemetry using ThingSpeak.

  13. Provide remote command capability.

  14. Maintain an event history.

  15. Create a modular platform for future AI-agent functionality.


5. Existing System

A conventional surveillance robot may have:

Camera
   ↓
Monitor

or:

Remote Controller
       ↓
    Robot

A basic IoT robot may instead use:

ESP32
  ↓
Wi-Fi
  ↓
Mobile/Web App

These systems can perform their individual functions but may not provide integrated AI detection, workflow automation, cloud logging, and conversational alerts.


6. Proposed System

The proposed architecture combines all major components.

                 ┌───────────────────┐
                 │    WEB CLIENT      │
                 │ Control + Camera   │
                 └─────────┬─────────┘
                           │
                           ▼
                    ┌─────────────┐
                    │    ESP32    │
                    │ Robot Node  │
                    └──────┬──────┘
                           │
          ┌────────────────┼────────────────┐
          ▼                ▼                ▼
       Motors           Sensors          Camera
                                             │
                                             ▼
                                      AI Detection
                                             │
                                             ▼
                                        n8n Webhook
                                             │
                         ┌───────────────────┼──────────────────┐
                         ▼                   ▼                  ▼
                    Telegram           Google Sheets       ThingSpeak
                         │                   │                  │
                         ▼                   ▼                  ▼
                    Voice/Text             Logs            Dashboard

7. Applications

Potential applications include:

  • Remote surveillance

  • Industrial inspection

  • Laboratory monitoring

  • Educational robotics

  • Smart security research

  • Warehouse monitoring

  • Remote environmental observation

  • Object detection experiments

  • IoT and automation demonstrations

  • AI-agent robotics research


8. System Requirements

8.1 Hardware

Component Purpose
ESP32 / ESP32-CAM Main IoT controller/camera
Motor driver Drives DC motors
DC motors Robot movement
Robot chassis Mechanical platform
Servo motor Camera/sensor positioning
Ultrasonic sensor Distance measurement
IR sensors Obstacle detection
Battery Power supply
Voltage regulator Stable power
Camera Video capture
LEDs/buzzer Local status indication

8.2 Software

Arduino IDE
ESP32 Arduino Core
HTML
CSS
JavaScript
Python
Computer Vision / Object Detection Model
n8n
Telegram Bot
Google Sheets
ThingSpeak
Web browser

9. ESP32 / ESP32-CAM

The ESP32 provides:

  • Wi-Fi connectivity

  • GPIO

  • PWM

  • UART

  • I²C

  • SPI

  • ADC

  • low-cost embedded processing

An ESP32-CAM variant can additionally provide camera functionality.

A practical architecture is:

ESP32
 ├── Motor control
 ├── Sensor acquisition
 ├── Wi-Fi
 ├── Web/API communication
 └── Robot state

ESP32-CAM / Camera
 └── Image acquisition

AI Computer/Raspberry Pi
 └── Object detection

For heavier computer-vision models, the AI inference should normally be performed on a computer, Raspberry Pi-class edge device, or another suitable accelerator rather than assuming a conventional ESP32 can run a full-size object detector efficiently.


10. Motor Driver

The ESP32 GPIO pins should not directly drive DC motors.

The architecture is:

ESP32 GPIO
    │
    ▼
Motor Driver
    │
    ├──── Motor A
    │
    └──── Motor B

A suitable H-bridge motor driver can provide:

  • Forward

  • Reverse

  • Stop

  • Speed control using PWM


11. DC Motors

A two-wheel differential-drive configuration can be used.

              FRONT
       ┌─────────────────┐
       │                 │
       │      CAMERA     │
       │        ▲        │
       │                 │
   M1  │                 │  M2
  LEFT │                 │ RIGHT
       │                 │
       └───────┬─────────┘
               │
             CASTER

Movement:

Command Left motor Right motor
Forward Forward Forward
Reverse Reverse Reverse
Left Reverse/Stop Forward
Right Forward Reverse/Stop
Stop Stop Stop

12. Servo

The servo can rotate:

  • Camera

  • Ultrasonic sensor

  • Sensor mount

For example:

             Camera
                │
                ▼
           ┌────────┐
           │ Servo  │
           └────────┘
           ← 180° →

This allows the robot to scan different directions.


13. Ultrasonic / IR Sensors

An ultrasonic sensor can provide distance information.

Conceptually:

ESP32
 │
 ├── TRIG ───────► Sensor
 │
 └── ECHO ◄────── Sensor

Distance can be estimated from the measured echo time.

IR sensors can provide additional close-range obstacle detection.

A combined system is more useful:

             Camera
                │
                ▼
           AI Detection

Left IR ──┐
Front US ─┼──► ESP32 ──► n8n
Right IR ─┘

14. Battery

A separate power design should be used for:

Battery
 ├── Motor power
 └── Regulated electronics power

Motors can generate electrical noise and voltage drops, so appropriate regulation, grounding, decoupling, and protection are important.


15. Computer / Server for AI Inference

The AI inference computer receives camera frames:

ESP32-CAM
    │
    │ JPEG/video
    ▼
AI Server
    │
    ▼
Object Detection Model
    │
    ▼
Detection JSON

Example:

{
  "object": "person",
  "confidence": 0.94,
  "timestamp": "2026-10-03T10:42:18",
  "camera": "robot-01"
}

16. Wi-Fi

The ESP32 connects to the local wireless network.

                  Internet
                     │
                Wi-Fi Router
                 /         \
                /           \
           ESP32 Robot     AI Server
                │
                └──────── n8n

The system can operate locally, remotely, or in a hybrid architecture depending on how the server and n8n instance are deployed.


17. Hardware Architecture

                 ┌───────────────┐
                 │    Battery    │
                 └───────┬───────┘
                         │
                ┌────────▼────────┐
                │ Power Regulation│
                └───────┬─────────┘
                        │
        ┌───────────────┴────────────────┐
        │                                │
 ┌──────▼──────┐                  ┌──────▼──────┐
 │    ESP32    │                  │ Motor Driver│
 └──────┬──────┘                  └──────┬──────┘
        │                                │
 ┌──────┼──────────┐                 ┌───┴───┐
 │      │          │                 │       │
 ▼      ▼          ▼                 ▼       ▼
Camera Sensors    Servo             M1       M2

18. Complete Circuit / Schematic

A generic connection architecture:

                         +----------------+
                         |     ESP32      |
                         |                |
                         | GPIO ──────────┼──── Motor Driver IN1
                         | GPIO ──────────┼──── Motor Driver IN2
                         | GPIO ──────────┼──── Motor Driver IN3
                         | GPIO ──────────┼──── Motor Driver IN4
                         | GPIO ──────────┼──── Ultrasonic TRIG
                         | GPIO ◄─────────┼──── Ultrasonic ECHO
                         | GPIO ──────────┼──── Servo PWM
                         |                |
                         | Wi-Fi          |
                         +-------┬--------+
                                 │
                                 │
                              Network
                                 │
             ┌───────────────────┼─────────────────┐
             ▼                   ▼                 ▼
          Browser              n8n             AI Server

Important: exact GPIO numbers depend on the specific ESP32/ESP32-CAM board. They should be selected after accounting for camera pins, boot-strapping pins, flash/PSRAM usage, and available GPIOs rather than blindly assigning pins.


19. ESP32 Pin Configuration

The final report will contain a table like:

ESP32 GPIO Function Direction
GPIO xx Motor IN1 Output
GPIO xx Motor IN2 Output
GPIO xx Motor IN3 Output
GPIO xx Motor IN4 Output
GPIO xx Ultrasonic TRIG Output
GPIO xx Ultrasonic ECHO Input
GPIO xx Servo PWM
GPIO xx Status LED Output

The exact table should be finalized against the specific ESP32 board model.


20. Robot Chassis and Motor Wiring

       LEFT MOTOR                 RIGHT MOTOR
           │                          │
           ▼                          ▼
      ┌─────────┐                ┌─────────┐
      │         │                │         │
      │    O────┴────────────────┴────O    │
      │              CHASSIS               │
      │                                    │
      │           ESP32-CAM                │
      │               ▲                    │
      │               │                    │
      │             SERVO                  │
      └────────────────────────────────────┘

21. Camera / Video Streaming

The camera captures frames:

Camera
  ↓
Frame Capture
  ↓
JPEG
  ↓
HTTP/MJPEG stream
  ↓
Browser

The browser displays:

<img src="/stream">

The actual implementation depends on the ESP32 camera firmware and network architecture.


22. Web-Based Robot Controller

The web interface can contain:

┌─────────────────────────────────────────┐
│       AI ESP32 ROBOT CONTROL            │
├─────────────────────────────────────────┤
│                                         │
│            LIVE CAMERA                  │
│         ┌───────────────┐               │
│         │               │               │
│         │     VIDEO     │               │
│         │               │               │
│         └───────────────┘               │
│                                         │
│              [ UP ]                     │
│                                         │
│        [ LEFT ] [ STOP ] [ RIGHT ]      │
│                                         │
│             [ DOWN ]                    │
│                                         │
│ Distance: 1.85 m                        │
│ AI: PERSON 94%                          │
│ Status: ONLINE                          │
└─────────────────────────────────────────┘

JavaScript sends commands:

Browser
   │
   │ POST /api/move
   ▼
ESP32
   │
   ▼
Motor Driver

23. Real-Time AI Object Detection

The AI pipeline:

Camera Frame
     ↓
Image Preprocessing
     ↓
Object Detection Model
     ↓
Bounding Boxes
     ↓
Confidence Filtering
     ↓
Object Classification
     ↓
Event Generation

Example:

┌─────────────────────────────┐
│                             │
│       ┌─────────────┐       │
│       │   PERSON    │       │
│       │    94%      │       │
│       └─────────────┘       │
│                             │
└─────────────────────────────┘

24. ESP32 ↔ Web Server Communication

REST-style communication can be used:

POST /api/move
GET  /api/status
GET  /api/sensors
POST /api/servo
POST /api/stop

Example:

{
  "command": "forward",
  "speed": 180
}

ESP32 response:

{
  "success": true,
  "command": "forward"
}

25. n8n Workflow Architecture

n8n becomes the automation layer:

              Detection Event
                    │
                    ▼
              ┌───────────┐
              │ Webhook   │
              └─────┬─────┘
                    ▼
             Validate Event
                    │
                    ▼
              AI / Logic Node
                    │
        ┌───────────┼───────────┐
        ▼           ▼           ▼
    Telegram    Google Sheet ThingSpeak
        │           │           │
        ▼           ▼           ▼
      Alert         Log       Dashboard

26. AI-Agent Decision Workflow

The agentic layer can receive:

{
  "object": "person",
  "confidence": 0.94,
  "distance": 2.1,
  "robot_id": "R01"
}

Decision logic:

IF confidence < threshold
       ↓
Ignore / log

IF confidence >= threshold
       ↓
Check object type
       ↓
Check distance
       ↓
Generate event
       ↓
Notify user
       ↓
Record event

A more advanced implementation can use an AI model to interpret structured events, but safety-critical robot movement should remain constrained by deterministic rules rather than allowing an unconstrained language model to directly command motors.


27. Telegram Bot Integration

Basic architecture:

ESP32 / AI
     │
     ▼
    n8n
     │
     ▼
Telegram Bot API
     │
     ▼
User Telegram

Possible commands:

/start
/status
/forward
/backward
/left
/right
/stop
/photo
/scan

28. Telegram Voice Notification Generation

Event:

Person detected
       ↓
n8n
       ↓
Create notification text
       ↓
Text-to-Speech
       ↓
Audio file
       ↓
Telegram
       ↓
Voice notification

Example spoken message:

“Alert. A person has been detected by Robot One with ninety-four percent confidence.”


29. Google Sheets Data Logging

Each event can become one spreadsheet row:

Timestamp Robot Object Confidence Distance Action
10:42:18 R01 Person 94% 2.1m Alert
10:43:02 R01 Vehicle 89% 4.3m Log
10:44:12 R01 Animal 91% 3.2m Alert

This creates a searchable event history.


30. ThingSpeak Cloud Dashboard

Telemetry can include:

Field 1 → Distance
Field 2 → Temperature
Field 3 → Object confidence
Field 4 → Robot state
Field 5 → Motor state
Field 6 → Detection count

Conceptually:

ESP32
  ↓
Telemetry
  ↓
ThingSpeak
  ↓
Charts

31. End-to-End Data Flow

The complete system:

                    USER
                     │
            ┌────────┴────────┐
            ▼                 ▼
         Browser           Telegram
            │                 │
            └────────┬────────┘
                     ▼
                  Internet
                     │
             ┌───────▼───────┐
             │      n8n      │
             │ Automation    │
             └───────┬───────┘
                     │
            ┌────────┴─────────┐
            ▼                  ▼
         ESP32 API          AI Server
            │                  │
       ┌────┼─────┐            │
       ▼    ▼     ▼            ▼
    Motors Servo Sensors   Object Detection
                              │
                              ▼
                            n8n
                              │
             ┌────────────────┼───────────────┐
             ▼                ▼               ▼
          Telegram       Google Sheets    ThingSpeak

32. Security and Authentication

Security should include:

  • Wi-Fi credentials stored securely.

  • Authentication for web commands.

  • HTTPS where practical.

  • n8n webhook authentication.

  • Telegram bot-token protection.

  • API-key protection.

  • Restricted network exposure.

  • Input validation.

  • Motor command limits.

  • Emergency stop.

Never hard-code secrets into publicly shared source code:

const char* WIFI_PASSWORD = "YOUR_PASSWORD";
const char* TELEGRAM_TOKEN = "YOUR_TOKEN";

Instead, credentials should be supplied through protected configuration.


33. Complete ESP32 Firmware

The firmware will be divided into modules:

setup()
  ├── Serial
  ├── GPIO
  ├── Motors
  ├── Sensors
  ├── Servo
  ├── Wi-Fi
  └── Web/API

loop()
  ├── Read sensors
  ├── Process commands
  ├── Update robot state
  └── Send telemetry

Example architecture:

void loop() {
    readSensors();
    processWebCommands();
    updateRobotState();
    sendTelemetryIfRequired();
}

The final code should be adapted to the exact ESP32 board and motor-driver model.


34. Web HTML / CSS / JavaScript

The project will contain:

index.html
style.css
app.js

JavaScript concept:

async function moveRobot(command) {
    await fetch("/api/move", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            command: command
        })
    });
}

Buttons:

<button onclick="moveRobot('forward')">▲</button>
<button onclick="moveRobot('left')">◀</button>
<button onclick="moveRobot('stop')">STOP</button>
<button onclick="moveRobot('right')">▶</button>
<button onclick="moveRobot('backward')">▼</button>

35. AI Detection Code

The AI program will perform:

Read camera
     ↓
Resize/preprocess
     ↓
Inference
     ↓
Extract detections
     ↓
Filter confidence
     ↓
Draw boxes
     ↓
Generate JSON event
     ↓
POST to n8n

Example event:

{
  "robot_id": "R01",
  "object": "person",
  "confidence": 0.94,
  "distance_m": 2.1,
  "timestamp": "2026-10-03T10:42:18"
}

36. n8n Workflow Configuration

A practical workflow:

[Webhook]
    ↓
[Validate JSON]
    ↓
[Normalize Event]
    ↓
[Decision / AI Agent]
    ↓
 ┌──┴──────────┬──────────────┐
 ▼             ▼              ▼
Telegram    Google Sheets   ThingSpeak
 ▼             ▼              ▼
Voice/Text     Record        Telemetry

Additional branches can include:

Detection
   ↓
IF confidence > threshold
   ↓ YES
Telegram Alert

   ↓ NO
Log Only

37. Telegram Integration Code / Configuration

The workflow will contain:

Telegram credentials
       ↓
Send message
       ↓
Optional text-to-speech
       ↓
Send audio

The bot should not be allowed to execute arbitrary commands from untrusted users. User identity/chat ID validation should occur before accepting robot-control commands.


38. Google Sheets Integration

Workflow:

n8n
 ↓
Google Sheets node
 ↓
Append Row

Example mapping:

timestamp → Timestamp
robot_id → Robot
object → Object
confidence → Confidence
distance → Distance
action → Action

39. ThingSpeak Integration

Workflow:

ESP32 / n8n
      ↓
ThingSpeak API
      ↓
Channel
      ↓
Fields
      ↓
Charts

The final implementation will document API keys, channel configuration, field mapping, and update frequency without publishing private keys.


40. Testing Procedure

Testing will be performed in stages.

Hardware testing

Power
 ↓
ESP32
 ↓
Wi-Fi
 ↓
Motor driver
 ↓
Motors
 ↓
Sensors
 ↓
Camera

Software testing

Web page
 ↓
ESP32 API
 ↓
Robot movement
 ↓
AI detection
 ↓
n8n webhook
 ↓
Telegram
 ↓
Google Sheets
 ↓
ThingSpeak

41. Test Cases and Expected Results

Test Input Expected result
T01 ESP32 powered ESP32 boots
T02 Wi-Fi available ESP32 connects
T03 Forward command Robot moves forward
T04 Stop command Motors stop
T05 Obstacle detected Distance reported
T06 Camera active Video available
T07 Person detected Detection generated
T08 High-confidence event n8n receives event
T09 Alert event Telegram message sent
T10 Voice enabled Telegram audio generated
T11 Event received Google Sheets row added
T12 Telemetry sent ThingSpeak updated

42. Troubleshooting

ESP32 doesn't connect to Wi-Fi

Check:

SSID
Password
2.4-GHz compatibility
Signal strength
Power supply

Motors behave incorrectly

Check:

Motor-driver wiring
Common GND
Motor polarity
PWM configuration
Battery voltage

Camera stream fails

Check:

Camera model
Camera pin configuration
PSRAM
Power stability
Network address

AI detections are unreliable

Check:

Lighting
Camera resolution
Model
Confidence threshold
Inference hardware
Frame rate

Telegram alerts fail

Check:

Bot token
Chat ID
Internet connectivity
n8n credentials
Telegram API response

43. Advantages and Limitations

Advantages

  • Wireless operation

  • Browser control

  • Live video

  • AI object detection

  • Automated notifications

  • Cloud logging

  • Historical data

  • Modular architecture

  • Expandable IoT platform

Limitations

  • Wi-Fi dependency

  • Battery limitations

  • AI inference may require additional computing hardware

  • Network latency

  • Camera quality affects detection

  • Cloud services may introduce availability/API limitations

  • ESP32 resources are limited


44. Future Enhancements

Possible upgrades:

Current system
     │
     ├── GPS
     ├── GPS geofencing
     ├── Thermal camera
     ├── Night vision
     ├── Edge AI accelerator
     ├── SLAM
     ├── Autonomous navigation
     ├── Voice commands
     ├── Multi-robot coordination
     ├── Battery monitoring
     └── Mobile application

An additional safety enhancement would be an independent hardware emergency-stop mechanism so that network or AI failures cannot leave the motors running indefinitely.


45. Conclusion

The proposed AI Web-Controlled Spy Robot demonstrates the integration of embedded systems, robotics, IoT, computer vision, cloud services, workflow automation, and conversational notification systems.

The ESP32 provides the embedded control layer, while the camera supplies visual information for AI analysis. n8n connects the robot to external services and automates event processing. Telegram provides human notifications and remote interaction, Google Sheets provides historical event storage, and ThingSpeak provides cloud-based visualization.

The architecture is intentionally modular, allowing individual components to be upgraded without redesigning the complete system.


46. Bill of Materials

No. Component Qty.
1 ESP32 development board 1
2 ESP32-CAM / compatible camera 1
3 2WD/4WD robot chassis 1
4 DC geared motors 2/4
5 H-bridge motor driver 1
6 Servo motor 1
7 Ultrasonic sensor 1
8 IR obstacle sensors 2
9 Battery pack 1
10 Voltage regulator 1
11 Jumper wires Set
12 Switch 1
13 LEDs As required
14 Buzzer 1
15 AI inference computer 1
16 Wi-Fi router/network 1

47. Project Folder Structure

AI-ESP32-AGENTIC-ROBOT/
│
├── firmware/
│   ├── robot.ino
│   ├── motors.h
│   ├── sensors.h
│   ├── camera.h
│   ├── web_server.h
│   └── config.h
│
├── web/
│   ├── index.html
│   ├── style.css
│   └── app.js
│
├── ai/
│   ├── detector.py
│   ├── requirements.txt
│   └── models/
│
├── n8n/
│   ├── workflow.json
│   └── workflow-documentation.md
│
├── telegram/
│   └── telegram-configuration.md
│
├── google-sheets/
│   └── spreadsheet-schema.md
│
├── thingspeak/
│   └── channel-configuration.md
│
├── hardware/
│   ├── schematic/
│   ├── wiring/
│   ├── pinout.md
│   └── bom.md
│
├── tests/
│   ├── hardware-tests.md
│   └── software-tests.md
│
└── documentation/
    ├── project-report.md
    ├── architecture.md
    └── viva-questions.md

48. Viva / Interview Questions and Answers

Q1. Why is ESP32 used?

ESP32 provides Wi-Fi, GPIO, PWM and sufficient embedded processing capability at low cost, making it suitable for IoT robot control.

Q2. Why use a motor driver?

The ESP32 GPIO cannot directly supply the current required by DC motors. The motor driver provides the required power switching and direction control.

Q3. What is the purpose of n8n?

n8n acts as the workflow automation layer connecting robot events with Telegram, Google Sheets, ThingSpeak, and other services.

Q4. Why is AI inference separated from the ESP32?

Object-detection models can require substantially more compute and memory than a conventional ESP32 can efficiently provide. An external edge/server processor allows more capable models while keeping the ESP32 responsible for real-time robot control.

Q5. What happens when an object is detected?

Camera
 ↓
AI Model
 ↓
Detection
 ↓
Event JSON
 ↓
n8n
 ↓
Decision
 ↓
Telegram + Sheets + ThingSpeak

Q6. What is an AI agent in this project?

The AI-agent layer interprets structured robot events and can select configured workflows/actions. It should operate within predefined permissions and safety rules rather than having unrestricted motor control.

Q7. Why use Google Sheets?

It provides a simple human-readable historical event log.

Q8. Why use ThingSpeak?

It provides cloud-oriented telemetry visualization and time-series data.

Q9. What happens if the Internet fails?

Local robot functions can be designed to continue operating, depending on the implementation, but cloud automation and remote notifications will be unavailable until connectivity returns.

Q10. What is the most important safety feature?

An independent emergency stop and fail-safe motor timeout should be included so that communication, software, or AI failures do not result in uncontrolled movement.


Recommended next stage

The documentation above gives the complete report architecture. The next stage should be the actual implementation package:

Part 1 — Hardware: exact ESP32 board selection, motor driver selection, complete GPIO pinout, power circuit, and a detailed wiring/schematic.

Part 2 — Firmware: complete compilable ESP32 Arduino program for motors, ultrasonic/IR sensors, servo, Wi-Fi, REST API and robot status.

Part 3 — Web: complete index.html, style.css, and app.js with live camera, directional controls, sensor values and AI detection display.

Part 4 — AI: complete Python object-detection server with camera input, bounding boxes and n8n webhook events.

Part 5 — Automation: complete n8n workflow, Telegram text/voice alerts, Google Sheets logging and ThingSpeak telemetry.

Part 6 — Final report: combine everything into a submission-ready document with flowcharts, schematics, screenshots/placeholders, test results, references, and viva questions.

For the actual circuit and code, the one hardware detail that must be fixed first is the exact board: ESP32 DevKit V1 + separate camera, AI-Thinker ESP32-CAM, or another ESP32-CAM board. The GPIO assignments and camera wiring are different between boards.

 

Project Summary

Title:
AI Web-Controlled Spy Robot with Real-Time Object Detection, Agentic IoT, n8n Automation, Telegram Voice Alerts, Google Sheets & ThingSpeak

Core idea

A Wi-Fi-enabled ESP32 robotic vehicle is controlled through a web interface and equipped with a camera and sensors. Camera data is analyzed by an AI object-detection system, while n8n acts as the automation/agentic layer.

Web Browser
     │
     ▼
 ESP32 Robot ─── Camera ───► AI Detection Server
     │                              │
     │                              ▼
     │                         Detection Event
     │                              │
     └──────────────► n8n ◄─────────┘
                         │
          ┌──────────────┼──────────────┐
          ▼              ▼              ▼
      Telegram      Google Sheets    ThingSpeak
      Text/Voice       Event Log      Dashboard

Main functions

  • Web-based forward/reverse/left/right/stop control

  • Live camera streaming

  • Servo-controlled camera/sensor positioning

  • Ultrasonic and IR obstacle detection

  • Real-time AI object detection

  • ESP32 ↔ server communication

  • n8n event automation

  • AI-agent-style decision workflow

  • Telegram text notifications

  • Telegram voice alerts

  • Google Sheets event logging

  • ThingSpeak telemetry dashboard

  • Remote Telegram commands

  • Safety/emergency-stop mechanisms

Main hardware

  • ESP32 / ESP32-CAM

  • Motor driver

  • 2 or 4 DC geared motors

  • Robot chassis

  • Servo motor

  • Ultrasonic sensor

  • IR sensors

  • Camera

  • Battery and voltage regulation

  • Optional AI inference computer/Raspberry Pi

Main software

Arduino IDE
ESP32 Arduino Framework
HTML / CSS / JavaScript
Python
AI Object Detection Model
n8n
Telegram Bot
Google Sheets
ThingSpeak

Important architecture decision

The ESP32 handles real-time robot control, sensors, Wi-Fi and camera functions, while computationally heavier object detection can run on a PC/Raspberry Pi/edge AI device. This is more practical than expecting a conventional ESP32 to run a large object-detection model.

Documentation chapters

The final report will cover:

  1. Abstract and introduction

  2. Problem statement and objectives

  3. Existing and proposed systems

  4. Applications

  5. Hardware/software requirements

  6. Hardware architecture and schematic

  7. ESP32 pin configuration

  8. Motor, sensor, servo and camera wiring

  9. Video streaming

  10. Web robot controller

  11. AI object detection

  12. ESP32/server communication

  13. n8n automation

  14. AI-agent workflow

  15. Telegram and voice alerts

  16. Google Sheets

  17. ThingSpeak

  18. Security

  19. Complete source code

  20. Testing and troubleshooting

  21. Advantages and limitations

  22. Future enhancements

  23. BOM and project structure

  24. Viva questions and answers

Complete event example

Person detected
      ↓
AI: Person / 94%
      ↓
n8n Webhook
      ↓
Validate + decide
      ↓
 ┌────┼───────────┐
 ▼    ▼           ▼
TG  Sheets    ThingSpeak
 │
 ▼
Voice Alert

Final implementation should next lock down the exact ESP32 board and motor driver, because the GPIO pinout, camera connections, and firmware depend on those specific components.