AI Smart Electricity Metering & Fraud Detection System
Complete IoT + ESP32 + AI Agent + n8n Automation + Telegram Voice Alerts + Google Sheets + ThingSpeak
This project is an AI-powered smart electricity monitoring and suspected electricity theft detection system. It combines an ESP32 microcontroller, electrical sensors, cloud monitoring, an AI agent, and automated notifications to measure electricity usage, identify abnormal consumption patterns, record events, and alert the user through Telegram voice messages.
The system can be developed as an academic final-year project, engineering prototype, IoT research project, or proof of concept for smart energy management.
The important design principle is that the ESP32 measures electrical quantities, a detection algorithm flags suspicious patterns, and the AI agent explains and coordinates the response. AI should not be the sole authority for declaring electricity theft.
1. Project overview
1. ESP32 smart meter
Measures voltage, current, active power, energy consumption, and sensor status. Sends readings to the cloud over Wi-Fi.
2. Electrical measurement and anomaly detection
Uses an appropriate energy-metering sensor or metering IC to calculate electrical parameters and detect unusual readings, bypass indications, or meter tampering signals where suitable sensors are installed.
3. n8n automation and AI agent
Receives readings through a webhook or scheduled cloud polling, evaluates rules, calls an AI model when appropriate, and coordinates alerts, logging, and dashboard updates.
4. Telegram voice alerts
Sends an immediate text alert and, optionally, generates a spoken warning using text-to-speech and delivers it as a Telegram audio or voice message.
5. Web dashboard and data storage
ThingSpeak visualizes time-series measurements; Google Sheets stores historical readings and alert records; an optional custom webpage displays live values and event history.
Project objectives
-
Monitor electricity usage in near real time.
-
Calculate voltage, current, power, energy, and estimated cost.
-
Detect abnormal consumption and potential meter tampering.
-
Send automated Telegram notifications and spoken alerts.
-
Use an AI agent to summarize anomalies and recommend safe investigation steps.
-
Store data in Google Sheets for reports and analysis.
-
Display historical measurements using ThingSpeak and a custom IoT webpage.
-
Provide a modular design that can later support multiple meters and locations.
2. System architecture
The following diagram shows how the components communicate.
Electrical supply / monitored load
Voltage, current, energy and optional tamper sensors
ESP32 smart meter
Sensor acquisition · calibration · calculations · local thresholds
Wi-Fi / HTTPS / MQTT or HTTP webhook
Secure data transmission and device identification
n8n automation workflow
Validate → calculate risk → deduplicate → route events
AI agent
Explain anomalies and suggest checks
Telegram
Text and generated voice alerts
Google Sheets
Readings and incident log
ThingSpeak
Time-series graphs and history
Custom IoT webpage
Live readings · anomaly status · consumption graphs · alert history
Recommended communication design: ESP32 → HTTPS webhook → n8n → storage, alerting, and AI. Send ThingSpeak updates separately if convenient. This avoids depending on the AI service for basic measurement or immediate local safety logic.
3. Hardware and software requirements
3.1 Hardware components
Suggested prototype components; select ratings appropriate to the load and local electrical standards.
|
Component |
Purpose |
|---|---|
|
ESP32 DevKit V1 |
Main controller and Wi-Fi connectivity |
|
PZEM-004T v3.0 or equivalent certified energy meter |
Voltage, current, power, energy, power factor and frequency measurements |
|
Appropriate current transformer (CT) |
Current sensing for compatible meter models |
|
Isolated, rated power supply |
Powers the low-voltage controller |
|
Enclosure, fuse and terminals |
Electrical protection and physical safety |
|
Wi-Fi router |
Network communication |
|
Optional tamper sensor or meter-status input |
Detects enclosure opening or another defined tamper event |
|
Computer or server |
Runs n8n and the optional web dashboard |
The PZEM-004T v3.0 family supports voltage, current, active power, energy, frequency and power-factor measurements, but its exact current range and interface must match the chosen module.
Important safety requirement: Household mains voltage can cause fatal electric shock and fire. Do not connect mains voltage directly to an ESP32, breadboard, or unprotected sensor input. Have the mains-side installation, isolation, enclosure, overcurrent protection and meter connections designed and verified by a qualified electrician. Start software testing with simulated readings or a safe low-voltage test setup.
3.2 Software and services
|
Software / service |
Role |
|---|---|
|
Arduino IDE |
ESP32 firmware development |
|
ESP32 Arduino board package |
Wi-Fi and microcontroller support |
|
|
Meter readings |
|
n8n |
Workflow automation and agent orchestration |
|
Telegram Bot API |
Text and audio notifications |
|
Google Sheets |
Historical data and incident log |
|
ThingSpeak |
IoT charts and time-series visualization |
|
AI model supported by n8n |
Explain suspicious readings and summarize incidents |
|
Text-to-speech (TTS) service |
Convert alert text into spoken audio |
|
HTML, CSS and JavaScript |
Optional custom dashboard |
For the meter library, see the PZEM-004T v3.0 library documentation . For ThingSpeak, see the channel API reference .
4. Electrical and ESP32 schematic
This is a functional block schematic, not a mains wiring diagram. Exact terminal connections depend on the selected meter module and its revision.
AC supply and monitored load
Installed and protected by a qualified electrician
Rated energy-metering module
Voltage and current measurement; isolated low-voltage communication where specified
ESP32 DevKit V1
UART RX/TX · Wi-Fi · firmware calculations
Meter UART
TX → ESP32 RX; RX → ESP32 TX
Wi-Fi
HTTPS request to n8n
The UART voltage levels, grounding, isolation requirements and supply pins must be verified against the exact module documentation. Do not assume a 5 V UART signal is safe for an ESP32 GPIO.
4.1 Example low-voltage UART pin assignment
For an ESP32 DevKit V1 using the Arduino HardwareSerial interface:
|
Meter communication signal |
ESP32 connection |
|---|---|
|
Meter TX |
GPIO 16 (ESP32 RX2) |
|
Meter RX |
GPIO 17 (ESP32 TX2) |
|
Meter communication ground |
Common reference only if the interface documentation permits it |
|
Meter supply |
Only the voltage specified by the module manufacturer |
These are example GPIO assignments, not universal PZEM terminal numbers. Some meter boards have different connectors, electrical isolation and voltage requirements. Verify compatibility before connecting them.
4.2 Optional tamper detection
An optional enclosure switch or dedicated tamper output can connect to a low-voltage GPIO using the correct pull-up, input protection and isolation. It can indicate events such as:
-
Meter enclosure opened.
-
Sensor communication interrupted.
-
Meter readings stopped unexpectedly.
-
A separately measured upstream/downstream energy balance deviated beyond a configured threshold.
A current spike, low power factor, sensor failure or communication interruption is not, by itself, proof of electricity theft.
5. How the energy monitoring calculations work
The metering module should provide calibrated electrical readings whenever possible.
Voltage, current and power
-
Voltage VV: volts (V)
-
Current II: amperes (A)
-
Active power PP: watts (W)
-
Energy EE: kilowatt-hours (kWh)
-
Power factor: dimensionless value, normally between 0 and 1
For a single-phase AC circuit, apparent power is S=VRMSIRMSS=V_{\mathrm{RMS}}I_{\mathrm{RMS}}. Active power depends on the waveform and power factor; it should preferably be read directly from a suitable energy meter rather than approximated by multiplying voltage and current.
Energy consumed
For a constant power level:
For example, a 1,000 W load running for 2 hours uses approximately 2 kWh.
Estimated electricity cost
This is an estimate only. Actual bills may include slab-based rates, taxes, fixed charges, demand charges and other adjustments.
Example anomaly rule
Suppose the baseline active power for a monitored appliance group is 500 W. A configured rule might flag readings above 1,000 W for at least 60 seconds.
That indicates an anomaly requiring investigation, not a theft verdict. A legitimate new appliance or changed operating condition could explain it.
6. Fraud and anomaly detection logic
A reliable system should combine deterministic rules, device health checks, historical baselines and AI-generated explanations.
Detection pipeline
-
Validate the readings. Check that voltage, current, power and energy values are numeric, in range and fresh.
-
Check device health. Identify missing messages, UART errors, unexpected resets and disconnected sensors.
-
Compare against a baseline. Evaluate expected usage for the same time of day, operating state or historical period.
-
Apply configured rules. Look for persistent overconsumption, unusual energy changes or a supported tamper sensor activation.
-
Calculate a risk category. For example, informational, warning or high priority. Keep the reason and measurement evidence.
-
Ask the AI agent to explain the event. Supply validated measurements and rule results; ask it to identify plausible explanations and safe next steps.
-
Notify and record. Send Telegram text, optionally generate a voice alert, and log the event in Google Sheets.
Suggested initial rules
|
Rule |
Example trigger |
Response |
|---|---|---|
|
Overconsumption |
Power exceeds a configured limit for 60 seconds |
Warning |
|
Meter offline |
No valid readings for 2 minutes |
Device-health alert |
|
Tamper input |
Dedicated sensor reports enclosure opening |
High-priority inspection alert |
|
Sudden energy anomaly |
Meter energy counter changes implausibly |
Verify meter data |
|
Data-quality failure |
Invalid or stale measurements |
Suppress fraud classification and report sensor issue |
Thresholds must be calibrated to the specific installation. These values are examples for a prototype, not universal limits.
Optional risk score
You can calculate a transparent score in n8n or the ESP32 firmware:
Here, T,A,D,HT,A,D,H are binary indicators for a supported tamper signal, abnormal consumption, energy discrepancy and hardware/data-health issue. The maximum is 100.
This is a demonstration score, not a statistically validated probability of theft. In production, tune and validate the scoring method using labeled, legitimate and suspicious operating conditions. A sensor fault should not automatically increase a theft score.
7. ESP32 firmware — complete starter implementation
This firmware reads the PZEM meter, checks the measurements, sends a JSON payload to an n8n webhook, and optionally updates a ThingSpeak channel.
It is a practical starting point, not certified utility-meter firmware. The example assumes the installed PZEM004Tv30 library supports your selected module and that the n8n webhook is configured to accept the payload.
7.1 Install the libraries
In Arduino IDE, install:
-
ESP32 board package by Espressif Systems.
-
PZEM004Tv30library. -
Built-in ESP32
WiFi,HTTPClientandWiFiClientSecurelibraries.
7.2 Firmware code
Replace the Wi-Fi credentials, webhook URL and ThingSpeak write API key with your own values. Do not publish real credentials in a public repository.
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <PZEM004Tv30.h>
// ESP32 UART2 example
static const int PZEM_RX = 16;
static const int PZEM_TX = 17;
// Configure your own network and endpoints.
const char* WIFI_SSID = "YOUR_WIFI_NAME";
const char* WIFI_PASSWORD = "YOUR_WIFI_PASSWORD";
const char* N8N_WEBHOOK =
"https://YOUR_N8N_HOST/webhook/electricity-meter";
const char* THINGSPEAK_WRITE_KEY =
"YOUR_THINGSPEAK_WRITE_KEY";
// Meter constructor: RX, TX
PZEM004Tv30 pzem(Serial2, PZEM_RX, PZEM_TX);
const char* DEVICE_ID = "meter-001";
const unsigned long SAMPLE_INTERVAL_MS = 20000;
const unsigned long POST_TIMEOUT_MS = 8000;
unsigned long lastSample = 0;
unsigned long sequenceNumber = 0;
bool validNumber(float x) {
return !isnan(x) && isfinite(x);
}
void connectWiFi() {
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to Wi-Fi");
unsigned long start = millis();
while (WiFi.status() != WL_CONNECTED &&
millis() - start < 20000) {
delay(500);
Serial.print(".");
}
Serial.println();
if (WiFi.status() == WL_CONNECTED) {
Serial.println("Wi-Fi connected");
Serial.println(WiFi.localIP());
} else {
Serial.println("Wi-Fi unavailable; will retry");
}
}
bool postJson(const char* url, const String& payload) {
if (WiFi.status() != WL_CONNECTED) {
return false;
}
// Use CA validation or certificate pinning in production.
// Do not use setInsecure() in a deployed meter.
WiFiClientSecure client;
client.setCACert(
R"PEM(
-----BEGIN CERTIFICATE-----
PASTE_THE_APPROPRIATE_CA_CERTIFICATE_HERE
-----END CERTIFICATE-----
)PEM"
);
HTTPClient http;
http.setConnectTimeout(POST_TIMEOUT_MS);
http.setTimeout(POST_TIMEOUT_MS);
if (!http.begin(client, url)) {
return false;
}
http.addHeader("Content-Type", "application/json");
int code = http.POST(payload);
Serial.printf("HTTP status: %d\n", code);
http.end();
return code >= 200 && code < 300;
}
void updateThingSpeak(float voltage, float current,
float power, float energy) {
if (WiFi.status() != WL_CONNECTED ||
strlen(THINGSPEAK_WRITE_KEY) == 0) {
return;
}
String url =
"https://api.thingspeak.com/update?api_key=" +
String(THINGSPEAK_WRITE_KEY) +
"&field1=" + String(voltage, 2) +
"&field2=" + String(current, 3) +
"&field3=" + String(power, 1) +
"&field4=" + String(energy, 3);
WiFiClientSecure client;
client.setCACert(
R"PEM(
-----BEGIN CERTIFICATE-----
PASTE_THE_APPROPRIATE_CA_CERTIFICATE_HERE
-----END CERTIFICATE-----
)PEM"
);
HTTPClient http;
http.setTimeout(POST_TIMEOUT_MS);
if (http.begin(client, url)) {
int code = http.GET();
Serial.printf("ThingSpeak HTTP status: %d\n", code);
http.end();
}
}
void setup() {
Serial.begin(115200);
Serial2.begin(9600, SERIAL_8N1, PZEM_RX, PZEM_TX);
connectWiFi();
}
void loop() {
if (WiFi.status() != WL_CONNECTED) {
connectWiFi();
}
if (millis() - lastSample < SAMPLE_INTERVAL_MS) {
delay(50);
return;
}
lastSample = millis();
sequenceNumber++;
float voltage = pzem.voltage();
float current = pzem.current();
float power = pzem.power();
float energy = pzem.energy();
float pf = pzem.pf();
float freq = pzem.frequency();
bool valid =
validNumber(voltage) &&
validNumber(current) &&
validNumber(power) &&
validNumber(energy) &&
validNumber(pf) &&
validNumber(freq) &&
voltage > 0 && voltage < 300 &&
current >= 0 && current < 200 &&
power >= 0 && power < 50000 &&
energy >= 0;
if (!valid) {
Serial.println("Invalid meter reading; not publishing");
return;
}
Serial.printf(
"V=%.1f V, I=%.3f A, P=%.1f W, E=%.3f kWh, PF=%.2f, f=%.1f Hz\n",
voltage, current, power, energy, pf, freq
);
// Example data-quality status. The cloud performs
// the configurable anomaly analysis.
String payload = "{";
payload += "\"device_id\":\"" + String(DEVICE_ID) + "\",";
payload += "\"sequence\":" + String(sequenceNumber) + ",";
payload += "\"voltage_v\":" + String(voltage, 2) + ",";
payload += "\"current_a\":" + String(current, 3) + ",";
payload += "\"power_w\":" + String(power, 1) + ",";
payload += "\"energy_kwh\":" + String(energy, 3) + ",";
payload += "\"power_factor\":" + String(pf, 2) + ",";
payload += "\"frequency_hz\":" + String(freq, 1) + ",";
payload += "\"tamper_input\":false,";
payload += "\"data_valid\":true";
payload += "}";
bool posted = postJson(N8N_WEBHOOK, payload);
Serial.println(posted ? "n8n: success" : "n8n: failed");
updateThingSpeak(voltage, current, power, energy);
}
7.3 Important implementation notes
-
TLS certificate: Replace the certificate placeholder with a valid CA certificate for the endpoint, and maintain it when the certificate chain changes. The placeholder will not validate a real connection.
-
Meter compatibility: Constructor signatures, UART settings and supported functions can vary by library version. Check the library examples before compiling.
-
Tamper input:
tamper_inputis hardcoded tofalsein this starter code. Replace it with a real, properly interfaced sensor input if tamper detection is required. -
Sequence numbers: The example sequence resets when the ESP32 restarts. A production implementation should persist a counter or use unique event IDs and timestamps.
-
Reliability: The sample does not include a durable offline queue, retry backoff or a clock-synchronized timestamp. Add those before relying on it for unattended monitoring.
-
ThingSpeak updates: The example sends a request each sampling cycle. Check the channel's current update-rate limits and return status before choosing your reporting interval.
GitHub+1
For an initial bench test, you can comment out updateThingSpeak() and test the n8n webhook first.
8. n8n automation workflow
n8n is the central orchestration layer. It receives telemetry, validates it, applies anomaly rules, requests an AI explanation when needed, and routes notifications and records.
8.1 Workflow diagram
Webhook trigger
Receive ESP32 JSON
Code node
Validate values, device ID, timestamp and sequence
IF node
Is the payload valid?
No
Reject and log data-quality error
Yes
Evaluate anomaly rules
Switch / IF node
Normal · Warning · High priority
AI Agent (conditional)
Summarize evidence; recommend safe checks
Telegram
Google Sheets
ThingSpeak / dashboard
8.2 Build the workflow step by step
-
Open your n8n instance.
-
Create a new workflow named
AI Smart Electricity Meter Fraud Detection. -
Add a Webhook node.
-
Method:
POST -
Path:
electricity-meter -
Response: configure an immediate response such as HTTP 200 after validating receipt, or use a Respond to Webhook node.
-
-
Add a Code node to validate the incoming fields and compute the anomaly result.
-
Add an IF node to route invalid data separately.
-
Add a Switch or additional IF nodes for normal, warning and high-priority readings.
-
Add an AI Agent node connected to a supported chat model, using the prompt in Section 9.
-
Add a Google Sheets node to append the reading and any incident.
-
Add a Telegram node to send the alert message.
-
Add a text-to-speech integration and Telegram audio-delivery step if voice notifications are required.
-
Optionally use a separate HTTP Request node for ThingSpeak if the ESP32 is not already sending readings there.
-
Activate the workflow and use its production webhook URL in the ESP32 firmware.
The test webhook and production webhook URLs differ. Use the production URL only after the workflow is activated.
8.3 Code node for basic anomaly detection
The following code expects the incoming payload to contain the fields sent by the firmware above. Set the Code node to run once for each incoming item.
const d = $json.body ?? $json;
const numericFields = [
"voltage_v",
"current_a",
"power_w",
"energy_kwh",
"power_factor",
"frequency_hz",
];
const invalidFields = numericFields.filter(
(key) =>
typeof d[key] !== "number" ||
!Number.isFinite(d[key])
);
if (
invalidFields.length > 0 ||
d.data_valid !== true ||
typeof d.device_id !== "string" ||
d.device_id.length === 0
) {
return [{
json: {
device_id: d.device_id ?? "unknown",
status: "INVALID_DATA",
invalid_fields: invalidFields,
alert: "Meter payload failed validation",
raw: d
}
}];
}
// Example thresholds only: configure for your installation.
const POWER_LIMIT_W = 1000;
const VOLTAGE_MIN_V = 180;
const VOLTAGE_MAX_V = 260;
const flags = [];
if (d.power_w > POWER_LIMIT_W) {
flags.push("HIGH_POWER");
}
if (
d.voltage_v < VOLTAGE_MIN_V ||
d.voltage_v > VOLTAGE_MAX_V
) {
flags.push("VOLTAGE_OUT_OF_CONFIGURED_RANGE");
}
if (d.tamper_input === true) {
flags.push("TAMPER_SENSOR_ACTIVE");
}
const severity =
flags.includes("TAMPER_SENSOR_ACTIVE")
? "HIGH"
: flags.length > 0
? "WARNING"
: "NORMAL";
return [{
json: {
...d,
status: severity,
flags,
suspicious: flags.length > 0,
detection_method: "RULE_BASED",
needs_ai_review: flags.length > 0
}
}];
Limitation: This basic code detects configured threshold violations, not electricity theft. For persistent-duration rules, the workflow needs state between readings, such as a database or a reliable stored counter. For energy-balance checks, it needs a second trusted measurement or other independent evidence.
8.4 Prevent duplicate notifications
The ESP32 may retry when the network is unreliable, and n8n may receive duplicate events. Production workflows should:
-
Create a unique event identifier.
-
Store processed event IDs in a database.
-
Suppress repeat alerts for a configurable cooldown period.
-
Reopen an incident if a condition returns after recovery.
-
Keep the original measurement and all follow-up actions for auditing.
For example, create an incident ID from the device ID and the start time of the anomaly rather than generating a new alert for every sample.
9. AI agent configuration
The AI agent should explain evidence and help prioritize inspections. It should not invent missing sensor readings or autonomously disconnect electricity.
9.1 Agent input
Pass the validated data from the Code node into the agent, for example:
{
"device_id": "meter-001",
"voltage_v": 231.4,
"current_a": 5.2,
"power_w": 1100,
"energy_kwh": 12.84,
"power_factor": 0.91,
"tamper_input": false,
"status": "WARNING",
"flags": ["HIGH_POWER"]
}
These values are illustrative test data, not actual readings.
9.2 System prompt for the AI Agent node
You are the AI assistant for an electricity monitoring system.
Your role is to explain validated meter readings, summarize
rule-based anomalies, identify plausible non-fraud explanations,
and recommend safe verification steps.
Rules:
1. Never claim that electricity theft is proven by an anomaly.
2. Use only the measurements and rule results supplied.
3. Distinguish sensor faults, normal load changes, unusual
consumption, and explicitly detected tamper events.
4. If data is invalid or stale, recommend checking the sensor
and communication before interpreting the reading.
5. Never instruct a user to touch exposed electrical conductors
or bypass electrical safety equipment.
6. Do not operate a breaker or disconnect a supply.
7. Do not fabricate energy readings, prices, timestamps, or
evidence.
8. Return concise, plain language suitable for a Telegram alert.
Output:
- Severity
- Observed evidence
- Possible explanations
- Recommended safe next step
- Whether human inspection is required
9.3 Example AI response
AI agent analysis
Illustrative example · Not a real incident
Severity: Warning
Observed evidence: Active power is 1,100 W, above the configured 1,000 W threshold.
Possible explanations: A new appliance may have switched on, the load may have changed, or the configured threshold may be too low.
Recommended action: Review recent usage and compare the reading with the meter's normal operating pattern.
Fraud conclusion: Insufficient evidence to establish theft.
9.4 Agentic behavior
To make the project genuinely agentic rather than simply adding an AI chatbot, give the agent a small set of controlled tools:
-
Read the latest validated measurement.
-
Retrieve recent historical readings.
-
Read the device's configured thresholds.
-
Create an incident summary.
-
Request a human inspection.
-
Prepare a notification for the Telegram workflow.
Keep the actual sending of alerts, database writes, threshold changes and other consequential actions in explicit n8n workflow nodes. Require authentication and human approval for changes to safety-critical configuration.
10. Telegram text and voice alert automation
The notification pipeline has three parts:
-
Create an alert sentence from the anomaly result.
-
Send the text through the Telegram Bot API.
-
If voice delivery is enabled, convert the same sentence to audio and upload the resulting audio file to Telegram.
A Telegram bot does not automatically turn arbitrary text into speech. You need a TTS service or a local speech engine for that step.
10.1 Create a Telegram bot
-
Open Telegram and find the official
@BotFatheraccount. -
Create a bot with
/newbot. -
Save the bot token securely.
-
Open the bot and start a conversation with it.
-
Obtain the chat ID through the bot's update data or your chosen n8n Telegram integration.
-
Create Telegram credentials in n8n and select the bot.
Do not place the bot token in public source code, browser JavaScript or a shared spreadsheet.
10.2 Example text alert
Smart Meter Alert
Electricity Usage Warning
Device: meter-001
Voltage: 231.4 V
Current: 5.20 A
Active power: 1,100 W
Status: Configured power threshold exceeded.
Action: Please review the recent load and verify the meter readings. This alert does not establish electricity theft.
10.3 Configure the Telegram node
Add a Telegram node after the severity and AI-analysis steps.
-
Resource: Message
-
Operation: Send Message
-
Chat ID: your authorized recipient or group
-
Text: build a message from the validated fields and AI summary
An expression for the text could be:
={{
"Electricity Meter Alert\n" +
"Device: " + $json.device_id + "\n" +
"Status: " + $json.status + "\n" +
"Power: " + $json.power_w + " W\n" +
"Evidence: " + $json.flags.join(", ")
}}
Use an appropriate fallback for invalid data, because invalid-data events may not contain the normal measurement fields.
10.4 Configure voice alerts
Use this flow:
Alert text
Created by the n8n workflow
Text-to-speech service
Produces MP3, OGG or another supported audio format
Binary audio data
Pass the generated file to the Telegram node
Telegram audio notification
Send as a voice message or audio attachment
For voice-message presentation, use a supported OGG/Opus format if the selected Telegram API operation requires it. An MP3 file may instead be sent as a regular audio attachment.
The TTS step can be implemented using an HTTP Request node to a speech-generation API. Configure its credentials, request format and binary response according to that provider's documentation. Then connect the resulting binary property to the Telegram node's audio or voice field.
Example spoken alert
“Smart meter warning. Meter zero zero one has exceeded its configured power threshold. Please review the load and check the meter readings. This alert does not confirm electricity theft.”
For high-priority events, send text immediately and generate the voice message in parallel or afterward. A slow AI or TTS service should never delay local safety functions.
11. Google Sheets database design
Use Google Sheets as a convenient prototype database and reporting tool. It is not a replacement for a transactional database in a high-volume or safety-critical deployment.
11.1 Create a spreadsheet
Create a workbook called AI_Smart_Electricity_Monitoring.
Add two worksheets.
Worksheet 1: Readings
|
Column |
Description |
|---|---|
|
timestamp |
Time the reading was received |
|
device_id |
ESP32 meter identifier |
|
sequence |
Sample sequence number |
|
voltage_v |
Voltage |
|
current_a |
Current |
|
power_w |
Active power |
|
energy_kwh |
Cumulative energy |
|
power_factor |
Power factor |
|
frequency_hz |
Frequency |
|
status |
Normal, warning or invalid |
|
flags |
Rule flags |
|
event_id |
Unique event or sample identifier |
Worksheet 2: Alerts
|
Column |
Description |
|---|---|
|
event_id |
Unique incident ID |
|
timestamp |
Alert time |
|
device_id |
Meter identifier |
|
severity |
Informational, warning or high |
|
evidence |
Observed values and triggered rules |
|
ai_summary |
Agent explanation |
|
telegram_status |
Text/voice delivery status |
|
resolution |
Pending, reviewed or resolved |
|
reviewer_notes |
Human investigation notes |
11.2 n8n integration
-
Connect a Google account using n8n credentials.
-
Add a Google Sheets node after the validation and routing steps.
-
Choose the workbook and worksheet.
-
Use the append-row operation to record each valid reading.
-
Append an alert row only when an incident is created or updated.
-
Include an event ID to make later reconciliation possible.
-
Restrict access to the spreadsheet because it may contain energy-usage patterns and site information.
For a prototype, you can store all readings in Readings and only flagged events in Alerts. For larger deployments, use a proper database for event state and keep Sheets for reporting.
12. ThingSpeak cloud dashboard
ThingSpeak provides a straightforward way to visualize telemetry as time-series graphs. Its channel API supports writing readings and retrieving channel data.
12.1 Create a channel
-
Sign in to ThingSpeak .
-
Create a new channel named
AI Smart Electricity Meter. -
Enable and label these fields:
|
Field |
Name |
|---|---|
|
Field 1 |
Voltage (V) |
|
Field 2 |
Current (A) |
|
Field 3 |
Active Power (W) |
|
Field 4 |
Energy (kWh) |
|
Field 5 |
Power Factor |
|
Field 6 |
Frequency (Hz) |
|
Field 7 |
Anomaly Score |
|
Field 8 |
Device Status |
-
Save the channel.
-
Open its API Keys section and copy the write key.
-
Put the key in the ESP32 configuration, or store it in n8n if n8n is responsible for publishing the data.
The sample firmware currently writes Fields 1–4. Add fields 5–8 when the extra data becomes available. If n8n publishes readings, remove the duplicate ESP32 write path to avoid duplicate samples.
12.2 Recommended graphs
-
Voltage over time.
-
Current over time.
-
Active power over time.
-
Cumulative energy over time.
-
Power factor and frequency.
-
Anomaly score and device health.
Keep the channel private by default if it contains information about a real installation. Never expose a write API key in a public webpage.
13. Custom IoT webpage
A separate webpage gives the project a more polished interface than a raw sensor feed.
Suggested page sections:
-
Current voltage, current and active power.
-
Today's energy consumption and estimated cost.
-
Connection status and last update.
-
Current anomaly status.
-
Recent incidents and AI summaries.
-
Power and energy trend charts.
-
Links to the ThingSpeak channel and incident spreadsheet.
13.1 Web dashboard architecture
ESP32 → n8n → authorized data API
Dashboard webpage
HTML · CSS · JavaScript
Live values
Trends
Anomalies
13.2 Simple dashboard starter code
Save the following as index.html. This is a static demonstration of the interface, with simulated values. It is not yet connected to live telemetry.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>AI Smart Electricity Meter</title>
<style>
body {
margin: 0;
padding: 24px;
font-family: system-ui, sans-serif;
background: #f3f6fb;
color: #182238;
}
h1 { margin-bottom: 6px; }
.muted { color: #64748b; }
.grid {
display: grid;
grid-template-columns:
repeat(auto-fit, minmax(190px, 1fr));
gap: 16px;
margin-top: 24px;
}
.card {
background: white;
border-radius: 14px;
padding: 20px;
box-shadow: 0 2px 10px #17255412;
}
.value {
font-size: 30px;
font-weight: 700;
margin-top: 12px;
}
.status {
display: inline-block;
border-radius: 20px;
padding: 7px 12px;
background: #dcfce7;
color: #166534;
}
</style>
</head>
<body>
<h1>AI Smart Electricity Meter</h1>
<p class="muted">IoT energy monitoring and anomaly detection</p>
<p><span class="status" id="status">DEMO MODE</span></p>
<section class="grid">
<article class="card">
<div>Voltage</div>
<div class="value" id="voltage">-- V</div>
</article>
<article class="card">
<div>Current</div>
<div class="value" id="current">-- A</div>
</article>
<article class="card">
<div>Active Power</div>
<div class="value" id="power">-- W</div>
</article>
<article class="card">
<div>Energy</div>
<div class="value" id="energy">-- kWh</div>
</article>
</section>
<section class="card" style="margin-top:20px">
<h2>Monitoring result</h2>
<p id="analysis">
Waiting for demonstration data.
</p>
<p class="muted">
An anomaly is not proof of electricity theft.
</p>
</section>
<script>
// Demonstration values only.
// Replace with a secure, authenticated API.
const sample = {
voltage_v: 231.4,
current_a: 5.2,
power_w: 1100,
energy_kwh: 12.84,
status: "WARNING"
};
document.getElementById("voltage").textContent =
sample.voltage_v.toFixed(1) + " V";
document.getElementById("current").textContent =
sample.current_a.toFixed(2) + " A";
document.getElementById("power").textContent =
sample.power_w.toFixed(1) + " W";
document.getElementById("energy").textContent =
sample.energy_kwh.toFixed(2) + " kWh";
document.getElementById("status").textContent =
sample.status;
document.getElementById("analysis").textContent =
sample.power_w > 1000
? "Configured power threshold exceeded. Review recent load."
: "No configured power threshold exceeded.";
</script>
</body>
</html>
13.3 Connect it to live data
For production, create a read-only dashboard API in your backend that:
-
Authenticates the viewer.
-
Returns the latest validated measurement.
-
Returns recent historical readings and incident records.
-
Enforces device-level access permissions.
-
Never exposes Telegram tokens, ThingSpeak write keys, AI API keys or unrestricted n8n credentials.
Replace the demonstration sample object with data returned by that API. Do not use an unrestricted n8n webhook as a public read endpoint, and do not put secret API keys in client-side JavaScript.
14. Complete end-to-end project execution
Follow these stages in order. This helps isolate hardware, network, automation and AI errors instead of debugging everything simultaneously.
Implementation checklist
0 of 9
Suggested test cases
|
Test |
Simulated input |
Expected result |
|---|---|---|
|
Normal operation |
Power below threshold |
Log reading; no fraud alert |
|
High power |
Power exceeds configured threshold |
Warning and AI explanation |
|
Invalid sensor data |
Missing or non-numeric reading |
Reject reading and log a data-quality event |
|
Tamper signal |
|
High-priority inspection alert |
|
Wi-Fi loss |
Device cannot reach cloud |
Local measurements continue where possible; retry after reconnection |
|
Duplicate webhook |
Same event ID submitted twice |
No duplicate incident notification |
|
TTS service failure |
Audio generation returns an error |
Text alert remains available |
|
AI service failure |
AI model unavailable |
Rule-based alert still works |
|
Meter reset |
Energy counter drops unexpectedly |
Flag for counter reset or data validation |
Test tamper scenarios with simulated payloads or a safe low-voltage test input. Do not deliberately bypass a live electricity meter or interfere with a utility installation.
15. Troubleshooting guide
|
Problem |
Likely cause |
What to check |
|---|---|---|
|
PZEM readings return |
Wiring, power or incompatible library |
Verify the exact PZEM revision, supply and RX/TX mapping |
|
ESP32 does not connect to Wi-Fi |
Incorrect credentials or poor signal |
Check SSID, password and router connectivity |
|
n8n returns HTTP errors |
Wrong URL or inactive workflow |
Check the production webhook URL, activation and execution logs |
|
ThingSpeak does not update |
Wrong write key or rejected request |
Inspect HTTP status and response; confirm field configuration and rate limits |
|
Google Sheets rows are missing |
Credential or mapping error |
Test the account permissions and append-row operation |
|
Telegram text arrives but voice does not |
TTS or binary mapping problem |
Inspect the audio output format and Telegram node input |
|
Too many alerts |
Threshold too low or missing deduplication |
Tune the rules and implement event state/cooldown |
|
AI reports false theft |
Prompt or detection logic is too aggressive |
Restrict the agent to supplied evidence and treat anomalies as leads |
|
Dashboard is stale |
API caching or polling failure |
Check last-update time and backend connectivity |
16. Security, accuracy and production considerations
Before deploying this beyond a classroom prototype, implement the following:
-
Protect n8n with authentication and HTTPS.
-
Use valid TLS certificate verification on the ESP32.
-
Store secrets in managed credentials or environment configuration rather than in public code.
-
Authenticate device requests; use per-device credentials and reject unauthorized payloads.
-
Validate numeric ranges, event freshness and duplicate IDs.
-
Keep a reliable offline queue and retry strategy if readings must not be lost.
-
Protect historical records from unauthorized alteration.
-
Use independent evidence and human inspection before classifying a case as confirmed fraud.
-
Do not allow the AI agent to control electrical breakers or modify protection settings.
-
Validate measurement accuracy against a trusted reference instrument.
-
Consider applicable electricity-metering standards, utility rules, electrical codes and privacy requirements before real-world deployment.
17. Project documentation for an academic report
You can structure the final report as follows.
-
Abstract
-
Introduction and problem statement
-
Existing system and limitations
-
Proposed system
-
Objectives and scope
-
Hardware components and specifications
-
Software requirements and tools
-
System architecture and flowcharts
-
Electrical and communication schematic
-
ESP32 firmware design
-
n8n workflow implementation
-
Rule-based anomaly detection and AI agent design
-
Telegram text and voice alert integration
-
Google Sheets and ThingSpeak integration
-
Web dashboard implementation
-
Testing methodology and results
-
Security, limitations and future enhancements
-
Conclusion and references
Expected project outcomes
A successful prototype should demonstrate:
-
Continuous acquisition of electrical measurements.
-
Cloud transmission and historical logging.
-
Configurable anomaly detection.
-
Automated AI-assisted explanations.
-
Telegram text and generated voice notifications.
-
A working IoT dashboard.
-
Traceable incident records and reproducible test results.
Do not claim a fraud-detection accuracy percentage until you have evaluated the system against a representative, labeled dataset. Report precision, recall, false-positive rate and detection delay if you conduct a formal evaluation.
18. Future enhancements
After the basic system works, you can extend it with:
-
Multiple ESP32 meters and a centralized monitoring dashboard.
-
Time-of-day load baselines and statistical anomaly detection.
-
Anomaly models trained on verified historical data.
-
Independent feeder-versus-load energy balance measurement.
-
Electricity tariff schedules and daily/monthly cost reports.
-
Voice alerts in English, Hindi or Telugu using a suitable TTS service.
-
Role-based access for consumers, maintenance staff and administrators.
-
Offline event buffering and reliable event reconciliation.
-
A mobile-friendly Progressive Web App.
-
Signed device messages and firmware-update security.
19. Technical references
Recommended implementation order
Build and test the project in this order: ESP32 + meter → n8n webhook → Google Sheets → ThingSpeak → rule-based detection → AI agent → Telegram text alerts → voice alerts → live webpage.
That sequence delivers a working core system early and makes the AI and voice features easier to debug.
The code and diagrams above form a complete starter design, but they are not a single pre-tested, deployable package: you still need to configure your hardware variant, credentials, n8n workflow, AI provider, TTS provider and authenticated dashboard API.
Project Summary: AI Smart Electricity Metering & Fraud Detection System
Project title: AI-Powered Smart Electricity Metering and Anomaly Detection Using ESP32, n8n, Telegram Voice Alerts, Google Sheets and ThingSpeak.
1. Project overview
This project develops an IoT-based electricity monitoring system that measures power consumption, identifies suspicious electrical usage patterns, and automatically sends alerts using an AI agent and n8n workflow automation.
An ESP32 collects electrical measurements from an energy meter, such as the PZEM-004T. The readings are sent to n8n for validation and anomaly detection. The system records data in Google Sheets, displays graphs through ThingSpeak, and sends Telegram text and voice notifications when configured thresholds are exceeded.
2. System architecture
Energy Meter / Sensors
ESP32 Microcontroller
Wi-Fi → n8n Automation
Rule-Based Detection + AI Agent
Telegram
Text and voice alerts
Google Sheets
Historical records
ThingSpeak
Cloud graphs
IoT Webpage
Live dashboard
3. Main hardware and software
-
Hardware: ESP32 DevKit, compatible energy meter, appropriate sensors, protected power supply and enclosure.
-
Firmware: Arduino IDE and ESP32 libraries.
-
Automation: n8n workflows and webhook integration.
-
AI: An AI agent for anomaly explanations and recommendations.
-
Notifications: Telegram Bot API and a text-to-speech service.
-
Cloud storage: Google Sheets.
-
Monitoring: ThingSpeak and a custom HTML/CSS/JavaScript webpage.
4. Main features
-
Real-time voltage, current, power and energy monitoring.
-
Configurable detection of unusual electricity consumption.
-
Optional tamper-sensor monitoring.
-
AI-generated anomaly explanations.
-
Automated Telegram text and voice alerts.
-
Historical data logging and energy consumption graphs.
-
Web-based monitoring dashboard.
-
Device-health monitoring and incident records.
5. Working principle
-
The energy meter measures electrical parameters.
-
The ESP32 reads the measurements and transmits them over Wi-Fi.
-
n8n validates the data and applies configured detection rules.
-
The AI agent explains suspicious readings and suggests safe checks.
-
n8n sends Telegram notifications and optional voice messages.
-
Google Sheets records the readings and incidents.
-
ThingSpeak and the IoT webpage display the data and trends.
6. Expected outcome
The project provides a smart, automated electricity monitoring prototype that helps users understand consumption, identify abnormal readings, and respond quickly to potential meter problems or suspicious activity.
Important: An unusual reading is not proof of electricity theft. Confirmed fraud requires appropriate independent evidence and human investigation. Mains electrical installation must be handled by a qualified electrician.
