1173  IoT Application Protocols: Worked Examples and Case Studies

1173.1 Learning Objectives

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

  • Apply Protocol Selection Frameworks: Systematically evaluate protocol choices for real-world IoT deployments
  • Analyze Agricultural Sensor Networks: Design communication architecture for multi-protocol IoT systems
  • Balance Trade-offs: Navigate power, bandwidth, latency, and reliability constraints
  • Design Hybrid Architectures: Combine multiple protocols to leverage their respective strengths
  • Justify Protocol Decisions: Document technical rationale for protocol selection

1173.2 Prerequisites

Before diving into this chapter, you should have completed:

1173.3 How This Chapter Fits

Chapter Series Navigation: 1. Introduction and Why Lightweight Protocols Matter 2. Protocol Overview and Comparison 3. REST API Design for IoT 4. Real-time Protocols 5. Worked Examples (this chapter)

This final chapter synthesizes all previous concepts through a comprehensive case study of agricultural IoT protocol selection.


1173.4 Worked Example: Protocol Selection for Agricultural Sensor Network

1173.5 Worked Example: Choosing Protocols for a Smart Agriculture Deployment

Scenario: A farming cooperative is deploying soil sensors across 500 hectares of farmland to monitor soil moisture, temperature, pH, and nutrient levels. The deployment includes 200 battery-powered sensors with 5-year target battery life, 10 solar-powered weather stations, and 5 LoRaWAN gateways with cellular backhaul. Data must reach a cloud platform for irrigation control decisions, with some readings requiring near-real-time response (soil moisture triggering irrigation) and others tolerating hourly batching (soil pH for long-term analysis).

Goal: Select the optimal application protocol(s) for sensor-to-gateway and gateway-to-cloud communication, balancing power consumption, reliability, bandwidth efficiency, and implementation complexity.

What we do: Analyze data patterns, timing constraints, and device capabilities.

Why: Protocol selection depends on matching protocol characteristics to application needs.

Data flow analysis:

Source Count Data Type Size Frequency Urgency
Soil moisture sensor 200 Single value + ID 12 bytes Every 15 min High (irrigation trigger)
Temperature sensor 200 Single value + ID 10 bytes Every 15 min Low (trend analysis)
pH sensor 200 Single value + ID 10 bytes Every 4 hours Very low (monthly reports)
Nutrient sensor (NPK) 200 3 values + ID 18 bytes Every 4 hours Very low
Weather station 10 10 metrics + ID 80 bytes Every 5 min Medium (forecast input)

Aggregate traffic calculation:

Segment Messages/hour Bytes/hour Peak burst
Sensors to gateway 850 ~12 KB 200/min at top of hour
Gateway to cloud 850 (relayed) ~25 KB (with headers) Same
Cloud to gateway (commands) ~10 ~500 bytes Irrigation triggers

Device constraints:

Device Type CPU RAM Power Budget Radio
Soil sensor 16 MHz MCU 8 KB 3 uA sleep, 20 mA TX LoRa (SF7-12)
Weather station 48 MHz MCU 32 KB Solar, 100 mA continuous OK LoRa + cellular
Gateway ARM Cortex-A 512 MB Mains/solar, unconstrained LoRaWAN + LTE

Key insight: Sensors are extremely constrained (8 KB RAM rules out TLS). Gateway has resources for any protocol. Two-stage protocol strategy needed.

What we do: Compare MQTT, CoAP, and HTTP for each network segment.

Why: Different segments have different constraints; one protocol may not fit all.

Sensor-to-Gateway segment (LoRaWAN link):

Protocol Feasibility Pros Cons
CoAP Excellent 4-byte header, UDP-based, fits LoRa Limited QoS, no built-in pub-sub
MQTT-SN Good Designed for sensor networks, QoS options More complex, needs gateway translation
Raw payload Excellent Minimal overhead, maximum battery No standard tooling, custom parsing
HTTP Poor Universal but huge overhead 200+ byte headers kill battery

Gateway-to-Cloud segment (LTE cellular):

Protocol Feasibility Pros Cons
MQTT Excellent Persistent connection, QoS levels, broker ecosystem TCP overhead for small messages
CoAP Good Lightweight, works over UDP Less ecosystem support, NAT issues
HTTP Good Universal, RESTful, debugging tools High overhead, no push without SSE
AMQP Good Enterprise routing, transactions Overkill for this scale

Cloud-to-Device commands (irrigation triggers):

Protocol Feasibility Pros Cons
MQTT Excellent Bidirectional on same connection, subscribe pattern Already connected for telemetry
CoAP Observe Good Lightweight subscription Less mature than MQTT
HTTP polling Poor Constant overhead, latency Wastes battery, slow response

What we do: Select protocols for each segment and design the message flow.

Why: The right combination leverages each protocol’s strengths.

Recommended architecture:

[Soil Sensors]                    [Gateway]              [Cloud]
      |                               |                     |
      |----CoAP/LoRaWAN (minimal)--->|                     |
      |                               |                     |
      |                               |---MQTT/TLS/LTE---->|
      |                               |<--MQTT subscribe---|
      |                               |                     |
      |<--LoRaWAN Class C downlink---|<--MQTT command-----|

Protocol selection rationale:

Segment Protocol Rationale
Sensor to Gateway CoAP over LoRaWAN Minimal overhead (4 bytes), confirmable option, fits 51-byte LoRa payload
Gateway to Cloud MQTT with TLS Reliable delivery (QoS 1), persistent connection (no handshake per message), cloud platform support
Cloud to Gateway MQTT subscribe Same connection, instant push for irrigation commands
Gateway to Sensor LoRaWAN Class C Downlink for urgent commands, sensors listen continuously when powered

Why not MQTT-SN on sensors?

  • Requires UDP and broker—LoRaWAN provides reliability at MAC layer
  • CoAP NON (non-confirmable) for low-priority data = 4 bytes
  • CoAP CON (confirmable) for moisture = 4 bytes + ACK
  • MQTT-SN PUBLISH = 7+ bytes minimum

What we do: Optimize payload encoding for each protocol and link.

Why: Every byte matters for battery life; LoRa energy scales with payload size.

Sensor payload format (binary, 12 bytes total):

Byte 0-1:  Sensor ID (uint16)
Byte 2:    Message type (0=moisture, 1=temp, 2=pH, 3=NPK)
Byte 3-4:  Value 1 (uint16, scaled)
Byte 5-6:  Value 2 (uint16, for NPK only)
Byte 7-8:  Value 3 (uint16, for NPK only)
Byte 9:    Battery level (0-255)
Byte 10:   Sequence number (0-255, for dedup)
Byte 11:   Checksum (CRC8)

CoAP message structure (sensor to gateway):

CoAP Header (4 bytes):
  Ver=1, T=CON, TKL=1, Code=POST
  Message ID (2 bytes)
  Token (1 byte)

Options (3 bytes):
  Uri-Path: "d" (delta=11, len=1, value="d")

Payload (12 bytes):
  Binary sensor data as above

Total: 19 bytes over LoRa (vs 200+ for HTTP)

MQTT message structure (gateway to cloud):

Topic: farm/gateway-01/sensors/moisture
Payload (JSON for cloud compatibility):
{
  "sensor_id": "S-0142",
  "type": "moisture",
  "value": 34.7,
  "unit": "%",
  "battery": 92,
  "seq": 128,
  "ts": "2024-07-15T10:30:00Z",
  "gateway": "GW-01"
}

Total: ~180 bytes (acceptable over LTE)

Why binary on LoRa, JSON on LTE?

  • LoRa: 12 bytes binary vs 100+ bytes JSON = 8x battery savings
  • LTE: Bandwidth abundant, JSON enables debugging, cloud parsing

What we do: Quantify battery life impact of protocol choices.

Why: 5-year battery life is the primary constraint; wrong protocol = frequent replacement.

LoRa transmission energy (SF7, 125 kHz, 14 dBm):

Payload Size Time on Air Energy (uJ) Per Day (200 sensors)
12 bytes (binary) 36 ms 1,000 4,800 messages/day
51 bytes (max) 77 ms 2,100 -
100 bytes (JSON) N/A Would need SF12 Infeasible

Battery life calculation (2x AA lithium, 6,000 mAh):

Activity Current Duration Daily mAh
Sleep (23.8 hours) 3 uA 23.8 h 0.07
Sensor reading (96x) 5 mA 0.5 s each 0.07
LoRa TX (96x) 40 mA 36 ms each 0.04
LoRa RX (Class A) 12 mA 200 ms each 0.06
Daily total - - 0.24 mAh
Battery life - - ~7 years

If HTTP were used (hypothetical, requires cellular modem):

Activity Current Duration Daily mAh
Cellular wake 100 mA 5 s each 13.3
HTTP request 50 mA 2 s each 2.7
Daily total - - 16+ mAh
Battery life - - ~1 year

Key insight: CoAP over LoRaWAN achieves 7-year battery life. HTTP over cellular would last only 1 year. Protocol choice directly determines project economics.

What we do: Configure QoS and retry strategies for each data type.

Why: Not all data is equally important; over-protecting low-priority data wastes energy.

Reliability configuration by data type:

Data Type Urgency CoAP Mode MQTT QoS Retry Strategy
Soil moisture High CON (confirmable) QoS 1 3 retries, exponential backoff
Temperature Low NON (non-confirmable) QoS 0 No retry (loss acceptable)
pH Very low NON (batched) QoS 0 Daily batch upload
Irrigation command Critical N/A (downlink) QoS 2 Retry until ACK

Gateway buffering for connectivity loss:

class GatewayBuffer:
    def __init__(self, max_size_mb=100):
        self.buffer = []  # Persisted to SD card
        self.max_size = max_size_mb * 1024 * 1024

    def receive_from_sensor(self, msg):
        # Always accept from sensors
        self.buffer.append({
            'timestamp': time.time(),
            'priority': self.get_priority(msg),
            'data': msg
        })
        self.enforce_size_limit()

    def sync_to_cloud(self, mqtt_client):
        if not mqtt_client.is_connected():
            return  # Buffer until connected

        # Sort by priority, send critical first
        sorted_buffer = sorted(self.buffer, key=lambda x: -x['priority'])

        for msg in sorted_buffer:
            qos = 1 if msg['priority'] > 5 else 0
            if mqtt_client.publish(msg['data'], qos=qos):
                self.buffer.remove(msg)

    def get_priority(self, msg):
        # Moisture > 80% or < 20% = critical
        if msg['type'] == 'moisture':
            if msg['value'] > 80 or msg['value'] < 20:
                return 10
            return 5
        return 1

Outcome: A two-stage protocol architecture using CoAP over LoRaWAN for sensor-to-gateway and MQTT over TLS for gateway-to-cloud, achieving 7-year sensor battery life while meeting all reliability requirements.

Key decisions made and why:

Decision Choice Rationale
Sensor protocol CoAP (not MQTT-SN) 4-byte header vs 7+, simpler implementation on 8KB MCU
Sensor encoding Binary (12 bytes) 8x smaller than JSON, directly impacts battery
Gateway protocol MQTT with TLS Reliable, bidirectional, cloud platform compatibility
Cloud encoding JSON Debugging, analytics tools, bandwidth not constrained
Moisture reliability CoAP CON + MQTT QoS 1 Critical for irrigation timing
Temperature reliability CoAP NON + MQTT QoS 0 Loss of individual readings acceptable
Command delivery MQTT QoS 2 + LoRaWAN Class C Must guarantee irrigation commands execute

Protocol overhead comparison for this deployment:

Protocol Stack Sensor Payload Total on LoRa Efficiency
CoAP + binary 12 bytes 19 bytes 63%
MQTT-SN + binary 12 bytes 22 bytes 55%
HTTP + JSON 100 bytes Infeasible N/A

Quantified outcomes:

  • Battery life: 7 years (exceeds 5-year target)
  • Message overhead: 19 bytes total (63% payload efficiency)
  • Reliability: 99.9% for moisture readings (CoAP CON + retries)
  • Command latency: < 2 seconds from cloud trigger to sensor
  • Gateway buffer: 100 MB = 7 days of data during cellular outage
  • Cloud bandwidth: ~25 KB/hour (600 KB/day) - minimal LTE costs

1173.6 What’s Next?

Continue to MQTT Fundamentals for a deep dive into the most widely-used IoT messaging protocol, including topics, QoS levels, and practical implementation patterns.


1173.7 Summary

This chapter demonstrated practical protocol selection through a comprehensive agricultural sensor network case study:

Key insights: - Multi-protocol hybrid architectures: Leveraging CoAP for soil sensors, LoRaWAN for weather stations, MQTT for gateway-to-cloud, and HTTP for web dashboard - Systematic evaluation framework: Analyzing requirements (devices, data rates, connectivity), evaluating protocol trade-offs, and justifying decisions - Power-constrained design: Battery-powered soil sensors use CoAP over 6LoWPAN to achieve multi-year battery life - Long-range connectivity: LoRaWAN provides 2-5km coverage for remote weather stations with minimal power - Scalable cloud integration: MQTT broker handles thousands of devices with pub-sub fan-out to analytics and alerts - Real-world constraints: Balancing technical ideal with deployment realities (existing infrastructure, team expertise, cost)

1173.8 Conclusion: Application Protocols Series

Congratulations on completing the IoT Application Protocols series! You now have a comprehensive understanding of:

  1. Why lightweight protocols matter: HTTP/XMPP overhead vs CoAP/MQTT efficiency
  2. Protocol architectures: CoAP request-response, MQTT publish-subscribe, HTTP/2 multiplexing
  3. REST API design: Resource hierarchies, error handling, versioning, rate limiting
  4. Real-time protocols: RTP/SIP for audio/video IoT applications
  5. Practical application: Worked examples and protocol selection frameworks

1173.9 What’s Next?

Continue your IoT learning journey with protocol-specific deep dives:

For system design: - IoT Architecture Foundations - Privacy and Security - Data Management and Analytics