84 WSN Routing Labs and Exercises
84.1 Learning Objectives
By the end of this chapter, you will be able to:
- Experiment with Routing Protocols: Compare AODV, DSR, and LEACH in simulation environments
- Measure Energy Consumption: Quantify and optimize routing for network lifetime
- Implement Route Discovery: Practice route request/reply mechanisms in code
- Evaluate Protocol Trade-offs: Assess delivery rate, latency, and overhead trade-offs
For Beginners: WSN Routing Labs and Exercises
This chapter tests your knowledge through a 10-question quiz covering all WSN routing topics, then provides a hands-on coding lab where you can modify real routing algorithm code. If you have not yet read the earlier chapters in this series, start with WSN Routing Fundamentals. The quiz questions are drawn from all six topic areas: routing challenges, directed diffusion, data aggregation, link quality, Trickle, and protocol comparisons.
84.2 Prerequisites
Before diving into this chapter, you should be familiar with:
- WSN Routing Challenges: Understanding why specialized routing is needed
- Directed Diffusion: Data-centric routing concepts
- Data Aggregation: In-network processing benefits
- Link Quality Routing: ETX and link metrics
- Trickle Algorithm: Efficient dissemination
MVU: Minimum Viable Understanding
Core concept: WSN routing protocol selection depends on network characteristics – mobile vs static nodes, dense vs sparse deployment, event-driven vs continuous monitoring, and latency-critical vs best-effort delivery.
Why it matters: Choosing AODV for a 1000-node static farm (should use LEACH) or LEACH for a 10-node mobile scenario (should use AODV) wastes energy, reduces lifetime, and degrades performance.
Key takeaway: Compare protocols by running them under realistic conditions and measuring delivery rate, latency, and energy consumption simultaneously. A protocol that excels in one metric may fail badly in another.
Putting Numbers to It
Simulated protocol comparison for 200-node static WSN with 10 packets/minute reporting rate:
AODV (reactive, address-based):
- Route discovery: 5% of transmissions fail → trigger new RREQ flood (200 nodes × 40 bytes = 8 KB network-wide)
- Overhead: 5% failure rate × 10 pkts/min × 60 min = 30 route discoveries/hr × 8,000 bytes = 240 KB/hour control traffic
- Data delivery: 95% (5% loss triggers rediscovery)
- Average latency: 120 ms (includes route discovery delays)
- Data transmissions per hour: 200 nodes × 10 pkt/min × 60 min × 4 hops = 480,000 transmissions
- Energy: 480,000 × 50 µJ = 24,000,000 µJ = 24 J/hour data + 240,000 bytes × 0.4 µJ/byte = 96 mJ control ≈ 24.1 J/hour total
LEACH (hierarchical, cluster-based with p=0.1):
- Cluster formation: 20 CHs per round (20-second rounds = 180 rounds/hour)
- Overhead: 20 CH advertisements × 20 bytes × 180 rounds/hour = 72 KB/hour
- Data delivery: 98% (cluster heads aggregate and send redundant summaries)
- Average latency: up to 20,000 ms (nodes must wait for CH time slot in TDMA schedule with 20-second rounds)
- Per round: 180 members × 1 hop × 50 µJ + 20 CHs × 3 hops × 50 µJ = 9,000 + 3,000 = 12,000 µJ = 12 mJ/round
- Energy: 12 mJ × 180 rounds/hour = 2.16 J/hour
Counterintuitive result: In this continuous high-rate scenario, LEACH actually uses 11× LESS energy than AODV (2.16 vs 24.1 J/hour) because cluster-based aggregation dramatically reduces the number of multi-hop transmissions. However, LEACH’s latency is unacceptably high (~20 seconds per TDMA slot) for real-time applications. Lesson: LEACH wins on energy for dense high-rate deployments, but its latency makes it unsuitable for real-time alerts. AODV provides 95% delivery with lower latency but pays a high energy cost.
For Kids: Meet the Sensor Squad!
The Sensor Squad is taking their final exam! Time to show everything they have learned about routing!
84.2.1 The Sensor Squad Adventure: The Championship Quiz
It was the end of the semester at Sensor School, and the squad was ready for the big quiz!
“Question one!” said Teacher Router. “If Sammy is far away and needs to send a message to the farmhouse, should he shout really loud (direct) or pass it through friends (multi-hop)?”
“Multi-hop!” yelled Max. “Shouting uses way too much battery! Short passes are much cheaper!”
“Question two! If there are 100 sensors, should EVERY sensor send its own message?”
“No way!” said Lila. “That is 100 messages! We should use a group leader to combine them into just a few messages. That is data aggregation!”
“Final question! How do you pick the BEST path?”
Bella thought carefully. “NOT the shortest path! The BEST path has good signal quality, goes through sensors with plenty of battery, and avoids the busy area near the farmhouse!”
“A+ for the Sensor Squad!” cheered Teacher Router.
84.2.2 Key Words for Kids
| Word | What It Means |
|---|---|
| AODV | A protocol that finds routes only when it needs them (like asking for directions each trip) |
| DSR | A protocol where the message carries its full route with it (like a treasure map) |
| LEACH | A protocol that organizes sensors into teams with rotating leaders |
| ETX | A score that tells you how many tries it takes to send a message successfully |
84.3 Comprehensive Review Quiz
Test your understanding of all WSN routing concepts covered in this series.
84.4 WSN Routing Lab: Multi-Hop Routing Simulation
Key Concepts
- Routing Protocol: Algorithm determining the path a packet takes through the multi-hop WSN to reach the sink
- Convergecast: N-to-1 routing pattern where all sensor data flows toward a single sink along a tree structure
- Routing Table: Per-node data structure mapping destination addresses to next-hop neighbors
- Energy-Aware Routing: Protocol selecting paths based on node residual energy to balance consumption and maximize lifetime
- Link Quality Indicator (LQI): Metric quantifying the reliability of a wireless link — higher LQI means more reliable packet delivery
- Routing Tree: Spanning tree structure rooted at the sink used by hierarchical routing protocols
- Multi-path Routing: Maintaining multiple disjoint paths to improve reliability and enable load balancing
84.4.1 Lab Overview
This hands-on lab simulates a Wireless Sensor Network with multiple ESP32 nodes demonstrating different routing protocols. You’ll experiment with routing decisions, energy-aware path selection, and compare the performance of AODV, DSR, and LEACH protocols in real-time.
What You’ll Learn:
- How multi-hop routing works in wireless sensor networks
- Differences between reactive (AODV, DSR) and proactive (LEACH) routing
- Energy-aware routing decisions and their impact on network lifetime
- Route discovery, maintenance, and recovery mechanisms
- Cluster-based routing and aggregation strategies
84.4.2 Lab Setup
The simulation creates a 9-node WSN topology with:
- 3 Sensor Nodes (S1, S2, S3) - Generate temperature/humidity data
- 4 Intermediate Nodes (R1, R2, R3, R4) - Forward packets and aggregate data
- 1 Cluster Head (CH) - Coordinates LEACH protocol
- 1 Sink Node (SINK) - Destination for all data
Each node has a simulated battery level that depletes with transmission/reception, demonstrating energy-aware routing.
84.4.3 Network Topology
┌─────────────────────────────────────┐
│ Network Topology │
├─────────────────────────────────────┤
│ │
│ S1 ──┬── R1 ──┬── CH ── SINK │
│ │ │ │ │
│ S2 ──┼── R2 ──┤ │ │
│ │ │ │ │
│ S3 ──┴── R3 ──┴── R4 │
│ │
│ Links: S1-R1, S1-R2, S2-R2, S2-R3 │
│ S3-R3, S3-R4, R1-R2, R2-R3 │
│ R3-R4, R1-CH, R2-CH, R4-CH │
│ CH-SINK │
└─────────────────────────────────────┘
84.4.4 Challenge Exercises
Hands-On Challenges
Try these modifications to deepen your understanding:
- Energy-Aware Path Selection
- Modify
getNextHop()to prioritize high-energy nodes - Implement adaptive energy thresholds based on network-wide energy levels
- Compare network lifetime with and without energy awareness
- Modify
- Route Quality Metrics
- Add link quality estimation based on signal strength (RSSI)
- Implement Expected Transmission Count (ETX) metric
- Update
calculateLinkQuality()to factor in packet loss
- LEACH Cluster Rotation
- Implement probabilistic cluster head election (5% probability)
- Rotate cluster heads based on residual energy
- Compare energy consumption across nodes
- Multipath Routing
- Modify DSR to maintain multiple routes
- Implement route splitting for load balancing
- Measure improvement in delivery rate
- Route Recovery
- Add RERR (Route Error) packet handling for broken links
- Implement local route repair before triggering new discovery
- Measure reduction in route discovery overhead
- Protocol Comparison
- Run each protocol for 2 minutes and record statistics
- Compare delivery rate, latency, and energy consumption
- Analyze which protocol performs best under different network densities
84.4.5 Expected Learning Outcomes
After completing this lab, you should be able to:
- Explain the differences between reactive (AODV, DSR) and proactive (LEACH) routing
- Identify when energy-aware routing improves network lifetime
- Analyze the trade-offs between hop count and energy consumption
- Implement route discovery and maintenance mechanisms
- Evaluate protocol performance under different network conditions
- Design hierarchical routing strategies for large-scale WSNs
84.4.6 Key Observations
| Protocol | Route Discovery | Energy Efficiency | Scalability | Best Use Case |
|---|---|---|---|---|
| AODV | On-demand (flooded RREQ) | Moderate | Good | Mobile, dynamic networks |
| DSR | On-demand (source routing) | Low overhead | Limited | Small networks, stable topology |
| LEACH | Cluster-based (periodic) | High (aggregation) | Excellent | Dense, static sensor deployments |
Real-World Applications
- AODV: Smart city IoT with mobile nodes (vehicles, wearables)
- DSR: Indoor sensor networks with stable topology
- LEACH: Agricultural monitoring with thousands of static sensors
- Energy-Aware Routing: Battery-powered environmental monitoring
84.4.7 Further Exploration
To extend this lab:
- Add geographic routing using GPS coordinates
- Implement Quality of Service (QoS) routing for priority traffic
- Simulate network partitioning and reconnection
- Add data aggregation functions (min, max, median) for LEACH
- Implement duty cycling where nodes sleep to save energy
84.5 Interactive: ETX Path Comparison Calculator
Compare hop-count routing vs ETX-based routing. Adjust link quality for two paths to see which metric makes better decisions.
84.6 Visual Reference Gallery
Directed Diffusion
Directed diffusion data-centric routing with interest propagation and gradient-based forwarding.
LEACH Clustering
LEACH hierarchical routing with rotating cluster heads for load balancing.
Epidemic Routing
Epidemic routing for delay-tolerant and intermittently connected sensor networks.
Worked Example: Link Quality Metric (ETX) vs. Hop Count Comparison
Scenario: Two paths from sensor to sink, compare ETX-based routing vs. hop-count routing.
Path A (Hop Count Winner): 3 hops
- Link 1: Node S → Node M1, distance 80m, PRR = 55% (marginal quality)
- Link 2: Node M1 → Node M2, distance 85m, PRR = 50% (poor quality)
- Link 3: Node M2 → Sink, distance 90m, PRR = 60%
- Hop count: 3 ✓ (shortest path)
Path B (ETX Winner): 4 hops
- Link 1: Node S → Node G1, distance 50m, PRR = 95%
- Link 2: Node G1 → Node G2, distance 55m, PRR = 92%
- Link 3: Node G2 → Node G3, distance 50m, PRR = 95%
- Link 4: Node G3 → Sink, distance 45m, PRR = 97%
- Hop count: 4 (longer path)
ETX Calculation (Expected Transmission Count = 1/PRR):
Path A ETX: \[ETX_A = \frac{1}{0.55} + \frac{1}{0.50} + \frac{1}{0.60} = 1.82 + 2.00 + 1.67 = 5.49\]
Path B ETX: \[ETX_B = \frac{1}{0.95} + \frac{1}{0.92} + \frac{1}{0.95} + \frac{1}{0.97} = 1.05 + 1.09 + 1.05 + 1.03 = 4.22\]
Energy Comparison (assuming 50 µJ/byte, 50-byte packets):
Path A (hop count routing would choose this):
- Expected transmissions: 5.49 (due to retransmissions on lossy links)
- Energy: 5.49 × 50 bytes × 50 µJ = 13.7 mJ
Path B (ETX routing chooses this):
- Expected transmissions: 4.22
- Energy: 4.22 × 50 × 50 = 10.6 mJ
- Energy savings: 23% despite longer path!
Reliability Comparison:
- Path A end-to-end success: 0.55 × 0.50 × 0.60 = 16.5% (83.5% packet loss!)
- Path B end-to-end success: 0.95 × 0.92 × 0.95 × 0.97 = 80.5% (19.5% loss)
- Path B is 4.9× more reliable
Key Insight: Hop count is a terrible metric for WSN routing. Even though Path B has more hops (4 vs. 3), its high-quality links result in 23% lower energy consumption and 4.9× better reliability. ETX accounts for real-world link losses that hop count ignores completely.
Decision Framework: Wokwi Lab Protocol Selection
| Lab Goal | AODV | DSR | LEACH | Directed Diffusion |
|---|---|---|---|---|
| Learn reactive routing | ✓✓✓ Best | ✓✓ Good | ✗ Not reactive | ✗ Not reactive |
| Understand route discovery | ✓✓✓ RREQ/RREP | ✓✓ Source routing | ✗ No discovery | ✓✓ Interest flood |
| Study clustering | ✗ No clusters | ✗ No clusters | ✓✓✓ Core feature | ✗ Flat routing |
| Measure energy hotspots | ✓✓ Visible | ✓✓ Visible | ✓ Mitigated by rotation | ✓ Gradient balancing |
| Explore data aggregation | ✗ No aggregation | ✗ No aggregation | ✓✓✓ Built-in | ✓✓ Interest-based |
| Test network recovery | ✓✓✓ RERR handling | ✓✓ Cache invalidation | ✓✓ Re-cluster | ✓✓ Gradient refresh |
| Complexity (beginner-friendly) | Medium | High (source routing) | Medium-high | Medium |
Recommended Lab Sequence:
- Start with AODV: Easiest to visualize (RREQ flooding, explicit routes)
- Compare with LEACH: See clustering benefits for energy
- Challenge: DSR: Understand source routing trade-offs
Common Mistake: Not Accounting for Bidirectional Link Quality
The Mistake: Implementing ETX using only forward link PRR, assuming symmetric links (if A hears B at 90%, then B hears A at 90%).
Why It’s Wrong: Real WSN links are asymmetric 30-50% of the time due to: - Different transmission powers (node A: 0 dBm, node B: -3 dBm) - Antenna orientation (directional effects) - Local interference (only affecting one direction) - Hardware calibration differences
Lab Impact: Your Wokwi simulation shows AODV working with 95% delivery. Real deployment shows 60% delivery. The missing piece: reverse link (ACK) failures cause retransmissions even when forward link is perfect.
Real Measurement (Urban WSN):
- Link A→B: PRR = 88% (forward)
- Link B→A: PRR = 64% (reverse, due to B’s weaker radio)
- Effective ETX: 1/0.88 + 1/0.64 = 1.14 + 1.56 = 2.70 (not 1.14!)
- Without accounting for reverse link, ETX underestimates cost by 2.4×
The Fix for Labs:
- Measure both directions: ETX = 1/(PRR_forward × PRR_reverse)
- Implement bidirectional probing: Send probe in both directions, measure each
- Update routing tables with bidirectional ETX: Route selection considers full round-trip cost
Code Fix Example:
// WRONG (symmetric assumption)
float etx = 1.0 / prr_forward;
// CORRECT (bidirectional)
float prr_reverse = measureReversePRR(); // Send probe, measure ACK success
float etx = 1.0 / (prr_forward * prr_reverse);Rule of Thumb: Always probe bidirectionally in real deployments. Asymmetry is the norm, not exception, in low-power wireless networks.
84.7 Chapter Summary
This series explored specialized routing approaches for Wireless Sensor Networks:
Key Takeaways:
WSN Routing is Different: Data-centric, energy-aware, application-specific vs traditional address-centric routing
Directed Diffusion: Interest propagation -> gradient establishment -> data delivery -> reinforcement creates efficient data-driven paths
Data Aggregation: Combining data from multiple sensors reduces transmissions, saving energy while maintaining acceptable accuracy
Link Quality Matters: Hop count is insufficient; MIN-T metric accounts for expected retransmissions on lossy links
WMEWMA: Effective link estimation balances short-term responsiveness (Window Mean) with long-term stability (EWMA)
Trickle Algorithm: Polite gossip achieves zero maintenance cost when consistent, rapid propagation when updated
Trade-offs: Message overhead vs latency vs energy consumption requires protocol selection based on application requirements
WSN routing protocols must navigate unique constraints - extreme energy limits, dense deployment, unreliable links - to achieve application objectives efficiently.
Common Pitfalls
1. Building Routing Tables Without Energy Awareness
Shortest-hop routing concentrates relay load on nodes near the sink, depleting them 10-100× faster than edge nodes. Always incorporate residual energy into route metric (e.g., ETX × energy factor) to balance consumption and prevent premature network partitioning.
2. Forgetting to Handle Routing Table Staleness
WSN topology changes as nodes die or move — routing tables become stale within hours in dynamic deployments. Implement periodic route discovery with a timeout proportional to expected node lifetime, and use link-quality metrics that decay when no recent transmissions are observed.
3. Using Flooding for Data Collection in Dense Networks
Flooding generates O(n²) messages in a 100-node network — a single data collection round produces 10,000 transmissions. Use directed diffusion or tree-based convergecast to reduce collection overhead to O(n) messages.
84.8 Further Reading
Intanagonwiwat, C., et al. (2003). “Directed diffusion for wireless sensor networking.” IEEE/ACM Transactions on Networking, 11(1), 2-16.
Woo, A., Tong, T., & Culler, D. (2003). “Taming the underlying challenges of reliable multihop routing in sensor networks.” ACM SenSys, 14-27.
Levis, P., et al. (2004). “Trickle: A self-regulating algorithm for code propagation and maintenance in wireless sensor networks.” USENIX NSDI, 15-28.
Fasolo, E., et al. (2007). “In-network aggregation techniques for wireless sensor networks: A survey.” IEEE Wireless Communications, 14(2), 70-87.
Gnawali, O., et al. (2009). “Collection tree protocol.” ACM SenSys, 1-14.
84.9 Knowledge Check
84.10 Concept Relationships
| Concept | Relates To | Relationship Type | Significance |
|---|---|---|---|
| LEACH vs Direct Transmission | Network Lifetime | Energy Savings | LEACH reduces per-node energy ~3× through hierarchical aggregation: members transmit 50m instead of 180m, exploiting quadratic distance energy model |
| ETX vs Hop Count | Link Quality | Routing Metric | ETX-based routing saves 23% energy and provides 4.9x better reliability despite longer paths |
| WMEWMA vs Pure EWMA | Link Estimation | Responsiveness | WMEWMA detects link degradation immediately (12% estimate) vs EWMA’s stale 85% estimate after 5 consecutive losses |
| Asymmetric Links | Bidirectional PRR | Real-World Impact | Forward PRR=88%, reverse PRR=64% → effective ETX=2.70 (not 1.14) - 2.4x underestimation without bidirectional measurement |
| AODV vs LEACH | Protocol Selection | Energy Trade-off | AODV: 95% delivery, 64 mJ/node; LEACH: 87% delivery, 18 mJ/node - 3.5x energy savings justifies 8% delivery reduction |
| Tree-Based Aggregation | Transmission Count | Energy Efficiency | 105 transmissions (100 short + 5 long) vs 100 long-distance transmissions saves 70% energy despite similar count |
| Trickle Suppression | Consistent Networks | Overhead Reduction | Zero maintenance transmissions when all nodes have same version - polite gossip achieves efficiency |
84.11 What’s Next?
| Topic | Chapter | Description |
|---|---|---|
| WSN Coverage Fundamentals | WSN Coverage Fundamentals | How to ensure sensor deployments cover the target area without gaps |
| WSN Routing Overview | WSN Routing Overview | Series index for all WSN routing chapters |
| Routing Challenges | WSN Routing Challenges | Why traditional routing fails in sensor networks |
| Directed Diffusion | Directed Diffusion | Data-centric routing with interest propagation |
| Data Aggregation | Data Aggregation | In-network processing to reduce transmissions |
| Link Quality Routing | Link Quality Routing | ETX and link quality metrics for better path selection |
| Trickle Algorithm | Trickle Algorithm | Efficient network reprogramming via polite gossip |