Siddhant Kumar
Project 082 · Smart City

Water Pipeline Leak Detector.

Uses pressure analytics across the water network to find leaks that waste an enormous share of treated water — pinpointing roughly where a pipe is losing, not just that the system leaks.

Advanced 14–22 hours 29 min read WaterPressureCity
Jump to source Bill of materials
Water Pipeline Leak Detector — reference build illustration MCU VCC · GND · SIG · NC
Difficulty
Advanced
Build time
14–22 hours
Indicative cost
₹8,000 – ₹14,000 (multi-node)
Platform
ESP32 DevKit V1 (ESP-WROOM-32)
Category
Smart City
Last updated
28 July 2026
Contents — 26 sections

Project Overview

Uses pressure analytics across the water network to find leaks that waste an enormous share of treated water — pinpointing roughly where a pipe is losing, not just that the system leaks.

Water utilities lose a staggering amount of treated water to leaks — often a fifth to a third of everything pumped, so-called non-revenue water — and most of it drips away underground, unseen, for years. A burst main is obvious; the slow, hidden leaks that add up to the biggest losses are not, and finding them across kilometres of buried pipe is the hard part. This project attacks that with pressure analytics: pressure sensors across the network, and the insight that leaks leave a signature in how pressure behaves — so you can detect that a district is leaking and narrow down roughly where.

The physics is the lever. A leak is a continuous loss of water and pressure, so it shows up in the pressure field: a district with a leak has a characteristically lower and differently-behaving pressure than a healthy one, and the pattern of pressures across sensors, especially at night when legitimate demand is low, reveals leakage that daytime demand masks. Sudden pressure transients mark a new burst; a persistent depression localises to the leaking area. Combined with district metering (comparing water flowing into a zone against what is legitimately consumed — the difference is loss), pressure analytics can both quantify leakage and point to the district, and sometimes the stretch, where it is happening.

The nodes are pressure sensors at hydrants, valves and district boundaries, reporting over LoRa/cellular (buried infrastructure has no power or network), with analytics that compare pressures across the network and over time. The output is not "somewhere there's a leak" but "district 7 is losing ~X, concentrated toward the north end" — enough to send a crew with acoustic gear to the right place instead of the whole city. It is honest that pressure analytics localises rather than pinpoints to the exact fitting (final location needs acoustic correlation), that good results need adequate sensor density and modelling, and that this is one layer of a leakage-management programme. But as a pressure-analytics leak detector, it directs scarce leak-hunting effort at the districts and stretches actually losing water — turning a huge, invisible, expensive loss into a findable, prioritised one.

A city skyline at night
Pressure analytics across the network finds the hidden leaks that waste a third of treated water. Photograph sourced from Wikimedia Commons — Smart city.jpg. Reused under the licence stated on that page; please check it before republishing.

What this project does

  • Senses pressure across the water network at key points
  • Detects leakage from pressure behaviour (especially at night)
  • Localises leaks to a district/stretch (pressure pattern + transients)
  • Combines with district metering (inflow vs consumption = loss)
  • Quantifies non-revenue water and prioritises leak hunting
  • Reports over LoRa/cellular from buried, powerless infrastructure
  • Directs crews with acoustic gear to the right area

Real-World Applications

SettingHow it is used
Utility leakage managementDetecting/localising leaks to cut non-revenue water across a network.
District metered areas (DMA)Zone-level inflow-vs-consumption and pressure analytics.
Burst detectionCatching new bursts from pressure transients quickly.
Water-efficiency programmesPrioritising leak repair by quantified loss.

Deployment contexts where a build of this kind earns its keep.

Features & Capabilities

  • Pressure-analytics leak detection
  • Night-flow/minimum-pressure analysis
  • District localisation (not just "somewhere")
  • District metering integration (NRW quantification)
  • Burst-transient detection
  • LoRa/cellular for buried infrastructure
  • Honest: localises, acoustic gear pinpoints

Difficulty, Time & Required Skills

AttributeValue
Difficulty levelAdvanced
Estimated completion time14–22 hours
Indicative build cost₹8,000 – ₹14,000 (multi-node)
Primary disciplineSmart City
Reference platformESP32 DevKit V1 (ESP-WROOM-32)

Skills you should have (or will pick up)

  • Network pressure sensing (buried, powerless)
  • Pressure-analytics leak detection and localisation
  • District metering and night-flow analysis
  • LoRa/cellular telemetry
  • Interpreting results for leak hunting

Bill of Materials

Every part below is commonly available from Indian and international hobby-electronics suppliers. Prices are indicative 2026 retail figures in Indian rupees and will drift — treat them as a budgeting guide, not a quotation.

ComponentKey specificationQtyApprox. cost
ESP32 DevKit V1 (ESP-WROOM-32)
Wi-Fi transmit bursts peak near 500 mA — size the regulator accordingly.
Dual-core Xtensa LX6 @ 240 MHz, 520 KB SRAM, 4 MB flash, Wi-Fi 802.11 b/g/n + BLE 4.2, 34 GPIO, 18× 12-bit ADC, 2× 8-bit DAC1₹450
ZMPT101B AC voltage sensor
Trim the on-board pot so the idle output sits exactly at Vcc/2.
0–250 VAC input, 2 mA:2 mA precision transformer, ±1 % linearity1₹220
DS18B20 waterproof temperature probe
Dozens can share one GPIO — you address them by ROM code.
−55 to +125 °C, ±0.5 °C from −10 to +85 °C, 9–12-bit resolution, unique 64-bit ROM ID1₹160
SX1278 LoRa 433 MHz module (Ra-02)
Never power the radio without an antenna — the PA will destroy itself.
−148 dBm sensitivity, +20 dBm output, up to 10 km line of sight, SF7–SF121₹480
SIM800L GSM/GPRS module
Transmit bursts hit 2 A — needs a 4.0 V supply and a 1000 µF bulk capacitor.
Quad-band 850/900/1800/1900 MHz, GPRS class 12, SMS + TCP/IP1₹550
20 W 12 V polycrystalline solar panel
Rated watts assume 1000 W/m² — plan for 60–70 % of nameplate in real installs.
Vmp 17.5 V, Imp 1.14 A, Voc 21.6 V, 350 × 290 mm, aluminium frame1₹1,200
TP4056 Li-ion charger + DW01 protection
Buy the version *with* protection ICs — the bare charger will over-discharge your cell.
1 A programmable CC/CV charge to 4.2 V ±1 %, over-discharge and short protection1₹45
18650 Li-ion cell 3400 mAh + holder
Never charge below 0 °C; always use a protected cell or a BMS.
3.7 V nominal, 4.2 V full, 3400 mAh, ~12.6 Wh, 2 C discharge1₹450
Pressure transducer (network)
Multiple points enable localisation
Pressure sensor at hydrant/valve/DMA boundary (rated for the main)6₹7,200
DMA flow meterZone inflow metering for non-revenue-water quantification1₹3,000
Battery + LoRa/cellularBuried infrastructure has no power/network1₹700
Analytics platformServer correlating pressures/flows to detect/localise leaks1

Estimated total: ₹14,455, excluding tools, shipping and consumables.

Tools and consumables

  • Soldering iron (temperature controlled, 350 °C) with 0.8 mm 60/40 or lead-free solder
  • Digital multimeter — continuity, DC volts and current ranges
  • Wire strippers, flush cutters and a small set of precision screwdrivers
  • Heat-shrink tubing and a heat gun (or a lighter, carefully)
  • A laptop with a USB port and the toolchain listed above

Hardware Specifications

PartSpecificationSupplyInterfaceReference
ESP32 DevKit V1 (ESP-WROOM-32)Dual-core Xtensa LX6 @ 240 MHz, 520 KB SRAM, 4 MB flash, Wi-Fi 802.11 b/g/n + BLE 4.2, 34 GPIO, 18× 12-bit ADC, 2× 8-bit DAC3.3 V logic / 5 V USBUART, SPI, I²C, I²S, CAN, PWMDatasheet
ZMPT101B AC voltage sensor0–250 VAC input, 2 mA:2 mA precision transformer, ±1 % linearity5 VAnalogueDatasheet
DS18B20 waterproof temperature probe−55 to +125 °C, ±0.5 °C from −10 to +85 °C, 9–12-bit resolution, unique 64-bit ROM ID3.0–5.5 V1-Wire (multi-drop)Datasheet
SX1278 LoRa 433 MHz module (Ra-02)−148 dBm sensitivity, +20 dBm output, up to 10 km line of sight, SF7–SF123.3 VSPIDatasheet
SIM800L GSM/GPRS moduleQuad-band 850/900/1800/1900 MHz, GPRS class 12, SMS + TCP/IP3.4–4.4 V (NOT 5 V)UART AT commandsDatasheet
20 W 12 V polycrystalline solar panelVmp 17.5 V, Imp 1.14 A, Voc 21.6 V, 350 × 290 mm, aluminium frame12 V nominalMC4 / screw terminalsDatasheet
TP4056 Li-ion charger + DW01 protection1 A programmable CC/CV charge to 4.2 V ±1 %, over-discharge and short protection4.5–5.5 V inmicro-USB / padsDatasheet
18650 Li-ion cell 3400 mAh + holder3.7 V nominal, 4.2 V full, 3400 mAh, ~12.6 Wh, 2 C discharge3.0–4.2 VHolder / spot-welded tabsDatasheet

Consolidated electrical and interface specifications for every active part in the build.

Power Budget & Supply Sizing

Add up the typical active current of every part, then size the supply with at least 50 % headroom so transmit bursts and motor inrush never brown out the controller.

LoadSupply railTypical current (mA)Notes
ESP32 DevKit V1 (ESP-WROOM-32)3.3 V logic / 5 V USB160Wi-Fi transmit bursts peak near 500 mA — size the regulator accordingly.
ZMPT101B AC voltage sensor5 V20Trim the on-board pot so the idle output sits exactly at Vcc/2.
DS18B20 waterproof temperature probe3.0–5.5 V1.5Dozens can share one GPIO — you address them by ROM code.
SX1278 LoRa 433 MHz module (Ra-02)3.3 V120Never power the radio without an antenna — the PA will destroy itself.
SIM800L GSM/GPRS module3.4–4.4 V (NOT 5 V)2000Transmit bursts hit 2 A — needs a 4.0 V supply and a 1000 µF bulk capacitor.
20 W 12 V polycrystalline solar panel12 V nominal1140Rated watts assume 1000 W/m² — plan for 60–70 % of nameplate in real installs.
TP4056 Li-ion charger + DW01 protection4.5–5.5 V in1000Buy the version *with* protection ICs — the bare charger will over-discharge your cell.

Summed typical draw is 4441.5 mA. With a 1.5× design margin the supply should deliver at least 6700 mA continuously at the stated rail voltage.

Software Requirements & Development Environment

Reference toolchain: Arduino IDE 2.3.x with the ESP32 board package 3.x (or PlatformIO on VS Code). Anything newer normally works; anything older may lack the board definitions used here.

  • Install the Arduino IDE 2.3.x (or PlatformIO if you prefer a real editor and dependency locking).
  • Add https://espressif.github.io/arduino-esp32/package_esp32_index.json under File → Preferences → Additional Board Manager URLs, then install esp32 from the Boards Manager.
  • Set the correct port under Tools → Port. On Linux add yourself to the dialout group: sudo usermod -aG dialout $USER and log out and back in.
  • Open the Serial Monitor at 115200 baud — every sketch here logs its state there.
  • Keep File → Preferences → Show verbose output during: compilation switched on while you are debugging build errors.

Required libraries

LibraryWhy it is neededInstall
WiFi (ESP32 core) bundledStation/AP connection management for the ESP32.Bundled with the ESP32 Arduino core
LoRa (sandeepmistry) 0.8.0SX127x radio configuration, packet TX/RX and callbacks.Library Manager → "LoRa" by Sandeep Mistry
ArduinoJson 7.xZero-allocation JSON serialisation and parsing.Library Manager → "ArduinoJson" by Benoit Blanchon
Preferences (NVS) bundledWear-levelled key/value storage in ESP32 flash for settings.Bundled with the ESP32 core
NTPClient / configTime bundledWall-clock time from an NTP server for timestamping.Bundled (`configTime()` on ESP32)

Block Diagram

The block diagram shows the functional decomposition of the system — what senses, what decides, what acts, and where the data ends up.

Water Pipeline Leak Detector — system block diagramFunctional block diagram of the Water Pipeline Leak Detector system. SensePressurenetwork pointsDMA flowinflowAnalyseServerpressure patternNight/transientleak signatureLocaliseDistrict/stretchwhereNRWquantifyActPrioritisecrewsAcousticpinpointrightrightnone
Water Pipeline Leak Detector — system block diagram

Circuit Diagram & Wiring

Every signal line in the build is shown below, followed by a pin-by-pin connection table you can work through with a multimeter in hand.

Water Pipeline Leak Detector — wiring schematicConnection schematic showing which controller pin drives each peripheral. Sensors / InputsControllerActuators / OutputsESP32 DevKit V1(ESP-WROOM-32)3.3 V logic / 5 V USBPressure transducerGPIO 34 (ADC)Network pressureTempGPIO 4CompensationLoRa/cellularSPI/UARTPressure reportSolar + TP40563V3 regCharged supplyBattery senseGPIO 35SupervisionStatus LEDGPIO 2Health
Water Pipeline Leak Detector — wiring schematic
PeripheralPeripheral pinController pinSignal
Pressure transducer4-20mA/AOUTGPIO 34 (ADC)Network pressure
TempDQGPIO 4Compensation
LoRa/cellularbusSPI/UARTPressure report
Solar + TP4056OUT3V3 regCharged supply
Battery senseADCGPIO 35Supervision
Status LEDINGPIO 2Health

Wire one row at a time and tick it off — most "it does not work" reports trace back to a single swapped pair.

Wiring explanation

  • Fit pressure transducers rated for the main at hydrants, valves and DMA boundaries; multiple points enable localisation.
  • Sample frequently enough to catch pressure transients (bursts) as well as slow trends.
  • Battery + LoRa/cellular and solar where possible — buried water infrastructure has no power/network.
  • Integrate a DMA inflow meter for non-revenue-water quantification (inflow vs legitimate consumption).
  • Analytics run on a server correlating pressures/flows across the network and over time (especially at night).
An ESP32 development board with the ESP-WROOM-32 module and USB connector
ESP32 pressure nodes report from buried, powerless infrastructure over LoRa/cellular on solar. Photograph sourced from Wikimedia Commons — ESP32 Espressif ESP-WROOM-32 Dev Board.jpg. Reused under the licence stated on that page; please check it before republishing.

System Architecture

Read the stack from the bottom up: physical hardware, the firmware that drives it, the transport that moves data off the device, and the software a human actually looks at.

Water Pipeline Leak Detector — architecture stackLayered architecture from hardware to user interface. Hardware layerESP32 DevKit V1 (ESP-WROOM-32) · ZMPT101B AC voltage sensor · DS18B20waterproof temperature probeDriver layerwifi · lorolib · arduinojson · preferencesApplication logicsampling loop · filtering · thresholds · state machineTransport layerLoRa/cellular → leakage-analytics platform · TLS · retry and backoffPresentation layerdashboard · mobile notifications · historical charts
Water Pipeline Leak Detector — architecture stack

Working Principle

The scale of the problem is what motivates a network approach: water utilities routinely lose a fifth to a third of treated water to leaks — non-revenue water — and the bulk of it is not dramatic bursts but slow, hidden leaks dripping away underground for years. The challenge is that these leaks are invisible and spread across kilometres of buried pipe, so the question is not usually "is the system leaking?" (it is) but "where, and how much, so we can fix the biggest ones first?". Digging up the whole network is impossible; the value is in localising the loss so scarce leak-hunting effort goes to the right place.

Pressure is the signal that makes this possible, because a leak is fundamentally a continuous loss of water and therefore leaves a signature in the pressure field. A district with significant leakage runs at a characteristically lower pressure and responds differently to demand than a tight one; a new burst causes a sudden pressure transient that propagates through the network; and a persistent, localised pressure depression points toward the leaking area. Reading the pattern of pressures across multiple sensors, and how it changes, converts an invisible underground loss into an observable, analysable phenomenon — you cannot see the leak, but you can see its effect on pressure.

The single most powerful technique is night analysis. During the day, legitimate consumption dominates the flow and pressure picture and masks leakage; but in the small hours, when almost no one is using water, whatever is still flowing and depressing pressure is overwhelmingly leakage. So the minimum night flow into a district, and the night-time pressure behaviour, are direct measures of how much that district leaks — a healthy zone goes quiet at night, a leaky one does not. Combined with district metering — comparing the metered inflow to a zone against the legitimate consumption within it, the difference being loss — pressure analytics both quantifies the leakage (litres per hour of non-revenue water) and, from the pressure pattern, localises it to a district and often a stretch.

The honest output and deployment shape complete the picture. The system does not pinpoint the exact leaking fitting — pressure analytics localises to an area, and the final metres are found by a crew with acoustic correlation gear (listening for the leak's sound) sent to that area rather than roaming the city. That division of labour — analytics to narrow it down, acoustics to pinpoint — is what makes leak hunting tractable and cheap. The nodes themselves must live in buried, powerless infrastructure, so they are battery-powered and report over LoRa or cellular, and good results depend on adequate sensor density and modelling. The design is candid that this is one layer of a broader leakage-management programme, and that localisation quality scales with how many pressure points you have. But the contribution is exactly what utilities need: turning a huge, invisible, expensive loss into a quantified, prioritised, localised one — telling you which districts and stretches are actually bleeding water, so you fix the biggest losses first instead of guessing.

The maths behind it

Minimum night flow (leakage)

plainMinimum night flow (leakage)
At night, legitimate demand ≈ 0, so residual flow ≈ leakage:

  leakage ≈ min_night_flow(zone) − small legitimate night use

A healthy zone goes quiet at night; a leaky one keeps
flowing/depressing pressure → measure it in the small hours.

District metering (non-revenue water)

plainDistrict metering (non-revenue water)
NRW(zone) = inflow − legitimate consumption

  inflow from the DMA meter; consumption from billed use.
  the difference is loss (leakage + theft + meter error).
Quantifies how much each district is losing.

Pressure localisation

plainPressure localisation
A leak depresses/behaves-differently in the pressure field:

  compare pressures across sensors vs a healthy baseline/model
  a persistent local depression → leak in that area
  a sudden transient → new burst; timing across sensors hints
    at direction. Localises to a district/stretch (not exact).

Program Flowchart

The firmware is a single cooperative loop. Nothing blocks for long, so networking, sensing and the user interface all stay responsive.

Water Pipeline Leak Detector — firmware flowchartControl flow through the main program loop. Sense pressure (and DMA flow)Report to analyticsNight min-flow / pressureanomaly?Flag leakage; localise districtTrendFlag leakage; localisedistrictTrendQuantify NRW; prioritiseDispatch acoustic pinpointing
Water Pipeline Leak Detector — firmware flowchart

Assembly Instructions

Build on a breadboard first and only commit to solder once the whole system has run for an hour without a fault.

  1. Deploy pressure sensing and metering

    Fit pressure transducers at hydrants/valves/DMA boundaries (rated for the main) and a DMA inflow meter, battery-powered with LoRa/cellular and solar where possible.

    Sample fast enough for transients and log/report to the analytics server.

  2. Set up analytics

    On the server, baseline healthy pressures, run night-flow and pressure-pattern analysis, and integrate district metering for non-revenue-water quantification.

  3. Localise and dispatch

    Localise leakage to a district/stretch, prioritise by quantified loss, and dispatch acoustic pinpointing to the right area.

Step-by-Step Implementation Guide

Work through these in order. Each step ends in something you can observe, so a failure is always localised to the step you just finished.

  1. Analyse night flow and pressure pattern

    Measure minimum night flow and compare district pressures to a healthy baseline to detect and localise leakage; catch transients for bursts.

    pythonleak-analytics.py
    def minimum_night_flow(inflow_series, night_window):
        night = inflow_series.between(*night_window)     # e.g. 02:00-04:00
        return night.min()                               # residual ~ leakage
    
    def leakage_estimate(dma):
        mnf = minimum_night_flow(dma.inflow, ("02:00","04:00"))
        legit_night = dma.expected_night_use              # small
        return max(0, mnf - legit_night)                  # L/h leakage
    
    def localise(pressures, baseline_model):
        # persistent local depression vs healthy model => leak area
        dev = {sid: p - baseline_model[sid] for sid, p in pressures.items()}
        worst = min(dev, key=dev.get)                     # most depressed sensor
        if dev[worst] < -PRESS_THRESH:
            return area_around(worst)                     # district/stretch
        return None
    
    def detect_burst(pressure_series):
        dP = pressure_series.diff()
        return (dP < -BURST_STEP).any()                   # sudden drop = burst
    def minimum_night_flow(The minimum night flow into a district is measured when legitimate demand is near zero, so the residual is essentially leakage.
    return max(0, mnf - legit_night) # L/h leakageSubtracting the small legitimate night use gives a direct quantitative leakage estimate for the district.
    worst = min(dev, key=dev.get) # most depressed sensorThe sensor most depressed below the healthy model localises the leak to its area — turning "somewhere" into a district/stretch.
    return (dP < -BURST_STEP).any() # sudden drop = burstA sudden pressure drop flags a new burst quickly, distinct from slow background leakage.
  2. Quantify NRW, prioritise and pinpoint

    Combine night flow and district metering to quantify non-revenue water per district, prioritise repairs by loss, and dispatch acoustic gear to the localised area for exact pinpointing.

Complete Source Code

The listing below is complete and compiles as written — there are no elided sections. Read the annotations under each block before you upload it.

cpppipeline-pressure-node.ino
/* ═══════════════════════════════════════════════════════════════
   Water Pipeline Pressure Node — ESP32, LoRa/cellular, solar

   Reports network pressure (and catches bursts) for server-side leak
   analytics: night-flow/pressure-pattern localises leakage to a
   district/stretch, quantified with district metering. Acoustic gear
   pinpoints the exact leak.
   ══════════════════════════════════════════════════════════════════ */

#include <LoRa.h>
#include <SPI.h>
#include <Preferences.h>
#include <math.h>

#define PIN_PRESSURE 34
#define P_FS 16.0f            // bar full-scale
#define BURST_STEP 0.5f       // bar sudden drop = burst
#define NODE_ID 7
#define SLEEP_S 300           // 5 min (faster if a transient)

Preferences prefs;
RTC_DATA_ATTR float prevP = NAN;

float readPressureBar(){
  long s=0; for(int i=0;i<64;i++) s+=analogRead(PIN_PRESSURE);
  return (s/64.0f)/4095.0f * P_FS;
}

void report(float p, bool burst){
  LoRa.beginPacket();
  LoRa.printf("{\"node\":%d,\"bar\":%.2f,\"burst\":%d}",
              NODE_ID, p, burst?1:0);
  LoRa.endPacket();
}

void setup(){
  Serial.begin(115200);
  analogSetPinAttenuation(PIN_PRESSURE, ADC_11db);
  SPI.begin(); LoRa.setPins(5,14,2); LoRa.begin(433E6); LoRa.setSpreadingFactor(10);

  float p = readPressureBar();
  bool burst = !isnan(prevP) && (p - prevP) < -BURST_STEP;   // sudden drop
  prevP = p;
  report(p, burst);

  // sample faster briefly after a suspected burst
  uint32_t sleep_s = burst ? 30 : SLEEP_S;
  esp_sleep_enable_timer_wakeup((uint64_t)sleep_s*1000000ULL);
  esp_deep_sleep_start();
}
void loop(){}
float readPressureBar()Averages many ADC samples for a stable network-pressure reading, the raw signal the server's leak analytics work on.
bool burst = !isnan(prevP) && (p - prevP) < -BURST_STEP; // sudden dropA sudden pressure drop between reads flags a possible new burst, which the node reports immediately.
uint32_t sleep_s = burst ? 30 : SLEEP_S;After a suspected burst the node samples faster to capture the event, then returns to a slow, battery-saving cadence.
esp_deep_sleep_start();Deep sleep between reads gives the long battery life a buried, powerless network node needs.
report(p, burst)The pressure (and burst flag) go to the server, where cross-sensor and night-flow analytics detect and localise leakage.

Configuration & Calibration

Configuration steps

  • Configure pressure transducers and sampling (fast enough for transients), and DMA inflow metering.
  • Set up server-side baselines, night windows, thresholds and localisation.
  • Configure LoRa/cellular reporting and battery/solar supervision.
  • Integrate consumption data for non-revenue-water quantification.

Calibration procedure

An uncalibrated sensor produces confident, precise, wrong numbers. Do this once per physical unit and record the constants.

  1. Pressure

    Calibrate transducers against a reference; verify readings across the network.

  2. Baselines/night

    Establish healthy pressure baselines and typical night flows so anomalies stand out.

  3. Localisation

    Validate localisation against known leaks/bursts; adjust density/model as needed.

Network Architecture & Connectivity

Water Pipeline Leak Detector — network topologyPath taken by telemetry from field node to end user. Edge nodesGatewayCloudClientsPressure nodeESP32DMA meterinflowLoRa / cellularCity gatewayto serverMQTTLeakage platformpressure + NRWDashboardleak mapCrewslocalise + pinpoint
Water Pipeline Leak Detector — network topology

Communication protocol

Nodes report pressure on a cadence (faster on transients); the server runs night-flow and pressure-pattern analytics and district metering to detect, quantify and localise leakage.

Topic / endpointDirectionPayload
water/node/<id>/pressurenode → serverpressure, burst flag
water/dma/<id>/flowmeter → serverinflow (NRW)
water/leak/alertserver → crewslocalised leakage + quantity

Message contract between the device and the broker.

Cloud platform configuration

A leakage platform maps pressures/flows, detects and localises leaks (night analysis, pressure pattern), quantifies non-revenue water, and prioritises repairs; crews pinpoint with acoustics.

Dashboard setup

A network map of pressures/leakage, district NRW, burst alerts, and prioritised repair list.

Mobile app integration

Burst and leakage alerts with localisation; repair priorities.

Security considerations

  • Authenticate node data; secure the analytics.
  • Supervise battery/health; alert on silent nodes.
  • Combine with acoustic pinpointing for final location.

Testing Procedure & Expected Output

Test from the bottom up. Confirm power, then each sensor in isolation, then the integrated loop — the first failing step tells you exactly where to look.

TestWhat you should see
Baseline a healthy districtStable pressures; low night flow
Induce/observe a leakHigher night flow / local pressure depression; localised to the district
Simulate a burstPressure transient flagged; node reports quickly
Compute NRW (inflow vs consumption)Loss quantified per district
Dispatch acoustic gearExact leak pinpointed in the localised area
Solar/battery cycleNodes report over a season; supervision works

Bench-test checklist. If a row fails, stop and fix it before moving on.

Expected output

The platform maps district pressures and night flows, flags/localises leakage, quantifies non-revenue water, and prioritises repairs; bursts alert quickly.

jsonpressure.json
{
  "node": 7,
  "bar": 2.9,
  "burst": 0
}

Node 7's pressure feeds analytics that, with its neighbours and the DMA night flow, localise leakage to a district and quantify it — directing a crew with acoustic gear to the right stretch instead of the whole city.

A Grafana time-series dashboard
Night-flow and pressure-pattern analytics localise and quantify leakage, directing crews to pinpoint it. Photograph sourced from Wikimedia Commons — Grafana dashboard.png. Reused under the licence stated on that page; please check it before republishing.

Troubleshooting: Common Errors & Fixes

Leaks not localised

Likely cause. Too few sensors / no model

Fix. Increase sensor density; baseline a healthy model; use night analysis

Daytime data misleading

Likely cause. Demand masks leakage

Fix. Analyse minimum night flow when legitimate demand is near zero

NRW not quantified

Likely cause. No district metering

Fix. Meter inflow vs consumption per DMA

Bursts missed

Likely cause. Sampling too slow

Fix. Sample fast enough for transients; report bursts immediately

Nodes die

Likely cause. Battery/power

Fix. Battery + LoRa/cellular + solar; deep sleep; supervise

The sketch will not upload — "Failed to connect" or "avrdude: stk500_recv()"

Likely cause. The bootloader is not being reached: wrong port, wrong board, a serial monitor holding the port open, or a USB cable that only carries power.

Fix. Close every serial monitor, confirm Tools → Board and Port, and swap to a known data-capable USB cable. On an ESP32 hold BOOT while the IDE prints "Connecting…", then release. If a peripheral is wired to the UART pins (GPIO 1/3 on ESP32, D0/D1 on Uno) unplug it — it fights the programmer.

The board resets in a loop, or the serial monitor prints "Brownout detector was triggered"

Likely cause. The supply cannot deliver peak current. Wi-Fi transmit bursts, relay coils and servos all pull far more than their average draw.

Fix. Power peripherals from a separate regulated supply with a common ground rather than from the board 5 V pin. Add a 470–1000 µF electrolytic capacitor across the supply near the load, and use a real power adapter rather than a laptop USB port.

Serial monitor shows garbage characters

Likely cause. Baud rate mismatch between Serial.begin() and the monitor, or a floating/shared UART line.

Fix. Set the monitor to 115200 to match the sketch. If it still garbles, the crystal or the USB bridge is being confused by noise — shorten the cable and keep motor wiring away from the USB lead.

Wi-Fi connects but MQTT never does (state -2)

Likely cause. Wrong broker address or port, a firewall in the way, or the broker requiring credentials the sketch is not sending.

Fix. Test from a laptop on the same network first: mosquitto_sub -h <broker> -t "#" -v. If that works, the problem is on the device — check the IP literal, port 1883 (or 8883 for TLS), and that client.setServer() runs before connect(). PubSubClient state codes are documented in its header.

Readings arrive for a while and then stop

Likely cause. The Wi-Fi or MQTT session dropped and the sketch never reconnects, or the broker dropped the client on keep-alive timeout.

Fix. Never assume the link stays up. Check WiFi.status() and client.connected() at the top of every loop and reconnect with exponential backoff. Add a watchdog so a wedged network stack reboots the device instead of going silent.

Performance Optimisation

  • Deep-sleep between pressure reads; sample faster on transients.
  • Run night-flow and pattern analytics on the server; combine with district metering.
  • Localise to a district/stretch; hand off to acoustics for pinpointing.
  • Quantify and prioritise by loss.
  • Replace every delay() with a millis() comparison — blocking delays are the single most common cause of dropped readings.
  • Sample sensors on a fixed cadence and publish on a slower one; you almost never need to transmit at the sampling rate.
  • Move networking into its own FreeRTOS task so a slow DNS lookup cannot stall the control loop.
  • Use uint8_t / uint16_t where the range allows; on an 8-bit AVR a 32-bit add costs four times as much.
  • Batch several samples into one MQTT publish. Radio time, not CPU time, dominates the energy budget.
  • Set the MQTT keep-alive to a value that matches your reporting interval so the broker does not churn reconnections.
  • For battery builds use deep sleep between samples: an ESP32 drops from ~160 mA awake to about 10 µA asleep, which is the difference between days and months of runtime.

Safety Precautions

  • Use pressure transducers rated for the main; install safely on live water infrastructure (qualified work).
  • Pressure analytics localises; final pinpointing needs acoustic correlation gear.
  • Buried infrastructure has no power/network — design battery + LoRa/cellular for long life.
  • This is one layer of a leakage-management programme.
  • Mains voltage kills. Anything on the load side of the relay is at 230 V. Do not work on a powered circuit, and never leave exposed mains wiring on a bench where someone could touch it.
  • Keep at least 6 mm of creepage between the mains and low-voltage sides of any board you make, and never route mains tracks under the microcontroller.
  • Have a qualified electrician do the final installation into a consumer unit or wall fitting. In most jurisdictions this is a legal requirement, not a suggestion.
  • Fit an RCD/RCBO upstream and fuse the load appropriately for its rating.
  • Lithium cells vent and burn when abused. Only use protected cells or a proper BMS, never charge below 0 °C, and never leave a charging pack unattended on a wooden desk.
  • Never power an RF module without its antenna fitted — the reflected power destroys the output stage. Check your local licence-free band and duty-cycle limits before transmitting.
  • Wear eye protection when soldering or cutting, and solder in a ventilated space — rosin flux fumes are a respiratory irritant.
  • Power the circuit through a bench supply with a current limit while you are testing. A 300 mA limit turns a wiring mistake into a beep instead of a dead board.
  • Disconnect power before changing any wiring. Hot-plugging a sensor onto a live bus is the fastest way to lose a controller.

Maintenance

  • Verify transducer calibration and node battery/health.
  • Update healthy baselines/models as the network changes.
  • Act on leak alerts; pinpoint and repair; verify loss reduction.
  • Maintain district metering and consumption data.
  • Re-check every screw terminal and header after the first week — thermal cycling loosens connections that felt tight on day one.
  • Log pack voltage. When resting voltage after a full charge drops below about 4.0 V, the cell is near end of life — replace it.
  • Wash the panel every few weeks in dusty conditions; a visible dust film costs 15–25 % of the harvest.
  • Keep the broker and dashboard containers patched, and rotate device credentials at least once a year.
  • Recalibrate at the interval given in the calibration section, and keep the constants in a text file next to the firmware — not only in flash.
  • Keep a short logbook of firmware versions and what changed. Six months later you will not remember why that constant is 1.083.

Future Improvements & Upgrades

A working v1 is a platform, not a finish line. These are the upgrades that add the most capability for the least rework.

  • Add acoustic/correlating sensors for automated pinpointing.
  • Add hydraulic modelling for better localisation.
  • Fuse smart-meter consumption for tighter NRW.
  • Add pressure management to reduce leakage rates.
  • Design a proper PCB. Once the breadboard version has run for a month, moving to a two-layer board removes the intermittent-contact failures that dominate prototype faults.
  • Add over-the-air firmware updates so you never have to physically reach a deployed node again.
  • Add persistent local storage (microSD or the on-chip flash) so a network outage does not create a hole in your data.
  • Move configuration out of the source: a captive-portal setup page or a JSON config file makes the build reusable without a recompile.
  • Add a battery and solar option so the unit survives a power cut and can be sited away from a socket.
  • Write a small test harness that feeds synthetic sensor values through the decision logic, so you can validate thresholds without physically triggering the event.

Frequently Asked Questions

How can pressure find a buried leak?

A leak continuously loses water and depresses pressure, so it leaves a signature in the pressure field — a district runs lower and behaves differently, a burst causes a transient, and a persistent local depression points to the leaking area.

Why analyse at night?

During the day, legitimate consumption masks leakage. At night, when almost no one uses water, whatever is still flowing and depressing pressure is essentially leakage — so night flow and night pressure directly measure how much a district leaks.

Does it pinpoint the exact leak?

No — it localises to a district or stretch. The final metres are found by a crew with acoustic correlation gear sent to that area, which is far cheaper than searching the whole network. Analytics narrows it down; acoustics pinpoints.

How does it quantify the loss?

With district metering: comparing the metered inflow to a zone against the legitimate consumption within it. The difference is loss (non-revenue water), which lets you prioritise the biggest-losing districts.

Why is this worth doing?

Utilities lose a fifth to a third of treated water to mostly-hidden leaks. Localising and quantifying that loss lets them fix the biggest leaks first — recovering large amounts of water and money that would otherwise drip away for years.

References & Learning Resources

These are the primary sources worth reading in full. Manufacturer datasheets always outrank forum posts when the two disagree.

  1. Non-revenue waterReference
  2. Water leak detectionReference
  3. District metered areas / minimum night flowReference
  4. Acoustic leak correlationReference
  5. Pressure management in water networksReference