AI-Based Smart Water Leakage Detection and Alert System
ESP32 + IoT + AI Agent + n8n Automation + Telegram Voice Alerts + Google Sheets + ThingSpeak Cloud Dashboard
AI-Powered ESP32 Agentic IoT n8n Automation Telegram Alerts Cloud Dashboard ```
1. Complete Project Overview
The AI-Based Smart Water Leakage Detection and Alert System is an intelligent Agentic IoT platform designed to detect water leakage, abnormal water consumption, pipe bursts, continuous water flow, and unusual water usage.
The ESP32 acts as the main IoT controller. It collects data from water flow sensors, leakage sensors, temperature sensors, and optional water-level sensors.
The collected data is transmitted through Wi-Fi to a PHP IoT API, n8n automation workflow, ThingSpeak cloud dashboard, Google Sheets, and an AI Agent.
When the AI Agent detects a possible water leakage, the system automatically generates Telegram text alerts, voice notifications, data logs, and maintenance alerts.
2. Main Project Objectives
Water Leakage Detection
Detect abnormal water flow and physical water leakage.
AI-Based Analysis
Analyze sensor data and calculate leakage probability.
Telegram Notification
Send instant Telegram alerts when leakage is detected.
Voice Notification
Automatically generate and send voice alerts.
Cloud Monitoring
Display real-time data using ThingSpeak.
Historical Data
Store sensor information in Google Sheets.
3. Complete System Architecture
``` +-------------------------------------------------------------+ | WATER PIPELINE | | | | +----------------+ +----------------+ | | | Water Flow | | Water Leakage | | | | Sensor | | Sensor | | | +--------+-------+ +--------+-------+ | | | | | +-----------------+-------------------------+----------------+ | v +------------------------+ | ESP32 | | | | Sensor Reading | | Wi-Fi Communication | | Local Alarm | +-----------+------------+ | +-----------+------------+ | | v v +---------------+ +------------------+ | PHP IoT API | | ThingSpeak Cloud | +-------+-------+ +------------------+ | v +---------------+ | MySQL Database| +-------+-------+ | v +---------------+ | IoT Webpage | | Dashboard | +---------------+ ESP32 | v n8n Webhook | v AI Agent | +------------------+ | | v v Telegram Alert Google Sheets | v Voice Notification
4. Hardware Components List
| Component | Quantity | Purpose |
|---|---|---|
| ESP32 DevKit V1 | 1 | Main IoT controller |
| YF-S201 Water Flow Sensor | 1 or more | Measures water flow |
| Water Leakage Sensor | 1 or more | Detects physical water presence |
| DS18B20 Temperature Sensor | 1 | Measures pipe temperature |
| HC-SR04 Ultrasonic Sensor | Optional | Measures tank water level |
| Buzzer | 1 | Local warning |
| Red LED | 1 | Leakage indication |
| Green LED | 1 | Normal operation indication |
| OLED Display | 1 | Local data display |
| 5V Power Supply | 1 | Power source |
| Waterproof Enclosure | 1 | Protects electronics |
5. ESP32 Pin Configuration
| ESP32 Pin | Component |
|---|---|
| GPIO 27 | Water Flow Sensor Signal |
| GPIO 34 | Leakage Sensor Analog Output |
| GPIO 4 | DS18B20 Temperature Sensor |
| GPIO 5 | Buzzer |
| GPIO 2 | Red LED |
| GPIO 15 | Green LED |
| GPIO 21 | OLED SDA |
| GPIO 22 | OLED SCL |
6. Circuit Schematic Diagram
+----------------------+
| ESP32 |
| |
| GPIO27 <-------------| FLOW SENSOR
| |
| GPIO34 <-------------| LEAK SENSOR
| |
| GPIO4 <-------------| DS18B20
| |
| GPIO5 --------------> BUZZER
| |
| GPIO2 --------------> RED LED
| |
| GPIO15 --------------> GREEN LED
| |
| GPIO21 <-------------> OLED SDA
| GPIO22 <-------------> OLED SCL
| |
| 3.3V ---------------> SENSOR VCC
| GND ----------------> COMMON GROUND
+----------------------+
+------------------+
| WATER FLOW SENSOR|
+------------------+
VCC ----------> ESP32 VCC
GND ----------> ESP32 GND
SIGNAL --------> GPIO27
+------------------+
| LEAK SENSOR |
+------------------+
VCC ----------> ESP32 VCC
GND ----------> ESP32 GND
ANALOG --------> GPIO34
+------------------+
| DS18B20 SENSOR |
+------------------+
VCC ----------> 3.3V
GND ----------> GND
DATA ----------> GPIO4
Water and electricity must be properly isolated. Use waterproof connectors, insulated wiring, low-voltage DC power, fuse protection, and a waterproof enclosure.
7. Complete System Flowchart
8. Water Leakage Detection Logic
Continuous Flow Detection
``` IF flow_rate > minimum_flow AND flow continues for a long duration AND no expected water usage is detected THEN ``` Possible Water Leakage
Sudden Water Flow Detection
``` Previous Flow = 0 L/min Current Flow = 20 L/min IF sudden_flow_change > threshold THEN ``` Possible Pipe Burst
Physical Leakage Sensor Detection
``` IF leak_sensor_value > threshold THEN ``` Immediate Water Leakage Alert```
9. Complete ESP32 Source Code
```
#include
#include
#include
#include
const char* WIFI_SSID =
"YOUR_WIFI_NAME";
const char* WIFI_PASSWORD =
"YOUR_WIFI_PASSWORD";
const char* SERVER_URL =
"http://YOUR_SERVER_ADDRESS/water-leakage/api/receive_data.php";
const char* THINGSPEAK_API_KEY =
"YOUR_THINGSPEAK_WRITE_API_KEY";
const char* THINGSPEAK_URL =
"http://api.thingspeak.com/update";
#define FLOW_SENSOR_PIN 27
#define LEAK_SENSOR_PIN 34
#define TEMP_SENSOR_PIN 4
#define BUZZER_PIN 5
#define RED_LED_PIN 2
#define GREEN_LED_PIN 15
OneWire oneWire(TEMP_SENSOR_PIN);
DallasTemperature temperatureSensor(
&oneWire
);
volatile unsigned long pulseCount = 0;
float flowRate = 0.0;
float totalLiters = 0.0;
float temperature = 0.0;
unsigned long lastTime = 0;
unsigned long lastSendTime = 0;
const float FLOW_CALIBRATION = 7.5;
const float MIN_LEAK_FLOW = 0.5;
const unsigned long LEAK_TIME_LIMIT =
300000;
unsigned long continuousFlowStart = 0;
void IRAM_ATTR pulseCounter()
{
pulseCount++;
}
void setup()
{
Serial.begin(115200);
```
pinMode(
FLOW_SENSOR_PIN,
INPUT_PULLUP
);
pinMode(
LEAK_SENSOR_PIN,
INPUT
);
pinMode(
BUZZER_PIN,
OUTPUT
);
pinMode(
RED_LED_PIN,
OUTPUT
);
pinMode(
GREEN_LED_PIN,
OUTPUT
);
digitalWrite(
BUZZER_PIN,
LOW
);
digitalWrite(
RED_LED_PIN,
LOW
);
digitalWrite(
GREEN_LED_PIN,
HIGH
);
temperatureSensor.begin();
attachInterrupt(
digitalPinToInterrupt(
FLOW_SENSOR_PIN
),
pulseCounter,
RISING
);
WiFi.begin(
WIFI_SSID,
WIFI_PASSWORD
);
while (
WiFi.status()
!= WL_CONNECTED
)
{
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println(
"WiFi Connected"
);
Serial.println(
WiFi.localIP()
);
lastTime = millis();
```
}
void loop()
{
readFlowData();
```
readTemperature();
detectLeakage();
if (
millis()
-
lastSendTime
>=
30000
)
{
sendDataToPHP();
sendDataToThingSpeak();
lastSendTime =
millis();
}
delay(1000);
```
}
void readFlowData()
{
unsigned long currentTime =
millis();
```
if (
currentTime
-
lastTime
>=
1000
)
{
noInterrupts();
unsigned long pulses =
pulseCount;
pulseCount = 0;
interrupts();
flowRate =
pulses
/
FLOW_CALIBRATION;
float litersPerSecond =
flowRate
/
60.0;
totalLiters +=
litersPerSecond;
Serial.print(
"Flow Rate: "
);
Serial.print(
flowRate
);
Serial.println(
" L/min"
);
lastTime =
currentTime;
}
```
}
void readTemperature()
{
temperatureSensor.requestTemperatures();
```
temperature =
temperatureSensor.getTempCByIndex(
0
);
```
}
void detectLeakage()
{
int leakValue =
analogRead(
LEAK_SENSOR_PIN
);
```
bool physicalLeakDetected =
leakValue > 1500;
bool continuousFlow =
flowRate > MIN_LEAK_FLOW;
if (
continuousFlow
)
{
if (
continuousFlowStart
==
0
)
{
continuousFlowStart =
millis();
}
}
else
{
continuousFlowStart =
0;
}
bool longContinuousFlow =
continuousFlowStart > 0
&&
millis()
-
continuousFlowStart
>
LEAK_TIME_LIMIT;
if (
physicalLeakDetected
||
longContinuousFlow
)
{
digitalWrite(
RED_LED_PIN,
HIGH
);
digitalWrite(
GREEN_LED_PIN,
LOW
);
digitalWrite(
BUZZER_PIN,
HIGH
);
Serial.println(
"POSSIBLE WATER LEAKAGE"
);
}
else
{
digitalWrite(
RED_LED_PIN,
LOW
);
digitalWrite(
GREEN_LED_PIN,
HIGH
);
digitalWrite(
BUZZER_PIN,
LOW
);
}
```
}
void sendDataToPHP()
{
if (
WiFi.status()
!=
WL_CONNECTED
)
{
return;
}
```
HTTPClient http;
http.begin(
SERVER_URL
);
http.addHeader(
"Content-Type",
"application/json"
);
String jsonData =
"{";
jsonData +=
"\"device_id\":\"ESP32_WATER_001\",";
jsonData +=
"\"flow_rate\":"
+
String(flowRate)
+
",";
jsonData +=
"\"total_liters\":"
+
String(totalLiters)
+
",";
jsonData +=
"\"temperature\":"
+
String(temperature)
+
",";
jsonData +=
"\"leak_sensor\":"
+
String(
analogRead(
LEAK_SENSOR_PIN
)
);
jsonData +=
"}";
int httpCode =
http.POST(
jsonData
);
Serial.println(
httpCode
);
http.end();
```
}
void sendDataToThingSpeak()
{
if (
WiFi.status()
!=
WL_CONNECTED
)
{
return;
}
```
HTTPClient http;
String url =
String(
THINGSPEAK_URL
)
+
"?api_key="
+
THINGSPEAK_API_KEY
+
"&field1="
+
String(
flowRate
)
+
"&field2="
+
String(
totalLiters
)
+
"&field3="
+
String(
temperature
)
+
"&field4="
+
String(
analogRead(
LEAK_SENSOR_PIN
)
);
http.begin(
url
);
int httpCode =
http.GET();
Serial.println(
httpCode
);
http.end();
```
}
10. PHP and MySQL Backend Architecture
``` water-leakage/ ├── index.php ├── dashboard.php ├── config.php ├── api/ │ ├── receive_data.php │ ├── get_latest_data.php │ └── get_history.php ├── database/ │ └── water_leakage.sql ├── css/ │ └── style.css └── js/ ``` └── dashboard.js```
11. MySQL Database
```
CREATE DATABASE water_leakage;
USE water_leakage;
CREATE TABLE sensor_data (
```
id INT AUTO_INCREMENT PRIMARY KEY,
device_id VARCHAR(100),
flow_rate FLOAT,
total_liters FLOAT,
temperature FLOAT,
leak_sensor INT,
leakage_status VARCHAR(50),
ai_probability FLOAT,
created_at TIMESTAMP
DEFAULT CURRENT_TIMESTAMP
```
);
12. PHP Configuration File
```
connect_error
)
{
die(
"Database connection failed"
);
}
?>
13. PHP ESP32 API
```
"error",
```
"message" =>
"Invalid JSON data"
]
);
exit;
```
}
$device_id =
$data["device_id"]
??
"UNKNOWN";
$flow_rate =
floatval(
$data["flow_rate"]
??
0
);
$total_liters =
floatval(
$data["total_liters"]
??
0
);
$temperature =
floatval(
$data["temperature"]
??
0
);
$leak_sensor =
intval(
$data["leak_sensor"]
??
0
);
$leakage_status =
"NORMAL";
if (
$flow_rate > 0.5
&&
$leak_sensor > 1500
)
{
$leakage_status =
"POSSIBLE_LEAKAGE";
}
$sql =
"
INSERT INTO sensor_data
(
device_id,
flow_rate,
total_liters,
temperature,
leak_sensor,
leakage_status
)
VALUES (?, ?, ?, ?, ?, ?)
";
$stmt =
$conn->prepare(
$sql
);
$stmt->bind_param(
"sdddis",
```
$device_id,
$flow_rate,
$total_liters,
$temperature,
$leak_sensor,
$leakage_status
```
);
$stmt->execute();
echo json_encode(
[
"status" =>
"success",
```
"leakage_status" =>
$leakage_status
]
```
);
?>
14. n8n Automation Workflow
``` ESP32 | v Webhook | v Receive JSON | v Calculate Leakage Risk | v AI Agent | v Leakage Probability | v IF Risk >= 60% | +---------------------+ | | v v Telegram Alert Google Sheets | | v v Voice Alert Data Logging | v Maintenance Action```
n8n Workflow JSON
```
{
"name":
"AI Water Leakage Detection",
```
"nodes":
[
{
"name":
"ESP32 Webhook",
"type":
"n8n-nodes-base.webhook",
"parameters":
{
"path":
"water-leakage",
"httpMethod":
"POST"
}
},
{
"name":
"Calculate Leakage Risk",
"type":
"n8n-nodes-base.code",
"parameters":
{
"jsCode":
"const data = $json.body || $json;
let risk = 0;
if (data.flow_rate > 0.5)
{
risk += 25;
}
if (data.leak_sensor > 1500)
{
risk += 50;
}
if (data.flow_rate > 5)
{
risk += 25;
}
return [{
json: {
...data,
leakage_probability: risk,
timestamp:
new Date().toISOString()
}
}];"
}
},
{
"name":
"Leakage Detected?",
"type":
"n8n-nodes-base.if",
"parameters":
{
"condition":
"leakage_probability >= 60"
}
},
{
"name":
"Telegram Alert",
"type":
"n8n-nodes-base.telegram",
"parameters":
{
"text":
"WATER LEAKAGE ALERT"
}
},
{
"name":
"Google Sheets Log",
"type":
"n8n-nodes-base.googleSheets",
"parameters":
{
"operation":
"append"
}
}
]
```
}
15. Telegram Bot Setup
- Open Telegram.
- Search for BotFather.
- Send: /start
- Send: /newbot
- Enter the bot name.
- Enter a unique bot username.
- Copy the generated bot token.
- Configure the token inside n8n.
``` WATER LEAKAGE DETECTED Device: ESP32_WATER_001 Flow Rate: 5.8 L/min Leakage Probability: 94% Action: Inspect the water pipeline immediately.```
16. Voice Notification Automation
``` Leakage Detected | v AI Creates Alert Text | v Text-to-Speech Service | v Generate Audio File | v Telegram Send Voice Message```
Example voice message:
17. Google Sheets Integration
Create a Google Sheet with the following columns:
| Column | Description |
|---|---|
| Timestamp | Event time |
| Device ID | ESP32 device identity |
| Flow Rate | Current water flow |
| Total Liters | Total water consumption |
| Temperature | Pipe temperature |
| Leak Sensor | Leakage sensor value |
| AI Probability | Leakage probability |
| AI Decision | Normal or Leakage |
18. ThingSpeak Cloud Dashboard Setup
| Field | Data |
|---|---|
| Field 1 | Flow Rate |
| Field 2 | Total Water Consumption |
| Field 3 | Temperature |
| Field 4 | Leakage Sensor |
| Field 5 | AI Leakage Probability |
| Field 6 | Daily Consumption Prediction |
19. AI Leakage Detection Logic
``` Current Flow Rate + Historical Average Flow + Flow Duration + Time of Day + Leak Sensor Value + Daily Water Consumption | v AI Agent Analysis | v Leakage Probability | +----------------------+ | | v v Normal Usage Possible Leakage | | v v Data Logging Telegram Alert | v Voice Alert```
Example AI Decision
Flow Rate: 5.8 L/min
Time: 02:30 AM
Historical Average: 0.2 L/min
Leakage Probability: 94%
Recommendation: Immediately inspect the main water pipeline.
20. AI Water Consumption Prediction
``` Average Daily Consumption = ## Total Water Used Number of Days```
``` IF current_usage > historical_average * 1.5 THEN HIGH CONSUMPTION ALERT```
Example
``` Historical Average = 800 Liters Threshold = 800 x 1.5 Threshold = 1200 Liters Current Consumption = 1500 Liters Result: ABNORMAL WATER CONSUMPTION
21. Complete End-to-End Data Flow
``` Water Flow | v Flow Sensor | v ESP32 | +--------------------> Local Buzzer | +--------------------> PHP API | | | v | MySQL Database | | | v | IoT Web Dashboard | +--------------------> ThingSpeak | +--------------------> n8n Webhook | v AI Agent | v Leakage Probability | +-------------+-------------+ | | | v v v Telegram Voice Alert Google Sheets Message Audio Alert Data Logging
22. Step-by-Step Installation
Step 1: Hardware Installation
Connect the water flow sensor, leakage sensor, temperature sensor, buzzer, LEDs, and optional ultrasonic sensor to the ESP32.
Step 2: ESP32 Programming
Install Arduino IDE and ESP32 board support. Install required libraries. Configure Wi-Fi and API credentials. Upload the ESP32 program.
Step 3: Web Server Setup
Install Apache, PHP, and MySQL. Copy the project files to the server. Create the water_leakage database.
Step 4: API Testing
Send test JSON data to the PHP API and confirm that the data is inserted into the MySQL database.
Step 5: n8n Configuration
Configure the webhook, AI Agent, IF condition, Telegram node, voice notification node, and Google Sheets node.
Step 6: ThingSpeak Configuration
Create a ThingSpeak channel and configure the required fields.
Step 7: Complete Testing
Test normal flow, small leakage, continuous flow, and pipe burst conditions.
```23. Testing Procedure
| Test | Input | Expected Result |
|---|---|---|
| Normal Condition | Flow = 0 | Normal Status |
| Small Leakage | Low Continuous Flow | Warning Alert |
| Major Leakage | High Flow | Telegram + Voice Alert |
| Pipe Burst | Sudden Very High Flow | Critical Alert |
24. Security Recommendations
Never expose Wi-Fi passwords, Telegram bot tokens, ThingSpeak API keys, database passwords, or AI API keys inside public source code.
Use environment variables, server-side configuration, HTTPS, authentication, and encrypted credentials.
25. Future Enhancements
Automatic Water Valve Control
Add a relay and solenoid valve. Automatically close the main water supply when critical leakage is detected.
Multiple ESP32 Nodes
Install sensors in kitchens, bathrooms, gardens, tanks, and industrial pipelines.
Predictive Maintenance
Predict pipe degradation, repeated leakage, increasing water usage, and possible future failures.
Mobile Application
Create Android, iOS, Flutter, or React Native applications.
AI Voice Assistant
Ask the AI system: "Is there any water leakage?"
26. Final Project Summary
This project combines ESP32, IoT sensors, Wi-Fi, PHP, MySQL, n8n automation, AI Agent technology, Telegram notifications, voice alerts, Google Sheets, and ThingSpeak cloud monitoring.
The result is an intelligent Agentic IoT water management platform capable of monitoring water flow, detecting leakage, analyzing abnormal usage, predicting consumption, and automatically notifying users.

No comments:
Post a Comment