29  Protocol Scenarios & Interview

Key Concepts
  • Scenario Interview: A structured discussion where a candidate or student is given a real-world IoT deployment scenario and must reason through protocol and topology choices aloud
  • Requirements Elicitation: The process of extracting implicit and explicit constraints from a scenario description before proposing a solution
  • Trade-off Articulation: The ability to explain why one option is preferred over alternatives by explicitly naming the costs and benefits of each
  • STAR Method: Situation, Task, Action, Result — a framework for structuring scenario answers in interviews
  • Constraint Hierarchy: Ordering requirements by severity so that must-have constraints are addressed before optimising for nice-to-have features
  • Failure Mode Analysis: Identifying how each design choice could fail and what the consequence would be
  • Design Justification: Providing evidence (measurements, standards references, case studies) to support a design recommendation

29.1 In 60 Seconds

This chapter prepares you for IoT technical interviews with common questions covering protocol stack design, MQTT QoS levels (0/1/2 trade-offs), 6LoWPAN header compression walkthroughs, layer-by-layer connectivity debugging, and maximum payload calculations for constrained networks. Practice these scenarios to demonstrate both theoretical knowledge and practical protocol architecture skills.

Learning Objectives

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

  • Formulate Interview Responses: Construct structured answers to common IoT protocol interview questions
  • Design Protocol Stacks: Architect protocol stacks for real-world IoT deployment scenarios based on constraints
  • Differentiate MQTT QoS Levels: Justify the selection of QoS 0, 1, or 2 for specific data criticality requirements
  • Trace 6LoWPAN Compression: Walk through 6LoWPAN header compression step-by-step with byte-level examples
  • Diagnose Connectivity Issues: Apply layer-by-layer debugging to isolate IoT connectivity failures
  • Calculate Application Payloads: Compute maximum usable payload for constrained network frames

This chapter presents realistic IoT scenarios and asks you to choose the best protocol for each one. It is like a job interview question where you explain your reasoning – there is often no single right answer, but your thought process matters. Great practice for both exams and real-world decision-making.

“Imagine you are in a job interview,” said Max the Microcontroller. “The interviewer asks: ‘Design a protocol stack for 500 soil sensors across a 5-square-kilometer farm.’ How do you answer?”

“Start with requirements!” said Sammy the Sensor. “Battery-powered, long range, small data payloads, infrequent readings. That immediately points to LoRaWAN at the physical layer and CoAP at the application layer.”

Lila the LED added another scenario. “What if they ask about MQTT QoS levels? QoS 0 means fire-and-forget – fast but no guarantee. QoS 1 means at-least-once delivery – the broker acknowledges receipt. QoS 2 means exactly-once – no duplicates, but slower. Choose based on how critical the data is.”

“The secret to interview success,” said Bella the Battery, “is showing your REASONING, not just your answer. Walk through the layers systematically: What is the range? What is the power source? How much data? How often? How critical? Each answer narrows your protocol options. There is rarely one perfect answer, but a clear thought process impresses every interviewer!”

29.2 Prerequisites

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

29.3 Interview Prep: Common Questions on IoT Protocols

This section prepares you for technical interviews by covering frequently asked questions about IoT protocols, architectures, and design decisions.

29.3.1 Conceptual Questions

Q1: Explain the difference between MQTT and CoAP. When would you choose one over the other?

Key Points to Cover:

  • Architecture Pattern: MQTT uses publish-subscribe with a broker; CoAP uses request-response (RESTful) pattern
  • Transport Layer: MQTT runs over TCP (reliable, stateful); CoAP uses UDP (lightweight, stateless)
  • Overhead: MQTT has 2-byte fixed header; CoAP has 4-byte header
  • Use Cases:
    • Choose MQTT for: Continuous telemetry streams, dashboard updates, many subscribers, reliable delivery
    • Choose CoAP for: Battery-constrained devices, infrequent updates, direct device-to-device, request-response patterns

Example Answer: “MQTT and CoAP serve different IoT communication needs. MQTT is a publish-subscribe protocol over TCP, ideal for scenarios like smart home sensors streaming data to dashboards where multiple applications subscribe to topics. CoAP is a RESTful protocol over UDP, better for battery-powered parking sensors that report status changes infrequently—its UDP transport avoids TCP’s connection overhead, and direct request-response is simpler than broker-based pub/sub when you don’t need multiple subscribers.”


Q2: Why would you choose LoRaWAN over Wi-Fi for an IoT deployment?

Key Points to Cover:

  • Range vs Bandwidth Trade-off: LoRaWAN (10-15 km) vs Wi-Fi (50-100m)
  • Power Consumption: LoRaWAN devices last 5-10 years on battery; Wi-Fi drains batteries in weeks
  • Data Rate: LoRaWAN (0.3-50 kbps) vs Wi-Fi (10-1000 Mbps)
  • Use Cases: Agricultural sensors, smart parking, water meters (LoRaWAN) vs video surveillance, high-throughput sensors (Wi-Fi)

Example Answer: “The choice depends on application requirements. For a smart agriculture deployment monitoring soil moisture across a 100-acre farm, LoRaWAN wins: sensors send 50-byte readings hourly, battery life needs to exceed 5 years, and cellular coverage is spotty. LoRaWAN’s 15km range covers the entire farm from one gateway, and its ultra-low power consumption meets battery requirements. Conversely, for warehouse inventory management with fixed power and high data rates, Wi-Fi makes more sense despite its shorter range.”


Q3: What is 6LoWPAN and why is it essential for IEEE 802.15.4 networks?

Key Points to Cover:

  • Problem Statement: IPv6 header (40 bytes) doesn’t fit well in 802.15.4 frame (127 bytes max with ~25-byte MAC header)
  • Solution: 6LoWPAN compresses IPv6 headers to 2-7 bytes using stateless header compression (IPHC)
  • Benefits: Enables IP connectivity for constrained devices, more payload space for application data
  • Context Compression: Uses context information (link-local addresses, known prefixes) to omit redundant header fields

Example Answer: “6LoWPAN is the adaptation layer that makes IPv6 viable on 802.15.4 radios. Without it, a 25-byte 802.15.4 MAC header plus 40-byte IPv6 header plus 8-byte UDP header plus 2-byte FCS consumes 75 of the 127-byte frame, leaving only 52 bytes for application data – unacceptable overhead. 6LoWPAN’s IPHC compression reduces the IPv6 header to as little as 2 bytes by omitting predictable fields and using link-local context. This gives Zigbee and Thread networks full IP connectivity while preserving precious frame space for sensor data.”


29.3.2 Scenario-Based Questions

Q4: Design a protocol stack for a smart parking system with 1000 sensors reporting occupancy status in real-time. Consider power, cost, and reliability.

Approach to Demonstrate:

Step 1 - Analyze Requirements:

- 1000 sensors (city-wide deployment)
- Payload: Occupancy status (1 bit) + sensor ID + timestamp = ~10 bytes
- Update frequency: On status change (event-driven) + hourly heartbeat
- Battery life: 5+ years
- Reliability: High (parking revenue depends on it)
- Range: City-wide coverage

Step 2 - Evaluate Options: | Layer | Option A | Option B | Option C | Chosen | |——-|———-|———-|———-|——–| | Application | CoAP | MQTT | HTTP | CoAP (lightweight, event-driven) | | Transport | UDP | TCP | TCP | UDP (CoAP requirement, low overhead) | | Network | IPv6/6LoWPAN | IPv6 | IPv4 | IPv6/6LoWPAN (constrained network) | | Link | LoRaWAN | NB-IoT | Wi-Fi | NB-IoT (city coverage, reliability) |

Step 3 - Justify Choice:

  • Application (CoAP): Event-driven updates fit request-response better than pub/sub; 4-byte header minimal
  • Transport (UDP): No connection state = battery savings; CoAP adds reliability at application layer
  • Network (IPv6): Future-proof addressing; no NAT complexity
  • Link (NB-IoT): Cellular coverage city-wide; power-saving modes (PSM, eDRX); better reliability than LoRaWAN for revenue-critical application

Example Answer: “I’d use CoAP over UDP with IPv6 on NB-IoT. NB-IoT provides city-wide cellular coverage with PSM power-saving modes for 5+ year battery life. CoAP’s request-response pattern is simpler than MQTT for ‘sensor reports status, server acknowledges’ workflows. UDP avoids TCP’s connection overhead. IPv6 with NB-IoT’s built-in IP support (no 6LoWPAN needed) gives each sensor a unique address. The stack’s total overhead is ~50 bytes (NB-IoT headers + IPv6 + UDP + CoAP), leaving plenty of bandwidth for the 10-byte payload on NB-IoT’s ~20 kbps uplink.”


Q5: Your smart home system uses Zigbee for sensors but needs to integrate with a cloud dashboard. Design the network architecture.

Approach to Demonstrate:

Smart home protocol bridging architecture showing Zigbee sensors in mesh network communicating via 802.15.4/6LoWPAN/CoAP to IoT gateway hub, which translates protocols and forwards data via Wi-Fi using MQTT with TLS to cloud broker and web dashboard

Smart home protocol bridging architecture
Figure 29.1: Smart home protocol bridging architecture showing four Zigbee sensors (temperature, light switch, door lock, motion) in mesh network communicating via 802.15.4/6LoWPAN/CoAP to IoT gateway hub, which translates protocols and forwards data via Wi-Fi using MQTT with TLS encryption to cloud MQTT broker (AWS IoT or Azure IoT Hub), then to web dashboard for visualization with structured topic hierarchy (home/room/device/sensor)

Design Decisions:

  1. Sensor to Hub (Zigbee): Low power mesh network, 802.15.4 radio, 6LoWPAN for IPv6
  2. Hub to Cloud (MQTT over Wi-Fi): Gateway translates Zigbee to MQTT, Wi-Fi has bandwidth for multiple sensors
  3. Protocol Bridge: Hub acts as protocol translator (Zigbee Application Layer to MQTT topics)
  4. Security: Zigbee link keys + TLS for MQTT connection
  5. Topic Structure: home/room/device/sensor (e.g., home/livingroom/temp/reading)

Example Answer: “The gateway hub is the critical component. It runs a Zigbee coordinator to form the mesh network where sensors communicate using 802.15.4/6LoWPAN. The hub translates Zigbee application data into MQTT messages—for example, a temperature sensor’s Zigbee packet becomes an MQTT PUBLISH to topic ‘home/livingroom/temp’. The hub connects to the cloud MQTT broker over Wi-Fi with TLS encryption. This architecture leverages Zigbee’s strengths (low power, mesh, short-range) locally while using Wi-Fi/MQTT (higher bandwidth, internet connectivity) for cloud integration.”


29.3.3 Technical Deep-Dives

Q6: Walk me through MQTT QoS levels. When would you use each?

QoS 0 - At Most Once (Fire and Forget):

Client -> PUBLISH -> Broker -> PUBLISH -> Subscriber
         (no ACK)              (no ACK)

Use When:
- Data loss acceptable (temperature readings every second)
- Lowest latency critical
- Minimal bandwidth/power consumption needed
Example: Weather station sending updates every 10 seconds

QoS 1 - At Least Once (Acknowledged Delivery):

Client -> PUBLISH -> Broker -> PUBACK -> Client
                   |
         PUBLISH -> Subscriber -> PUBACK -> Broker

Use When:
- Data loss unacceptable but duplicates OK
- Balance reliability vs overhead
Example: Security alarm sensor reporting intrusion

QoS 2 - Exactly Once (Four-way Handshake):

Client -> PUBLISH -> Broker -> PUBREC -> Client
Client -> PUBREL -> Broker -> PUBCOMP -> Client
                   |
         PUBLISH -> Subscriber -> [same 4-way handshake]

Use When:
- Critical data, no loss or duplication tolerated
- Billing, financial transactions, control commands
Example: Medical device dosage control

Trade-off Analysis: | QoS | Messages | Bandwidth | Latency | Battery | Use Case | |—–|———-|———–|———|———|———-| | 0 | 1 | Lowest | ~1ms | Best | Telemetry streams | | 1 | 2 | Medium | ~50ms | Good | Alerts, events | | 2 | 4 | Highest | ~100ms | Worst | Financial, control |

Example Answer: “QoS selection depends on application tolerance for loss and duplicates. For a factory temperature sensor sending readings every second, QoS 0 is ideal—missing one reading out of thousands is acceptable, and the overhead of acknowledgments wastes bandwidth. For a fire alarm system, QoS 1 ensures the alarm reaches the monitoring station—a duplicate alarm is harmless, but missing one is catastrophic. For a chemical plant valve control system, QoS 2 guarantees exactly-once delivery—duplicate ‘close valve’ commands could cause equipment damage, and missed commands risk safety incidents.”


Q7: Explain how 6LoWPAN header compression works. Walk through a compression example.

Uncompressed IPv6 Packet (127-byte 802.15.4 frame):

Uncompressed IPv6 packet structure within 127-byte 802.15.4 frame showing 802.15.4 header (25 bytes), IPv6 header (40 bytes), UDP header (8 bytes), and remaining payload space (54 bytes), demonstrating why header compression is necessary for constrained networks
Figure 29.2: Uncompressed IPv6 packet structure

6LoWPAN IPHC Compressed Packet:

6LoWPAN IPHC compressed packet structure within 127-byte 802.15.4 frame showing 802.15.4 header (25 bytes), 6LoWPAN IPHC header (2-7 bytes with dispatch, IPHC encoding, inline fields), compressed UDP header (4 bytes), and payload space (91-96 bytes), demonstrating dramatic efficiency improvement from header compression
Figure 29.3: 6LoWPAN IPHC compressed packet structure

Compression Techniques:

  1. Context-based compression: Link-local addresses derived from MAC addresses (omit all 16 bytes when derivable)
  2. Well-known values: Version (always 6), Traffic Class (usually 0) = 0 bits
  3. Next Header compression: UDP = common, single bit instead of 8
  4. Hop Limit: Fixed values (1, 64, 255) = 2 bits instead of 8
  5. Address elision: Both addresses link-local = 2 bytes total instead of 32

Example Answer: “6LoWPAN’s IPHC looks at an IPv6 packet and asks: what can we omit or compress? For link-local addresses like fe80::0200:5aff:fe00:1234, the first 64 bits (fe80::/64 prefix) are predictable—omitted. The bottom 64 bits derive from the 802.15.4 MAC address already in the frame—also omitted. Result: 16-byte address becomes 0 bytes in IPHC header. Similar compression applies to well-known fields (version, traffic class), common values (UDP next header), and fixed hop limits. A 40-byte IPv6 header compresses to 2-7 bytes, freeing 33-38 bytes for payload—critical for 127-byte 802.15.4 frames.”

Let’s quantify MQTT QoS trade-offs with concrete energy and latency numbers for a battery-powered sensor:

Scenario: Door sensor reporting open/close events, 2000 mAh battery, 30 mA TX, 25 mA RX, 250 kbps link, 50 ms network RTT.

QoS 0 analysis (Fire and Forget): \[ \begin{aligned} \text{Messages per event} &= 1\text{ (PUBLISH only)} \\ \text{Packet size} &= 40\text{ bytes (TCP + MQTT + payload)} \\ \text{TX time} &= \frac{40 \times 8}{250{,}000} = 1.28\text{ ms} \\ \text{Energy per event} &= 30\text{ mA} \times 0.00128\text{ s} = 0.0384\text{ mAs} = 0.0000107\text{ mAh} \\ \text{Latency} &= 1.28\text{ ms (one-way, no wait for ACK)} \\[0.5em] \text{Events per day:} &\quad 50 \text{ (typical door usage)} \\ \text{Daily TX energy:} &\quad 50 \times 0.0000107 = 0.000535\text{ mAh} \\ \text{Daily sleep energy:} &\quad 5\text{ }\mu\text{A} \times 24\text{ h} = 0.12\text{ mAh} \\ \text{Battery life:} &\quad \frac{2000}{0.000535 + 0.12} \approx 16{,}600\text{ days} \approx 45\text{ years (sleep-dominated)} \end{aligned} \]

QoS 1 analysis (At-Least-Once): \[ \begin{aligned} \text{Messages per event} &= 2\text{ (PUBLISH + PUBACK)} \\ \text{PUBLISH} &= 40\text{ bytes} \\ \text{PUBACK} &= 4\text{ bytes} \\ \text{Total bytes} &= 44\text{ bytes (10\% more than QoS 0)} \\[0.5em] \text{TX energy} &= 30\text{ mA} \times \frac{40 \times 8}{250{,}000} = 0.0384\text{ mAs} \\ \text{RX energy} &= 25\text{ mA} \times \left(\text{RTT} + \frac{4 \times 8}{250{,}000}\right) \\ &= 25\text{ mA} \times (0.050 + 0.000128) = 1.253\text{ mAs} \\ \text{Total energy} &= 1.291\text{ mAs} = 0.000359\text{ mAh} \\ \text{Latency} &= 1.28\text{ ms} + 50\text{ ms RTT} = 51.28\text{ ms} \\[0.5em] \text{Daily TX+RX energy:} &\quad 50 \times 0.000359 = 0.01795\text{ mAh} \\ \text{Daily sleep energy:} &\quad 0.12\text{ mAh} \\ \text{Battery life:} &\quad \frac{2000}{0.01795 + 0.12} \approx 14{,}500\text{ days} \approx 40\text{ years (still sleep-dominated)} \end{aligned} \]

QoS 2 analysis (Exactly-Once): \[ \begin{aligned} \text{Messages per event} &= 4\text{ (PUBLISH, PUBREC, PUBREL, PUBCOMP)} \\ \text{Client TX bytes} &= 40\text{ (PUBLISH)} + 4\text{ (PUBREL)} = 44\text{ bytes} \\ \text{Client RX bytes} &= 4\text{ (PUBREC)} + 4\text{ (PUBCOMP)} = 8\text{ bytes} \\ \text{Roundtrips} &= 2 \times \text{RTT} = 100\text{ ms} \\[0.5em] \text{TX energy} &= 30\text{ mA} \times \frac{44 \times 8}{250{,}000} = 0.04224\text{ mAs} \\ \text{RX energy (2 RTTs)} &= 25\text{ mA} \times 0.100 = 2.5\text{ mAs} \\ \text{Total energy} &= 2.542\text{ mAs} = 0.000706\text{ mAh} \\ \text{Latency} &= 1.41\text{ ms TX} + 100\text{ ms} = 101.4\text{ ms} \\[0.5em] \text{Daily TX+RX energy:} &\quad 50 \times 0.000706 = 0.0353\text{ mAh} \\ \text{Daily sleep energy:} &\quad 0.12\text{ mAh} \\ \text{Battery life:} &\quad \frac{2000}{0.0353 + 0.12} \approx 12{,}900\text{ days} \approx 35\text{ years (still sleep-dominated)} \end{aligned} \]

Summary comparison:

QoS Energy/event Latency Relative energy Best for
0 0.0107 uAh 1.3 ms 1x (baseline) Non-critical telemetry
1 0.359 uAh 51.3 ms 34x Alarms, events
2 0.706 uAh 101.4 ms 66x Control commands

Key insight: At only 50 events/day, sleep current (0.12 mAh/day) dominates over TX energy in all QoS levels, making battery life differences small in absolute terms. The QoS energy difference becomes significant for high-frequency sensors (hundreds or thousands of events per day), where TX energy overtakes sleep current.


Q8: You’re debugging an IoT system where sensors can’t reach the cloud. Walk through your troubleshooting approach layer by layer.

Systematic Debugging Approach:

Layer 1 - Physical/Link Layer:

# Check sensor radio is working
$ iwconfig  # Check radio interface
$ iw dev wlan0 scan  # Scan for networks
$ ping -I wlan0 192.168.1.1  # Test link-local connectivity

Questions to Ask:
- Is the radio powered on? (LED indicators, battery voltage)
- Is the antenna connected? (RSSI readings)
- Are we in range of the gateway? (check distance, obstacles)
- Channel interference? (spectrum analyzer, channel scan)

Layer 2 - Network/6LoWPAN Layer:

# Check IPv6 addressing and routing
$ ip -6 addr show  # Verify IPv6 address assigned
$ ip -6 route show  # Check routing table
$ ping6 fe80::1%wpan0  # Ping gateway link-local

Questions to Ask:
- Does the device have an IPv6 address? (DHCPv6, SLAAC)
- Is 6LoWPAN header compression working? (packet capture)
- Can we reach the 6LoWPAN border router? (ping6 test)
- Fragmentation issues? (packet too large for MTU)

Layer 3 - Transport Layer:

# Check UDP/TCP connectivity
$ nc -u 2001:db8::1 5683  # Test UDP to CoAP server
$ ss -u  # Show UDP sockets
$ tcpdump -i wpan0 -vvv udp  # Capture UDP traffic

Questions to Ask:
- Are UDP ports open? (firewall rules)
- Packet loss rate? (ICMP statistics, retransmission counters)
- NAT64 gateway working? (if translating IPv6 to IPv4)

Layer 4 - Application Layer:

# Check CoAP/MQTT connectivity
$ coap-client -m get coap://[2001:db8::1]/temp
$ mosquitto_pub -h broker.mqtt.com -t "test" -m "hello"

Questions to Ask:
- Is the CoAP/MQTT server reachable? (endpoint URL correct)
- Authentication working? (credentials, TLS certificates)
- Protocol version mismatch? (MQTT 3.1 vs 5.0)
- Application-level errors? (check server logs)

Example Debugging Session:

Problem: Zigbee temperature sensor not sending to cloud

1. Physical Check:
   - Sensor LED blinking -> radio active
   - RSSI -75 dBm -> adequate signal

2. Network Check:
   - `ip -6 addr` -> no IPv6 address!
   - Root Cause: Gateway DHCPv6 server down

3. Fix: Restart gateway DHCPv6 daemon
   - `systemctl restart radvd`
   - Sensor gets address: fe80::0200:5aff:fe00:1234

4. Verify:
   - `ping6 fe80::1%wpan0` -> 0% loss
   - `coap-client -m get coap://[fe80::1]/sensor` -> 200 OK
   - Data flowing to cloud

Example Answer: “I use bottom-up troubleshooting. First, verify Layer 1/2—is the radio on, are we in range, do we have an IPv6 address? Tools: iwconfig, ip addr, ping6. Second, check Layer 3—is UDP traffic flowing? tcpdump on the gateway shows if packets arrive. Third, Layer 4—does the application protocol handshake work? For MQTT, try mosquitto_pub directly; for CoAP, use coap-client. This approach isolated a recent issue where sensors had connectivity but MQTT CONNECT was timing out—turned out the broker’s certificate expired, and TLS handshake failed silently at the application layer.”


29.3.4 System Design Questions

Q9: Design a battery-powered environmental monitoring network for a 500-acre farm. Sensors measure soil moisture, temperature, and rainfall.

Requirements Analysis:

Scope: 500 acres (2 km x 1 km)
Sensors: 100 nodes (soil moisture + temp every 5 acres)
Data: 20 bytes/reading, 1 reading/hour
Battery Life: 5 years minimum
Environment: Outdoor, no power, unreliable cellular

Architecture Design:

Agricultural IoT system architecture spanning 500-acre farm with 100 LoRaWAN sensor nodes using adaptive data rate, connecting to solar-powered central gateway with 4G backhaul to cloud platform with InfluxDB and Grafana

Agricultural LoRaWAN IoT architecture
Figure 29.4: Agricultural IoT system architecture spanning 500-acre farm (2km x 1km) with 100 LoRaWAN sensor nodes measuring soil moisture and temperature sending 20-byte readings hourly, using adaptive data rate (spreading factor SF7 near gateway for fast transmission, SF12 at edges for extended 2-5km range), connecting to solar-powered central LoRaWAN gateway with 4G/LTE cellular backhaul transmitting aggregated data via MQTT to cloud platform (InfluxDB time-series database, Grafana visualization), enabling farmer to monitor real-time soil conditions and historical trends for irrigation optimization

Technology Stack:

Layer Technology Justification
Application Custom payload (20 bytes) Minimal overhead for battery life
Network LoRaWAN (Class A) Long-range (2+ km), ultra-low power, license-free
Physical LoRa modulation (SF7-SF12) Adaptive data rate for range vs power trade-off
Gateway Single LoRaWAN gateway, solar-powered Covers 2 km radius, 4G backhaul to cloud
Cloud MQTT to InfluxDB to Grafana Standard time-series stack for ag monitoring

Battery Life Calculation:

Power Budget per Node:
- Sleep mode: 5 uA x 23.9 hours/day = 119.5 uAh
- Sensing (1/hour): 10 mA x 5 sec x 24 = 333 uAh
- LoRa TX (1/hour, SF9): 100 mA x 2 sec x 24 = 1,333 uAh
- Daily total: 1,785 uAh = 1.79 mAh/day

Battery capacity: 2x AA lithium (3.6V, 3000 mAh) = 6000 mAh
Lifetime: 6000 mAh / 1.79 mAh/day = 3,352 days = 9.2 years
Try It: IoT Battery Life Calculator

Adjust sleep current, TX parameters, and battery capacity to estimate sensor node battery life for LoRaWAN and similar LPWAN deployments.

Key Design Decisions:

  1. LoRaWAN over NB-IoT: No cellular coverage; LoRaWAN’s 2+ km range covers farm from one gateway
  2. Class A not Class C: Downlink rarely needed; Class A’s RX-only-after-TX saves power
  3. Adaptive Data Rate: SF7 near gateway (faster, less power), SF12 at edges (longer range)
  4. Gateway Placement: Central location with solar panel, 4G modem for cloud backhaul
  5. Data Format: Custom 20-byte payload (no JSON overhead): [sensor_id:4][moisture:2][temp:2][battery:2][timestamp:4][crc:2]

Example Answer: “LoRaWAN is ideal for this scenario. One solar-powered gateway covers the entire 500 acres with 2 km range. Sensors use LoRa’s adaptive data rate—nodes near the gateway transmit at SF7 (faster, 5.5 kbps, lower power), while distant nodes use SF12 (slower, 250 bps, better range). Class A operation minimizes power—sensors sleep 59 minutes, wake, measure soil moisture/temperature (5 seconds), transmit via LoRa (2 seconds at ~100 mA), then sleep again. With 6000 mAh lithium batteries, this yields 9+ years of operation. The gateway forwards data via 4G/MQTT to a cloud InfluxDB instance where farmers visualize trends in Grafana.”


29.3.5 Coding/Analysis Questions

Q10: Calculate the maximum application payload for a Zigbee (802.15.4) packet using 6LoWPAN compression. Show your work.

Given:

  • 802.15.4 MAC frame: 127 bytes max
  • Addresses: 16-bit short addresses (4 bytes total in frame)
  • Security: AES-CCM-128 (5 bytes security header + 16 bytes MIC = 21 bytes overhead)

Calculation:

802.15.4 frame structure breakdown for Zigbee with 6LoWPAN compression showing layer-by-layer byte allocation: 802.15.4 header (14 bytes including frame control, sequence number, addresses, security header), 6LoWPAN IPHC header (2 bytes best case), compressed UDP header (4 bytes), AES-CCM MIC (16 bytes), FCS (2 bytes), totaling 38 bytes overhead leaving 89 bytes maximum payload in 127-byte frame
Figure 29.5: 802.15.4 frame structure with 6LoWPAN compression

Maximum Application Payload: 89 bytes (Total Overhead: 38 bytes)

Try It: 802.15.4 Payload Calculator

Adjust parameters to see how compression, security, and addressing affect available payload in a 127-byte 802.15.4 frame.

Worst Case (No Compression):

If 6LoWPAN compression fails (non-compressible addresses):
- 802.15.4 Header: 14 bytes (including 5-byte security header)
- Full IPv6 Header: 40 bytes (no compression)
- Full UDP Header: 8 bytes
- AES-CCM MIC: 16 bytes
- FCS: 2 bytes
Total Overhead: 80 bytes
Available Payload: 47 bytes (47% less than compressed case!)

Example Answer: “With optimal 6LoWPAN compression and 802.15.4 security enabled, the maximum payload is 89 bytes. Here’s the breakdown: 14 bytes for the 802.15.4 header with short addresses and security, 2 bytes for the compressed 6LoWPAN IPHC header (link-local addresses omitted), 4 bytes for compressed UDP header (port range 0xF0B0-0xF0BF allows 4-bit encoding), 16 bytes for the AES-CCM authentication tag, and 2 bytes for the frame check sequence. That’s 38 bytes of overhead, leaving 89 bytes for your CoAP or application data. This shows why header compression is critical—without 6LoWPAN, the uncompressed IPv6 header alone consumes 40 bytes, reducing payload to just 47 bytes.”

Common Mistake: Deploying MQTT Without Proper QoS Configuration

The Error: A smart factory deploys 500 vibration sensors reporting machine health every second. All sensors use MQTT with default QoS 0 (fire-and-forget). After 3 months, maintenance finds that critical alerts about bearing failure were missed because messages were lost during network congestion. Post-mortem reveals 8% packet loss during peak hours, resulting in 8% of all alerts being silently dropped.

Why It’s Wrong:

MQTT offers three QoS levels specifically to handle different reliability needs:

QoS Delivery Overhead Use Case When to Avoid
QoS 0 At most once 1 message Non-critical telemetry Critical alerts, control commands
QoS 1 At least once 2 messages (+ retries) Important data, duplicates OK Billing, dosage control
QoS 2 Exactly once 4 messages Financial, control High-frequency telemetry

The specific failure:

QoS 0 message flow (fire-and-forget):
Sensor → PUBLISH → Broker
        (no ACK)

If network drops packet: Message lost forever
If broker crashes: Message lost forever
No retry, no confirmation, no recovery

Real-world impact:

  • 8% packet loss during peak congestion = 8% of alerts missing
  • Critical alert lost: Bearing temperature exceeded threshold, but PUBLISH packet dropped during network spike
  • Machine failure: Bearing seized 2 hours later, $150K damage + 3 days downtime
  • Root cause: Using QoS 0 for safety-critical alerts

How QoS 1 would have prevented this:

QoS 1 message flow (at-least-once):
Sensor → PUBLISH (msgID=123) → Broker
       ← PUBACK (msgID=123) ← Broker

If PUBLISH dropped: Sensor retries after 5s timeout
If PUBACK dropped: Sensor retries (broker de-duplicates)
Guaranteed delivery with duplicate detection

Battery impact comparison (for 500 sensors @ 1 msg/sec):

QoS 0:

Messages: 86,400/day per sensor
Packets: 1× per message = 86,400 packets/day
Network load: 43.2 million packets/day (500 sensors)

QoS 1 (with 8% loss):

Messages: 86,400/day per sensor
Initial PUBLISH: 86,400 packets
Retries (8% loss): 6,912 additional packets
PUBACKs: 86,400 packets (broker → sensor)
Total: 179,712 packets/day per sensor (+108% overhead)
Network load: 89.9 million packets/day (500 sensors) (+2.08×)

Revised strategy (multi-tier approach):

Data Type QoS Frequency Why
Routine vibration reading 0 1/sec Non-critical, occasional loss OK, reduces load by 50%
Threshold alert (warning) 1 Event-driven Important but duplicate OK, ensures delivery
Critical alert (danger) 2 Event-driven No loss or duplicates, prevents false positives AND false negatives
Machine stop command 2 On-demand Control command, exactly-once critical for safety

Cost-benefit:

  • QoS 0 for routine data: 43.2M packets/day
  • QoS 1 for warnings: ~5,000 alerts/day = 10K packets
  • QoS 2 for critical: ~500 alerts/day = 3K packets
  • Total: 43.2M packets (vs 89.9M with all QoS 1)

Result: 52% reduction in network load vs QoS-1-for-everything, while guaranteeing critical alert delivery.

Implementation gotcha: Many IoT libraries default to QoS 0 for performance. You must explicitly configure QoS per topic:

# Mosquitto Python example
client.publish("sensors/vibration/data", payload, qos=0)     # Routine
client.publish("alerts/warning", payload, qos=1)             # Warnings
client.publish("alerts/critical", payload, qos=2)            # Critical
client.publish("commands/stop", payload, qos=2)              # Control

Interview tip: When asked “How do you ensure MQTT message delivery?”, don’t just say “Use QoS 2 for everything.” Show understanding of trade-offs: - QoS 0 for non-critical high-frequency data (battery/bandwidth savings) - QoS 1 for important events where duplicates are harmless (95% of alerts) - QoS 2 only for critical control commands or financial transactions (expensive but necessary)

The lesson: MQTT QoS isn’t a “set once and forget” configuration. It’s a per-topic, per-message decision based on data criticality, battery constraints, and network capacity. Choosing wrong QoS for mission-critical data is as bad as not using MQTT at all.

Common Pitfalls

Saying “I would use LoRaWAN” without first asking about data rate, latency, and indoor vs outdoor coverage shows poor engineering discipline. Fix: always restate the requirements and ask one or two clarifying questions before proposing a solution.

A single answer suggests limited knowledge of the protocol landscape. Fix: present two or three options with explicit trade-offs and then recommend one with justification.

Many IoT scenarios involve battery-powered sensors. Recommending Wi-Fi for a device expected to last 5 years on two AA batteries reveals a knowledge gap. Fix: always ask about or address power budget before proposing a radio technology.

Experienced interviewers expect security considerations in every design discussion. Fix: include at least one sentence about encryption, authentication, or key management in every scenario response.

29.4 Summary

This chapter covered practical scenarios and interview preparation for IoT protocols:

  • MQTT vs CoAP selection depends on communication pattern (pub/sub vs request-response), transport requirements (TCP vs UDP), and device constraints
  • Protocol stack design requires analyzing requirements (power, range, reliability, cost) and matching protocols at each layer
  • MQTT QoS levels offer trade-offs: QoS 0 for high-frequency telemetry, QoS 1 for alerts, QoS 2 for critical control
  • 6LoWPAN compression is essential for 802.15.4 networks, reducing 40-byte IPv6 headers to 2-7 bytes
  • Layer-by-layer debugging systematically isolates IoT connectivity issues from physical radio to application protocol
  • System design for IoT requires calculating power budgets, choosing appropriate protocols for each layer, and optimizing for deployment constraints

29.5 Knowledge Check

29.6 Concept Relationships

Builds Upon:

Enables:

  • IoT Protocols Review: Comprehensive assessment
  • Real-world protocol stack design skills for interviews and deployments

Related Concepts:

  • MQTT QoS levels provide reliability tradeoffs (QoS 0 vs 1 vs 2)
  • 6LoWPAN IPHC compression is essential for 802.15.4 networks
  • Layer-by-layer debugging systematically isolates connectivity issues

29.7 What’s Next

Direction Chapter Focus
Next IoT Protocols: Labs and Selection Hands-on protocol implementation, Python tools, and selection frameworks
Previous IoT Protocols: Stack Architecture Complete IoT protocol stack layer by layer
Review IoT Protocols Review Comprehensive protocol comparison and assessment

Deep Dives:

Application Protocols:

Network Layer:

Foundational Concepts:

Learning:

External Resources: