Thursday, 20 August 2026

⚡ AI-Powered Smart Power Grid Monitoring & Safety Automation System Using ESP32, IoT & n8n

⚡ AI-Powered Smart Power Grid Monitoring & Safety Automation System

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

Below is a complete project architecture that you can use as a final-year/major project, prototype, research project, or industrial IoT demonstration.

Important electrical-safety note: Do not connect an ESP32 GPIO directly to 230/240 V AC mains. For a real electrical installation, use appropriately rated isolated voltage/current sensors, CTs, transducers, fuses, isolation, enclosures and protection equipment, and have mains wiring performed/checked by a qualified electrician. The ESP32 system described here should be treated as a monitoring/automation controller, not as a replacement for certified protection equipment.


1. Project Title

AI-Powered Smart Power Grid Monitoring and Safety Automation System Using ESP32, IoT, n8n, AI Agent, Telegram Voice Alerts, Google Sheets and ThingSpeak

Short title

Agentic IoT Smart Grid Safety System


2. Abstract

The proposed system is an intelligent IoT-based electrical monitoring and safety platform built around an ESP32 microcontroller. The ESP32 continuously measures electrical parameters such as voltage, current, power, energy, frequency, power factor, temperature and abnormal operating conditions using suitable isolated sensors/transducers.

The measured data is transmitted through Wi-Fi to a cloud automation layer implemented using n8n. n8n acts as the central automation/orchestration platform. It receives sensor data through a webhook or MQTT/HTTP interface, processes the measurements, stores historical information in Google Sheets, and sends telemetry to ThingSpeak for visualization and analysis.

An AI Agent evaluates abnormal conditions and generates a human-readable diagnosis. Depending on the severity, the automation system can send a normal Telegram notification or generate a voice alert for critical events.

The system therefore combines:

Embedded IoT + Cloud + Automation + AI + Data Logging + Human Alerts

The ESP32's Wi-Fi station mode is appropriate for connecting the controller to an Internet-connected access point.


3. Main Objectives

The project has the following objectives:

  1. Monitor electrical parameters continuously.
  2. Detect abnormal voltage/current conditions.
  3. Detect overload conditions.
  4. Detect excessive temperature.
  5. Detect power-quality anomalies.
  6. Send sensor data to the cloud.
  7. Store historical data.
  8. Visualize data through ThingSpeak.
  9. Automate responses using n8n.
  10. Use an AI Agent to analyze abnormal events.
  11. Send Telegram notifications.
  12. Generate Telegram voice alerts for critical faults.
  13. Provide a web dashboard.
  14. Maintain an event/history log.
  15. Provide an architecture that can be expanded to multiple ESP32 nodes.

4. Overall Architecture

┌──────────────────────────┐
│ ELECTRICAL LOAD │
│ Home / Lab / Industrial │
└────────────┬─────────────┘
Isolated Sensors
┌──────────────────────┼──────────────────────┐
│ │ │
▼ ▼ ▼
Voltage Sensor Current CT Temperature
│ │ │
└──────────────────────┼──────────────────────┘
┌───────────────────┐
│ ESP32 │
│ │
│ ADC / GPIO │
│ Processing │
│ Local Protection │
│ Wi-Fi │
└─────────┬─────────┘
HTTPS
┌──────────────────────┐
│ n8n Webhook │
│ Automation Gateway │
└──────────┬───────────┘
┌───────────────┼────────────────┐
│ │ │
▼ ▼ ▼
┌─────────────┐ ┌──────────────┐ ┌──────────────┐
│ Rule Engine │ │ AI Agent │ │ Data Logger │
│ Thresholds │ │ Fault Analyse│ │ Google Sheet │
└──────┬──────┘ └──────┬───────┘ └──────────────┘
│ │
└───────┬───────┘
┌────────┴──────────┐
│ │
▼ ▼
┌─────────────┐ ┌───────────────┐
│ Telegram │ │ ThingSpeak │
│ Text Alert │ │ Cloud Charts │
└──────┬──────┘ └───────────────┘
┌───────────────┐
│ Telegram Voice│
│ Critical Alert│
└───────────────┘

5. How the System Works

The operation can be divided into nine stages.

Stage 1 — Measurement

Electrical sensors measure:

  • Voltage
  • Current
  • Power
  • Energy
  • Frequency
  • Power factor
  • Temperature

The sensors must provide an appropriate isolated/conditioned signal to the ESP32.


Stage 2 — ESP32 Processing

The ESP32:

  1. Reads sensor values.
  2. Applies calibration.
  3. Calculates derived parameters.
  4. Checks basic local thresholds.
  5. Creates a JSON telemetry packet.
  6. Sends the packet to n8n.

Example:

{
"device_id": "ESP32-GRID-01",
"voltage": 228.6,
"current": 8.42,
"power": 1847.5,
"energy": 12.83,
"frequency": 49.9,
"power_factor": 0.96,
"temperature": 42.1,
"status": "NORMAL",
"timestamp": "2026-08-20T22:40:00+05:30"
}

6. Proposed Hardware

Component Purpose
ESP32 DevKit Main IoT controller
Isolated voltage transducer Voltage measurement
Current transformer/transducer Current measurement
Energy-meter IC/module Accurate electrical measurements
Temperature sensor Panel/device temperature
OLED/LCD Local display
Buzzer Local warning
Status LEDs System status
Relay/contactor interface Optional controlled load
Isolated power supply ESP32 power
Fuse/protection Hardware protection
Enclosure Electrical safety

Recommended architecture

For a serious prototype, rather than trying to derive accurate mains RMS measurements directly from a hobbyist ADC circuit, use a proper energy-metering module or isolated voltage/current transducers.


7. Example Hardware Block Diagram

AC SUPPLY
┌──────────────────┐
│ Protection/Fuse │
└────────┬─────────┘
├───────────────────── LOAD
┌──────────────────┐
│ Current Sensor │
│ CT/Transducer │
└────────┬─────────┘
│ isolated signal
┌──────────────────┐
│ Voltage Sensor │
│ / Transducer │
└────────┬─────────┘
├───────────────┐
│ │
▼ ▼
┌───────────┐ ┌─────────────┐
│ Energy IC │ │ Temperature │
└─────┬─────┘ └──────┬──────┘
│ │
└───────┬────────┘
┌──────────┐
│ ESP32 │
└────┬─────┘
Wi-Fi
n8n

8. Suggested Sensor Parameters

A practical prototype can use:

Voltage → V
Current → A
Active Power → W
Apparent Power → VA
Energy → kWh
Frequency → Hz
Power Factor → PF
Temperature → °C
Wi-Fi RSSI → dBm
Device Uptime → seconds
Fault Code → integer/string

9. ESP32 Pin Architecture

An example configuration:

ESP32
├── GPIO 34 → Voltage sensor ADC
├── GPIO 35 → Current sensor ADC
├── GPIO 32 → Temperature sensor
├── GPIO 25 → Buzzer
├── GPIO 26 → Warning LED
├── GPIO 27 → Status LED
├── GPIO 21 → I2C SDA
├── GPIO 22 → I2C SCL
└── Wi-Fi → Cloud/n8n

These are example pins, not mandatory wiring. The exact pins depend on the ESP32 board and the sensor modules selected.


10. Local Safety vs Cloud Safety

This is extremely important.

Do not make cloud AI the only protection mechanism.

Use two levels:

LEVEL 1
Hardware / ESP32
├── Immediate local threshold
├── Buzzer
├── LED
└── Optional certified protection interface
LEVEL 2
Cloud / n8n / AI
├── Analysis
├── Diagnosis
├── Historical logging
├── Telegram alert
└── Voice notification

If the Internet fails, the local monitoring and safety logic should still operate.


11. Fault Detection Logic

Example thresholds for a prototype:

Voltage < 200 V → UNDER_VOLTAGE
Voltage > 250 V → OVER_VOLTAGE
Current > 10 A → OVER_CURRENT
Temperature > 70 °C → OVER_TEMPERATURE
Frequency < 48 Hz → LOW_FREQUENCY
Frequency > 52 Hz → HIGH_FREQUENCY
PF < 0.70 → LOW_POWER_FACTOR

These values are example project thresholds, not universal electrical safety limits. For a real installation, thresholds must be selected according to the equipment, local standards and protection design.


12. Multi-Level Alarm System

I recommend three levels.

LEVEL 0 — NORMAL

Everything within configured limits.

Action:

Store data
Update dashboard
No urgent alert

LEVEL 1 — WARNING

Example:

Voltage = 251 V
Current = 9.5 A
Temperature = 61 °C

Action:

Google Sheets → Log
ThingSpeak → Update
Telegram → Text notification
AI → Analyze

LEVEL 2 — CRITICAL

Example:

Current = 14.8 A
Temperature = 82 °C
Voltage = 268 V

Action:

ESP32 → Local alarm
n8n
AI Agent
Critical classification
Telegram text
Text-to-Speech
Telegram voice alert
Google Sheets
ThingSpeak

13. n8n Architecture

n8n becomes the central automation brain.

A recommended workflow:

┌───────────────┐
│ Webhook │
│ ESP32 Data │
└───────┬───────┘
┌─────────────────┐
│ Validate JSON │
└───────┬─────────┘
┌─────────────────┐
│ Normalize Data │
└───────┬─────────┘
┌─────────────────┐
│ Rule Evaluation │
└───────┬─────────┘
┌────┴─────┐
│ │
NORMAL ABNORMAL
│ │
│ ▼
│ ┌──────────────┐
│ │ AI Agent │
│ └──────┬───────┘
│ │
│ ┌────┴────┐
│ │ │
│ WARNING CRITICAL
│ │ │
│ ▼ ▼
│ Telegram Voice Alert
└──────┬───────────────┐
│ │
▼ ▼
Google Sheets ThingSpeak

n8n currently provides built-in Telegram integration, Google Sheets integration, OpenAI-related nodes and an AI Agent node/tool ecosystem.


14. n8n Workflow — Detailed Node List

Create the following nodes.

Workflow A — ESP32 Telemetry

1. Webhook
2. Code / Set
3. Validation
4. Fault Classification
5. Google Sheets
6. ThingSpeak
7. IF abnormal?
8. AI Agent
9. Telegram

15. Webhook

Create an n8n Webhook node:

Method:
POST
Path:
esp32/grid-monitor

The ESP32 sends:

POST
https://YOUR-N8N-DOMAIN/webhook/esp32/grid-monitor

with JSON.


16. ESP32 JSON Payload

Use:

{
"device_id": "ESP32-GRID-01",
"voltage": 228.6,
"current": 8.42,
"power": 1847.5,
"energy": 12.83,
"frequency": 49.9,
"power_factor": 0.96,
"temperature": 42.1,
"wifi_rssi": -61,
"uptime": 85432,
"timestamp": "2026-08-20T22:40:00+05:30"
}

17. n8n Data Validation

Use a Code node.

const d = $json;
const required = [
"device_id",
"voltage",
"current",
"power",
"energy",
"frequency",
"power_factor",
"temperature"
];
for (const field of required) {
if (d[field] === undefined || d[field] === null) {
throw new Error(`Missing field: ${field}`);
}
}
return [{
json: {
...d,
received_at: new Date().toISOString()
}
}];

18. Fault Classification Code

Add another Code node:

const d = $json;
const faults = [];
if (d.voltage < 200) {
faults.push("UNDER_VOLTAGE");
}
if (d.voltage > 250) {
faults.push("OVER_VOLTAGE");
}
if (d.current > 10) {
faults.push("OVER_CURRENT");
}
if (d.temperature > 70) {
faults.push("OVER_TEMPERATURE");
}
if (d.frequency < 48) {
faults.push("LOW_FREQUENCY");
}
if (d.frequency > 52) {
faults.push("HIGH_FREQUENCY");
}
if (d.power_factor < 0.70) {
faults.push("LOW_POWER_FACTOR");
}
let severity = "NORMAL";
if (faults.length > 0) {
severity = "WARNING";
}
if (
faults.includes("OVER_CURRENT") ||
faults.includes("OVER_TEMPERATURE") ||
faults.includes("OVER_VOLTAGE")
) {
severity = "CRITICAL";
}
return [{
json: {
...d,
faults,
fault_count: faults.length,
severity
}
}];

19. Why Use Rule-Based Detection + AI?

Do not allow an LLM to decide electrical limits by itself.

Instead:

Sensor
Deterministic Rules
Fault Detected
AI
Explain / Prioritize / Recommend

This is much safer than:

Sensor → AI → "Maybe there is a fault"

The rules provide deterministic detection.

The AI provides:

  • explanation
  • correlation
  • severity interpretation
  • recommended inspection
  • natural-language notification

20. AI Agent Design

The AI Agent receives:

{
"device_id": "ESP32-GRID-01",
"voltage": 268,
"current": 14.8,
"power": 3900,
"temperature": 82,
"frequency": 49.7,
"power_factor": 0.68,
"faults": [
"OVER_VOLTAGE",
"OVER_CURRENT",
"OVER_TEMPERATURE",
"LOW_POWER_FACTOR"
],
"severity": "CRITICAL"
}

The AI should produce structured information such as:

{
"severity": "CRITICAL",
"fault": "Multiple electrical abnormalities",
"summary": "High voltage and over-current are accompanied by elevated temperature.",
"recommended_action": "Inspect the load and electrical installation immediately.",
"voice_alert": true
}

21. AI Agent System Prompt

Use a prompt along these lines:

You are an electrical IoT monitoring assistant.
You receive telemetry from an ESP32-based monitoring device.
Your responsibilities are:
1. Interpret the supplied sensor data.
2. Identify the detected faults.
3. Explain the abnormal condition clearly.
4. Do not invent sensor readings.
5. Do not override deterministic safety thresholds.
6. Never claim that an electrical circuit is safe merely because readings appear normal.
7. For critical events, recommend immediate inspection by qualified personnel.
8. Produce concise Telegram-ready messages.
9. Decide whether a voice alert should be generated based on the supplied severity.
10. Return structured JSON.
Required output:
{
"severity": "",
"fault": "",
"summary": "",
"recommended_action": "",
"voice_alert": true/false,
"telegram_message": ""
}

n8n's current AI functionality includes AI Agents and tool-oriented workflows, making this architecture suitable for an agentic automation layer.


22. Telegram Alert

For WARNING:

⚠️ SMART GRID WARNING
Device: ESP32-GRID-01
Voltage: 251.4 V
Current: 9.7 A
Temperature: 62.4 °C
Fault:
Voltage above configured threshold.
Status:
WARNING
Please inspect the electrical system.

23. Critical Telegram Alert

🚨 CRITICAL POWER GRID ALERT
Device: ESP32-GRID-01
Voltage: 268 V
Current: 14.8 A
Temperature: 82 °C
Detected:
• OVER VOLTAGE
• OVER CURRENT
• OVER TEMPERATURE
AI Assessment:
Multiple abnormal electrical parameters detected.
Recommended Action:
Inspect the electrical installation immediately
using appropriate safety procedures.
⚠️ Do not rely on this message as a substitute
for certified electrical protection.

n8n's Telegram node supports Telegram automation and message/file-related operations, so it can serve as the notification stage.


24. Telegram Voice Alert

The voice-alert path should be:

AI Agent
Voice Alert = TRUE
Text-to-Speech
Audio file
Telegram
Voice message

Example spoken message:

"Critical power system alert. Device ESP32 Grid 01 has detected over-voltage, over-current and high temperature. Immediate inspection is recommended."

The exact n8n nodes used for TTS depend on the TTS provider you select. n8n currently has OpenAI integration capabilities, including audio-related operations.


25. Google Sheets Database

Create a spreadsheet:

Smart Grid Monitoring

Sheet:

Telemetry

Columns:

Timestamp
Device ID
Voltage
Current
Power
Energy
Frequency
Power Factor
Temperature
WiFi RSSI
Faults
Severity
AI Summary
Recommended Action
Alert Sent

Example:

Timestamp Device Voltage Current Power Temp Fault Severity
22:40 GRID-01 228.6 8.42 1847 42.1 None NORMAL
22:41 GRID-01 253.1 11.2 2835 64.2 Overcurrent WARNING
22:42 GRID-01 268.0 14.8 3900 82.0 Multiple CRITICAL

26. ThingSpeak Dashboard

ThingSpeak is useful for historical IoT visualization. Its REST API supports channel updates through HTTP GET/POST, while channels can contain multiple fields.

Configure:

Channel Name:
AI Smart Grid Monitor
Field 1:
Voltage
Field 2:
Current
Field 3:
Power
Field 4:
Energy
Field 5:
Frequency
Field 6:
Power Factor
Field 7:
Temperature
Field 8:
Fault Code

27. ThingSpeak HTTP Request

n8n HTTP Request node:

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

Body:

api_key={{ $env.THINGSPEAK_WRITE_KEY }}
field1={{ $json.voltage }}
field2={{ $json.current }}
field3={{ $json.power }}
field4={{ $json.energy }}
field5={{ $json.frequency }}
field6={{ $json.power_factor }}
field7={{ $json.temperature }}
field8={{ $json.fault_count }}

ThingSpeak documents api_key plus field1 through field8 for channel updates. A successful update returns an entry identifier; failure returns 0.

Keep your ThingSpeak write key secret. ThingSpeak also provides separate read/write permissions for channels.


28. ESP32 Software

The following is a prototype framework. The sensor-reading functions must be replaced with calibration appropriate to your actual hardware.

#include <WiFi.h>
StaticJsonDocument<512> doc;
doc["device_id"] = DEVICE_ID;
doc["voltage"] = voltage;
doc["current"] = current;
doc["power"] = power;
doc["energy"] = 0.0;
doc["frequency"] = 50.0;
doc["power_factor"] = 0.95;
doc["temperature"] = temperature;
doc["wifi_rssi"] = WiFi.RSSI();
doc["uptime"] = millis() / 1000;
String payload;
serializeJson(doc, payload);
HTTPClient http;
http.begin(N8N_URL);
http.addHeader(
"Content-Type",
"application/json"
);
int responseCode =
http.POST(payload);
Serial.print("HTTP Response: ");
Serial.println(responseCode);
Serial.print("Payload: ");
Serial.println(payload);
http.end();
}
// =============================
// Setup
// =============================
void setup()
{
Serial.begin(115200);
pinMode(BUZZER_PIN, OUTPUT);
pinMode(STATUS_LED, OUTPUT);
digitalWrite(BUZZER_PIN, LOW);
digitalWrite(STATUS_LED, LOW);
connectWiFi();
}
// =============================
// Loop
// =============================
void loop()
{
if (
millis() - lastSend >= SEND_INTERVAL
)
{
lastSend = millis();
sendTelemetry();
}
}

The Arduino-ESP32 Wi-Fi API supports station mode, which is the mode used above for connecting the ESP32 to an access point.


29. Improved ESP32 Architecture

For a production-quality prototype, I recommend splitting the firmware into tasks:

ESP32
┌──────────┼──────────┐
│ │ │
▼ ▼ ▼
Sensor Task Safety Task Network Task
│ │ │
▼ ▼ ▼
Read data Thresholds HTTP/MQTT
│ │ │
└──────────┼──────────┘
JSON Buffer

This prevents a slow Internet connection from interfering with local monitoring.


30. Recommended Firmware Logic

START
Initialize GPIO
Initialize Sensors
Connect Wi-Fi
Read Voltage
Read Current
Read Temperature
Calculate Power
Calculate Energy
Check Local Limits
├── NORMAL ──────────────┐
│ │
└── FAULT │
│ │
▼ │
Local Alarm │
│ │
└────────┬─────────┘
Create JSON
Send to n8n
Wait / Repeat

31. Energy Calculation

For a simple prototype:

Energy(kWh) =
Power(W) × Time(hours) / 1000

Example:

Power = 2000 W
Time = 30 minutes
= 0.5 hours
Energy =
2000 × 0.5 / 1000
= 1 kWh

For accurate energy measurement, use the readings from a suitable metering IC/meter rather than relying on a simplistic V × I calculation.


32. Web Dashboard

You can create a simple web interface with:

┌───────────────────────────────────────────┐
│ ⚡ AI SMART GRID MONITOR │
├───────────────────────────────────────────┤
│ │
│ Voltage Current │
│ 228.6 V 8.42 A │
│ │
│ Power Temperature │
│ 1.85 kW 42.1 °C │
│ │
│ Frequency Power Factor │
│ 49.9 Hz 0.96 │
│ │
├───────────────────────────────────────────┤
│ SYSTEM STATUS: 🟢 NORMAL │
├───────────────────────────────────────────┤
│ │
│ Voltage Graph │
│ ╭──╮ │
│ ─────╯ ╰──────╮ │
│ ╰──────── │
│ │
├───────────────────────────────────────────┤
│ Recent Events │
│ │
│ 22:40 Normal │
│ 22:39 Normal │
│ 22:38 Warning │
└───────────────────────────────────────────┘

33. Webpage Architecture

A simple web application could be:

Browser
Dashboard
├── Current Values
├── Charts
├── Fault Status
├── Device Status
├── Historical Data
└── AI Diagnosis
n8n API
Data Store

The dashboard can retrieve:

Latest telemetry
Historical telemetry
Fault events
AI analysis
Device status

34. AI Agentic Flow

The "agentic" part should be designed as a controlled decision workflow rather than allowing unrestricted AI control.

SENSOR DATA
┌────────────────┐
│ Rule Engine │
└───────┬────────┘
Abnormal?
/ \
NO YES
│ │
▼ ▼
LOG AI AGENT
┌────────┼────────┐
│ │ │
▼ ▼ ▼
Analyse Prioritize Recommend
│ │ │
└────────┼────────┘
Policy Engine
┌─────────┼─────────┐
│ │ │
▼ ▼ ▼
Telegram Voice Log

35. Why This Is "Agentic IoT"

Traditional IoT:

Sensor → Cloud → Dashboard

Your proposed system:

Sensor
Cloud
Automation
AI Agent
Reasoning
Decision
Action
Feedback

That makes it an agent-assisted IoT automation system.


36. Example AI Decision

Input:

Voltage = 267 V
Current = 14.7 A
Temperature = 81 °C
PF = 0.66

Rules:

OVER_VOLTAGE
OVER_CURRENT
OVER_TEMPERATURE
LOW_POWER_FACTOR

AI receives:

{
"severity": "CRITICAL",
"faults": [
"OVER_VOLTAGE",
"OVER_CURRENT",
"OVER_TEMPERATURE",
"LOW_POWER_FACTOR"
]
}

AI response:

CRITICAL EVENT
Multiple electrical abnormalities are occurring
simultaneously.
The combination of high current and elevated
temperature indicates that the load/electrical
installation should be inspected immediately.
Voice notification recommended.

37. Fault Correlation

This is one of the strongest features of the project.

Instead of:

Current high → Alert

the AI can correlate:

Current ↑
+
Temperature ↑
+
Voltage abnormal
+
Power factor ↓
Possible abnormal operating condition

The AI should call this a possible condition requiring inspection, rather than claiming a specific physical failure without evidence.


38. Event Deduplication

Without deduplication:

14.7 A → Alert
14.8 A → Alert
14.9 A → Alert
15.0 A → Alert
15.1 A → Alert

The user receives hundreds of messages.

Instead:

FAULT START
Send alert
Suppress duplicates
Monitor
FAULT CLEARED
Send recovery message

Example:

🚨 CRITICAL ALERT STARTED
Over-current detected.
Current: 14.8 A

Later:

🟢 ALERT CLEARED
Current returned to:
7.8 A
Device:
ESP32-GRID-01

39. n8n Alert-State Logic

Store:

device_id
last_fault
last_severity
last_alert_time
fault_active

Then:

New Event
Compare with Previous Event
├── Same fault?
│ │
│ ├── YES → suppress duplicate
│ │
│ └── NO → send alert
└── Fault cleared?
Send recovery

40. Google Sheets as an Audit Log

Google Sheets should not be the only database for a high-volume production system, but it is excellent for a student prototype and demonstration.

Example event:

2026-08-20 22:42:18
ESP32-GRID-01
268
14.8
3900
82
CRITICAL
OVER_VOLTAGE,OVER_CURRENT,OVER_TEMPERATURE
AI analysis generated
Telegram sent
Voice sent

41. ThingSpeak Role

Use ThingSpeak for:

Live charts
Historical charts
Remote visualization
Trend analysis

ThingSpeak supports REST and MQTT approaches for channel data.

A useful separation is:

Google Sheets
Event/audit records
ThingSpeak
Time-series visualization

42. Complete Data Flow

ELECTRICAL SYSTEM
SENSORS
ESP32
Read + Calculate
JSON DATA
Wi-Fi
┌────────────┐
│ n8n │
└─────┬──────┘
┌──────┼──────────┐
│ │ │
▼ ▼ ▼
Rules Sheets ThingSpeak
Abnormal?
AI Agent
Severity
┌─────┼─────────────┐
│ │ │
▼ ▼ ▼
Text Voice Log
│ │ │
└─────┼─────────────┘
Telegram

43. Complete Fault Flow

Sensor
ESP32
├── Local threshold
│ │
│ └── Immediate local warning
n8n
Validation
Rule Engine
Fault?
┌┴─────────────┐
NO YES
│ │
▼ ▼
Log AI Agent
│ │
▼ ▼
Dashboard Classification
┌─────┴─────┐
▼ ▼
WARNING CRITICAL
│ │
▼ ▼
Telegram Telegram
Text-to-Speech
Voice Message

44. Communication Options

There are two main architectures.

Option A — HTTP

ESP32
│ HTTPS POST
n8n Webhook

Advantages:

  • Easy to understand
  • Easy to debug
  • Excellent for project demonstrations

Option B — MQTT

ESP32
│ MQTT
MQTT Broker
n8n

Advantages:

  • Better IoT architecture
  • Publish/subscribe
  • Multiple devices
  • Easier scaling

ThingSpeak itself also supports MQTT as an alternative to REST for channel updates.

For your first implementation, HTTP → n8n Webhook is simpler.


45. Multiple ESP32 Devices

The architecture can be expanded:

ESP32-01 ──┐
ESP32-02 ──┤
ESP32-03 ──┤
ESP32-04 ──┤
ESP32-05 ──┤
MQTT / n8n
┌─────┼─────┐
▼ ▼ ▼
AI DB Dashboard

Each device has:

device_id
location
panel_id
phase
sensor configuration

Example:

{
"device_id": "SUBSTATION-A-FEEDER-02",
"location": "Panel-A",
"phase": "L1"
}

46. Three-Phase Expansion

For a more advanced project:

3-PHASE SUPPLY
L1 ─── Voltage + Current
L2 ─── Voltage + Current
L3 ─── Voltage + Current
N ─── Reference
┌──────────────┐
│ Energy Meter │
└──────┬───────┘
ESP32

Data:

{
"L1_voltage": 231.2,
"L1_current": 7.2,
"L2_voltage": 229.8,
"L2_current": 8.1,
"L3_voltage": 232.1,
"L3_current": 6.9
}

AI can then detect:

Phase imbalance
Overloaded phase
Missing phase
Abnormal phase voltage

Again, actual protection limits must come from the electrical design/specification rather than arbitrary AI-generated thresholds.


47. Suggested n8n Production Workflow

I recommend separating the system into five workflows rather than putting everything into one enormous workflow.

Workflow 1 — Telemetry

ESP32
Webhook
Validate
Normalize
Database/Sheets

Workflow 2 — Fault Detection

Telemetry
Rules
Fault classification
Severity

Workflow 3 — AI Analysis

Fault event
AI Agent
Diagnosis
Recommendation

Workflow 4 — Notifications

AI result
IF severity
├── Normal
├── Warning → Telegram text
└── Critical → Telegram text + voice

Workflow 5 — Dashboard

Telemetry
API
Web dashboard

This is easier to maintain and troubleshoot.


48. Recommended Folder Structure

For a complete project:

smart-grid-ai/
├── esp32/
│ ├── smart_grid.ino
│ ├── config.h
│ ├── sensors.h
│ ├── sensors.cpp
│ └── network.h
├── n8n/
│ ├── telemetry-workflow.json
│ ├── fault-workflow.json
│ ├── ai-workflow.json
│ └── notification-workflow.json
├── dashboard/
│ ├── index.html
│ ├── style.css
│ └── app.js
├── documentation/
│ ├── architecture.md
│ ├── hardware.md
│ ├── software.md
│ ├── testing.md
│ └── user-manual.md
└── README.md

49. Testing Plan

Test 1 — Normal Voltage

Voltage = 230 V
Current = 5 A
Temperature = 35 °C

Expected:

NORMAL
No alert
Data logged
Dashboard updated

Test 2 — Over Voltage

Voltage = 260 V

Expected:

OVER_VOLTAGE
WARNING/CRITICAL according to configured policy
Telegram alert
Google Sheets log

Test 3 — Over Current

Current = 12 A

Expected:

OVER_CURRENT
Alert
AI analysis

Test 4 — High Temperature

Temperature = 75 °C

Expected:

OVER_TEMPERATURE
Alert

Test 5 — Multiple Faults

Voltage = 265 V
Current = 13 A
Temperature = 80 °C

Expected:

CRITICAL
AI Agent
Telegram text
Telegram voice

Test 6 — Internet Failure

Disconnect Wi-Fi.

Expected:

ESP32 continues local monitoring
Local alarm continues to work
Cloud notification unavailable

This test is particularly important.


50. Failure-Safe Design

The system should never assume:

No Internet = No Fault

Instead:

Internet available
├── Cloud monitoring
└── Local monitoring
Internet unavailable
└── Local monitoring continues

51. Security

Use:

HTTPS
API authentication
Secret management
Strong Wi-Fi password
Unique device IDs
Signed/controlled firmware
n8n authentication
Telegram bot token protection
ThingSpeak key protection

Never put production credentials directly into publicly shared firmware:

const char* PASSWORD = "actual-password";

Instead use a private configuration mechanism.


52. n8n Secret Strategy

Use environment variables/credentials where possible:

N8N_DOMAIN
THINGSPEAK_WRITE_KEY
TELEGRAM_BOT_TOKEN
TELEGRAM_CHAT_ID
OPENAI_API_KEY
GOOGLE_CREDENTIALS

Do not expose these in:

GitHub
screenshots
college reports
public videos
frontend JavaScript

53. AI Safety Rules

The AI Agent should never be allowed to directly:

Switch high-voltage equipment
Change protection thresholds
Disable safety systems
Override hardware interlocks

Instead:

AI
Recommendation
Policy
Human / Certified controller

For example:

AI:
"Possible overload. Inspect feeder."
NOT:
AI:
"Disable protection and switch the feeder."

54. Optional Automatic Load Control

If you eventually add load control:

AI Agent
Recommendation
Safety Policy
Human approval
Isolated control output
Certified contactor/control system

Do not directly drive a mains load from an ESP32 GPIO. Use an appropriately rated, isolated interface and suitable protection/control hardware.


55. Project Novelty

Your project combines several technologies:

ESP32
+
IoT
+
Electrical Monitoring
+
Cloud
+
n8n
+
AI Agent
+
Google Sheets
+
ThingSpeak
+
Telegram
+
Voice Notification
+
Web Dashboard

The interesting part is not any individual component.

The novelty is the integration:

"An agent-assisted IoT architecture that combines real-time electrical telemetry, deterministic safety rules, AI-based event interpretation, workflow automation, historical logging and multimodal human alerts."


56. Advantages

Technical

  • Low-cost IoT controller
  • Wi-Fi connectivity
  • Cloud monitoring
  • Remote alerts
  • Historical data
  • AI-assisted analysis
  • Automation

Operational

  • Faster fault awareness
  • Remote monitoring
  • Event history
  • Voice notification
  • Reduced manual checking

Educational

The project demonstrates:

Embedded systems
Networking
IoT
Cloud computing
APIs
Automation
Artificial intelligence
Database concepts
Web development
Electrical instrumentation

57. Limitations

The system is not automatically a certified power-grid protection system.

Limitations include:

  • Sensor accuracy
  • ESP32 ADC limitations
  • Wi-Fi dependency for cloud functions
  • Cloud availability
  • AI interpretation errors
  • Sensor calibration
  • Electrical installation constraints
  • Need for certified protection equipment

Therefore:

AI + IoT = Monitoring/Decision Support

not:

AI + IoT = Replacement for electrical protection

58. Future Enhancements

You can extend the project with:

Phase 1

ESP32
Voltage
Current
Temperature
n8n
Telegram
ThingSpeak

Phase 2

AI Agent
Voice alerts
Google Sheets
Dashboard

Phase 3

MQTT
Multiple ESP32 nodes
Three-phase monitoring

Phase 4

Predictive maintenance
Anomaly detection
Machine learning
Load forecasting

Phase 5

Digital twin
Edge AI
Federated monitoring
Substation/feeder-level architecture

59. Predictive Maintenance Extension

Instead of only detecting:

FAULT NOW

the system can learn:

Normal current
Normal temperature
Normal voltage
Normal power factor

and detect gradual trends:

Temperature:
40°C
42°C
45°C
49°C
53°C
58°C

AI:

"Temperature is increasing gradually over the
observed period. Consider inspection before a
critical threshold is reached."

This transforms the project from:

Reactive Monitoring

into:

Predictive Monitoring


60. Final System Architecture

┌──────────────────────────┐
│ ELECTRICAL SYSTEM │
└────────────┬─────────────┘
┌────────────▼────────────┐
│ ISOLATED SENSORS / │
│ ENERGY METERING │
└────────────┬────────────┘
┌──────────────┐
│ ESP32 │
│ │
│ Measurement │
│ Processing │
│ Local Safety │
└──────┬───────┘
Wi-Fi
┌───────────────────┐
│ n8n WEBHOOK │
└────────┬──────────┘
┌───────────────────┐
│ VALIDATION + │
│ NORMALIZATION │
└────────┬──────────┘
┌───────────────────┐
│ RULE ENGINE │
└────────┬──────────┘
┌────────┴─────────┐
│ │
NORMAL FAULT
│ │
│ ▼
│ ┌───────────────┐
│ │ AI AGENT │
│ └───────┬───────┘
│ │
│ ┌──────┴──────┐
│ │ │
│ WARNING CRITICAL
│ │ │
│ ▼ ▼
│ Telegram Telegram
│ │
│ ▼
│ Text-to-
│ Speech
│ │
│ ▼
│ Voice Alert
└─────────┬────────────────┐
│ │
▼ ▼
Google Sheets ThingSpeak
│ │
└───────┬────────┘
WEB DASHBOARD

61. Recommended Implementation Order

Don't build everything simultaneously.

Step 1

Get ESP32 working.

ESP32 → Serial Monitor

Step 2

Add sensors.

ESP32 → Sensor values

Step 3

Add local fault detection.

Sensor → Threshold → Buzzer/LED

Step 4

Add Wi-Fi.

ESP32 → Wi-Fi

Step 5

Create n8n webhook.

ESP32 → n8n

Step 6

Send JSON.

ESP32 → JSON → n8n

Step 7

Add Google Sheets.

n8n → Google Sheets

Step 8

Add ThingSpeak.

n8n → ThingSpeak

Step 9

Add Telegram text.

n8n → Telegram

Step 10

Add AI Agent.

Fault → AI → Diagnosis

Step 11

Add TTS.

AI → TTS → Audio

Step 12

Add Telegram voice.

Audio → Telegram

Step 13

Build dashboard.

Data → Web UI

Step 14

Add multi-device support.

ESP32-01
ESP32-02
ESP32-03
n8n

62. Official Documentation References

For implementation, the current ESP32 Arduino documentation describes Wi-Fi station mode and networking APIs.

Arduino ESP32 Wi-Fi API documentation

For n8n, the official documentation covers Telegram integration and its broader AI/Google Sheets integration ecosystem.

n8n Telegram node documentation

ThingSpeak's official documentation describes REST channel updates, API keys and MQTT/REST channel communication.

ThingSpeak REST API documentation


63. Final Project Summary

The complete system can be summarized as:

⚡ POWER SYSTEM
📡 SENSORS
🟦 ESP32
🌐 Wi-Fi
⚙️ n8n
🧠 AI AGENT
🔍 FAULT ANALYSIS
┌───────────────┬────────────────┬────────────────┐
│ │ │
📱 Telegram 🔊 Voice 📊 Dashboard
│ │ │
└───────────────┴────────────────┘
├──────── Google Sheets
└──────── ThingSpeak

The strongest version of the project is therefore not simply "ESP32 sends data to Telegram." It is a complete closed-loop monitoring architecture:

Sense → Validate → Detect → Analyze → Decide → Notify → Log → Visualize → Learn/Improve

That gives you a solid basis for a major-project report, IEEE-style project documentation, hardware prototype, n8n workflow, ESP32 firmware and web dashboard.

No comments:

Post a Comment