AI Smart Grid Failure Prediction System using ESP32, IoT, AI Agent, n8n, Telegram, Google Sheets & ThingSpeak
This project is an AI-powered IoT smart-grid monitoring and failure prediction system that measures electrical parameters, detects abnormal operating conditions, sends intelligent alerts, records historical data, and displays live measurements on a web dashboard.
The system combines an ESP32 microcontroller, electrical sensors, an AI analysis service, n8n workflow automation, Telegram voice notifications, Google Sheets, and ThingSpeak cloud monitoring.
It is suitable for a final-year engineering project, an IoT prototype, an academic demonstration, or a proof of concept for predictive maintenance.
Important design distinction: The initial implementation will be a low-voltage monitoring prototype. It can detect anomalies and demonstrate failure prediction, but it cannot reliably predict real utility-grid failures without representative historical fault data and a validated model. Do not connect an ESP32 or exposed prototype circuitry directly to utility mains.
1. Project overview
1. Edge monitoring — ESP32
Reads voltage, current, temperature and other available sensor measurements. Calculates power and sends telemetry to the cloud.
2. IoT dashboard — ThingSpeak and web page
Displays live readings, historical trends, threshold violations and equipment health indicators.
3. Automation and AI agent — n8n
Receives sensor data, checks safety rules, invokes AI anomaly analysis and decides which notification and logging workflows to execute.
4. Alerts and records
Sends Telegram text and generated voice alerts, saves events to Google Sheets and maintains historical data for analysis.
Project title
AI Smart Grid Failure Prediction and Predictive Maintenance Using ESP32, Agentic IoT, n8n Automation, Telegram Voice Alerts, Google Sheets and ThingSpeak
Main objectives
-
Monitor electrical operating parameters continuously.
-
Detect overcurrent, undervoltage, overvoltage, overheating and abnormal load behavior.
-
Calculate an equipment health score and estimate failure risk.
-
Use an AI agent to explain anomalies and recommend maintenance actions.
-
Automate Telegram notifications, including spoken alert messages.
-
Maintain event logs and historical sensor readings in Google Sheets.
-
Visualize live and historical data through ThingSpeak and a custom IoT webpage.
-
Build a modular system that can later support a trained machine-learning prediction model.
2. Complete system architecture
The recommended architecture uses the ESP32 for immediate measurements and basic anomaly detection, while n8n handles cloud automation and the AI agent handles explanations and maintenance recommendations.
Electrical monitoring sensors
Voltage · Current · Temperature · Optional vibration
ESP32 edge controller
Sampling · RMS calculations · Threshold rules · Device ID
Wi-Fi / HTTPS telemetry
n8n webhook + ThingSpeak cloud API
n8n automation workflow
Validate → Calculate risk → AI agent → Route event
Telegram
Text and voice alerts
Google Sheets
Readings and incident logs
ThingSpeak
Time-series charts
IoT webpage
Status and event dashboard
How the data moves
-
The ESP32 samples the sensors.
-
It calculates electrical measurements and checks local thresholds.
-
It sends a JSON payload over HTTPS to an n8n webhook.
-
n8n validates the payload and computes rule-based anomaly severity.
-
If an anomaly is detected, an AI agent receives the measurements and event context.
-
n8n sends the appropriate Telegram alert and records the event in Google Sheets.
-
ThingSpeak stores time-series measurements, and the webpage displays the latest readings.
-
The system continues monitoring and can escalate a persistent anomaly.
The n8n Webhook node is designed to receive external events and trigger workflows; its test and production URLs are separate. See the n8n Webhook documentation .
3. Hardware requirements and components
The following is a practical prototype bill of materials. The exact voltage and current sensors depend on whether your demonstration uses DC or AC.
Recommended baseline: low-voltage DC bench prototype first.
|
Component |
Quantity |
Purpose |
|---|---|---|
|
ESP32 DevKit |
1 |
Main controller and Wi-Fi |
|
Low-voltage DC supply |
1 |
Safe test source |
|
Voltage sensor or calibrated divider module |
1 |
Measures input voltage |
|
Hall-effect current sensor, e.g. ACS712-compatible module |
1 |
Measures load current |
|
DS18B20 temperature sensor |
1 |
Monitors component temperature |
|
Breadboard and jumper wires |
1 set |
Prototype connections |
|
Resistor and pull-up components |
As needed |
Signal conditioning |
|
LED and resistor |
Optional |
Local warning indicator |
|
Wi-Fi access point |
1 |
Internet connectivity |
Optional extensions include an isolated AC measurement module, vibration sensor, relay driver for a separate low-voltage demonstration, backup power and a small enclosure.
Sensor selection notes
-
Voltage: Choose a measurement range that safely covers the source. A resistor divider is appropriate only for suitable low-voltage DC and requires calibration.
-
Current: Select a sensor with adequate current range, polarity support where required and suitable output voltage for the ESP32 ADC.
-
Temperature: A DS18B20 can monitor a safe, accessible test component; it is not automatically suitable for measuring transformer winding temperatures.
-
AC measurement: Use appropriately rated, isolated measurement hardware. AC voltage and current require waveform sampling and RMS calculations, not a single ADC reading.
The ESP32 ADC is not a certified power-quality analyzer. Accuracy depends on sensor tolerances, calibration, sampling, noise and the measurement circuitry.
4. Schematic diagram and wiring
4.1 Low-voltage DC prototype schematic
Use the following conceptual connections as the starting point. Verify your particular sensor module's pinout before applying power.
LOW-VOLTAGE DC SOURCE
+ -
| |
| +-----+-------------------- GND
| | |
v v |
+-----------+ |
| DC LOAD | |
+-----------+ |
| |
Current sensor |
(in series) |
| |
+-----> Load supply return --------+
ESP32 DEVKIT
============
GPIO34 (ADC1) <---- Current sensor analog output
GPIO35 (ADC1) <---- Calibrated voltage sensor output
GPIO4 <---- DS18B20 DATA
3V3 ------ DS18B20 VDD
GND ------ DS18B20 GND
DS18B20 DATA --- 4.7k resistor --- 3V3
Wiring conditions
-
Connect sensor grounds to ESP32 ground only when the sensor's electrical design permits a shared reference.
-
Keep every analog output within the ESP32's permitted input range. Never apply a 5 V analog signal directly to an ESP32 GPIO.
-
Connect the current sensor in series with the load's current path; do not wire it as a parallel voltage sensor.
-
Place the voltage sensor across the measured DC source, with the correct polarity.
-
Use GPIO34 and GPIO35 as ADC inputs on a classic ESP32 DevKit; check pin availability on your exact board.
-
Select the sensor's power supply according to its datasheet. Some modules operate at 5 V but have output signals unsuitable for direct 3.3 V ADC inputs.
4.2 AC smart-grid extension
For an AC demonstration, use an appropriately rated isolated voltage sensor and an isolated current sensor or current transformer with the correct burden and conditioning circuit.
AC SOURCE
|
+----[ Properly rated isolated voltage sensor ]----+
| |
+----[ Load conductor through current sensor ]-----+
|
Sensor outputs
|
Signal conditioning
|
ESP32
|
Wi-Fi / HTTPS
|
n8n + Cloud
This is a functional block diagram, not a mains wiring drawing. Do not build exposed mains circuitry on a breadboard. Use a qualified person and suitable enclosures, fusing, isolation, creepage and clearance if an AC installation is ever undertaken.
5. Software architecture and installation
The project uses these software components:
|
Software |
Responsibility |
|---|---|
|
Arduino IDE |
Compile and upload ESP32 firmware |
|
ESP32 Arduino core |
Wi-Fi, ADC sampling and HTTP requests |
|
n8n |
Workflow automation and webhook API |
|
AI model connected to n8n |
Explain anomalies and suggest actions |
|
Telegram Bot API |
Text and voice-message delivery |
|
Google Sheets |
Store measurements and incidents |
|
ThingSpeak |
Cloud time-series dashboard |
|
HTML, CSS and JavaScript |
Custom monitoring webpage |
Useful documentation:
Step 1 — Create the ThingSpeak channel
-
Create a ThingSpeak account.
-
Create a channel named
AI Smart Grid Monitor. -
Enable these fields:
|
Field |
Measurement |
|---|---|
|
Field 1 |
Voltage (V) |
|
Field 2 |
Current (A) |
|
Field 3 |
Power (W) |
|
Field 4 |
Temperature (°C) |
|
Field 5 |
Anomaly score (%) |
|
Field 6 |
Health score (%) |
|
Field 7 |
Failure-risk estimate (%) |
|
Field 8 |
Alarm code |
-
Copy the channel's Write API Key.
-
Keep the channel private unless you have a specific reason to publish its data.
ThingSpeak supports up to eight numeric fields in a channel entry.
Step 2 — Configure the ESP32 development environment
-
Install the Arduino IDE.
-
Install the Espressif ESP32 board package using Boards Manager.
-
Select your ESP32 board and serial port.
-
Use the built-in libraries
WiFi.handHTTPClient.h. -
Add a compatible DallasTemperature library and OneWire library if using the DS18B20 sensor.
Step 3 — Create the n8n webhook
-
Create a new workflow.
-
Add a Webhook node.
-
Set HTTP Method to
POST. -
Set Path to
smart-grid. -
Select JSON request handling and configure authentication.
-
Copy the Test URL.
-
Click Listen for Test Event.
-
Send a test JSON payload to the webhook.
-
Once the workflow works, activate or publish it and use the Production URL.
For cloud access, the ESP32 must be able to reach the webhook over the internet. A local localhost URL on your laptop will not work from the ESP32.
Example test payload:
{
"device_id": "GRID-ESP32-01",
"voltage": 12.1,
"current": 1.4,
"power": 16.94,
"temperature": 34.5,
"anomaly_score": 10,
"health_score": 90,
"failure_risk": 8,
"alarm_code": 0
}
6. ESP32 firmware — complete starter implementation
The following sketch reads two analog inputs, calculates voltage and current using calibration constants, reads a DS18B20 temperature sensor, calculates simple power and risk indicators, writes measurements to ThingSpeak and sends telemetry to n8n.
It is a starter firmware for low-voltage DC. The calibration values must be measured for your actual sensors. The anomaly score and failure-risk value are rule-based demonstration indicators, not a trained predictive model.
Before uploading, replace the configuration values with your own.
#include <WiFi.h>
#include <HTTPClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>
// ---------- CONFIGURATION ----------
const char* WIFI_SSID = "YOUR_WIFI_NAME";
const char* WIFI_PASSWORD = "YOUR_WIFI_PASSWORD";
const char* N8N_WEBHOOK =
"https://YOUR_N8N_HOST/webhook/smart-grid";
const char* THINGSPEAK_WRITE_KEY =
"YOUR_THINGSPEAK_WRITE_KEY";
// Classic ESP32 ADC1 pins
const int VOLTAGE_PIN = 35;
const int CURRENT_PIN = 34;
const int ONE_WIRE_PIN = 4;
// Calibrate for your actual voltage sensor.
// Example: 3.30 V at ADC corresponds to 16.5 V input.
float VOLTAGE_SCALE = 5.0;
// Example only: replace with your current sensor's
// calibrated sensitivity in volts per ampere.
float CURRENT_SENSITIVITY = 0.100;
float CURRENT_ZERO_VOLTAGE = 1.65;
const unsigned long SAMPLE_INTERVAL_MS = 20000;
OneWire oneWire(ONE_WIRE_PIN);
DallasTemperature tempSensor(&oneWire);
unsigned long lastSample = 0;
// ---------- HELPERS ----------
float readAdcAverage(int pin) {
const int samples = 100;
double total = 0;
for (int i = 0; i < samples; i++) {
total += analogReadMilliVolts(pin);
delay(2);
}
return (total / samples) / 1000.0;
}
float readVoltage() {
// Simple DC average. Calibrate with a multimeter.
return readAdcAverage(VOLTAGE_PIN) * VOLTAGE_SCALE;
}
float readCurrent() {
// Illustrative for a DC Hall sensor.
// For better accuracy, subtract the calibrated zero
// offset and average multiple instantaneous samples.
float sensorV = readAdcAverage(CURRENT_PIN);
float current =
(sensorV - CURRENT_ZERO_VOLTAGE) /
CURRENT_SENSITIVITY;
// Demo assumes positive current direction.
if (current < 0) current = 0;
return current;
}
int calculateAlarm(float voltage, float current,
float temperature) {
if (voltage < 10.5 || voltage > 14.5) return 2;
if (current > 3.0) return 3;
if (temperature > 60.0) return 4;
return 0;
}
void sendHttpPost(String url, String payload) {
if (WiFi.status() != WL_CONNECTED) {
Serial.println("WiFi disconnected; upload skipped");
return;
}
WiFiClientSecure client;
// DEMO ONLY: disables TLS certificate verification.
// Replace with proper CA certificate validation
// before using a real deployment.
client.setInsecure();
HTTPClient http;
http.setTimeout(8000);
if (!http.begin(client, url)) {
Serial.println("HTTP initialization failed");
return;
}
http.addHeader("Content-Type", "application/json");
int status = http.POST(payload);
Serial.printf("HTTP status: %d\n", status);
if (status > 0) {
Serial.println(http.getString());
} else {
Serial.println(http.errorToString(status));
}
http.end();
}
void sendThingSpeak(float voltage, float current,
float power, float temperature,
int anomaly, int health,
int risk, int alarm) {
String url = "https://api.thingspeak.com/update";
String payload =
"api_key=" + String(THINGSPEAK_WRITE_KEY) +
"&field1=" + String(voltage, 2) +
"&field2=" + String(current, 3) +
"&field3=" + String(power, 2) +
"&field4=" + String(temperature, 2) +
"&field5=" + String(anomaly) +
"&field6=" + String(health) +
"&field7=" + String(risk) +
"&field8=" + String(alarm);
if (WiFi.status() != WL_CONNECTED) return;
WiFiClientSecure client;
// DEMO ONLY. Use proper CA validation in deployment.
client.setInsecure();
HTTPClient http;
if (!http.begin(client, url)) return;
http.addHeader(
"Content-Type",
"application/x-www-form-urlencoded"
);
int status = http.POST(payload);
Serial.printf("ThingSpeak HTTP status: %d\n", status);
if (status > 0) {
Serial.println("ThingSpeak entry: " + http.getString());
}
http.end();
}
void setup() {
Serial.begin(115200);
analogReadResolution(12);
tempSensor.begin();
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi connected");
Serial.println(WiFi.localIP());
}
void loop() {
if (millis() - lastSample < SAMPLE_INTERVAL_MS) {
delay(20);
return;
}
lastSample = millis();
if (WiFi.status() != WL_CONNECTED) {
WiFi.reconnect();
}
float voltage = readVoltage();
float current = readCurrent();
float power = voltage * current;
tempSensor.requestTemperatures();
float temperature =
tempSensor.getTempCByIndex(0);
if (temperature == DEVICE_DISCONNECTED_C) {
Serial.println("Temperature sensor error");
return;
}
int alarm = calculateAlarm(
voltage, current, temperature
);
// Transparent demonstration indicators, not ML output.
int anomaly = (alarm == 0) ? 0 : 80;
int health = (alarm == 0) ? 100 : 40;
int risk = (alarm == 0) ? 5 : 70;
String json = "{";
json += "\"device_id\":\"GRID-ESP32-01\",";
json += "\"voltage\":" + String(voltage, 2) + ",";
json += "\"current\":" + String(current, 3) + ",";
json += "\"power\":" + String(power, 2) + ",";
json += "\"temperature\":" +
String(temperature, 2) + ",";
json += "\"anomaly_score\":" +
String(anomaly) + ",";
json += "\"health_score\":" +
String(health) + ",";
json += "\"failure_risk\":" +
String(risk) + ",";
json += "\"alarm_code\":" + String(alarm);
json += "}";
Serial.println(json);
sendHttpPost(N8N_WEBHOOK, json);
sendThingSpeak(
voltage, current, power, temperature,
anomaly, health, risk, alarm
);
}
Firmware configuration and calibration
Before trusting the readings:
-
Measure the source voltage using a suitable calibrated multimeter.
-
Compare it with the ESP32's calculated voltage and adjust
VOLTAGE_SCALE. -
Calibrate the current sensor at zero current, then compare readings against a suitable reference meter at multiple safe load currents.
-
Replace the illustrative current sensitivity and zero-offset values.
-
Check the sensor's output range before connecting it to the ESP32.
-
Test sensor disconnection, Wi-Fi loss and HTTP failure conditions.
-
Use certificate validation instead of
setInsecure()in deployment.
Important limitation: readAdcAverage() calculates a DC average. It does not calculate true AC RMS current or voltage. For AC monitoring, use properly designed isolated measurement circuitry and sample the waveform at a suitable rate to calculate RMS values. A real predictive-maintenance deployment should also use non-blocking sampling, fault-event buffering and retry logic.
The 20-second upload interval is an example; confirm the rate limits of your ThingSpeak account before selecting the final interval.
7. n8n automation workflow — node-by-node design
This is the central automation layer of the project. It receives ESP32 telemetry and routes normal measurements and abnormal events through different paths.
7.1 Main workflow diagram
flowchart TD
A[ESP32 sends JSON] --> B[Webhook: POST smart-grid]
B --> C[Validate payload]
C --> D{Valid data?}
D -- No --> E[Reject / log bad request]
D -- Yes --> F[Calculate rules and risk]
F --> G[Google Sheets: Save reading]
G --> H{Alarm or anomaly?}
H -- No --> I[Update dashboard / normal status]
H -- Yes --> J[AI Agent: Explain anomaly]
J --> K[Build alert message]
K --> L[Telegram text alert]
K --> M[Text-to-speech service]
M --> N[Telegram voice alert]
L --> O[Incident log]
N --> O
O --> P[Finish]
7.2 Create the workflow
|
Node |
Configuration |
Purpose |
|---|---|---|
|
1. Webhook |
|
Receive ESP32 JSON |
|
2. Code |
Validate and normalize data |
Reject invalid measurements |
|
3. Code |
Apply thresholds and risk rules |
Generate alarm severity |
|
4. Google Sheets |
Append row |
Save each reading |
|
5. IF |
|
Separate normal and abnormal events |
|
6. AI Agent |
Input measurements and event history |
Explain possible cause |
|
7. Edit Fields |
Create alert text |
Standardize notification |
|
8. Telegram |
Send Message |
Deliver text alert |
|
9. HTTP Request / TTS integration |
Generate audio |
Convert alert text to speech |
|
10. Telegram |
Send Voice |
Deliver playable voice message |
|
11. Google Sheets |
Append incident row |
Save alert and AI assessment |
You can create a separate workflow for Telegram alerts and use an n8n Execute Sub-workflow node to keep the design modular.
7.3 Payload validation
Use a Code node after the Webhook node. Configure the workflow to process the incoming item as JSON.
const d = $json.body ?? $json;
const fields = [
"voltage",
"current",
"power",
"temperature"
];
for (const field of fields) {
if (
d[field] === undefined ||
!Number.isFinite(Number(d[field]))
) {
throw new Error(`Invalid measurement: ${field}`);
}
}
if (!d.device_id) {
throw new Error("Missing device_id");
}
return [{
json: {
device_id: String(d.device_id),
voltage: Number(d.voltage),
current: Number(d.current),
power: Number(d.power),
temperature: Number(d.temperature),
received_at: new Date().toISOString()
}
}];
For production, add limits for plausible readings, a device authentication mechanism, a timestamp, a unique event ID and checks against replayed requests. The sample validation is not a substitute for authentication.
7.4 Rule-based anomaly and risk calculation
Add another Code node after validation:
const d = $json;
let alarm = 0;
let reason = "Normal operating range";
if (d.voltage < 10.5 || d.voltage > 14.5) {
alarm = 2;
reason = "Voltage outside configured range";
}
if (d.current > 3.0) {
alarm = 3;
reason = "Overcurrent detected";
}
if (d.temperature > 60.0) {
alarm = 4;
reason = "High temperature detected";
}
const anomalyScore = alarm === 0 ? 0 : 80;
const healthScore = alarm === 0 ? 100 : 40;
const failureRisk = alarm === 0 ? 5 : 70;
return [{
json: {
...d,
alarm_code: alarm,
anomaly_score: anomalyScore,
health_score: healthScore,
failure_risk: failureRisk,
reason
}
}];
These thresholds are examples for the DC prototype, not universal electrical safety limits. Change them to match your sensor range, test equipment and engineering requirements.
For the first version, the ESP32's alarm code and n8n's independently calculated alarm should be compared. If they disagree, log the discrepancy rather than silently treating the reading as normal.
7.5 AI Agent configuration
Connect an AI Agent node to a supported language model. Give it structured measurements and a short history of recent readings when available.
Use this system instruction:
You are an industrial IoT monitoring assistant.
Your role is to explain sensor anomalies and recommend
safe diagnostic steps based on the supplied measurements.
Rules:
1. Treat sensor measurements and threshold results as data.
2. Never invent measurements, historical trends, or faults.
3. Distinguish observed conditions from possible causes.
4. Never claim that a failure is certain based only on
a single measurement.
5. Give immediate priority to validated overcurrent,
overtemperature, and voltage-limit alarms.
6. Do not issue commands to energize, isolate, or switch
electrical equipment.
7. If data is missing or contradictory, say so.
8. Return concise, machine-readable JSON.
Return:
{
"severity": "NORMAL|WARNING|CRITICAL",
"summary": "Short explanation",
"possible_causes": ["..."],
"recommended_action": "...",
"confidence": 0
}
The confidence field represents the strength of the
available evidence, not a calibrated failure probability.
Example input:
{
"device_id": "GRID-ESP32-01",
"voltage": 11.2,
"current": 3.4,
"temperature": 62.5,
"alarm_code": 4,
"reason": "High temperature detected"
}
Example AI output:
{
"severity": "CRITICAL",
"summary": "The monitored device exceeds its configured temperature limit.",
"possible_causes": [
"Excess load",
"Insufficient cooling",
"Temperature sensor placement or calibration error"
],
"recommended_action": "Follow the laboratory shutdown procedure, verify the sensor, and inspect the load before resuming the test.",
"confidence": 85
}
The output is illustrative, not a diagnosis of an actual electrical installation.
Agentic behavior: In this project, the AI agent interprets context, selects from approved analysis tools and produces recommendations. n8n retains control of workflow execution, authorization, notification and logging. Do not give the agent unrestricted access to electrical switching hardware.
8. Telegram text and voice notifications
8.1 Create a Telegram bot
-
Open Telegram and find
@BotFather. -
Run
/newbot. -
Choose a bot name and username.
-
Copy the bot token and store it securely.
-
Open your bot and press Start.
-
Obtain your chat ID using an authenticated bot update request or an appropriate Telegram integration.
-
Configure Telegram credentials in n8n.
Never publish the bot token in your webpage, source repository or project report.
8.2 Example Telegram alert
Smart Grid AI Monitor
Example message
CRITICAL ALERT — GRID-ESP32-01
Temperature: 62.5 °C
Voltage: 11.2 V
Current: 3.4 A
Detected condition: High temperature
AI assessment: Excess load or insufficient cooling may be contributing factors.
Action: Follow the test system's safety procedure and verify the readings.
8.3 n8n Telegram message template
Use an Edit Fields node to prepare a message field:
={{
"🚨 SMART GRID ALERT\n" +
"Device: " + $json.device_id + "\n" +
"Condition: " + $json.reason + "\n" +
"Voltage: " + $json.voltage + " V\n" +
"Current: " + $json.current + " A\n" +
"Temperature: " + $json.temperature + " °C\n" +
"Risk indicator: " + $json.failure_risk + "%"
}}
In the Telegram Send Message node, map message into the text field and configure your chat ID.
8.4 How Telegram voice alerts work
A voice alert needs actual audio, not merely text labeled as speech. Use this sequence:
flowchart LR
A[AI alert summary] --> B[Text-to-speech API]
B --> C[Generate audio]
C --> D[Convert to OGG Opus]
D --> E[Telegram sendVoice]
E --> F[User plays voice message]
-
Take the final approved alert text.
-
Pass it to a text-to-speech service through an n8n HTTP Request node.
-
Receive an audio file or binary response.
-
If necessary, convert the audio to OGG/Opus using a suitable audio-conversion service.
-
Use the Telegram Bot API
sendVoicemethod to upload the audio. -
Include a caption identifying the affected device and severity.
Telegram documents sendVoice for voice messages; use the audio format supported by that endpoint.
For a first demonstration, use a pre-recorded voice message to verify Telegram delivery, then add text-to-speech. The exact n8n node fields depend on the selected TTS provider.
8.5 Alert priority and notification rules
|
Severity |
Example condition |
Notification |
|---|---|---|
|
Normal |
All measurements within limits |
Log data; no Telegram alert |
|
Warning |
Repeated small deviations |
Telegram text |
|
Critical |
Confirmed configured safety threshold breach |
Immediate text and voice |
|
Sensor fault |
Missing, stale or implausible readings |
Sensor-health notification |
Use cooldowns and event IDs to avoid sending the same alert every 20 seconds. Critical notifications should remain independent of the AI model so that a slow or unavailable AI service does not delay a threshold alarm.
9. Google Sheets database and reporting
Google Sheets provides a simple cloud database for a college project. Use two worksheets in one spreadsheet.
Sheet 1 — Sensor_Readings
|
Timestamp |
Device ID |
Voltage |
Current |
Power |
Temperature |
Anomaly |
Health |
Risk |
Alarm |
|---|---|---|---|---|---|---|---|---|---|
|
2026-10-16 21:00 |
GRID-ESP32-01 |
12.1 |
1.4 |
16.94 |
34.5 |
0 |
100 |
5 |
0 |
|
2026-10-16 21:01 |
GRID-ESP32-01 |
11.2 |
3.4 |
38.08 |
62.5 |
80 |
40 |
70 |
4 |
Example data only.
Configure an n8n Google Sheets node to append each validated reading to the matching columns.
Sheet 2 — Incident_Log
Recommended columns:
-
Event ID
-
Timestamp
-
Device ID
-
Severity
-
Alarm code
-
Observed condition
-
AI summary
-
Recommended action
-
Telegram text status
-
Telegram voice status
-
Resolution time
-
Technician notes
Only append incident rows when an alarm occurs or when the incident changes state. This avoids filling the incident log with duplicate alerts.
Example reporting metrics
-
Number of alarms per day
-
Maximum recorded temperature
-
Average current
-
Total warning and critical events
-
Number of sensor communication failures
-
Mean time to acknowledge an alert
-
Mean time to resolve an incident
Google Sheets is suitable for a prototype. For high-volume deployments, consider a time-series database rather than treating a spreadsheet as an unlimited telemetry store.
10. Custom IoT webpage and cloud dashboard
The webpage gives users a visual interface for the monitoring system. A simple implementation can display voltage, current, temperature, power, risk and recent trends.
10.1 Dashboard layout
DEVICE STATUS
GRID-ESP32-01
Voltage
12.1 V
Current
1.4 A
Temperature
34.5 °C
Rule status
Normal
*Illustrative layout with sample readings, not live sensor data.
10.2 Working webpage code
Save the following as index.html. It fetches the latest ThingSpeak channel entry using the channel ID and a read-only API key if the channel is private. It includes an automatic refresh, basic status labels and an alert log for the latest reading.
Replace the configuration placeholders before opening the page.

No comments:
Post a Comment