34  Protocol Python Lab

Key Concepts
  • paho-mqtt: The Eclipse Paho Python library for MQTT clients; supports QoS 0/1/2, TLS, and persistent sessions
  • aiocoap: An asynchronous CoAP library for Python using asyncio; suitable for building both CoAP clients and servers
  • asyncio: Python’s built-in framework for writing concurrent single-threaded code using coroutines; used by aiocoap and many IoT libraries
  • Callback Function: A function registered with the MQTT client that is invoked automatically when a message arrives or a connection event occurs
  • TLS/SSL: Transport Layer Security; encrypts MQTT or CoAP traffic; requires certificate files and port 8883 (MQTT) or 5684 (CoAPS)
  • JSON Serialisation: Converting Python dicts to JSON strings (json.dumps) for transmission and back (json.loads) on receipt
  • Virtual Environment: An isolated Python environment (venv) that prevents library version conflicts between projects

34.1 In 60 Seconds

This lab provides Python tools for quantitative IoT protocol analysis: a stack overhead calculator, a battery life estimator based on transmission patterns, and an automated protocol selector engine. A comprehensive worked example walks through designing a complete protocol architecture for a building management system, demonstrating how calculations – not intuition – should drive protocol decisions.

34.2 Learning Objectives

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

  • Construct protocol stack analyzers: Compute overhead and efficiency for different protocol combinations programmatically
  • Implement battery life calculators: Estimate device longevity from transmission patterns, sleep current, and radio parameters
  • Develop protocol selector engines: Automate protocol recommendations by encoding decision criteria into executable logic
  • Architect complete protocol stacks: Synthesize end-to-end communication stacks for multi-sensor building management systems
  • Validate designs with quantitative analysis: Justify protocol choices through iterative energy budget calculations and cost modeling

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:

34.3 Python Implementations

34.3.1 Implementation 1: Protocol Stack Analyzer

######################################################################################
# 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 (63% 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)
Try It: Protocol Stack Overhead Calculator

Adjust the payload size and see how efficiency changes across protocol stacks. Observe how larger payloads dramatically improve efficiency for compressed stacks.

Packet-size reductions translate directly into less radio-on time and lower energy use.

\[ T_{day} = N_{msg}\times \frac{L\times 8}{R} \]

Where \(N_{msg}\) is messages/day, \(L\) is packet bytes, and \(R\) is link bitrate.

Worked example: For \(N_{msg}=288\) messages/day at \(R=250\) kbps:

\[ \begin{aligned} T_{day,\ 30B} &= 288\times\frac{30\times 8}{250000}=0.276\text{ s/day}\\ T_{day,\ 81B} &= 288\times\frac{81\times 8}{250000}=0.746\text{ s/day} \end{aligned} \]

Compression cuts daily TX airtime by \(0.746-0.276=0.470\) seconds (about 63%). On constrained nodes, that saving compounds over years of operation.


34.3.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)

34.3.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 (every 5 min, 288 msgs/day):
   Sleep current dominates → Protocol choice has minimal impact
   All protocols achieve >40 years (limited by battery self-discharge)

2. For frequent transmission (every 10 sec, 8640 msgs/day):
   Active energy grows → Protocol overhead becomes significant
   CoAP (compressed): 40.5 years
   CoAP (uncompressed): 33.3 years
   MQTT: 31.9 years
   HTTP: 26.3 years
   → CoAP compressed provides ~1.5× longer battery life vs HTTP
==========================================================================================
Try It: Battery Life Estimator

Adjust transmission frequency, packet size, and battery capacity to see how protocol choice affects device longevity. Watch how sleep current dominates at low frequencies while active energy dominates at high frequencies.


Protocol Deep Dives:

Protocol Comparisons:

Network Design:

Learning Resources:

34.4 Worked Example: Building Energy Management System

34.5 Sensor Network Protocol Selection for a 250-Sensor BMS

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:

  1. Upgrade batteries: 4x AA Lithium (6,000 mAh) → 4.8 years ✓
  2. Reduce reporting: Every 15 minutes → 7.2 years ✓
  3. 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)

Many IoT deployments benefit from using different protocols at different network layers, rather than one protocol end-to-end. Use this framework:

Network Segment Distance Device Class Power Best Protocol Why
Sensor → Gateway <100m Class 1-2 Battery Zigbee/Thread/BLE Ultra-low power, mesh extends range, lightweight
Gateway → Edge <100m Full Mains Wi-Fi or Ethernet High bandwidth, reliable infrastructure
Edge → Cloud Internet N/A Mains MQTT/TLS over TCP Broker scalability, cloud compatibility

When to Use Hybrid:

Scenario 1: Battery-Powered Sensors in Building

250 sensors → [Thread mesh] → Border Router → [Ethernet] → BMS Server → [MQTT/TLS] → Cloud

Why hybrid:
- Thread: 5-year battery life for sensors (CoAP/UDP/6LoWPAN optimized)
- Ethernet: Reliable on-premise infrastructure (border router has power)
- MQTT/TLS: Cloud services already support it (no custom integration)

Why not homogeneous:
- MQTT all the way: Sensors can't run TCP/TLS (Class 1, 16KB RAM)
- Thread all the way: Cloud doesn't support CoAP natively
- Wi-Fi all the way: 300× higher power would drain batteries in weeks

Scenario 2: Smart Agriculture

Soil sensors → [LoRa] → Gateway → [Cellular LTE] → Cloud

Why hybrid:
- LoRa: 15 km range, 10-year battery life on unlicensed spectrum
- Cellular: Gateway has power, gets internet anywhere on farm
- No Wi-Fi infrastructure in fields

Why not homogeneous:
- Cellular end-to-end: $3/month × 500 sensors = $18,000/year subscription
- LoRa end-to-end: Gateway can't reach cloud (LoRa is not internet-routable)

When to Use Homogeneous:

Scenario 3: Factory Floor with Ethernet

Industrial PLCs → [Modbus/TCP] → Factory Server → [MQTT/TLS] → Cloud

Why homogeneous:
- All devices mains-powered (no battery constraint)
- All devices within Ethernet reach (no range constraint)
- Existing industrial protocol (Modbus) already TCP-based
- Minimal protocol translation (Modbus TCP → MQTT at server, not at device)

Decision Rules:

  1. If sensors are battery-powered: Use lightweight protocol (CoAP/UDP, LoRa) at sensor layer
  2. If coverage > 100m: Use LPWAN (LoRa, NB-IoT) at sensor layer, gateway translates
  3. If cloud integration required: Use MQTT or HTTP at cloud edge, regardless of sensor protocol
  4. If Class 0-1 devices: Use minimal protocol at device, translate at gateway
  5. If all mains-powered + Ethernet available: Use single protocol (MQTT, Modbus) end-to-end

Cost of Hybrid Architecture:

Component Cost Alternative (Homogeneous)
Protocol translation code Development: $5K-15K $0 (no translation)
Gateway hardware $200-2,000/gateway \(0 (direct to cloud) | | Maintenance complexity | Medium (2+ protocols) | Low (1 protocol) | | **Savings** | **Battery life: years vs weeks** | N/A | | **Savings** | **Spectrum: unlicensed (free) vs cellular (\)$$)**

Hybrid ROI: Initial complexity pays off when: - 100+ battery-powered devices (years vs weeks battery life = massive operational savings) - Unlicensed spectrum saves $3/month × devices × years (e.g., 500 devices × $3 × 10 years = $180,000)

Anti-Pattern: Using a single protocol everywhere because “it’s simpler” when devices have fundamentally different constraints.

Best Practice: Match protocol to constraints at each segment, translate at natural boundaries (gateway, edge server).

Common Pitfalls

The paho-mqtt client does not process incoming messages without an event loop. Forgetting to start the loop means callbacks never fire. Fix: call client.loop_start() before publish() calls, or client.loop_forever() at the end of a script.

Running time.sleep() inside an async function blocks the entire event loop, stopping all concurrent CoAP requests. Fix: use await asyncio.sleep() for delays inside async functions.

Committing password = "secret123" to a Git repository exposes credentials. Fix: load broker address and credentials from environment variables or a config file excluded from version control.

Network interruptions will disconnect the MQTT client. Without reconnection logic, the script silently stops receiving messages. Fix: implement on_disconnect callback and call client.reconnect() with exponential back-off.

34.6 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 overhead increasingly significant (up to 1.5x 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

34.7 Knowledge Check

34.8 Concept Relationships

Python implementation tools automate the manual calculations from earlier chapters:

Related Concepts:

  • Protocol stack analysis programmatically calculates overhead for any layer combination (application + transport + network + link)
  • Battery life modeling requires transmission energy (packet size × data rate × current) + sleep energy (time × sleep current)
  • Protocol selector engines encode decision trees from selection framework into executable logic
  • Worked examples demonstrate iterative optimization: initial calculation identifies shortfall, optimizations improve result
  • Total cost of ownership balances technical metrics (battery life) with economic factors (infrastructure cost, subscriptions)

Prerequisite Knowledge:

Builds Foundation For:

34.9 See Also

Implementation Resources:

Related Tools:

Deployment Guides:

34.10 What’s Next

If you want to… Read this
Learn the theory behind MQTT and CoAP Application Layer Protocols
Understand protocol selection trade-offs Protocol Selection Guide
Explore real-world protocol deployments Real-World Examples
Run the IPv6/6LoWPAN lab IPv6 and 6LoWPAN Lab
See all protocol labs in one place Labs and Selection

ython tools - Routing Fundamentals: Learn how packets traverse networks through routing tables and algorithms