83  WSN Routing Labs & Games

In 60 Seconds

WSN routing protocol selection directly determines network lifetime: LEACH clustering extends operation by 8x over direct transmission, while AODV reactive routing reduces control overhead by 60-80% compared to proactive approaches in sparse networks. Hands-on experimentation with these protocols reveals that energy-aware metrics (remaining battery, hop count, link quality) outperform shortest-path routing by 2-3x in lifetime for networks exceeding 100 nodes.

83.1 Learning Objectives

By the end of this chapter, you will be able to:

  • Compare Routing Protocols: Experiment with AODV, DSR, and LEACH implementations in simulation
  • Measure Energy Trade-offs: Quantify energy consumption differences between routing approaches
  • Design Optimal Routes: Apply learned concepts to select paths in interactive simulations
  • Implement Routing Decisions: Code and test routing algorithms on simulated WSN hardware

This chapter is where theory meets practice. You have learned about LEACH, Directed Diffusion, and link quality metrics – now you will experiment with them hands-on. The game lets you build routing paths and watch energy deplete in real time. The lab provides working code to modify. The quiz tests whether the concepts have stuck. Think of it as a “flight simulator” for WSN routing – make mistakes here, not in a real field deployment.

83.2 Prerequisites

Before diving into this chapter, you should be familiar with:

MVU: Minimum Viable Understanding

Core concept: WSN routing protocols have fundamental trade-offs between energy efficiency, delivery reliability, latency, and scalability – the best way to understand these trade-offs is through hands-on experimentation.

Why it matters: Reading about AODV, LEACH, and Directed Diffusion only gives theoretical understanding. Interactive simulations reveal emergent behaviors like energy hotspots, route failures, and the real cost of protocol overhead that are invisible in textbook descriptions.

Key takeaway: No single routing protocol wins in all scenarios. AODV suits mobile/dynamic networks, DSR suits small/stable networks, and LEACH excels in dense static deployments. Always measure delivery rate, latency, AND energy consumption together.

Time to play a game! The Sensor Squad needs YOUR help to design the best message routes across the farm!

83.2.1 The Sensor Squad Adventure: The Route Design Challenge

“We need a new plan!” announced Sammy. “The old routes are not working well – some sensors are running out of battery while others are barely used!”

Farmer Jones set up a challenge: “Design routes for our farm sensors. But here is the catch – you have THREE goals at the same time!”

  1. Save energy – Do not use the same path every time or the sensors along it will get tired
  2. Deliver messages – Every message MUST reach the farmhouse
  3. Be fast – The greenhouse alarm must arrive in under 5 seconds!

“That is tricky!” said Lila. “If I pick the fastest path, it might waste energy. If I save energy, messages might be slow!”

“That is the fun part,” said Max. “You have to BALANCE all three goals. Try different strategies and see which works best!”

Can YOU beat the Sensor Squad at designing routes? Try the game below!

83.3 WSN Route Optimizer Game

Test your understanding of WSN routing by designing optimal routes in this interactive strategy game. Balance energy consumption, latency, and reliability while learning different routing protocols.

How to Play
  1. Select a level to learn different routing paradigms (Flat, Hierarchical, Geographic)
  2. Click nodes to build routing paths from sources to the sink
  3. Watch packet flow and energy depletion in real-time
  4. Complete objectives while maximizing network lifetime
Game Scenarios

Single-Path vs Multi-Path Routing: In manual mode, try creating redundant paths. Multi-path routing improves reliability but increases energy consumption.

Cluster Head Selection (Level 2): LEACH rotates cluster heads to balance energy drain. Watch how fixed CH selection creates hot spots.

Energy-Aware Route Selection: Avoid nodes with low energy (red). The ETX metric favors reliable links over shortest paths.

Handling Node Failures: When nodes die (turn dark), the network must adapt. Geographic routing can route around voids.

Hot Spot Problem: Nodes near the sink relay more traffic. Use hierarchical routing or multi-path to distribute load.

Strategy Tips
  1. Level 1 (Flat): Compare flooding (high overhead, reliable) vs gossiping (low overhead, less reliable). Use Directed Diffusion for a balance.

  2. Level 2 (Hierarchical): Let LEACH auto-select cluster heads. Watch how rotation extends network lifetime vs fixed CH.

  3. Level 3 (Geographic): Observe greedy forwarding toward the sink. Dead nodes create “voids” that require perimeter routing.

  4. Manual Mode: Click nodes to build custom paths. Start from a source, connect through intermediate nodes to the sink. Monitor link quality percentages.


83.4 Hands-On Lab: Multi-Hop Routing Simulation

⏱️ ~45 min | ⭐⭐⭐ Advanced | 🧪 Hands-On Lab

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

83.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

83.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.

83.4.3 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

83.4.4 Key Code Sections

The complete simulation code is available in the Wokwi editor. Key sections include:

AODV Route Discovery:

void aodvRouteDiscovery(int source, int dest) {
  // Flood RREQ to neighbors
  for (int i = 0; i < NUM_NODES; i++) {
    if (topology[source][i] && nodes[i].active) {
      updateEnergy(source, true);   // TX cost
      updateEnergy(i, false);       // RX cost
      // Forward RREQ...
    }
  }
}

LEACH Cluster Formation:

void leachClusterFormation() {
  // Probabilistic cluster head selection
  for (int i = 0; i < numNodes; i++) {
    if (random(0, 100) < p * 100) {
      nodes[i].isClusterHead = true;
    }
  }
  // Assign members to nearest CH
}

Energy-Aware Forwarding:

int getNextHop(int current, int dest) {
  int bestHop = -1, bestMetric = 999999;
  for (int i = 0; i < MAX_ROUTES; i++) {
    if (routingTable[current][i].valid) {
      int metric = routingTable[current][i].hopCount;
      // Penalize low-energy nodes
      if (nodes[nextHop].energy < 30) metric += 10;
      if (metric < bestMetric) {
        bestMetric = metric;
        bestHop = routingTable[current][i].nextHop;
      }
    }
  }
  return bestHop;
}

83.4.5 Challenge Exercises

Hands-On Challenges

Try these modifications to deepen your understanding:

  1. 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
  2. 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
  3. LEACH Cluster Rotation
    • Implement probabilistic cluster head election (5% probability)
    • Rotate cluster heads based on residual energy
    • Compare energy consumption across nodes
  4. Multipath Routing
    • Modify DSR to maintain multiple routes
    • Implement route splitting for load balancing
    • Measure improvement in delivery rate
  5. 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
  6. 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

83.4.6 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

83.4.7 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

83.5 Comprehensive Review Quiz

Test your understanding of WSN routing protocols with this comprehensive quiz.


Scenario: 100-node forest monitoring network, compare LEACH clustering vs. direct transmission to sink.

Network Parameters:

  • Area: 500m × 500m square
  • Sink: Center (250m, 250m)
  • Nodes: Uniformly distributed
  • Average distance to sink: ~180m
  • Cluster count (LEACH): 5 clusters = 20 nodes each
  • Transmission model (standard LEACH): \(E_{TX} = k \times (E_{elec} + E_{amp} \times d^2)\) where \(E_{elec} = 50\) nJ/bit, \(E_{amp} = 100\) pJ/bit/m², k = 400 bits (50 bytes)

Direct Transmission (Baseline):

  • Each node transmits 50 bytes (400 bits) directly to sink at 180m: \[E_{direct} = 400 \times (50 \times 10^{-9} + 100 \times 10^{-12} \times 180^2) = 400 \times 3{,}290 \text{ nJ} = 1.316 \text{ mJ}\]
  • Total network energy: 100 × 1.316 mJ = 131.6 mJ per round
  • With 2,000 mAh battery (3.7V = 26,640 J = 26,640,000 mJ):
    • Rounds to failure: 26,640,000 / 131.6 = 202,432 rounds
    • If 1 round/hour: ~23 years (but hotspot nodes near relay points die much sooner)

LEACH Clustering:

  • Member nodes (80 nodes):
    • Transmit to cluster head (avg 50m): \(E = 400 \times (50 \text{ nJ} + 100 \text{ pJ} \times 50^2) = 400 \times 300 \text{ nJ} =\) 0.12 mJ
  • Cluster heads (20 nodes, rotated):
    • Receive from 19 members: \(19 \times 400 \times 50 \text{ nJ} = 380{,}000 \text{ nJ} = 0.38 \text{ mJ}\)
    • Aggregate 20 readings to 1 summary: ~0.04 mJ (5 nJ/bit/signal × 20 signals × 400 bits)
    • Transmit to sink (avg 180m): 1.316 mJ
    • Total CH energy: 0.38 + 0.04 + 1.316 ≈ 1.74 mJ per round
  • Average energy per node (with 20% CH rotation):
    • 80% chance of being member: 0.80 × 0.12 = 0.096 mJ
    • 20% chance of being CH: 0.20 × 1.74 = 0.348 mJ
    • Average: 0.444 mJ per round
  • Total network: 100 × 0.444 = 44.4 mJ per round
  • Rounds to failure: 26,640,000 / 0.444 mJ = 59,977,000 rounds
  • Network lifetime: ~6,849 years for uniform depletion (battery limited by shelf life)
  • More meaningful metric – lifetime vs. direct transmission: 0.444 mJ vs. 1.316 mJ = 3× less energy per node per round

Takeaway: LEACH’s hierarchical clustering reduces average per-node energy by 3× through two mechanisms: (1) 80% of nodes transmit short distances (50m) to cluster heads instead of long distances (180m) to the sink; the quadratic distance term means 50m vs 180m saves (180/50)² = 13× in amplifier energy for member transmissions. (2) Aggregation reduces long-haul transmissions from sink by 80%.

LEACH clustering reduces per-node energy by approximately 3× compared to direct transmission by exploiting the quadratic relationship between distance and transmission energy.

\[ E_{TX} = k \times (E_{elec} + E_{amp} \times d^2) \]

where \(E_{elec} = 50\) nJ/bit, \(E_{amp} = 100\) pJ/bit/m², and \(k\) = packet size in bits.

Worked example: 100-node forest network, average 180m to sink, packet = 50 bytes = 400 bits.

  • Direct TX at 180m: \(400 \times (50 \text{ nJ} + 100 \text{ pJ} \times 180^2) = 400 \times 3{,}290 \text{ nJ} = 1.316 \text{ mJ}\)
  • LEACH member TX at 50m: \(400 \times (50 \text{ nJ} + 100 \text{ pJ} \times 50^2) = 400 \times 300 \text{ nJ} = 0.12 \text{ mJ}\) (80% of nodes)
  • LEACH CH TX at 180m: 1.316 mJ (20% of nodes, after aggregation)
  • Average per node with rotation: \(0.8 \times 0.12 + 0.2 \times 1.316 = 0.096 + 0.263 = 0.359\) mJ

Note: CH also receives from members (19 × 400 × 50 nJ = 0.38 mJ), giving total CH cost ≈ 1.74 mJ and average ≈ 0.44 mJ. Net savings: 1.316 / 0.44 ≈ 3× energy reduction through hierarchical aggregation.

Network Characteristic AODV (Reactive) DSR (Source Routing) LEACH (Clustering) GPSR (Geographic)
Node count 10-200 10-50 100-1000+ 50-500
Mobility High tolerance Moderate Low (static best) High tolerance
Memory per node ~1KB routing ~2-4KB path cache ~256B cluster info ~512B neighbor table
Control overhead Medium (RREQ floods) Low (source caches routes) Low (local clusters) Low (greedy forwarding)
GPS required? No No No Yes (location-based)
Energy efficiency Medium Medium-high High (aggregation) Medium-high
Latency Medium (route discovery) Low (cached routes) Medium (aggregation delay) Low (greedy)
Best for Mobile ad hoc Small stable nets Large static sensors GPS-equipped mobile

Selection Logic:

  1. Do you have GPS? → Yes: Consider GPSR. No: Continue.
  2. Is network static (>90% nodes stationary)? → Yes: Consider LEACH if node count > 100. No: Use AODV.
  3. Is node count < 50? → Yes: DSR (lower overhead). No: AODV or LEACH.
  4. Is energy THE critical constraint? → Yes: LEACH mandatory for static, GPSR for mobile. No: Any protocol works.
Common Mistake: Ignoring Route Repair Costs in Lab Simulations

The Mistake: Measuring protocol energy consumption for 1000 packets with zero node failures, declaring “Protocol X uses 15 mJ/packet average.”

Why It’s Wrong: Real deployments experience 10-30% node failure rates over 2-3 years. Route repairs (RERR packets, new RREQ floods) dominate energy consumption in mature networks. A protocol using 15 mJ/packet in perfect conditions may use 40-60 mJ/packet with 20% node churn.

Lab Validation Gap: Student lab runs 20-minute simulation with 9 healthy nodes. Real deployment runs 2 years with nodes failing gradually due to battery depletion, environmental damage, and hardware failures.

Real-World Example: AODV performed excellently in 30-node lab demo (12 mJ/packet). After 6-month field deployment, actual energy consumption was 47 mJ/packet (4× higher). Analysis revealed: - Route repairs: 15 failures/day × 8 RREQ floods × 30 nodes × 0.5 mJ = 1,800 mJ/day overhead - Divided by 1,440 packets/day = +1.25 mJ/packet overhead - Plus increased retransmissions due to lossy links: +20 mJ/packet - Plus stale routes (nodes moved slightly): +12 mJ/packet

The Fix for Labs: Introduce realistic failure models: 1. Battery depletion model: Nodes die when energy reaches zero (simulates hotspot failures) 2. Random failures: 5% chance per hour of node failure (simulates hardware/environmental) 3. Link quality variation: ±30% fluctuation in link RSSI (simulates interference) 4. Measure protocol over entire network lifetime, not just first 1000 packets

Rule of Thumb: Multiply lab-measured “perfect conditions” energy by 2-3× for production estimates. Protocols that handle failures gracefully (LEACH cluster reformation, GPSR local repair) scale better than protocols requiring global re-discovery (AODV).

83.6 Concept Relationships

Concept Relates To Relationship Type Significance
LEACH Clustering Network Lifetime Energy Extension Hierarchical clustering extends operation 8x over direct transmission through aggregation and short-hop communication
AODV Routing Route Maintenance Overhead Trade-off Periodic route maintenance ensures 95%+ delivery but consumes 3-5x more energy than reactive DSR
Link Quality ETX Metric Path Selection ETX-based routing outperforms hop-count by 2-3x in lossy networks, accounting for retransmissions
Cluster Head Rotation Energy Hotspots Mitigation Random rotation prevents fixed nodes from dying early due to aggregation burden
Energy-Aware Metrics Battery Depletion Route Avoidance Routes that avoid low-battery nodes extend first-node-death time by 60-180 days in 500-node networks
Delivery Rate vs Energy Protocol Selection Impossible Triangle Energy, latency, and delivery rate form trade-off triangle - no protocol optimizes all three simultaneously
Reactive vs Proactive Control Overhead Sparse vs Dense AODV reduces overhead 60-80% vs proactive in sparse networks; proactive wins in dense continuous-traffic scenarios

Common Pitfalls

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.

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.

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.

83.7 Summary

This chapter provided hands-on experience with WSN routing protocols:

Key Takeaways:

  1. Interactive Learning: The WSN Route Optimizer game lets you experiment with different routing paradigms and see energy trade-offs in real-time

  2. Protocol Comparison: AODV, DSR, and LEACH each have strengths for different network conditions (mobile vs. static, small vs. large)

  3. Energy Awareness: Routing decisions must consider node energy levels to maximize network lifetime

  4. Practical Implementation: The Wokwi lab provides working code for routing algorithms that can be modified and tested

  5. Measurement Matters: Always compare delivery rate, latency, AND energy consumption when evaluating protocols


83.8 What’s Next

Topic Chapter Description
Stationary/Mobile Review WSN Stationary/Mobile Review Production deployment strategies for stationary, mobile, and hybrid WSN architectures
Coverage Fundamentals WSN Coverage Fundamentals Coverage algorithms, K-coverage, and rotation scheduling
Tracking Fundamentals WSN Tracking Fundamentals Target tracking algorithms including Kalman and particle filters
Routing Fundamentals WSN Routing Fundamentals Overview of WSN routing challenges and classification