Thursday, 20 August 2026

GridGuard AI ⚡: ESP32 Smart Power Monitoring System | IoT, n8n & AI Telegram Voice Alerts

GridGuard AI ⚡

ESP32 Smart Power Monitoring System with IoT, n8n Automation, AI Agent and Telegram Voice Alerts


1. Project Overview

GridGuard AI is an IoT-based electrical energy monitoring and intelligent alert system built around an ESP32 microcontroller.

The system continuously measures electrical parameters such as:

  • Voltage
  • Current
  • Active power
  • Energy consumption
  • Power factor
  • Frequency
  • Device status
  • Abnormal/high-load conditions

The ESP32 sends measurements through Wi-Fi to an n8n automation server.

n8n becomes the central automation and AI orchestration layer.

It can:

  1. Receive measurements from the ESP32.
  2. Validate and normalize the data.
  3. Store measurements in Google Sheets.
  4. Publish telemetry to ThingSpeak.
  5. Detect abnormal electrical conditions.
  6. Send measurements to an AI agent.
  7. Generate a human-readable explanation.
  8. Send Telegram notifications.
  9. Generate a voice response.
  10. Accept Telegram voice commands.
  11. Convert voice commands into text.
  12. Ask the AI agent what action should be performed.
  13. Return an answer through Telegram.

The result is an agentic IoT system, rather than merely a sensor dashboard.


2. Main Objective

The main objective is to create an intelligent energy-monitoring system capable of answering questions such as:

"What is the current power consumption?"

"Is the load normal?"

"Why did I receive an alert?"

"How much energy did I consume today?"

"Is there an abnormal load?"

"Give me a voice summary of the power status."

The system can automatically generate an alert such as:

⚠️ GridGuard Alert
Power consumption has reached 3.42 kW.
Current: 15.1 A
Voltage: 227.0 V
Power factor: 0.91
Status: HIGH LOAD
Recommended action: Check high-power appliances.

The same alert can optionally be converted into a voice message and delivered through Telegram.


3. High-Level Architecture

                    ┌───────────────────────┐
                    │       AC LOAD         │
                    │ Refrigerator / Motor  │
                    │ Heater / Appliances   │
                    └───────────┬───────────┘
                                │
                                ▼
                    ┌───────────────────────┐
                    │ Energy Measurement    │
                    │ Module                │
                    │ PZEM-004T / Equivalent│
                    └───────────┬───────────┘
                                │
                Voltage/Current/Power/Energy
                                │
                                ▼
                    ┌───────────────────────┐
                    │        ESP32          │
                    │                       │
                    │ Sensor Interface      │
                    │ Data Processing       │
                    │ Wi-Fi                 │
                    │ JSON/HTTP             │
                    └───────────┬───────────┘
                                │
                              Wi-Fi
                                │
                                ▼
                    ┌───────────────────────┐
                    │        n8n            │
                    │ Automation Server     │
                    │                       │
                    │ Webhook               │
                    │ Validation             │
                    │ Rules Engine          │
                    │ AI Agent              │
                    └───────┬───────┬───────┘
                            │       │
                ┌───────────┘       └─────────────┐
                ▼                                 ▼
       ┌─────────────────┐               ┌─────────────────┐
       │ Google Sheets   │               │   ThingSpeak    │
       │ Historical Data │               │ Cloud Dashboard │
       └─────────────────┘               └─────────────────┘
                            │
                            ▼
                   ┌─────────────────┐
                   │   AI Agent      │
                   │                 │
                   │ Analyze load    │
                   │ Explain anomaly │
                   │ Recommend action│
                   └────────┬────────┘
                            │
                            ▼
                   ┌─────────────────┐
                   │    Telegram     │
                   │                 │
                   │ Text Alert      │
                   │ Voice Alert     │
                   │ Voice Commands  │
                   └─────────────────┘

4. Recommended Hardware

Core Hardware

Component Purpose
ESP32 DevKit Main IoT controller
PZEM-004T v3 or equivalent certified energy meter Voltage/current/power/energy measurement
5 V USB power supply ESP32 power
Wi-Fi router Internet connectivity
Enclosure Electrical/mechanical protection
Terminal/connectors Wiring
Fuse/protection components Electrical protection

For a multi-channel version, multiple compatible measurement modules can be used.


5. Important Electrical Safety

This project involves mains electricity if it measures household AC power.

Do not connect an ESP32 GPIO directly to mains voltage.

Do not prototype exposed mains wiring on a breadboard.

The preferred architecture is to use a properly rated, certified energy-measurement module and an appropriately enclosed installation.

For an educational prototype, first test the ESP32/n8n/Telegram/cloud portion using simulated measurements or a low-voltage measurement setup.

The mains-side installation should be performed by a qualified electrician and should follow the applicable electrical standards.

The ESP32 portion should remain galvanically isolated from dangerous mains conductors wherever the selected measurement architecture requires isolation.


6. Why PZEM-004T?

A PZEM-type energy measurement module is convenient because it can provide several useful parameters without requiring the ESP32 to implement its own mains waveform measurement algorithm.

Typical parameters include:

Voltage
Current
Power
Energy
Frequency
Power Factor

The exact measurement range and electrical characteristics depend on the specific module/version, so use the datasheet for the exact module purchased.


7. ESP32 Connection Concept

For a typical UART-based energy meter:

PZEM TX  ─────────► ESP32 RX
PZEM RX  ◄───────── ESP32 TX
PZEM GND ────────── ESP32 GND
PZEM power ──────── Appropriate supply

Example ESP32 pins:

ESP32 GPIO16 = RX2
ESP32 GPIO17 = TX2

The exact UART/pin configuration can be changed in software.

Do not assume that every energy-meter module has identical voltage levels or pin requirements. Verify the particular module's documentation before wiring.


8. Complete System Flow

Normal telemetry flow

START
  │
  ▼
ESP32 boots
  │
  ▼
Connect to Wi-Fi
  │
  ▼
Initialize energy sensor
  │
  ▼
Read electrical parameters
  │
  ▼
Calculate/validate measurements
  │
  ▼
Create JSON packet
  │
  ▼
HTTP POST → n8n Webhook
  │
  ▼
n8n validates data
  │
  ├──────────────► Google Sheets
  │
  ├──────────────► ThingSpeak
  │
  ▼
Threshold evaluation
  │
  ├── Normal ──► Continue monitoring
  │
  └── Abnormal
          │
          ▼
       AI Agent
          │
          ▼
   Generate explanation
          │
          ▼
   Telegram text alert
          │
          ▼
    Voice generation
          │
          ▼
   Telegram voice/audio

ThingSpeak supports HTTP REST updates using its /update endpoint and channel write API key.


9. JSON Data Format

The ESP32 should send a consistent JSON structure.

Example:

{
  "device_id": "GRIDGUARD-ESP32-001",
  "timestamp": "2026-08-20T23:10:00+05:30",
  "voltage": 228.4,
  "current": 7.82,
  "power": 1648.5,
  "energy": 12.84,
  "frequency": 50.0,
  "power_factor": 0.92,
  "status": "NORMAL",
  "rssi": -61
}

This common schema makes the n8n workflow much easier to maintain.


10. Suggested ThingSpeak Channel

Create one ThingSpeak channel with fields such as:

Field 1 = Voltage
Field 2 = Current
Field 3 = Power
Field 4 = Energy
Field 5 = Power Factor
Field 6 = Frequency
Field 7 = Alert Level
Field 8 = Device Status

ThingSpeak channels support up to eight fields.

Example:

Field1 = 228.4
Field2 = 7.82
Field3 = 1648.5
Field4 = 12.84
Field5 = 0.92
Field6 = 50.0
Field7 = 0
Field8 = 1

11. ThingSpeak HTTP Request

The ESP32 or n8n can update ThingSpeak using:

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

Example POST body:

api_key=YOUR_WRITE_API_KEY
field1=228.4
field2=7.82
field3=1648.5
field4=12.84
field5=0.92
field6=50

ThingSpeak documents both GET and POST methods for channel updates.

For this project, I recommend:

ESP32
   │
   ▼
n8n
   │
   ▼
ThingSpeak

rather than making the ESP32 communicate independently with every cloud service.

That gives you one central automation layer.


12. n8n Architecture

Use n8n as the central brain.

Recommended workflows:

Workflow A
ESP32 → Webhook → Validate → Store → ThingSpeak → Alert Decision

Workflow B
Alert → AI Agent → Telegram Text → Text-to-Speech → Telegram Audio

Workflow C
Telegram Voice → Download Audio → Transcription → AI Agent → Response

Workflow D
Telegram Text → AI Agent → Query Data → Answer

Workflow E
Scheduled → Google Sheets → Daily Energy Report → AI → Telegram

n8n provides Telegram integration including receiving files and sending messages/audio, which makes it suitable for the Telegram part of this architecture.


13. Workflow A — ESP32 Telemetry

Nodes

Webhook
   ↓
Code / Edit Fields
   ↓
IF: Valid Data?
   ↓
 ┌───────────────┐
 │               │
YES             NO
 │               │
 ▼               ▼
Google Sheets   Error Log
 │
 ├──────────────► ThingSpeak
 │
 ▼
Threshold Check

14. n8n Webhook

Create:

HTTP Method: POST
Path:

/gridguard/telemetry

The ESP32 sends:

POST /webhook/gridguard/telemetry
Content-Type: application/json

Body:

{
  "device_id": "GRIDGUARD-ESP32-001",
  "voltage": 228.4,
  "current": 7.82,
  "power": 1648.5,
  "energy": 12.84,
  "frequency": 50,
  "power_factor": 0.92
}

15. n8n Data Validation

Use a Code node to validate the incoming values.

Example:

const d = $json;

const voltage = Number(d.voltage);
const current = Number(d.current);
const power = Number(d.power);
const energy = Number(d.energy);
const pf = Number(d.power_factor);

const valid =
  Number.isFinite(voltage) &&
  Number.isFinite(current) &&
  Number.isFinite(power) &&
  Number.isFinite(energy) &&
  Number.isFinite(pf);

return [{
  json: {
    ...d,
    valid,
    received_at: new Date().toISOString()
  }
}];

16. Threshold Logic

A basic first version can use:

Voltage:
< 200 V       → LOW_VOLTAGE
200–250 V     → NORMAL
> 250 V       → HIGH_VOLTAGE

Power:
< 2 kW        → NORMAL
2–3 kW        → HIGH_LOAD
> 3 kW        → CRITICAL_LOAD

These are example software thresholds, not electrical safety limits.

Use thresholds appropriate to the actual installation and equipment.


17. Better Alert Algorithm

Do not alert every time the power briefly crosses a threshold.

Use:

IF power > HIGH_POWER
AND condition remains true for N consecutive readings
THEN alert

For example:

Reading 1: 3.2 kW
Reading 2: 3.4 kW
Reading 3: 3.5 kW
Reading 4: 3.4 kW

Then:

HIGH LOAD CONFIRMED

This prevents notification spam.


18. Alert State Machine

             ┌─────────────┐
             │    NORMAL   │
             └──────┬──────┘
                    │
             Power exceeds limit
                    │
                    ▼
             ┌─────────────┐
             │   WARNING   │
             └──────┬──────┘
                    │
             persists N times
                    │
                    ▼
             ┌─────────────┐
             │  CRITICAL   │
             └──────┬──────┘
                    │
             power returns
                    │
                    ▼
             ┌─────────────┐
             │   RECOVERY  │
             └──────┬──────┘
                    │
                    ▼
                  NORMAL

19. Google Sheets Database

Create a spreadsheet:

GridGuard_Data

Sheet:

Telemetry

Columns:

Timestamp
Device_ID
Voltage
Current
Power
Energy
Power_Factor
Frequency
Status
Alert_Level
AI_Message

Example:

Timestamp Device Voltage Current Power Energy PF Status
23:10 GRIDGUARD-001 228.4 7.82 1648 12.84 0.92 NORMAL
23:11 GRIDGUARD-001 227.8 8.10 1710 12.87 0.91 NORMAL
23:12 GRIDGUARD-001 226.9 14.2 3200 12.92 0.89 HIGH

20. AI Agent

The AI Agent should not directly control dangerous electrical equipment in the first version.

Its primary responsibilities should be:

Observe
  ↓
Analyze
  ↓
Explain
  ↓
Recommend
  ↓
Notify

Instead of:

AI
 ↓
Directly switch mains relay

For a production control system, any electrical switching action should have deterministic safety interlocks and authorization independent of the language model.


21. AI Agent Input

Provide the AI agent with:

{
  "device_id": "GRIDGUARD-001",
  "voltage": 228.4,
  "current": 14.2,
  "power": 3200,
  "energy": 12.92,
  "frequency": 50,
  "power_factor": 0.89,
  "alert": "HIGH_LOAD"
}

Optionally provide historical data:

Last 10 readings
Today's average
Today's maximum
Yesterday's average
Previous week's average

This makes the AI analysis considerably more useful.


22. AI System Prompt

Use a constrained prompt similar to:

You are GridGuard AI, an energy-monitoring assistant.

Your job is to analyze electrical telemetry.

You must:

1. Explain the current condition clearly.
2. Identify abnormal readings.
3. Compare current readings with supplied historical readings.
4. Never invent measurements.
5. Never claim an electrical fault unless the available data supports that conclusion.
6. Clearly distinguish between measurement and inference.
7. Give practical, non-dangerous recommendations.
8. Never instruct a user to touch exposed electrical wiring.
9. For potentially dangerous electrical conditions, recommend qualified electrical inspection.

Return:

STATUS:
SEVERITY:
SUMMARY:
MEASUREMENTS:
LIKELY EXPLANATION:
RECOMMENDATION:

23. Example AI Response

Input:

Voltage = 227 V
Current = 15.1 A
Power = 3.42 kW
PF = 0.91
Status = HIGH_LOAD

AI response:

STATUS: HIGH LOAD

SEVERITY: WARNING

SUMMARY:
GridGuard detected a sustained high electrical load.

MEASUREMENTS:
Voltage: 227 V
Current: 15.1 A
Power: 3.42 kW
Power factor: 0.91

LIKELY EXPLANATION:
The increase is consistent with one or more high-power appliances operating simultaneously.

RECOMMENDATION:
Check which high-power appliances are currently operating. If this condition is unexpected or persistent, have the electrical installation inspected by a qualified professional.

24. Telegram Alert

n8n can send:

⚡ GRIDGUARD AI ALERT

🔴 HIGH LOAD DETECTED

Voltage: 227 V
Current: 15.1 A
Power: 3.42 kW
Power Factor: 0.91

AI Analysis:
A sustained high electrical load has been detected.

Recommendation:
Check high-power appliances currently operating.

The n8n Telegram integration supports sending messages and audio and retrieving files from Telegram.


25. Telegram Voice Alert

The flow is:

Electrical Alert
      │
      ▼
    n8n
      │
      ▼
    AI Agent
      │
      ▼
Text response
      │
      ▼
Text-to-Speech
      │
      ▼
Audio binary
      │
      ▼
Telegram
      │
      ▼
User receives voice alert

OpenAI's audio API supports both transcription and speech generation.


26. Telegram Voice Command

The reverse flow is especially useful:

User
 │
 │ Telegram voice
 ▼
Telegram Bot
 │
 ▼
n8n Trigger
 │
 ▼
Get Telegram File
 │
 ▼
Download audio
 │
 ▼
Speech-to-Text
 │
 ▼
Text command
 │
 ▼
AI Agent
 │
 ├────► Query Google Sheets
 │
 ├────► Query ThingSpeak
 │
 └────► Analyze current telemetry
 │
 ▼
Generate response
 │
 ▼
Text-to-Speech
 │
 ▼
Telegram Audio

The OpenAI transcription endpoint accepts common audio formats including FLAC, MP3, MP4, MPEG, M4A, OGG, WAV and WebM.


27. Example Voice Conversation

User

"GridGuard, what is the current power consumption?"

System

Current power consumption is 2.18 kilowatts.

The voltage is 228 volts and current is approximately
9.6 amps.

The current load is within the configured normal range.

User

"How much energy have I used today?"

AI Agent:

Today's recorded energy consumption is approximately
12.9 kilowatt-hours.

Your highest recorded load today was 3.42 kilowatts.

User

"Why did you alert me?"

AI:

The alert was triggered because power remained above
the configured high-load threshold for several consecutive
measurements.

28. AI Agent Tools

The AI Agent can have tools such as:

Tool 1:
Get_Current_Telemetry

Tool 2:
Get_Today_Energy

Tool 3:
Get_Historical_Readings

Tool 4:
Get_ThingSpeak_Data

Tool 5:
Get_Device_Status

Tool 6:
Send_Telegram_Alert

A good architecture is:

                 ┌─────────────────┐
                 │    AI AGENT     │
                 └────────┬────────┘
                          │
        ┌─────────────────┼──────────────────┐
        │                 │                  │
        ▼                 ▼                  ▼
 Current Data       Historical Data     Device Status
        │                 │                  │
        ▼                 ▼                  ▼
    n8n Tool           Sheets Tool       n8n Tool

29. Daily Energy Report

Create an n8n Schedule Trigger.

Example:

Every day
08:00

Workflow:

Schedule
   ↓
Google Sheets
   ↓
Get yesterday's readings
   ↓
Calculate statistics
   ↓
AI Agent
   ↓
Generate daily report
   ↓
Telegram

Example report:

⚡ GRIDGUARD DAILY REPORT

Energy consumed: 18.42 kWh

Average power: 0.77 kW

Maximum power: 3.42 kW

Average voltage: 228.1 V

Power events: 2

AI Summary:
Energy consumption was higher than the normal baseline
during the evening period. The largest load occurred at
19:42.

30. Recommended n8n Workflow Structure

Workflow 1 — Telemetry

[Webhook]
     ↓
[Validate JSON]
     ↓
[Normalize Data]
     ↓
[Google Sheets]
     ↓
[ThingSpeak]
     ↓
[Threshold Check]
     ↓
[Alert Required?]
     ├── NO → END
     │
     └── YES
          ↓
      [AI Agent]
          ↓
      [Telegram]
          ↓
      [Text-to-Speech]
          ↓
      [Telegram Audio]

Workflow 2 — Telegram Voice

[Telegram Trigger]
       ↓
[Is Voice Message?]
       │
       ▼
[Get File]
       ↓
[Download Audio]
       ↓
[Speech-to-Text]
       ↓
[AI Agent]
       ↓
[Generate Answer]
       ↓
[Text-to-Speech]
       ↓
[Telegram Send Audio]

Workflow 3 — Telegram Text

[Telegram Trigger]
       ↓
[Extract Text]
       ↓
[AI Agent]
       ↓
[Tool Call]
       ↓
[Get Telemetry/Data]
       ↓
[Generate Answer]
       ↓
[Telegram Message]

Workflow 4 — Daily Report

[Schedule Trigger]
       ↓
[Google Sheets]
       ↓
[Calculate Statistics]
       ↓
[AI Agent]
       ↓
[Telegram]
       ↓
[Optional Voice]

31. ESP32 Firmware Architecture

The ESP32 firmware should be organized into these functions:

setup()
 ├── Serial initialization
 ├── Wi-Fi initialization
 └── Energy sensor initialization

loop()
 ├── Read energy sensor
 ├── Validate readings
 ├── Create JSON
 ├── Send HTTP request
 └── Wait until next interval

32. ESP32 Starter Firmware

The following example demonstrates the architecture. Adapt the sensor-library calls to the exact energy meter/module you use.

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

// ===============================
// USER CONFIGURATION
// ===============================

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

const char* N8N_URL =
    "https://YOUR_N8N_DOMAIN/webhook/gridguard/telemetry";

const char* DEVICE_ID =
    "GRIDGUARD-ESP32-001";

const unsigned long SEND_INTERVAL = 30000;

unsigned long lastSend = 0;

// Example measurement variables.
// Replace these with values obtained
// from your actual energy-meter library.
float voltage = 0;
float current = 0;
float power = 0;
float energy = 0;
float frequency = 0;
float powerFactor = 0;


// ===============================
// WIFI
// ===============================

void connectWiFi()
{
  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

  Serial.print("Connecting to Wi-Fi");

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

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


// ===============================
// SENSOR
// ===============================

bool readEnergyMeter()
{
  /*
     Replace this section with your
     PZEM/equivalent sensor library.

     Example concept:

     voltage = pzem.voltage();
     current = pzem.current();
     power = pzem.power();
     energy = pzem.energy();
     frequency = pzem.frequency();
     powerFactor = pzem.pf();
  */

  // Temporary demonstration values
  voltage = 228.4;
  current = 7.82;
  power = 1648.5;
  energy = 12.84;
  frequency = 50.0;
  powerFactor = 0.92;

  return true;
}


// ===============================
// SEND DATA TO N8N
// ===============================

bool sendTelemetry()
{
  if (WiFi.status() != WL_CONNECTED)
  {
    connectWiFi();
  }

  HTTPClient http;

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

  StaticJsonDocument<512> doc;

  doc["device_id"] = DEVICE_ID;
  doc["voltage"] = voltage;
  doc["current"] = current;
  doc["power"] = power;
  doc["energy"] = energy;
  doc["frequency"] = frequency;
  doc["power_factor"] = powerFactor;
  doc["rssi"] = WiFi.RSSI();

  String json;

  serializeJson(doc, json);

  Serial.println("Sending:");
  Serial.println(json);

  int responseCode = http.POST(json);

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

  if (responseCode > 0)
  {
    Serial.println(http.getString());
  }

  http.end();

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


// ===============================
// SETUP
// ===============================

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

  delay(1000);

  connectWiFi();

  Serial.println("GridGuard AI started");
}


// ===============================
// LOOP
// ===============================

void loop()
{
  if (millis() - lastSend >= SEND_INTERVAL)
  {
    lastSend = millis();

    if (readEnergyMeter())
    {
      sendTelemetry();
    }
    else
    {
      Serial.println("Energy sensor read failed");
    }
  }
}

33. Production ESP32 Improvements

The demonstration firmware should eventually be upgraded with:

Wi-Fi reconnect
HTTPS certificate validation
Watchdog
Sensor timeout detection
Local buffering
Retry queue
NTP time synchronization
Persistent configuration
OTA firmware updates
Device authentication
Message sequence number
Firmware version

For example, add:

{
  "device_id": "GRIDGUARD-001",
  "firmware": "1.0.0",
  "sequence": 14582,
  "timestamp": "...",
  "voltage": 228.4,
  "current": 7.82,
  "power": 1648.5
}

34. Security Architecture

Do not expose an unauthenticated webhook that accepts arbitrary telemetry.

Use:

ESP32
   │
   │ HTTPS
   │ + authentication token
   ▼
n8n Webhook
   │
   ▼
Authentication
   │
   ▼
Validation

Example header:

Authorization: Bearer YOUR_DEVICE_TOKEN

The ESP32 firmware should keep credentials outside the public source repository.

Never publish:

Wi-Fi password
n8n credentials
Telegram bot token
OpenAI API key
ThingSpeak write API key
Google credentials

35. Recommended Data Security

Use separate credentials:

ESP32 Token
      ↓
n8n Webhook

ThingSpeak Write Key
      ↓
n8n

Telegram Bot Token
      ↓
n8n

AI API Key
      ↓
n8n

Google OAuth Credential
      ↓
n8n

If one credential is compromised, it should not automatically compromise the entire system.


36. Telegram Bot Setup

Conceptually:

Telegram
   ↓
BotFather
   ↓
Create Bot
   ↓
Bot Token
   ↓
n8n Telegram Credential

Then configure the Telegram Trigger in n8n.

The n8n Telegram node supports Telegram message and file operations.


37. ThingSpeak Setup

Create a ThingSpeak channel.

Configure:

Channel Name:
GridGuard AI

Field 1:
Voltage

Field 2:
Current

Field 3:
Power

Field 4:
Energy

Field 5:
Power Factor

Field 6:
Frequency

Field 7:
Alert Level

Field 8:
Device Status

Copy the channel's write API key.

Use it only in n8n/server-side credentials where possible.

ThingSpeak supports both REST and MQTT interfaces; REST is particularly convenient for a simple HTTP-based n8n workflow.


38. Google Sheets Setup

Create:

GridGuard_AI.xlsx

or a Google Spreadsheet:

GridGuard AI

Tabs:

Telemetry
Alerts
Daily Reports
Devices
Configuration

Telemetry

timestamp
device_id
voltage
current
power
energy
pf
frequency
status

Alerts

timestamp
device_id
severity
trigger
power
message
ai_analysis
telegram_sent
voice_sent

39. Device Configuration Sheet

A useful configuration table is:

device_id | max_power | min_voltage | max_voltage | alert_enabled

Example:

GRIDGUARD-001 | 3000 | 200 | 250 | TRUE

This lets n8n change thresholds without recompiling ESP32 firmware.


40. Agentic Configuration

The AI agent can query the configuration before analyzing telemetry.

Incoming telemetry
       ↓
Get device configuration
       ↓
Get current measurements
       ↓
Get historical baseline
       ↓
AI Agent
       ↓
Decision

This is much better than hard-coding every threshold into the AI prompt.


41. AI Decision Format

Have the AI agent return structured JSON.

Example:

{
  "status": "HIGH_LOAD",
  "severity": "WARNING",
  "alert_required": true,
  "summary": "Power consumption is significantly above the configured normal level.",
  "recommendation": "Check currently operating high-power appliances.",
  "voice_message": "GridGuard has detected a high electrical load."
}

Then n8n can reliably route the result.


42. Why Structured AI Output Matters

Avoid:

AI says some random paragraph...

Prefer:

{
  "alert_required": true,
  "severity": "WARNING",
  "summary": "...",
  "recommendation": "...",
  "voice_message": "..."
}

Then:

alert_required
       │
       ├── false → END
       │
       └── true
             ↓
         Telegram

43. AI + Historical Analytics

The system becomes substantially more intelligent when historical data is available.

Example:

Current:
3.42 kW

Typical at this time:
1.10 kW

Difference:
+211%

AI can then say:

Current consumption is approximately three times
the normal evening baseline.

This is more useful than a simple fixed threshold.


44. Anomaly Detection

A future version can implement:

Moving average
Standard deviation
Z-score
EWMA
Peak detection
Time-of-day baseline
Day-of-week baseline

For example:

Expected power:
1.2 kW ± 0.3 kW

Observed:
3.4 kW

Anomaly:
YES

The AI then explains the anomaly rather than being responsible for the mathematical detection itself.


45. Recommended AI Architecture

                TELEMETRY
                    │
                    ▼
          ┌─────────────────┐
          │ Deterministic   │
          │ Rules Engine    │
          └────────┬────────┘
                   │
                   ▼
          ┌─────────────────┐
          │ Statistical     │
          │ Anomaly Engine  │
          └────────┬────────┘
                   │
                   ▼
          ┌─────────────────┐
          │     AI Agent    │
          │                 │
          │ Explanation     │
          │ Reasoning       │
          │ Recommendation  │
          └────────┬────────┘
                   │
          ┌────────┴────────┐
          ▼                 ▼
      Telegram          Dashboard

This division is important:

Rules/statistics detect. AI explains.


46. Full Telegram AI Agent

User sends:

"Show me today's energy usage"

n8n:

Telegram Trigger
       ↓
AI Agent
       ↓
Tool: Get Today's Energy
       ↓
Google Sheets
       ↓
Return data
       ↓
AI Agent
       ↓
Generate response
       ↓
Telegram

47. Voice Query Example

USER:
"GridGuard, is my power consumption normal?"

              ↓

Telegram
              ↓

n8n
              ↓

Speech-to-Text
              ↓

"Is my power consumption normal?"
              ↓

AI Agent
              ↓

Get Current Telemetry
              ↓

Get Baseline
              ↓

Analyze
              ↓

Text Response
              ↓

Text-to-Speech
              ↓

Telegram Audio

48. Voice Response Example

Your current power consumption is 1.65 kilowatts.

This is within the normal range for this device.

The measured voltage is 228 volts and the power factor
is approximately 0.92.

49. Complete Data Flow

┌──────────────┐
│ AC Electrical│
│    Load      │
└──────┬───────┘
       │
       ▼
┌──────────────┐
│ Energy Meter │
└──────┬───────┘
       │ UART
       ▼
┌──────────────┐
│    ESP32     │
└──────┬───────┘
       │ HTTPS/JSON
       ▼
┌──────────────┐
│     n8n      │
└──────┬───────┘
       │
       ├─────────────► Google Sheets
       │
       ├─────────────► ThingSpeak
       │
       ▼
┌──────────────┐
│ Rules Engine │
└──────┬───────┘
       │
       ▼
┌──────────────┐
│  AI Agent    │
└──────┬───────┘
       │
       ├────────────► Telegram Text
       │
       ▼
┌──────────────┐
│ Text-to-Speech│
└──────┬───────┘
       │
       ▼
┌──────────────┐
│Telegram Audio│
└──────────────┘

50. Reverse Voice Flow

        USER
          │
          ▼
   Telegram Voice
          │
          ▼
    Telegram Trigger
          │
          ▼
      Get File
          │
          ▼
   Download Audio
          │
          ▼
   Speech-to-Text
          │
          ▼
      AI Agent
          │
     ┌────┼────┐
     ▼    ▼    ▼
 Current  History  Reports
 Data     Data     Data
     │    │    │
     └────┼────┘
          ▼
    AI Response
          │
          ▼
   Text-to-Speech
          │
          ▼
   Telegram Audio
          │
          ▼
        USER

51. Software Stack

Hardware:
ESP32
Energy Meter

Firmware:
Arduino IDE / PlatformIO
C++

Automation:
n8n

Cloud:
ThingSpeak
Google Sheets

Messaging:
Telegram Bot

AI:
LLM + Speech-to-Text + Text-to-Speech

Transport:
HTTP/HTTPS
JSON

n8n is designed to connect applications and APIs and also provides AI-oriented workflow capabilities.


52. Suggested Project Directory

GridGuard-AI/
│
├── firmware/
│   ├── gridguard.ino
│   ├── config.h
│   ├── sensor.cpp
│   ├── sensor.h
│   ├── wifi_manager.cpp
│   └── wifi_manager.h
│
├── n8n/
│   ├── telemetry-workflow.json
│   ├── telegram-workflow.json
│   ├── daily-report-workflow.json
│   └── ai-agent-workflow.json
│
├── docs/
│   ├── architecture.md
│   ├── wiring.md
│   ├── setup.md
│   └── troubleshooting.md
│
└── README.md

53. Development Phases

Phase 1 — ESP32

ESP32
 ↓
Read sensor
 ↓
Serial Monitor

Do not add cloud services yet.


Phase 2 — Wi-Fi

ESP32
 ↓
Wi-Fi
 ↓
Internet

Verify stable reconnection.


Phase 3 — n8n

ESP32
 ↓
n8n Webhook

Verify JSON reception.


Phase 4 — Google Sheets

ESP32
 ↓
n8n
 ↓
Google Sheets

Verify historical logging.


Phase 5 — ThingSpeak

ESP32
 ↓
n8n
 ↓
ThingSpeak

Verify graphs.


Phase 6 — Rules

Telemetry
 ↓
Threshold
 ↓
Alert

Phase 7 — Telegram

Alert
 ↓
Telegram

Phase 8 — AI

Alert
 ↓
AI
 ↓
Explanation
 ↓
Telegram

Phase 9 — Voice

Alert
 ↓
AI
 ↓
TTS
 ↓
Telegram Voice

Phase 10 — Voice Agent

Telegram Voice
 ↓
STT
 ↓
AI Agent
 ↓
Tools
 ↓
TTS
 ↓
Telegram

This staged development makes debugging considerably easier.


54. Testing Plan

Test 1 — Sensor

Check:

Voltage
Current
Power
Energy
Frequency
PF

against a trusted meter.


Test 2 — Wi-Fi Failure

Disconnect Wi-Fi.

Expected:

ESP32 detects connection loss
ESP32 reconnects
System resumes transmission

Test 3 — n8n Failure

Stop n8n.

Expected:

ESP32 does not crash
ESP32 retries

For a production version, add local data buffering.


Test 4 — High Load

Use a controlled test condition.

Expected:

Threshold exceeded
 ↓
Alert generated
 ↓
Telegram message
 ↓
Optional voice alert

Test 5 — False Alert

Short transient spike.

Expected:

No alert

if debounce/persistence logic is correctly implemented.


Test 6 — Telegram Voice

Send:

"What is the current power?"

Expected:

Voice → text → AI → telemetry → answer → voice

55. Failure Handling

Every component should have a failure state.

Sensor failure
     ↓
SENSOR_ERROR

Wi-Fi failure
     ↓
OFFLINE

n8n failure
     ↓
RETRY

ThingSpeak failure
     ↓
CLOUD_ERROR

AI failure
     ↓
RULE_BASED_ALERT

Telegram failure
     ↓
LOG_AND_RETRY

The system should never depend on the AI service for basic electrical safety detection.


56. Offline Mode

A better ESP32 design stores recent data locally.

Example:

ESP32
 │
 ├── Internet available
 │       ↓
 │     n8n
 │
 └── Internet unavailable
         ↓
     Local buffer
         ↓
     Reconnect
         ↓
     Upload buffered data

Use a ring buffer or nonvolatile storage appropriate to the expected data volume.


57. Device Heartbeat

Send a heartbeat periodically:

{
  "device_id": "GRIDGUARD-001",
  "type": "heartbeat",
  "uptime": 123456,
  "rssi": -61,
  "firmware": "1.0.0"
}

n8n can then determine:

ONLINE
OFFLINE

For example:

No heartbeat for 5 minutes
        ↓
Device Offline
        ↓
Telegram Alert

58. Device Status Dashboard

A useful dashboard should show:

GridGuard AI

Device:
ONLINE 🟢

Voltage:
228.4 V

Current:
7.82 A

Power:
1.65 kW

Energy Today:
12.84 kWh

Power Factor:
0.92

Frequency:
50.0 Hz

Status:
NORMAL 🟢

59. Advanced Version

The system can later be expanded to:

Multiple ESP32 devices
Multiple rooms
Multiple circuits
Solar monitoring
Grid import/export
Battery monitoring
Generator monitoring
EV charger monitoring
Machine monitoring
Predictive maintenance
Energy-cost calculation
Demand forecasting

Architecture:

ESP32 #1 ──┐
ESP32 #2 ──┤
ESP32 #3 ──┤
ESP32 #4 ──┘
            │
            ▼
           n8n
            │
      ┌─────┼──────┐
      ▼     ▼      ▼
   Sheets ThingSpeak AI
                    │
                    ▼
                 Telegram

60. Energy Cost Calculation

If electricity tariff is:

₹8 / kWh

and today's consumption is:

18.42 kWh

estimated energy cost:

18.42 × ₹8
=
₹147.36

The actual bill may differ because real tariffs can include slabs, fixed charges, taxes, demand charges and other components.

The tariff should therefore be configurable rather than hard-coded.


61. Cost-Aware AI

The AI can say:

Today's recorded energy consumption is 18.42 kWh.

Using the configured reference tariff of ₹8/kWh,
the estimated energy charge is approximately ₹147.36.

This is an estimate and may not represent the final
electricity bill.

62. AI Energy Advisor

A future agent can answer:

Which hour consumes the most energy?

What was my highest load today?

Compare today with yesterday.

Why is today's consumption higher?

What appliances might explain the increase?

What is my estimated energy cost?

Which period has the highest average load?

The AI should answer from actual retrieved data rather than guessing.


63. Example Complete Conversation

USER:
GridGuard, how is the power right now?

GRIDGUARD:
Your current load is 1.65 kW.
Voltage is 228 V and current is 7.82 A.
The load is currently within the configured normal range.

Then:

USER:
Why was there an alert earlier?

GRIDGUARD:
An earlier high-load event reached approximately
3.42 kW and remained above the configured threshold
for several readings.

Then:

USER:
How much energy did I use today?

GRIDGUARD:
The recorded energy consumption today is 12.84 kWh.

64. Final System Architecture

                         ┌─────────────────────┐
                         │     ELECTRICAL      │
                         │        LOAD         │
                         └──────────┬──────────┘
                                    │
                                    ▼
                         ┌─────────────────────┐
                         │   ENERGY SENSOR     │
                         │ PZEM / Equivalent   │
                         └──────────┬──────────┘
                                    │
                                  UART
                                    │
                                    ▼
                         ┌─────────────────────┐
                         │       ESP32         │
                         │                     │
                         │ Measurement         │
                         │ Validation          │
                         │ Wi-Fi               │
                         │ HTTPS               │
                         └──────────┬──────────┘
                                    │
                                  JSON
                                    │
                                    ▼
                         ┌─────────────────────┐
                         │        n8n          │
                         │                     │
                         │ Webhook             │
                         │ Validation          │
                         │ Automation           │
                         │ Rules               │
                         │ AI Agent            │
                         └───────┬─┬─┬─────────┘
                                 │ │ │
                 ┌───────────────┘ │ └────────────────┐
                 │                 │                  │
                 ▼                 ▼                  ▼
        ┌────────────────┐ ┌──────────────┐ ┌─────────────────┐
        │ Google Sheets  │ │ ThingSpeak   │ │   AI Agent      │
        │                │ │              │ │                 │
        │ Historical     │ │ Charts       │ │ Analysis        │
        │ Data           │ │ Dashboard    │ │ Explanation     │
        └────────────────┘ └──────────────┘ │ Recommendation  │
                                             └────────┬────────┘
                                                      │
                                             ┌────────┴────────┐
                                             │                 │
                                             ▼                 ▼
                                      ┌─────────────┐   ┌─────────────┐
                                      │ Telegram    │   │ Text-to-    │
                                      │ Text        │   │ Speech      │
                                      └─────────────┘   └──────┬──────┘
                                                              │
                                                              ▼
                                                       ┌─────────────┐
                                                       │ Telegram    │
                                                       │ Voice       │
                                                       └─────────────┘

65. Recommended Final Project Name

GridGuard AI ⚡ — Agentic IoT Smart Power Monitoring and Voice Alert System

Subtitle:

ESP32 + Energy Meter + n8n Automation + AI Agent + Telegram Voice + Google Sheets + ThingSpeak


66. Final Project Features

The completed system provides:

  • ESP32-based IoT monitoring
  • Voltage monitoring
  • Current monitoring
  • Power monitoring
  • Energy monitoring
  • Power-factor monitoring
  • Frequency monitoring
  • Wi-Fi connectivity
  • JSON telemetry
  • HTTPS communication
  • n8n automation
  • Google Sheets logging
  • ThingSpeak dashboard
  • Deterministic threshold detection
  • Anomaly detection
  • AI-powered analysis
  • AI-generated explanations
  • Telegram text notifications
  • Telegram voice notifications
  • Telegram voice commands
  • Speech-to-text
  • Text-to-speech
  • Daily energy reports
  • Historical analysis
  • Device heartbeat
  • Offline/retry architecture
  • Multi-device expansion

67. Implementation Order

Build it in this exact order:

1. ESP32
      ↓
2. Energy sensor
      ↓
3. Serial measurement
      ↓
4. Wi-Fi
      ↓
5. n8n webhook
      ↓
6. JSON telemetry
      ↓
7. Google Sheets
      ↓
8. ThingSpeak
      ↓
9. Threshold engine
      ↓
10. Telegram text
      ↓
11. AI analysis
      ↓
12. Text-to-speech
      ↓
13. Telegram voice alert
      ↓
14. Telegram voice commands
      ↓
15. Historical AI analysis
      ↓
16. Offline buffering
      ↓
17. Security hardening
      ↓
18. Multi-device support

This order prevents the project from becoming difficult to debug.

68. Key Design Principle

The most important architectural decision is:

              SENSOR DATA
                   │
                   ▼
          DETERMINISTIC LOGIC
                   │
                   ▼
              AI ANALYSIS
                   │
                   ▼
             HUMAN ALERT

Do not make the language model the primary electrical safety mechanism.

The ESP32 and deterministic n8n rules should identify measurable conditions. The AI agent should provide interpretation, context, natural-language explanations and user interaction.

That gives GridGuard AI a much more reliable architecture for a real IoT project.

AI-Powered Smart Power Grid Monitoring & Safety Automation Using ESP32, IoT, n8n, Web Dashboard and Telegram Voice Alerts

AI-Powered Smart Power Grid Monitoring & Safety Automation Using ESP32

1. Project Title

AI-Powered Smart Power Grid Monitoring and Safety Automation Using ESP32, IoT, n8n, AI Agent, Web Dashboard and Telegram Voice Alerts

Short title

Agentic AI-Based Smart Power Grid Monitoring and Safety System


2. Abstract

The proposed system is an intelligent IoT-based electrical power monitoring and safety platform designed to continuously monitor electrical parameters such as voltage, current, power, energy consumption, frequency, temperature, and abnormal operating conditions.

An ESP32 acts as the edge controller. Sensors connected to the ESP32 acquire electrical and environmental measurements. The ESP32 processes the measurements locally and transmits the data to an IoT/cloud layer.

The system uses n8n as the automation and orchestration platform. n8n receives sensor data, evaluates predefined safety conditions, stores measurements in Google Sheets, publishes data to ThingSpeak, updates a web dashboard, and communicates with an AI agent.

When an abnormal condition such as over-voltage, under-voltage, over-current, excessive temperature, overload, or abnormal power consumption is detected, the automation system generates an alert. The AI agent can analyze the event and determine the appropriate response according to predefined safety rules.

The system can then send a Telegram notification and voice alert to the user. In severe situations, the ESP32 can activate a local protection mechanism such as a relay/contactor to disconnect a properly isolated, low-voltage-controlled load.

The project therefore combines:

Edge IoT + ESP32 + Electrical Monitoring + AI Agent + n8n Automation + Cloud Storage + Web Dashboard + Telegram Voice Alerts


3. Main Objectives

The major objectives are:

  1. Monitor electrical parameters in real time.
  2. Detect electrical abnormalities automatically.
  3. Process critical safety conditions at the ESP32 edge.
  4. Send sensor data to the cloud.
  5. Automate data processing using n8n.
  6. Use an AI agent for intelligent event analysis.
  7. Display measurements on a web dashboard.
  8. Store historical measurements in Google Sheets.
  9. Visualize IoT data using ThingSpeak.
  10. Send Telegram notifications.
  11. Generate Telegram voice alerts for critical events.
  12. Maintain an event/safety log.
  13. Automatically activate a protection output when a predefined dangerous condition occurs.
  14. Provide remote monitoring through the Internet.

4. Overall System Architecture

The complete system can be divided into six layers.

┌───────────────────────────────────────────────────────────┐
│ ELECTRICAL SYSTEM │
│ │
│ Voltage ──┐ │
│ Current ──┤ │
│ Power ────┤──> Sensors / Metering Circuit │
│ Energy ───┤ │
│ Temp ─────┘ │
└─────────────────────────┬─────────────────────────────────┘
┌───────────────────────────────────────────────────────────┐
│ EDGE LAYER │
│ │
│ ESP32 │
│ │
│ Sensor Reading │
│ Local Filtering │
│ Threshold Checking │
│ Emergency Logic │
│ Wi-Fi Communication │
│ Relay/Contactor Control* │
└─────────────────────────┬─────────────────────────────────┘
│ Wi-Fi / HTTPS / MQTT
┌───────────────────────────────────────────────────────────┐
│ IoT / AUTOMATION LAYER │
│ │
│ n8n │
│ │
│ Receive Data │
│ ↓ │
│ Validate Data │
│ ↓ │
│ Safety Rules │
│ ↓ │
│ AI Agent │
│ ↓ │
│ Decision / Classification │
└──────────────┬──────────┬──────────┬──────────────────────┘
│ │ │
▼ ▼ ▼
Google Sheets ThingSpeak Database
│ │
└────┬─────┘
Web Dashboard
User / Engineer
Telegram Bot
┌────────┴────────┐
▼ ▼
Text Alert Voice Alert

* For an actual mains/high-voltage installation, the protection hardware must be properly rated, isolated and installed by a qualified person. The ESP32 should not directly switch mains voltage.


5. Hardware Requirements

5.1 Main Controller

ESP32 Development Board

Recommended:

  • ESP32 DevKit V1
  • ESP32-WROOM-32
  • ESP32-S3 if additional processing/peripherals are desired

The ESP32 provides:

  • Wi-Fi
  • GPIO
  • ADC
  • UART
  • I²C
  • SPI
  • sufficient processing capability
  • low-cost edge computing

6. Sensors

The exact sensors depend on whether this is a laboratory low-voltage prototype or a real electrical installation.

Voltage measurement

Possible approach:

AC voltage sensor/module → isolated measurement → ESP32 ADC

For a prototype, an appropriately isolated voltage-sensing module can be used.

Current measurement

Possible options:

  • Current transformer
  • Hall-effect current sensor
  • INA219/INA226 for suitable DC applications

For AC mains measurement, a properly rated current transformer or isolated current transducer is preferable.

Temperature

Possible:

  • DS18B20
  • DHT22 for ambient monitoring
  • thermistor
  • industrial temperature sensor

For electrical-panel temperature, an appropriately mounted temperature sensor is preferable.

Energy measurement

Energy can be calculated approximately from:

Energy = Power × Time

For more accurate electrical metering, use a dedicated energy-metering IC/module or certified meter.


7. Protection Components

A prototype can include:

ESP32 GPIO
Driver Circuit
Relay / Contactor Control

Important:

Do not connect a relay module directly to an uncontrolled mains circuit merely because the relay is labeled "10 A" or "250 V".

For an academic prototype, demonstrate the switching function using a safe low-voltage load such as a DC lamp or DC motor.

For real distribution equipment, use appropriately rated:

  • contactor
  • fuse/MCB
  • circuit breaker
  • overload protection
  • surge protection
  • isolation
  • emergency shutdown

and have the electrical installation professionally designed.


8. Suggested Hardware Block Diagram

┌──────────────────┐
│ Electrical Load │
└────────┬─────────┘
┌───────┴────────┐
│ │
▼ ▼
Voltage Sensor Current Sensor
│ │
└───────┬────────┘
┌────────┐
Temperature ───►│ ESP32 │
Sensor │ │
└───┬────┘
┌───────┼───────────┐
│ │ │
▼ ▼ ▼
Relay Wi-Fi Local
Control │ Alarm
n8n

9. ESP32 Responsibilities

The ESP32 is the edge intelligence layer.

It should:

  1. Read sensors.
  2. Filter noisy readings.
  3. Calculate electrical parameters.
  4. Check safety thresholds.
  5. Identify immediate dangerous conditions.
  6. Send telemetry to the server.
  7. Receive commands.
  8. Control a safe protection output.
  9. Continue basic protection even if the Internet is unavailable.

This last point is extremely important.

Do not make the Internet your only safety mechanism.

For example:

Sensor
ESP32
├── Safe → Normal operation
└── Dangerous
├── Local protection
├── Local alarm
└── Send cloud event

The AI agent should assist monitoring and decision support, while deterministic safety rules remain responsible for immediate protection.


10. Example Safety Parameters

For an educational prototype, you can define configurable thresholds such as:

Parameter Example Normal Range Action
Voltage Configurable Detect under/over-voltage
Current Configurable Detect over-current
Power Configurable Detect overload
Temperature Configurable Detect overheating
Frequency Configurable Detect abnormal frequency
Energy Configurable Monitor consumption
Sensor status Valid Detect sensor failure

Don't copy these values blindly into a real power system. Thresholds should be based on the actual equipment and applicable electrical standards.


11. Operating Modes

The system can have four modes.

MODE 1 — NORMAL

Voltage ✓
Current ✓
Temperature ✓
Power ✓
Internet ✓
NORMAL STATE

Dashboard:

SYSTEM STATUS: 🟢 NORMAL

MODE 2 — WARNING

Example:

Current slightly above normal

System:

ESP32
n8n
AI Analysis
WARNING
Telegram notification

MODE 3 — CRITICAL

Example:

Over-current detected

Flow:

Sensor
ESP32
Local Safety Rule
Protection Output
n8n
AI Agent
Telegram Voice Alert

MODE 4 — COMMUNICATION FAILURE

If Internet connectivity disappears:

ESP32
├── Local monitoring continues
├── Local safety protection continues
└── Data buffered locally

When connectivity returns:

ESP32
Upload buffered measurements

12. IoT Data Format

A useful JSON telemetry structure is:

{
"device_id": "ESP32_GRID_01",
"timestamp": "2026-08-20T23:00:00",
"voltage": 230.4,
"current": 4.82,
"power": 1089.5,
"energy": 12.73,
"temperature": 36.4,
"frequency": 50.02,
"status": "NORMAL",
"alarm": false
}

An alarm message could be:

{
"device_id": "ESP32_GRID_01",
"event": "OVER_CURRENT",
"voltage": 228.6,
"current": 12.4,
"power": 2834.1,
"temperature": 48.2,
"severity": "CRITICAL",
"timestamp": "2026-08-20T23:02:12"
}

13. n8n Automation Architecture

The n8n workflow can be designed as:

ESP32
┌──────────────┐
│ Webhook/MQTT │
└──────┬───────┘
┌───────────────┐
│ Validate JSON │
└──────┬────────┘
┌───────────────┐
│ Normalize Data│
└──────┬────────┘
┌───────────────┐
│ Safety Rules │
└──────┬────────┘
┌──────┴──────────┐
│ │
▼ ▼
NORMAL ABNORMAL
│ │
│ ▼
│ AI Agent
│ │
│ ┌────────┴─────────┐
│ │ │
│ ▼ ▼
│ WARNING CRITICAL
│ │ │
└────────┼──────────────────┘
┌────────────────┐
│ Google Sheets │
└────────────────┘
ThingSpeak
Web Dashboard
Telegram
┌──────┴──────┐
▼ ▼
Text Voice

14. n8n Node-by-Node Workflow

Node 1 — Webhook

ESP32 sends:

POST /webhook/power-monitor

Body:

{
"device_id": "ESP32_GRID_01",
"voltage": 230.4,
"current": 4.82,
"power": 1089.5,
"temperature": 36.4
}

Node 2 — JSON Validation

Check:

device_id exists
voltage exists
current exists
timestamp exists

If invalid:

Reject packet

15. Node 3 — Function/Code Processing

n8n can calculate:

Power
Severity
Alarm state
Event type

Example logic:

const voltage = Number($json.voltage);
const current = Number($json.current);
const temperature = Number($json.temperature);
let severity = "NORMAL";
let event = "NORMAL";
if (temperature > 60) {
severity = "CRITICAL";
event = "OVER_TEMPERATURE";
} else if (current > 10) {
severity = "CRITICAL";
event = "OVER_CURRENT";
} else if (voltage > 250) {
severity = "WARNING";
event = "OVER_VOLTAGE";
}
return [{
json: {
...$json,
severity,
event
}
}];

These are example software thresholds, not real installation settings.


16. Node 4 — IF/Switch Node

severity
├── NORMAL
├── WARNING
└── CRITICAL

17. AI Agent

The AI agent receives structured information such as:

Device: ESP32_GRID_01
Voltage: 228.6 V
Current: 12.4 A
Power: 2834 W
Temperature: 48.2 °C
Event: OVER_CURRENT
Severity: CRITICAL

The AI agent can produce:

Classification:
CRITICAL
Reason:
Current is significantly above the configured operating threshold.
Recommended action:
Keep the protection state active and notify the operator.
Operator message:
"Critical over-current condition detected on Grid Device 01."

18. Important AI Safety Design

The AI should not be the sole authority for emergency electrical protection.

Use:

Deterministic Safety Logic
+
AI Analysis

instead of:

AI
Directly control mains

A safer architecture is:

Sensor
ESP32
┌─────────┴──────────┐
│ │
▼ ▼
Safety Rule Engine Cloud
│ │
▼ ▼
Protection n8n + AI
Notification

19. Telegram Alert System

The Telegram bot can send:

Normal notification

🟢 POWER GRID STATUS
Device: ESP32_GRID_01
Voltage: 230.4 V
Current: 4.82 A
Power: 1089 W
Temperature: 36.4 °C
Status: NORMAL

Critical notification

🚨 CRITICAL POWER ALERT
Device: ESP32_GRID_01
Event: OVER CURRENT
Current: 12.4 A
Voltage: 228.6 V
Power: 2834 W
Temperature: 48.2 °C
Severity: CRITICAL
Protection status: ACTIVE

20. Telegram Voice Alert

The voice-alert pipeline can be:

ESP32
n8n
AI Agent
Generate Alert Text
Text-to-Speech
Audio File
Telegram Bot
User's Phone

Example voice message:

"Critical power alert. Over-current has been detected on Grid Device 01. Please inspect the electrical system."

The voice message makes the project considerably more useful than a simple text notification.


21. Google Sheets Integration

Google Sheets can act as a simple historical log.

Recommended columns:

Timestamp Device Voltage Current Power Energy Temperature Event Severity Action
23:00 GRID01 230.4 4.82 1089 12.73 36.4 NORMAL NORMAL None
23:02 GRID01 228.6 12.4 2834 12.78 48.2 OVER_CURRENT CRITICAL Protection

This allows:

  • historical analysis
  • report generation
  • fault investigation
  • energy analysis
  • academic demonstration

22. ThingSpeak Integration

ThingSpeak can provide IoT visualization.

Example fields:

Field 1 → Voltage
Field 2 → Current
Field 3 → Power
Field 4 → Energy
Field 5 → Temperature
Field 6 → Frequency
Field 7 → Alarm

Dashboard:

┌─────────────────────────────────────┐
│ POWER GRID MONITOR │
├─────────────────────────────────────┤
│ Voltage 230.4 V │
│ Current 4.82 A │
│ Power 1089 W │
│ Energy 12.73 kWh │
│ Temperature 36.4 °C │
│ Frequency 50.02 Hz │
├─────────────────────────────────────┤
│ Status: 🟢 NORMAL │
└─────────────────────────────────────┘

23. Web Dashboard

A custom web dashboard can provide a professional user interface.

Dashboard sections

Header

AI SMART POWER GRID
ESP32 MONITORING SYSTEM

Device status

ESP32-GRID-01
🟢 ONLINE

Live parameters

┌────────────┬────────────┬────────────┐
│ VOLTAGE │ CURRENT │ POWER │
│ 230.4 V │ 4.82 A │ 1089 W │
└────────────┴────────────┴────────────┘
┌────────────┬────────────┬────────────┐
│ ENERGY │ TEMP │ FREQUENCY │
│ 12.73 kWh │ 36.4 °C │ 50.02 Hz │
└────────────┴────────────┴────────────┘

24. Dashboard Status Indicator

🟢 NORMAL
🟡 WARNING
🔴 CRITICAL
⚫ OFFLINE

25. Dashboard Event Log

TIME DEVICE EVENT STATUS
------------------------------------------------
23:00:01 GRID01 NORMAL 🟢
23:01:15 GRID01 HIGH CURRENT 🟡
23:02:12 GRID01 OVER CURRENT 🔴
23:02:13 GRID01 PROTECTION ACTIVE 🔴
23:05:42 GRID01 SYSTEM NORMAL 🟢

26. Complete Data Flow

┌──────────────┐
│ Electrical │
│ Parameters │
└──────┬───────┘
┌──────────────┐
│ Sensors │
└──────┬───────┘
┌──────────┐
│ ESP32 │
└────┬─────┘
Local safety check
┌──────┴───────┐
│ │
Normal Fault
│ │
└──────┬───────┘
Wi-Fi
n8n
┌───────────┼────────────┐
▼ ▼ ▼
Database AI Agent Google Sheets
│ │
│ ▼
│ Decision
│ │
└─────┬─────┘
Web Dashboard
Telegram
/ \
Text Voice

27. ESP32 Software Architecture

The ESP32 firmware should be divided into modules.

main.cpp
├── sensor_manager
├── electrical_calculation
├── safety_manager
├── wifi_manager
├── cloud_manager
├── relay_manager
└── watchdog_manager

28. Example ESP32 Arduino Code

Below is a prototype software framework. The sensor-reading functions must be replaced with the actual calibrated, isolated measurement hardware you use.

#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
const char* WIFI_SSID = "YOUR_WIFI";
const char* WIFI_PASSWORD = "YOUR_PASSWORD";
const char* SERVER_URL =
"https://YOUR-N8N-SERVER/webhook/power-monitor";
const int RELAY_PIN = 26;
const int LED_PIN = 2;
// Example software thresholds only.
// Do NOT use these values directly for a real electrical installation.
const float MAX_CURRENT = 10.0;
const float MAX_TEMPERATURE = 60.0;
const float MAX_VOLTAGE = 250.0;
float voltage = 0.0;
float current = 0.0;
float power = 0.0;
float temperature = 0.0;
String severity = "NORMAL";
String eventName = "NORMAL";
void connectWiFi() {
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
}
void readSensors() {
/*
Replace these examples with readings
from your actual sensor circuitry.
*/
voltage = 230.0;
current = 4.5;
temperature = 35.0;
power = voltage * current;
}
void safetyCheck() {
severity = "NORMAL";
eventName = "NORMAL";
bool critical = false;
if (current > MAX_CURRENT) {
severity = "CRITICAL";
eventName = "OVER_CURRENT";
critical = true;
}
if (temperature > MAX_TEMPERATURE) {

29. Improved Production Architecture

For the final version, don't put everything inside loop().

Use:

FreeRTOS Tasks
├── Sensor Task
├── Safety Task
├── Communication Task
├── Data Logging Task
└── Watchdog Task

This makes the firmware much more robust.


30. AI Agent Decision Architecture

The AI agent can receive a structured event:

{
"device_id": "ESP32_GRID_01",
"event": "OVER_CURRENT",
"current": 12.4,
"voltage": 228.6,
"power": 2834,
"temperature": 48.2,
"severity": "CRITICAL"
}

The AI should return structured information:

{
"classification": "CRITICAL",
"summary": "Over-current condition detected.",
"recommended_action": "Maintain protection state and alert operator.",
"notify_user": true,
"voice_alert": true
}

This is preferable to allowing arbitrary AI-generated commands to control hardware.


31. Agentic IoT Concept

The project becomes agentic when the system can perform a sequence of tasks rather than simply forwarding sensor data.

For example:

Observe
Analyze
Classify
Decide
Act
Notify
Record
Verify

Example:

ESP32 observes:
Current = 12.4 A
n8n receives event
Safety engine:
CRITICAL
AI Agent:
Over-current event
System:
Protection active
Telegram:
Voice alert
Google Sheets:
Event recorded
Dashboard:
RED ALERT
System waits for recovery
Normal condition detected
Telegram:
"System returned to normal."

32. Fault-Recovery Workflow

FAULT
Protection Activated
Telegram Alert
Monitor Parameters
Is condition safe?
┌┴──────────┐
│ │
NO YES
│ │
▼ ▼
Continue Recovery
Protection Logic
│ │
│ ▼
└──────► Operator Notification

For a real electrical system, automatic re-energization should not be implemented casually. Recovery/reclosing must follow the characteristics of the equipment and the applicable protection design.


33. Web Dashboard Software Stack

A suitable stack is:

Frontend:
HTML
CSS
JavaScript
Backend:
Node.js / Python / n8n
IoT:
ESP32
Cloud:
ThingSpeak
Automation:
n8n
Storage:
Google Sheets / Database
AI:
LLM-based AI Agent
Notification:
Telegram Bot

34. Example Dashboard HTML

A simple prototype can start with:

<!DOCTYPE html>
<html>
<head>
<title>AI Smart Power Grid</title>
<style>
body {
font-family: Arial, sans-serif;
background: #101820;
color: white;
margin: 0;
padding: 30px;
}
h1 {
text-align: center;
}
.dashboard {
display: grid;
grid-template-columns:
repeat(auto-fit, minmax(200px, 1fr));
gap: 20px;
}
.card {
background: #1d2a35;
padding: 25px;
border-radius: 15px;
text-align: center;
}
.value {
font-size: 32px;
color: #00d9ff;
}
.normal {
color: #00ff88;
}
.warning {
color: #ffd000;
}
.critical {
color: #ff4040;
}
</style>
</head>
<body>
<h1>AI SMART POWER GRID</h1>
<div class="dashboard">
<div class="card">
<h3>Voltage</h3>
<div class="value" id="voltage">-- V</div>
</div>
<div class="card">
<h3>Current</h3>
<div class="value" id="current">-- A</div>
</div>
<div class="card">
<h3>Power</h3>

35. Security Architecture

This project should include cybersecurity because the ESP32 is connected to the Internet.

Recommended:

ESP32
│ HTTPS
n8n
├── Authentication
├── Validation
├── Rate limiting
└── Logging

Use:

  • HTTPS
  • authentication tokens/API keys
  • secret storage
  • strong Wi-Fi credentials
  • n8n credentials management
  • input validation
  • device identification
  • TLS where supported
  • no hard-coded production secrets in public source code

36. Watchdog System

The ESP32 should use a watchdog strategy.

ESP32
├── Sensor task alive?
├── Communication task alive?
├── Safety task alive?
└── Watchdog
└── Fault → controlled restart

The local safety state should fail in a predictable manner.


37. Offline Data Buffer

If Wi-Fi fails:

Sensor
ESP32
Local buffer
Wi-Fi unavailable

After reconnection:

Wi-Fi restored
Upload buffered records
Cloud database

For larger systems, use non-volatile storage carefully to avoid excessive flash wear.


38. Complete n8n Workflow

A practical workflow could look like:

[Webhook]
[Validate JSON]
[Normalize Data]
[Safety Rule]
├────────────── NORMAL ───────────────┐
│ │
▼ ▼
[AI Agent] [Google Sheets]
│ │
▼ │
[Severity] │
│ │
┌──┴───────────────┐ │
│ │ │
▼ ▼ │
WARNING CRITICAL │
│ │ │
▼ ▼ │
Telegram Protection │
Text State │
│ │ │
▼ ▼ │
Voice TTS Telegram │
│ Voice │
└──────────┬───────┴────────────────────┘
[ThingSpeak]
[Dashboard]

39. Example n8n Pseudocode

TRIGGER:
Receive ESP32 data
VALIDATE:
Is device authenticated?
Is payload valid?
PROCESS:
Calculate/verify:
- voltage
- current
- power
- temperature
- status
SAFETY:
If critical threshold:
critical = true
AI:
Analyze event
IF critical:
Send Telegram text
Generate voice message
Send Telegram voice
Log event
ELSE IF warning:
Send Telegram text
Log event
ELSE:
Log normal measurement
ALWAYS:
Update dashboard
Store historical data
Update ThingSpeak

40. Database Structure

For a more professional project, replace Google Sheets as the primary database with a proper time-series or relational database.

Example:

TABLE power_readings
id
device_id
timestamp
voltage
current
power
energy
temperature
frequency
status
event
severity

Google Sheets can then be used as a reporting/export layer.


41. Communication Protocol Options

You have several choices.

Option A — HTTP

ESP32 → HTTP POST → n8n

Simple and easy for an academic project.

Option B — MQTT

ESP32
MQTT Broker
n8n

Better suited to scalable IoT systems.

Option C — HTTP + MQTT

ESP32
├── MQTT → IoT data
└── HTTPS → commands/API

For a final-year project, MQTT + n8n can make the architecture look more like a real IoT platform, while HTTP webhook integration is easier to demonstrate.


42. Recommended Final Architecture

I would recommend:

┌───────────────────┐
│ Electrical Sensors│
└─────────┬─────────┘
┌────────────┐
│ ESP32 │
│ Edge Node │
└─────┬──────┘
MQTT / HTTPS
┌────────────┐
│ n8n │
│ Automation │
└─────┬──────┘
┌───────────┼────────────┐
▼ ▼ ▼
Rule Engine AI Agent Database
│ │ │
│ │ ▼
│ │ Google Sheets
│ │
└─────┬─────┘
Decision Layer
┌─────────┼───────────┐
▼ ▼ ▼
Dashboard Telegram ThingSpeak
┌────┴────┐
▼ ▼
Text Voice

43. Project Demonstration

Your final demonstration can contain five test cases.

Test 1 — Normal condition

Voltage = normal
Current = normal
Temperature = normal
Result:
🟢 NORMAL

Test 2 — Over-current

Artificially create a safe simulated/low-voltage over-current condition.

Current > configured threshold
Result:
🟡/🔴 ALERT

Expected:

ESP32 → n8n → AI → Telegram

Test 3 — Over-temperature

Heat the sensor using a controlled test method.

Temperature > threshold

Expected:

CRITICAL
Telegram text
Telegram voice
Dashboard red status
Event stored

Test 4 — Internet failure

Turn off Wi-Fi.

Expected:

ESP32 continues local monitoring
Local safety logic continues
Cloud communication unavailable

Then reconnect.

Wi-Fi restored
Data synchronization

Test 5 — Recovery

Return the parameters to normal.

Expected:

FAULT
Monitoring
Normal condition
Recovery event
Telegram notification
Dashboard GREEN

44. Flowchart

START
Initialize ESP32
Connect Wi-Fi
Read Sensors
Validate Readings
Calculate Parameters
┌─────────────────────┐
│ Safety Threshold OK?│
└──────────┬──────────┘
YES │ NO
│ │
│ ▼
│ Critical
│ Event
│ │
│ ▼
│ Local Protection
│ │
└────┤
Send IoT Data
n8n
AI Analysis
┌──────┴───────┐
▼ ▼
Normal Abnormal
│ │
│ ▼
│ Telegram Alert
│ │
│ ▼
│ Voice Notification
└───────┬──────┘
Store Data
Update Dashboard
Repeat

45. Schematic-Level Architecture

For the academic schematic, use:

ESP32
┌───────────────┐
│ │
Voltage Sensor ─┤ ADC │
│ │
Current Sensor ─┤ ADC │
│ │
Temp Sensor ────┤ GPIO/I²C │
│ │
Relay Driver ◄──┤ GPIO │
│ │
│ Wi-Fi │
└───────┬───────┘
│ Wi-Fi
Internet
n8n Server
┌──────────────┼──────────────┐
│ │ │
▼ ▼ ▼
Google Sheets ThingSpeak AI Agent
│ │
└──────────────┬──────────────┘
Web Dashboard
Telegram
/ \
▼ ▼
Text Voice

For the actual electrical side, keep the sensor interface electrically isolated and use proper protection/isolation components. Do not put an ESP32 breadboard circuit directly across mains.


46. Project Modules

You can divide the project into 10 modules:

Module 1 — Sensor Module

Measures:

Voltage
Current
Temperature
Power
Energy
Frequency

Module 2 — ESP32 Edge Module

Sensor acquisition
Filtering
Local processing
Safety logic

Module 3 — IoT Communication Module

Wi-Fi
MQTT/HTTP
Cloud communication

Module 4 — n8n Automation Module

Data ingestion
Processing
Routing
Notifications

Module 5 — AI Agent Module

Event interpretation
Fault classification
Recommendation generation

Module 6 — Cloud Data Module

Google Sheets
ThingSpeak
Database

Module 7 — Web Dashboard

Live values
Charts
Device status
Alarm history

Module 8 — Telegram Module

Text alert
Voice alert
Recovery alert

Module 9 — Protection Module

Alarm
Relay/contactor interface
Emergency state

Module 10 — Security Module

Authentication
HTTPS
Secrets
Device identity

47. Expected Advantages

The system provides:

  • real-time monitoring
  • remote monitoring
  • automatic fault detection
  • AI-assisted analysis
  • automatic notifications
  • voice alerts
  • historical data
  • web visualization
  • IoT cloud integration
  • automation
  • local edge protection
  • scalable architecture

48. Limitations

The project should acknowledge:

  1. ESP32 ADC measurements require calibration.
  2. Low-cost sensors may have measurement errors.
  3. Internet connectivity can fail.
  4. AI decisions may be probabilistic.
  5. Cloud services can become unavailable.
  6. Google Sheets is not ideal for high-frequency telemetry.
  7. Real electrical installations require professionally designed protection.
  8. A prototype should not be treated as a certified grid-protection device.

49. Future Enhancements

You can extend the project with:

Predictive maintenance

Historical current
+
Temperature
+
Power patterns
ML model
Failure prediction

Load forecasting

Historical consumption
ML model
Predicted future load

Anomaly detection

Normal power signature
AI/ML model
Unexpected pattern
Alert

Multiple ESP32 nodes

ESP32 #1 ─┐
ESP32 #2 ─┤
ESP32 #3 ─┼──► MQTT ─► n8n ─► AI
ESP32 #4 ─┤
ESP32 #5 ─┘

This turns the project into a distributed smart-grid monitoring platform.


50. Final-Year Project Workflow

A practical implementation sequence is:

STEP 1
Build ESP32 sensor prototype
STEP 2
Read voltage/current/temperature
STEP 3
Calibrate sensors
STEP 4
Implement local safety rules
STEP 5
Connect ESP32 to Wi-Fi
STEP 6
Create n8n webhook/MQTT workflow
STEP 7
Send ESP32 telemetry to n8n
STEP 8
Add Google Sheets logging
STEP 9
Add ThingSpeak visualization
STEP 10
Build web dashboard
STEP 11
Create Telegram bot
STEP 12
Add Telegram text alerts
STEP 13
Add text-to-speech
STEP 14
Send Telegram voice alerts
STEP 15
Add AI agent
STEP 16
Add event classification
STEP 17
Test fault scenarios
STEP 18
Add authentication/security
STEP 19
Perform reliability testing
STEP 20
Prepare final demonstration

51. Suggested Project Folder Structure

AI-Smart-Power-Grid/
├── ESP32/
│ ├── main.cpp
│ ├── sensors.h
│ ├── sensors.cpp
│ ├── safety.h
│ ├── safety.cpp
│ ├── wifi_manager.h
│ └── cloud_manager.h
├── n8n/
│ ├── workflow.json
│ └── README.md
├── dashboard/
│ ├── index.html
│ ├── style.css
│ └── app.js
├── telegram/
│ └── bot_configuration.md
├── ai/
│ ├── agent_design.md
│ └── prompts.md
├── database/
│ └── schema.sql
├── documentation/
│ ├── abstract.md
│ ├── introduction.md
│ ├── methodology.md
│ ├── architecture.md
│ ├── testing.md
│ └── conclusion.md
└── README.md

52. Final Project Concept

The complete project can be summarized as:

AI SMART POWER GRID
┌────────────────┐
│ Electrical │
│ Sensors │
└───────┬────────┘
┌────────────────┐
│ ESP32 EDGE │
│ INTELLIGENCE │
└───────┬────────┘
Local Safety Logic
Wi-Fi/MQTT
┌────────────────┐
│ n8n │
│ AUTOMATION │
└───────┬────────┘
┌─────────┼──────────┐
▼ ▼ ▼
AI Agent Database IoT Cloud
│ │ │
└────┬────┴──────────┘
WEB DASHBOARD
TELEGRAM BOT
/ \
▼ ▼
TEXT VOICE

Core innovation

The strongest way to present the project is not simply "ESP32 sends data to Telegram."

Instead, present it as:

An edge-to-cloud agentic IoT safety platform in which the ESP32 performs real-time sensing and deterministic local protection, n8n orchestrates the IoT workflow, an AI agent interprets abnormal events, cloud services maintain historical telemetry, and Telegram provides real-time text and voice communication to the operator.

That framing makes the project substantially stronger for a final-year engineering project, mini-project, prototype demonstration, or research-oriented IoT project.

Safety note: For your physical prototype, demonstrate switching/protection with an isolated low-voltage load unless the mains side has been designed, enclosed, protected, and tested by a qualified electrical professional. The ESP32, breadboard, USB wiring, and ordinary hobby relay modules should not be treated as mains-rated protection equipment.