This is the index for hands-on CoAP implementation, organized into three chapters: methods and communication patterns (GET/POST/PUT/DELETE, CON vs NON tradeoffs), implementation labs (Python aiocoap servers and Arduino ESP32 clients), and advanced features (Observe for push notifications, block-wise transfer for large payloads, and /.well-known/core resource discovery).
52.1 Learning Objectives
This section covers hands-on CoAP implementation, from basic methods to advanced features like Observe and Block Transfer. The content has been organized into three focused chapters:
Observe Option: CoAP extension enabling publish/subscribe: client registers to receive notifications on resource changes
Block-wise Transfer: Fragmentation mechanism for transferring payloads larger than a single CoAP datagram
Token: Client-generated value matching responses to requests — enables concurrent request/response pairing
DTLS: Datagram TLS — CoAP’s security layer providing encryption and authentication over UDP
52.2 For Beginners: CoAP Features and Labs
This chapter combines learning about CoAP features with hands-on practice. You will explore how CoAP handles observations, block transfers, and caching while building working examples. It is like learning to cook by following a recipe – you understand the ingredients while making something real.
52.3 Prerequisites
Before diving into these chapters, you should be able to:
CoAP Fundamentals and Architecture: Explain CoAP’s core design, distinguish message types (CON, NON, ACK, RST), and compare how CoAP differs from HTTP — essential for implementing advanced features
IoT Protocols Fundamentals: Describe the IoT protocol stack, justify the use of UDP transport, and apply RESTful principles to constrained device communication
Networking Basics: Apply client-server architecture concepts, trace request-response patterns, and analyze basic networking to understand resource discovery and multicast operations
Experiment with the controls to see when Observe provides the greatest benefit. Notice how polling intervals shorter than change frequency waste massive bandwidth on unchanged data.
Decision Framework: Choosing Between CON and NON Messages in CoAP
CoAP offers two message reliability modes: Confirmable (CON) requires explicit acknowledgment, while Non-Confirmable (NON) is fire-and-forget. Choosing the wrong mode wastes energy or causes data loss. Use this framework to decide:
Decision Factor
Confirmable (CON)
Non-Confirmable (NON)
Reliability
Guaranteed delivery (retries until ACK)
Best-effort (0-10% loss typical)
Energy Cost
High (2-5x NON due to retries/ACKs)
Low (single transmission)
Latency
1-2 RTTs (wait for ACK)
0 RTTs (fire-and-forget)
Network Overhead
2 packets min (request + ACK)
1 packet (request only)
Retry Logic
Automatic (exponential backoff)
None (application must detect loss)
Use Case
Critical commands, alarms, config changes
Frequent sensor readings, status updates
Best For
Low-frequency, high-importance
High-frequency, low-importance
Decision Tree:
Step 1: What happens if this specific message is lost?
System fails unsafely (door unlocks, alarm doesn’t sound, valve doesn’t close) → CON
Data gap but system continues (one temp reading missing, one status update lost) → NON
Step 2: How frequently is this message sent?
Rarely (<1/minute) → CON (energy cost is negligible)
Frequently (>1/minute) → Continue to Step 3
Step 3: Can the application tolerate occasional gaps?
No (every data point is critical, e.g., financial transactions) → CON
Yes (next message replaces previous value, e.g., current temperature) → NON
Step 4: Is the network reliable?
Lossy (>5% packet loss, e.g., LoRaWAN, cellular) → CON if critical, NON + redundancy otherwise
Reliable (<1% packet loss, e.g., wired Ethernet, good Wi-Fi) → NON acceptable
Real-World Examples:
Message Type
Frequency
CON or NON?
Reasoning
Thermostat setpoint change
Once per hour
CON
User expects confirmation, failure means room temperature wrong all day
Temperature reading
Every 10 seconds
NON
Missing one reading doesn’t matter, next one replaces it
Smoke alarm trigger
Once per emergency
CON
Life-safety critical, must be acknowledged
Heartbeat/keepalive
Every 60 seconds
NON
Missing one heartbeat is tolerable, multiple failures trigger offline status
Firmware download block
Every 100ms during update
CON
Each block must be received to reconstruct firmware
Motion detection event
Every 5 seconds when motion detected
NON
Frequency makes CON too expensive, occasional miss acceptable
Door unlock command
Rarely (user action)
CON
Security-critical, user expects confirmation
Hybrid Strategy: CON for Commands, NON for Telemetry:
# ✅ GOOD: Use appropriate message type for each resource# Configuration endpoint (critical, infrequent)@app.route('/config', methods=['PUT'])def update_config():# CoAP server sends CON responsereturn CoapResponse(code=CHANGED, type=CON)# Temperature sensor (frequent, non-critical)@app.route('/temperature', methods=['GET'])def get_temperature():# CoAP server sends NON responsereturn CoapResponse(code=CONTENT, type=NON, payload=f"{temp:.1f}")# Alarm trigger (critical, rare)@app.route('/alarm', methods=['POST'])def trigger_alarm():# CoAP server sends CON responsereturn CoapResponse(code=CHANGED, type=CON)
Putting Numbers to It
How does message type (CON vs NON) impact battery life? Let’s calculate for an AA battery sensor on LoRaWAN.
Battery capacity: 2,500 mAh (AA battery) CON message energy: 0.063 mAh (TX + wait for ACK + retries) NON message energy: 0.021 mAh (TX only, no ACK)
\[\text{Battery Life (days)} = \frac{\text{Battery Capacity (mAh)}}{\text{Messages/Day} \times \text{Energy/Message (mAh)}}\]
Worked example: Temperature sensor every 10 seconds
Try adjusting the controls above to see how polling interval and message type dramatically affect battery life. Notice how switching from CON to NON can triple battery life, and how increasing the polling interval has exponential impact.
Energy Impact Summary (AA battery, 2,500 mAh, LoRaWAN network):
Scenario
Message Type
Messages/Day
Energy/Day
Battery Life
Temperature (10s interval)
CON
8,640
544.3 mAh
4.6 days
Temperature (10s interval)
NON
8,640
181.4 mAh
13.8 days
Temperature (1min interval)
NON
1,440
30.2 mAh
82.8 days
Temperature (10min interval)
NON
144
3.0 mAh
827 days (2.3 years)
Hybrid (10min NON + 1/day CON)
Mixed
145
3.1 mAh
810 days (2.2 years)
Interactive Calculator: CON vs NON Reliability-Energy Tradeoff
Adjust the controls to explore how network quality and message frequency affect the CON vs NON decision. Notice how CON provides near-perfect delivery even on lossy networks, but at 2-3× energy cost.
Common Mistakes:
Using CON for high-frequency telemetry: Developers treat every sensor reading as critical, wasting 3x energy on ACKs for data that doesn’t need reliability
Using NON for commands: Commands like “unlock door” sent as NON have no delivery confirmation, creating security vulnerabilities
Not implementing application-level redundancy for NON: When using NON messages, always design for occasional loss (e.g., send status 3x, majority vote)
Best Practice: Default to NON, Use CON Selectively:
Default to NON for all periodic measurements and status updates
Switch to CON only when: user initiated action, safety-critical command, infrequent configuration change, or application cannot tolerate loss
Monitor NON loss rates: If >10% loss, network is too unreliable for NON—either fix network or switch to CON with longer intervals
Key Takeaway: The CON vs NON decision is fundamentally about energy vs reliability tradeoff. CON messages cost 2-5x more energy due to ACKs and retries, making them unsustainable for frequent telemetry on battery-powered devices. NON messages sacrifice reliability for efficiency, which is acceptable when the next message replaces the previous value. For most IoT deployments, the optimal pattern is NON for telemetry (90% of messages) and CON for commands (10% of messages), achieving both long battery life and safety-critical reliability where it matters.
Check Your Understanding: CON vs NON Decision
Common Pitfalls
1. Using Confirmable Messages for Every CoAP Request
CON messages require an ACK roundtrip — on lossy networks with 20% packet loss, a 4-attempt retry with exponential backoff can delay responses by 45 seconds. Use NON for periodic telemetry where data freshness matters more than guaranteed delivery; reserve CON for actuation commands.
2. Ignoring CoAP Proxy Caching Semantics
CoAP proxies cache GET responses based on Max-Age option — a sensor returning temperature with Max-Age=60 will serve cached values for 60 seconds even if the physical reading changes. Set Max-Age to match your data freshness requirement, not the default 60 seconds.
3. Forgetting DTLS Session Management
DTLS handshake (6-8 roundtrips) dominates latency for short-lived CoAP connections — repeatedly creating new DTLS sessions for each request adds 500-2000ms overhead. Use DTLS session resumption (RFC 5077) to reduce reconnection to 1 roundtrip after the initial handshake.
Label the Diagram
💻 Code Challenge
Order the Steps
Quiz: CoAP Features and Labs
52.8 Concept Relationships
This lab series connects practical implementation to theoretical concepts:
Foundation Knowledge:
CoAP Fundamentals - REST principles, message types (CON/NON), UDP transport