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:
- Receive measurements from the ESP32.
- Validate and normalize the data.
- Store measurements in Google Sheets.
- Publish telemetry to ThingSpeak.
- Detect abnormal electrical conditions.
- Send measurements to an AI agent.
- Generate a human-readable explanation.
- Send Telegram notifications.
- Generate a voice response.
- Accept Telegram voice commands.
- Convert voice commands into text.
- Ask the AI agent what action should be performed.
- 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.



