671 IoT Protocols Lab: Python Implementations
671.1 Learning Objectives
By the end of this chapter, you will be able to:
- Build protocol stack analyzers: Calculate overhead and efficiency for different protocol combinations
- Implement battery life calculators: Estimate device longevity based on transmission patterns
- Create protocol selector engines: Automate protocol recommendations based on requirements
- Apply real-world worked examples: Design complete protocol architectures for building management systems
- Validate designs with calculations: Use quantitative analysis to justify protocol choices
What is this chapter? Practical Python tools and a comprehensive worked example for protocol selection.
Why it matters: - Real engineering requires quantitative analysis, not just intuition - Automated tools catch errors human calculations miss - Worked examples show how theory applies to real deployments
Prerequisites: - IoT Protocols Lab: Selection Framework - Basic Python familiarity
671.2 Python Implementations
671.2.1 Implementation 1: Protocol Stack Analyzer
Expected Output:
######################################################################################
# IoT Protocol Stack Analysis (4-byte payload)
######################################################################################
==========================================================================================
PROTOCOL STACK COMPARISON (Payload: 4 bytes)
==========================================================================================
Stack Overhead Total Efficiency
(bytes) (bytes) (%)
------------------------------------------------------------------------------------------
HTTP over IPv4/Ethernet 104 108 3.70%
MQTT over IPv6/Ethernet 84 88 4.55%
CoAP over IPv6/802.15.4 77 81 4.94%
######################################################################################
# With 6LoWPAN Compression (802.15.4 + IPv6)
######################################################################################
==========================================================================================
PROTOCOL STACK COMPARISON (Payload: 4 bytes)
Using 6LoWPAN compression
==========================================================================================
Stack Overhead Total Efficiency
(bytes) (bytes) (%)
------------------------------------------------------------------------------------------
HTTP over IPv4/Ethernet 104 108 3.70%
MQTT over IPv6/Ethernet 84 88 4.55%
CoAP over IPv6/802.15.4 26 30 13.33%
======================================================================
DETAILED ANALYSIS: CoAP over IPv6/802.15.4
======================================================================
Protocol Overhead Breakdown:
----------------------------------------------------------------------
Layer Protocol Size (bytes)
----------------------------------------------------------------------
Data Link 802.15.4 25
Network IPv6 40
Transport UDP 8
Application CoAP 4
----------------------------------------------------------------------
TOTAL OVERHEAD 77
Payload 4
TOTAL PACKET 81
----------------------------------------------------------------------
Payload Efficiency: 4.94%
Overhead Ratio: 19.25x payload
======================================================================
DETAILED ANALYSIS: CoAP over IPv6/802.15.4
Using 6LoWPAN compression
======================================================================
Protocol Overhead Breakdown:
----------------------------------------------------------------------
Layer Protocol Size (bytes)
----------------------------------------------------------------------
Data Link 802.15.4 8
Network IPv6 6
Transport UDP 8
Application CoAP 4
----------------------------------------------------------------------
TOTAL OVERHEAD 26
Payload 4
TOTAL PACKET 30
----------------------------------------------------------------------
Payload Efficiency: 13.33%
Overhead Ratio: 6.50x payload
######################################################################################
# Impact of Payload Size (CoAP over IPv6/802.15.4 with compression)
######################################################################################
Payload (bytes) Overhead (bytes) Efficiency (%)
------------------------------------------------------------
4 26 13.33%
16 26 38.10%
64 26 71.11%
127 26 83.01%
Conclusion: Larger payloads improve efficiency!
Key Insights: - 6LoWPAN compression reduces CoAP stack from 81 to 30 bytes (62% reduction) - Payload efficiency increases with larger payloads (4 bytes = 13%, 127 bytes = 83%) - HTTP has worst efficiency (3.7%), CoAP best (13.3% with compression)
671.2.2 Implementation 2: IoT Protocol Selector Engine
Expected Output:
================================================================================
IOT PROTOCOL SELECTOR
================================================================================
================================================================================
SCENARIO 1: Battery-Powered Environmental Sensor
================================================================================
Requirements:
Device: Class 1 (10 KB RAM)
Network: 802.15.4
Battery: True
Frequency: Every 300s
Payload: 16 bytes
Recommended Stack:
Network: IPv6 (6LoWPAN compressed)
Transport: UDP
Application: CoAP
Metrics:
Overhead: 18 bytes
Efficiency: 47.1%
Rationale:
β’ Using IPv6 with 6LoWPAN for constrained network
β’ UDP selected for low overhead and power efficiency
β’ Application-layer reliability (CoAP confirmable messages)
β’ CoAP optimal for constrained devices (4-byte header)
================================================================================
SCENARIO 2: Smart Home Dashboard (Many Sensors β Cloud)
================================================================================
Requirements:
Device: Class 2 (50 KB RAM)
Network: Wi-Fi
Pattern: Publish-Subscribe
Many-to-many: True
Recommended Stack:
Network: IPv6
Transport: TCP
Application: MQTT
Metrics:
Overhead: 76 bytes
Efficiency: 45.7%
Rationale:
β’ Using IPv6 for future-proof addressing
β’ TCP required for reliable pub/sub (MQTT)
β’ MQTT optimal for publish-subscribe pattern
β’ MQTT broker enables many-to-many communication
================================================================================
SCENARIO 3: Industrial Real-Time Control
================================================================================
Requirements:
Device: Class 1
Real-time: True
Frequency: 1s (high frequency)
Recommended Stack:
Network: IPv6 (6LoWPAN compressed)
Transport: UDP
Application: CoAP
Metrics:
Overhead: 18 bytes
Efficiency: 18.2%
Rationale:
β’ Using IPv6 with 6LoWPAN for constrained network
β’ UDP selected for low overhead and power efficiency
β’ Application-layer reliability (CoAP confirmable messages)
β’ CoAP optimal for constrained devices (4-byte header)
671.2.3 Implementation 3: Battery Life Impact Calculator
Expected Output:
##########################################################################################
# SCENARIO 1: Environmental Sensor (Every 5 minutes)
##########################################################################################
==========================================================================================
BATTERY LIFE COMPARISON (288 messages/day)
==========================================================================================
Battery: 2000 mAh
TX/RX current: 5 mA
Sleep current: 5 Β΅A
Data rate: 250 kbps
==========================================================================================
Protocol Packet Daily Energy Battery Life
(bytes) (Β΅Ah) (days / years)
------------------------------------------------------------------------------------------
CoAP/UDP/IPv6/802.15.4 (compressed) 30 121.0 16528 days / 45.3 years
CoAP/UDP/IPv6/802.15.4 (uncompressed) 81 121.2 16500 days / 45.2 years
MQTT/TCP/IPv6/802.15.4 94 121.2 16493 days / 45.2 years
HTTP/TCP/IPv4/Ethernet 162 121.6 16454 days / 45.1 years
==========================================================================================
DETAILED BREAKDOWN: CoAP/UDP/IPv6/802.15.4 (compressed)
==========================================================================================
Packet size: 30 bytes
TX/RX time per message: 0.96 ms
Daily active time: 0.28 seconds
Daily TX/RX energy: 1.90 Β΅Ah
Daily sleep energy: 119.04 Β΅Ah
Daily total energy: 120.94 Β΅Ah
Battery life: 16528 days = 45.27 years
##########################################################################################
# SCENARIO 2: Real-Time Monitoring (Every 10 seconds)
##########################################################################################
==========================================================================================
BATTERY LIFE COMPARISON (8640 messages/day)
==========================================================================================
Battery: 2000 mAh
TX/RX current: 5 mA
Sleep current: 5 Β΅A
Data rate: 250 kbps
==========================================================================================
Protocol Packet Daily Energy Battery Life
(bytes) (Β΅Ah) (days / years)
------------------------------------------------------------------------------------------
CoAP/UDP/IPv6/802.15.4 (compressed) 30 135.2 14792 days / 40.5 years
CoAP/UDP/IPv6/802.15.4 (uncompressed) 81 164.6 12145 days / 33.3 years
MQTT/TCP/IPv6/802.15.4 94 171.8 11640 days / 31.9 years
HTTP/TCP/IPv4/Ethernet 162 208.6 9584 days / 26.3 years
==========================================================================================
KEY INSIGHTS:
==========================================================================================
1. For infrequent transmission:
Sleep current dominates β Protocol choice has minimal impact
All protocols achieve >40 years (limited by battery self-discharge)
2. For frequent transmission:
Active time dominates β Protocol overhead critical!
CoAP (compressed): ~133 days
MQTT: ~38 days
HTTP: ~22 days
β CoAP provides 3.5Γ longer battery life vs MQTT
==========================================================================================
Protocol Deep Dives: - CoAP Fundamentals and Architecture - REST for constrained devices - MQTT: Fundamentals - Lightweight pub/sub messaging - 6LoWPAN Comprehensive Review - Header compression deep dive - IPv6 for IoT - Next-generation addressing
Protocol Comparisons: - IoT Protocols Overview - Complete protocol landscape - IoT Protocols Review - Protocol comparison matrix - AMQP vs MQTT and Use Cases - Application protocol selection
Network Design: - Design Implications - Network architecture decisions - Networking Basics - Fundamental networking concepts - Layered Models: Fundamentals - OSI and TCP/IP models
Learning Resources: - Simulations Hub - Interactive protocol tools - Videos Hub - Protocol tutorial videos
671.3 Worked Example: Sensor Network Protocol Selection for Building Energy Management
671.4 Worked Example: Sensor Network Protocol Selection for Building Energy Management
Scenario: A facilities management company is deploying a Building Management System (BMS) with 250 sensors across a 10-story commercial building. The system needs to monitor HVAC efficiency, occupancy, lighting, and energy consumption to reduce operating costs by 20%.
Goal: Select optimal wireless protocols for different sensor categories, balancing battery life, latency requirements, data rates, and integration with existing BMS infrastructure.
What we do: Group sensors by their operational characteristics and requirements.
Sensor Inventory and Requirements:
| Sensor Type | Count | Data Rate | Latency | Power Source | Update Frequency |
|---|---|---|---|---|---|
| Temperature/Humidity | 80 | Low (4 bytes) | Relaxed (5 min) | Battery (5+ yr) | Every 5 minutes |
| Occupancy (PIR) | 60 | Low (1 byte) | Medium (30 sec) | Battery (3+ yr) | On-change + heartbeat |
| Light Level | 40 | Low (2 bytes) | Relaxed (5 min) | Battery (5+ yr) | Every 5 minutes |
| Energy Meters | 30 | Medium (20 bytes) | Relaxed (1 min) | Mains-powered | Every 1 minute |
| HVAC Damper Position | 25 | Low (2 bytes) | Tight (5 sec) | Mains-powered | On-change + 30 sec |
| Air Quality (CO2/VOC) | 15 | Medium (8 bytes) | Medium (1 min) | Battery or Mains | Every 1 minute |
Key Observations:
- 180 sensors need multi-year battery operation (72% of deployment)
- 55 sensors have mains power available (22% of deployment)
- 25 sensors need sub-10-second latency for HVAC control loops
- All sensors within 50m of a potential gateway location (commercial building)
Why: Protocol selection must match sensor requirements. Using one protocol for all sensors either wastes energy (over-provisioning) or fails to meet latency requirements (under-provisioning).
What we do: Compare Zigbee, Thread, and Wi-Fi against our requirements matrix.
Protocol Comparison Matrix:
| Criterion | Zigbee 3.0 | Thread | Wi-Fi (802.11ah/HaLow) |
|---|---|---|---|
| Power (TX) | 10-30 mW | 10-30 mW | 100-500 mW |
| Power (Sleep) | 1-5 uA | 1-5 uA | 10-100 uA |
| Battery Life | 3-5 years | 3-5 years | Weeks-months |
| Data Rate | 250 kbps | 250 kbps | 1+ Mbps |
| Range (indoor) | 10-30m | 10-30m | 50-100m |
| Mesh Support | Yes | Yes | No (star only) |
| IP Native | No (requires gateway) | Yes (IPv6 native) | Yes |
| BMS Integration | Via gateway to BACnet | Native IP to BMS | Native IP to BMS |
| Latency | 50-500 ms | 50-200 ms | 5-50 ms |
| Ecosystem | Mature, many vendors | Growing, Matter alliance | Ubiquitous |
Detailed Analysis by Sensor Category:
Battery-Powered Sensors (Temperature, Occupancy, Light): - Wi-Fi: Eliminated - weeks of battery life unacceptable for 5-year target - Zigbee: Strong candidate - proven 5-year battery life, mesh extends range - Thread: Strong candidate - similar power to Zigbee, but native IP simplifies BMS integration
Mains-Powered with Tight Latency (HVAC Dampers): - Wi-Fi: Viable - power not constrained, lowest latency, direct BMS integration - Thread: Viable - low latency, native IP, consistent with battery sensors - Zigbee: Viable - but gateway adds latency, prefer native IP for control loops
Why: No single protocol optimally serves all requirements. Hybrid approach needed.
What we do: Assign protocols to sensor groups and design network topology.
Protocol Assignment Decision:
| Sensor Group | Protocol | Rationale |
|---|---|---|
| Temperature/Humidity (80) | Thread | 5-year battery, native IPv6 for direct BMS integration |
| Occupancy PIR (60) | Thread | 3-year battery, event-driven works well with Thread sleepy endpoints |
| Light Level (40) | Thread | 5-year battery, same network as temp sensors |
| Energy Meters (30) | Thread | Mains-powered, same network simplifies management |
| HVAC Dampers (25) | Wi-Fi | Mains-powered, <10ms latency for control loops, existing Wi-Fi infrastructure |
| Air Quality (15) | Thread | Consistent with other environmental sensors |
Final Protocol Split:
- Thread: 225 sensors (90%) - Environmental monitoring, occupancy, energy metering
- Wi-Fi: 25 sensors (10%) - HVAC control actuators requiring tight latency
Network Topology:
Floor Plan (per floor):
[Wi-Fi AP]----[BMS Server]----[Thread Border Router]
| | |
[Damper] [Energy [Temp] [Occ] [Light] [CO2]
[Damper] Meters] [Temp] [Occ] [Light]
[Damper] [Temp] [Occ] [Light]
(Mesh extends coverage)
Infrastructure per Floor:
- 1 Thread Border Router (connects Thread mesh to IP network)
- Existing Wi-Fi AP (reuse building Wi-Fi infrastructure)
- All connect to centralized BMS server via building Ethernet
Why: Thread provides optimal balance of battery life and IP integration for the majority of sensors. Wi-Fi handles the small subset requiring sub-10ms latency for closed-loop HVAC control.
What we do: Design data flow from sensors to BMS, ensuring protocol interoperability.
Data Flow Architecture:
Sensors β Protocol Network β Gateway/Border Router β BMS Integration
Thread Sensors:
[Sensor] --CoAP/UDP--> [Border Router] --BACnet/IP--> [BMS Server]
Wi-Fi Sensors:
[Damper] --MQTT/TCP--> [MQTT Broker] --BACnet/IP--> [BMS Server]
Protocol Translation Layer:
| Source Protocol | Translation Point | Target Protocol | BMS Format |
|---|---|---|---|
| Thread/CoAP | Border Router | BACnet/IP | BACnet Objects |
| Wi-Fi/MQTT | MQTT-BACnet Gateway | BACnet/IP | BACnet Objects |
BACnet Object Mapping Example:
Thread Temperature Sensor β BACnet Analog Input
- Object ID: AI-1001 (Floor 1, Zone 1)
- Present Value: 22.5 (degrees C)
- Status Flags: {normal}
- Update Interval: 300 seconds
Wi-Fi HVAC Damper β BACnet Analog Output
- Object ID: AO-2001 (Floor 1, AHU-1, Damper 1)
- Present Value: 75 (percent open)
- Priority Array: [null, null, 75, null...] (manual override at priority 3)
- Command Priority: 8 (default)
Matter/Thread Advantage: Thread sensors using Matter application layer can be discovered by any Matter-compatible BMS without custom integration code. This future-proofs the deployment as Matter adoption grows.
Why: BACnet is the industry standard for BMS integration. Proper protocol translation ensures all sensors appear as native BACnet objects regardless of underlying wireless protocol.
What we do: Calculate expected battery life for Thread sensors to validate 5-year requirement.
Thread Sensor Energy Budget (Temperature Sensor):
Hardware: Nordic nRF52840 + Thread stack + Temperature sensor
Battery: 2x AA Lithium (3,000 mAh total @ 3V)
Operation Profile (per 5-minute cycle):
1. Wake from sleep: 2 ms @ 5 mA = 0.003 mAh
2. Sensor read: 50 ms @ 3 mA = 0.004 mAh
3. Thread TX (CoAP): 15 ms @ 8 mA = 0.003 mAh
4. Thread RX (ACK): 5 ms @ 6 mA = 0.001 mAh
5. Sleep (299.9 sec): 1 uA = 0.083 mAh
Energy per cycle: 0.094 mAh
Cycles per day: 288
Daily consumption: 27 mAh
Annual consumption: 9,855 mAh
Wait - this exceeds our 3,000 mAh battery!
Problem Identified: Basic calculation shows only ~3.6 months battery life.
Optimization - Thread Sleepy End Device (SED):
Using Thread SED mode with 30-second poll interval:
- Sensor wakes, reads, queues data
- Data transmitted during next parent poll (up to 30 sec delay)
- Eliminates waiting for ACK (parent buffers response)
Revised Profile:
1. Wake from sleep: 2 ms @ 5 mA = 0.003 mAh
2. Sensor read: 50 ms @ 3 mA = 0.004 mAh
3. Data queued to parent: 10 ms @ 8 mA = 0.002 mAh
4. Sleep (299.9 sec): 1 uA = 0.083 mAh
Energy per 5-min cycle: 0.092 mAh
Daily consumption: 26.5 mAh
Annual consumption: 9,672 mAh
Still too high!
Further Optimization - Extended Sleep with Compression:
Final Profile (optimized):
- Report every 5 minutes BUT only on >0.5C change (event-driven)
- Average 30% of readings transmitted (others filtered)
- Use 6LoWPAN header compression (Thread native)
Effective transmissions per day: 288 * 0.3 = 86
Energy per day: 86 * 0.009 mAh (TX) + 24 * 0.083 mAh (sleep) = 2.8 mAh
Annual: 1,022 mAh
Battery life: 3,000 / 1,022 = 2.9 years
Add 20% safety margin: 2.4 years expected
Decision: 2.4 years is below 5-year target. Solutions:
- Upgrade batteries: 4x AA Lithium (6,000 mAh) β 4.8 years β
- Reduce reporting: Every 15 minutes β 7.2 years β
- Hybrid power: Small solar cell for window sensors β 10+ years β
Why: Battery life calculations often reveal that theoretical protocol power consumption and real-world operation differ significantly. Always validate with detailed energy budgets.
What we do: Create phased deployment plan with testing milestones.
Phase 1: Pilot (Floors 1-2, 50 sensors) - Deploy 10 Thread Border Routers (5 per floor) - Install 40 Thread sensors + 10 Wi-Fi damper sensors - Validate mesh coverage, battery consumption, BMS integration - Duration: 4 weeks
Phase 2: Expansion (Floors 3-6, 100 sensors) - Scale infrastructure based on pilot learnings - Optimize Thread parent assignment for battery life - Add monitoring dashboard for sensor health - Duration: 6 weeks
Phase 3: Full Deployment (Floors 7-10, 100 sensors) - Complete installation - Fine-tune HVAC control loops - Train facilities team on system management - Duration: 4 weeks
Bill of Materials:
| Item | Quantity | Unit Cost | Total |
|---|---|---|---|
| Thread Temperature/Humidity Sensor | 80 | $45 | $3,600 |
| Thread PIR Occupancy Sensor | 60 | $35 | $2,100 |
| Thread Light Sensor | 40 | $30 | $1,200 |
| Thread Energy Meter | 30 | $120 | $3,600 |
| Thread Air Quality Sensor | 15 | $85 | $1,275 |
| Wi-Fi HVAC Damper Controller | 25 | $150 | $3,750 |
| Thread Border Router | 20 | $200 | $4,000 |
| BACnet Integration Gateway | 2 | $1,500 | $3,000 |
| Installation Labor (250 sensors) | 1 | $15,000 | $15,000 |
| Total | $37,525 |
Why: Phased deployment reduces risk and allows optimization based on real-world performance data before full commitment.
Outcome: Hybrid Thread/Wi-Fi protocol architecture for 250-sensor BMS deployment.
Key Decisions Made and Why:
| Decision | Choice | Rationale |
|---|---|---|
| Primary protocol | Thread | Native IPv6, 5-year battery life, mesh coverage, Matter future-proofing |
| Secondary protocol | Wi-Fi | Sub-10ms latency for HVAC control loops, reuse existing infrastructure |
| Battery strategy | 4x AA Lithium + event filtering | Validated 4.8-year life meets 5-year target with margin |
| BMS integration | BACnet/IP via gateways | Industry standard, vendor-agnostic, existing BMS compatibility |
| Deployment approach | 3-phase over 14 weeks | Risk reduction, optimization opportunity, manageable scope |
Protocol Selection Summary:
Zigbee: NOT SELECTED
- Pro: Mature ecosystem, proven battery life
- Con: No native IP, requires translation gateway,
less future-proof than Thread/Matter
Thread: SELECTED (90% of sensors)
- Pro: Native IPv6, Matter-compatible, excellent battery life,
mesh networking, strong vendor support
- Con: Newer ecosystem than Zigbee (mitigated by Matter alliance)
Wi-Fi: SELECTED (10% of sensors)
- Pro: Lowest latency, existing infrastructure,
direct IP connectivity
- Con: Power consumption (not an issue for mains-powered actuators)
Expected Outcomes:
- Energy savings: 20% reduction in HVAC costs ($50,000/year for typical building)
- Battery replacement: Once every 4-5 years (vs. monthly for Wi-Fi sensors)
- System reliability: 99.9% data delivery via mesh redundancy
- ROI: System payback in 9 months ($37,525 / $50,000 annual savings)
671.5 Summary
This chapter provided practical Python implementations and a comprehensive worked example:
- Protocol stack analyzer calculates overhead and efficiency for different protocol combinations, showing 6LoWPAN compression reduces CoAP stack from 81 to 30 bytes
- Protocol selector engine automates recommendations based on device class, network type, and communication patterns
- Battery life calculator reveals that infrequent transmission is sleep-dominated while frequent transmission makes protocol choice critical (3.5Γ difference)
- Building management worked example demonstrates hybrid Thread/Wi-Fi architecture selection for 250 sensors with detailed battery validation
- Quantitative analysis shows initial battery calculations often fail (3.6 months instead of 5 years), requiring optimization through SED mode and event filtering
- ROI calculation justifies $37,525 deployment with 9-month payback from $50,000 annual HVAC savings
671.6 Whatβs Next
With protocol selection mastered through theory and practice, explore specialized networking topics:
- Layered Models: Fundamentals: Understand the OSI 7-layer and TCP/IP 4-layer models that organize network protocols into functional layers
- Layered Models: Labs and Implementation: Implement MAC/IP addressing, explore ARP resolution, and analyze encapsulation with hands-on Python tools
- Routing Fundamentals: Learn how packets traverse networks through routing tables and algorithms