1225  CoAP Methods, Multicast, and Features

1225.1 CoAP Methods

Like HTTP, CoAP uses REST methods:

Method Purpose HTTP Equivalent Idempotent
GET Retrieve resource GET Yes
POST Create resource POST No
PUT Update/Create PUT Yes
DELETE Remove resource DELETE Yes

1225.1.1 Examples

GET: Retrieve temperature

coap://sensor.local/temperature

POST: Add new sensor reading

coap://server.local/readings
Payload: {"temp": 23.5, "time": "2025-10-24T23:30:00Z"}

PUT: Update configuration

coap://device.local/config
Payload: {"interval": 60}

DELETE: Remove old data

coap://server.local/readings/old

1225.2 💻 Code Examples

1225.2.1 Python CoAP Server

import asyncio
from aiocoap import *

class TemperatureResource(resource.Resource):
    """Example resource for temperature readings"""

    async def render_get(self, request):
        """Handle GET requests"""
        temperature = 22.5  # Simulated sensor reading

        payload = f"{temperature}".encode('utf-8')

        return Message(
            code=Code.CONTENT,
            payload=payload,
            content_format=0  # text/plain
        )

    async def render_put(self, request):
        """Handle PUT requests to update config"""
        print(f'Received: {request.payload}')

        return Message(code=Code.CHANGED)

async def main():
    # Create CoAP server
    root = resource.Site()

    # Add temperature resource
    root.add_resource(
        ['temperature'],
        TemperatureResource()
    )

    # Start server
    await Context.create_server_context(root)

    print("CoAP server started on port 5683")
    await asyncio.get_running_loop().create_future()

if __name__ == "__main__":
    asyncio.run(main())

Install: pip install aiocoap

1225.2.2 Python CoAP Client

import asyncio
from aiocoap import *

async def get_temperature():
    """Fetch temperature from CoAP server"""

    # Create CoAP client protocol
    protocol = await Context.create_client_context()

    # Build GET request
    request = Message(
        code=Code.GET,
        uri='coap://localhost/temperature'
    )

    try:
        # Send request
        response = await protocol.request(request).response

        print(f'Response Code: {response.code}')
        print(f'Temperature: {response.payload.decode("utf-8")}°C')

    except Exception as e:
        print(f'Failed to fetch: {e}')

async def update_config():
    """Send PUT request to update configuration"""

    protocol = await Context.create_client_context()

    request = Message(
        code=Code.PUT,
        uri='coap://localhost/config',
        payload=b'{"interval": 30}'
    )

    response = await protocol.request(request).response
    print(f'Update result: {response.code}')

# Run client
asyncio.run(get_temperature())

1225.2.3 Arduino ESP32 CoAP Client

#include <Wi-Fi.h>
#include <coap-simple.h>

// Wi-Fi credentials
const char* ssid = "YourWi-Fi";
const char* password = "YourPassword";

// CoAP client
Coap coap;

// CoAP server details
IPAddress serverIP(192, 168, 1, 100);
int serverPort = 5683;

void callback_response(CoapPacket &packet, IPAddress ip, int port) {
  char payload[packet.payloadlen + 1];
  memcpy(payload, packet.payload, packet.payloadlen);
  payload[packet.payloadlen] = NULL;

  Serial.print("CoAP Response: ");
  Serial.println(payload);
}

void setup() {
  Serial.begin(115200);

  // Connect to Wi-Fi
  Wi-Fi.begin(ssid, password);
  while (Wi-Fi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("\nWi-Fi connected");

  // Start CoAP
  coap.response(callback_response);
  coap.start();
}

void loop() {
  // Send GET request every 10 seconds
  int msgid = coap.get(serverIP, serverPort, "temperature");

  Serial.print("Request sent, MID: ");
  Serial.println(msgid);

  delay(10000);

  coap.loop();
}

1225.3 📊 Interactive Comparison: CoAP vs MQTT vs HTTP

Let’s visualize how these protocols compare across key metrics for IoT applications:

NoteKey Insights

CoAP Advantages: - ✅ Smallest header size (4 bytes) - minimal overhead - ✅ Best battery life (UDP, no connection overhead) - ✅ RESTful design - familiar to web developers - ✅ Low latency - simple request/response

When CoAP Wins: - Resource-constrained devices (8-bit microcontrollers) - Battery-powered sensors (years not months) - Intermittent connectivity (devices sleep often) - Integration with web infrastructure (HTTP proxies)

When to Choose Alternatives: - MQTT: Publish-subscribe needed, TCP reliability required - HTTP: Full web stack needed, rich tooling ecosystem

1225.4 💻 Interactive Tool: CoAP Message Size Calculator

Calculate the actual bytes sent over the network for different protocols:

TipMessage Size Optimization

For small payloads (< 100 bytes), protocol overhead dominates:

Payload CoAP MQTT HTTP CoAP Savings
10 bytes {python} f”{calculate_coap_size(len(uri_topic), 10)} bytes” {/python} {python} f”{calculate_mqtt_size(len(uri_topic), 10)} bytes” {/python} {python} f”{calculate_http_size(len(uri_topic), 10)} bytes” {/python} {python} f”{int((1 - calculate_coap_size(len(uri_topic), 10)/calculate_http_size(len(uri_topic), 10))*100)}%” {/python} vs HTTP
50 bytes {python} f”{calculate_coap_size(len(uri_topic), 50)} bytes” {/python} {python} f”{calculate_mqtt_size(len(uri_topic), 50)} bytes” {/python} {python} f”{calculate_http_size(len(uri_topic), 50)} bytes” {/python} {python} f”{int((1 - calculate_coap_size(len(uri_topic), 50)/calculate_http_size(len(uri_topic), 50))*100)}%” {/python} vs HTTP

Recommendation: For sensors sending small readings frequently, CoAP’s low overhead translates to: - 📉 Reduced network congestion - 🔋 Longer battery life (less radio time) - ⚡ Lower latency (smaller packets = faster transmission)

1225.5 🔋 CON vs NON: Battery Life Calculator

Visualize how message type affects battery life:

WarningCritical Battery Life Insights

NON vs CON Performance:

Tip🎮 Interactive Simulator: CoAP-Style UDP Communication

What This Simulates: ESP32 demonstrating CoAP’s lightweight UDP request/response pattern

CoAP Communication Pattern:

Mermaid diagram

Mermaid diagram
Figure 1225.1: CoAP request/response communication pattern showing lightweight UDP exchange between ESP32 client and server with minimal 4-byte header overhead.

How to Use: 1. Click ▶️ Start Simulation 2. Watch Serial Monitor show UDP request/response cycle 3. Observe message types (CON, NON, ACK) 4. See CoAP-style resource addressing 5. Monitor round-trip times (RTT)

Note💡 Learning Points

What You’ll Observe:

  1. UDP Transport - Connectionless, lightweight communication
  2. 4-Byte Headers - Minimal overhead compared to HTTP
  3. Request/Response - RESTful pattern like HTTP GET
  4. Message IDs - Tracking requests and responses
  5. No Handshake - Direct communication without TCP overhead

CoAP Message Structure (Simplified):

 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|Ver| T |  TKL  |      Code     |          Message ID           |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

Ver = Version (2 bits)
T   = Type (CON, NON, ACK, RST)
TKL = Token Length
Code = Method (GET) or Response (2.05 Content)

Real-World Applications:

  1. Smart Home - Light bulbs responding to GET/PUT requests
  2. Industrial IoT - Sensors publishing data via RESTful interface
  3. Building Automation - HVAC systems with RESTful control
  4. Energy Management - Smart meters with resource discovery
  5. Wearables - Health sensors with minimal power consumption

Experiments to Try:

  1. Change Request Frequency - Modify delay() to see network load
  2. Add More Resources - Simulate /humidity, /pressure endpoints
  3. Implement Observe - Add subscription pattern (like MQTT subscribe)
  4. Calculate Overhead - Compare 4-byte CoAP vs HTTP headers
  5. Test Reliability - Implement CON (confirmable) message handling

CoAP vs HTTP Power Consumption:

HTTP Request:  ~500 bytes (headers + TCP)
CoAP Request:  ~20 bytes (4-byte header + minimal payload)
Power Savings: ~96% less data transmitted

1225.6 Multicast Support

CoAP supports multicast for group communication:

1225.6.1 IPv4 Multicast

224.0.1.187

1225.6.2 IPv6 Multicast

FF0X::FD

Use cases: - Discover devices on network - Broadcast commands to group - Query multiple sensors simultaneously

Example:

coap://[FF05::FD]/temperature

Sends GET request to all devices in multicast group.

1225.7 CoAP Features

NoteKey Features
  1. Reduced Overhead: 4-byte header vs 100+ bytes in HTTP
  2. URI Support: Resource addressing like HTTP
  3. Content-Type: Supports JSON, XML, CBOR, etc.
  4. Resource Discovery: Automatic service discovery (/.well-known/core)
  5. Observe Pattern: Subscribe to resources, receive push notifications
  6. Simple Caching: Based on maximum message age
  7. Block-wise Transfer: For large payloads
  8. Security: DTLS encryption

1225.7.1 Resource Discovery

Query available resources:

GET coap://device.local/.well-known/core

Response:

</temperature>;ct=0,
</humidity>;ct=0,
</pressure>;ct=0,
</config>;ct=50
Tip🎮 Interactive Simulator: CoAP Resource Discovery

What This Simulates: ESP32 CoAP server with automatic resource discovery via /.well-known/core

Resource Discovery Flow:

Step 1: Client queries server
   GET coap://device/.well-known/core

Step 2: Server responds with resource list
   </temperature>;rt="sensor";if="core.s",
   </humidity>;rt="sensor";if="core.s",
   </led>;rt="actuator";if="core.a"

Step 3: Client accesses specific resource
   GET coap://device/temperature
   Response: "23.5"

How to Use: 1. Click ▶️ Start Simulation 2. Watch ESP32 advertise available resources 3. See resource metadata (resource type, interface) 4. Observe clients discovering services automatically 5. Monitor GET requests to discovered resources

Note💡 Learning Points

What You’ll Observe:

  1. Automatic Discovery - Devices announce capabilities without manual configuration
  2. Standard Endpoint - /.well-known/core is CoAP convention (RFC 6690)
  3. Resource Attributes - Metadata describes resource type and interface
  4. Self-Describing - Servers advertise what they offer
  5. Plug-and-Play - New devices integrate without central registry

Resource Link Format:

</path>;attribute1=value1;attribute2=value2

Common Attributes:
rt = Resource Type (e.g., "temperature-sensor")
if = Interface Description (e.g., "sensor", "actuator")
ct = Content Type (0=text/plain, 50=application/json)
sz = Maximum Size
obs = Observable (supports observe pattern)

Example Resource Advertisement:

Graph diagram

Graph diagram
Figure 1225.2: CoAP resource link format showing the structure of a resource advertisement with path, resource type, interface description, observability, and content type attributes.

Real-World Applications:

  1. Smart Building - HVAC units discover sensors automatically
  2. Industrial IoT - Factory machines advertise capabilities
  3. Home Automation - New devices self-register with hub
  4. Healthcare - Medical sensors announce monitoring types
  5. Agriculture - Soil sensors advertise measurement types

Experiments to Try:

  1. Add New Resources - Implement /pressure, /battery endpoints
  2. Resource Attributes - Add obs for observable resources
  3. Content Types - Support JSON (ct=50) and XML (ct=41)
  4. Filtering - Query specific resource types: ?rt=sensor
  5. Observe Pattern - Implement push notifications when resource changes

Discovery vs Hardcoding:

Without Discovery (Hardcoded):
- Client: GET coap://192.168.1.100/temp  ❌ Must know IP & path
- Brittle: Breaks if device IP changes

With Discovery:
- Client: Multicast GET /.well-known/core  ✅ Finds all devices
- Response: Server at 192.168.1.100 offers /temp
- Robust: Adapts to network changes

CoAP Resource Discovery Benefits: - Zero configuration networking - Dynamic topology adaptation - Service versioning support - Reduces integration time by ~80%

1225.8 Protocol Comparison

1225.8.1 CoAP vs HTTP: Concrete Performance Numbers

Feature CoAP HTTP CoAP Advantage
Transport UDP TCP No handshake overhead
Header Size 4 bytes 100-200 bytes 96% reduction
Total Request Size 14-28 bytes 150-500 bytes 85-95% smaller
Connection Setup None (UDP) 3-way handshake Saves 150ms + 120 bytes
Methods GET, POST, PUT, DELETE Same + more Focused on IoT needs
Discovery Built-in (/.well-known/core) No standard Zero-config networking
Multicast Yes (FF0X::FD) No One-to-many efficiency
Observe Yes (push notifications) Server-Sent Events 99% less polling traffic
Security DTLS TLS UDP-optimized
Power per Message 3-5 mJ 30-50 mJ 10x more efficient
Battery Life Impact 2-5 years 2-6 months 10x longer life

Real Numbers Example - Temperature Reading:

Scenario: Send “22.5C” (5 bytes payload) from sensor to server

%%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#2C3E50', 'primaryTextColor': '#fff', 'primaryBorderColor': '#16A085', 'lineColor': '#16A085', 'secondaryColor': '#E67E22', 'tertiaryColor': '#7F8C8D'}}}%%
flowchart TB
    subgraph coap["CoAP Protocol - 23 bytes total"]
        c1["Header: 4 bytes"]
        c2["Token: 5 bytes"]
        c3["URI option: 8 bytes"]
        c4["Payload marker: 1 byte"]
        c5["Payload: 5 bytes"]
        cTotal["Total: 23 bytes<br/>RTT: 20-50ms<br/>Energy: ~3 mJ"]
    end

    subgraph http["HTTP Protocol - 690 bytes total"]
        h1["TCP handshake: 180 bytes"]
        h2["HTTP request: ~150 bytes"]
        h3["HTTP response: ~120 bytes"]
        h4["TCP close: 240 bytes"]
        hTotal["Total: 690 bytes<br/>RTT: 150-300ms<br/>Energy: ~45 mJ"]
    end

    subgraph result["Efficiency Comparison"]
        r1["CoAP uses 3.3% of HTTP bandwidth"]
        r2["CoAP uses 6.7% of HTTP energy"]
        r3["30x more efficient!"]
    end

    coap --> result
    http --> result

    style cTotal fill:#16A085,stroke:#2C3E50,stroke-width:2px,color:#fff
    style hTotal fill:#E67E22,stroke:#2C3E50,stroke-width:2px,color:#fff
    style r3 fill:#2C3E50,stroke:#16A085,stroke-width:2px,color:#fff

Figure 1225.3: CoAP versus HTTP comparison for temperature reading showing CoAP uses only 3.3 percent of HTTP bandwidth and 6.7 percent of energy

1225.8.2 CoAP vs MQTT

Feature CoAP MQTT
Pattern Request/Response Publish/Subscribe
Transport UDP TCP
Discovery Built-in External
QoS Via message type 3 levels (0,1,2)
Broker Optional Required
Best For RESTful IoT Event-driven IoT

%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#2C3E50', 'primaryTextColor': '#fff', 'primaryBorderColor': '#16A085', 'lineColor': '#E67E22', 'secondaryColor': '#16A085', 'tertiaryColor': '#E67E22'}}}%%
graph TB
    Decision["IoT Protocol<br/>Selection"]

    Q1{"Communication<br/>Pattern?"}
    Q2{"Transport<br/>Preference?"}
    Q3{"Broker<br/>Available?"}

    CoAP["✓ CoAP<br/>RESTful UDP<br/>Direct device-to-device"]
    MQTT["✓ MQTT<br/>Pub/Sub TCP<br/>Many-to-many via broker"]
    HTTP["✓ HTTP<br/>RESTful TCP<br/>Web integration"]

    Decision --> Q1

    Q1 -->|Request/Response| Q2
    Q1 -->|Publish/Subscribe| MQTT

    Q2 -->|UDP Preferred| CoAP
    Q2 -->|TCP Required| Q3

    Q3 -->|Yes| MQTT
    Q3 -->|No| HTTP

    style Decision fill:#E67E22,color:#fff
    style Q1 fill:#2C3E50,color:#fff
    style Q2 fill:#2C3E50,color:#fff
    style Q3 fill:#2C3E50,color:#fff
    style CoAP fill:#16A085,color:#fff
    style MQTT fill:#16A085,color:#fff
    style HTTP fill:#16A085,color:#fff

Figure 1225.4: IoT Protocol Selection Decision Tree: CoAP, MQTT, or HTTP
Knowledge Check: Protocol Selection Test Your Understanding

1225.9 Knowledge Check

Test your understanding of IoT protocol selection criteria.

Question 1: A smart agriculture system needs to collect soil moisture readings from 100 battery-powered sensors every 5 minutes and send them to a central monitoring dashboard. Which protocol is most appropriate?

Explanation: MQTT is the best choice. Reasons: 1) Publish-subscribe pattern - all 100 sensors publish to topics, dashboard subscribes once (not 100 direct connections), 2) QoS levels for reliability control, 3) Broker handles routing reducing sensor complexity, 4) Persistent connections more efficient than HTTP request/response, 5) Battery-friendly with keep-alive, 6) One-to-many pattern ideal for this scenario. CoAP would require each sensor to respond to polling requests or implement observe (more complex). HTTP has too much overhead for battery devices.

Question 2: Why does CoAP use UDP instead of TCP?

Explanation: UDP is used because: 1) Lower overhead - no connection setup/teardown handshake (saves ~100 bytes), 2) Lower latency - no connection establishment delay, 3) Simpler for constrained devices - less memory/processing, 4) Better for multicast - UDP supports multicast, TCP doesn’t. Challenges created: 1) No reliability - must implement retransmission (CON messages), 2) No flow control - can overwhelm slow receivers, 3) Packet loss handling required, 4) Security - DTLS (for UDP) more complex than TLS (for TCP). CoAP adds optional reliability at application layer via message types (CON/NON/ACK).

Question 3: What is the main advantage of CoAP’s 4-byte header compared to HTTP’s 100+ byte headers?

Explanation: Critical for constrained networks: 1) Low-bandwidth links - 6LoWPAN has ~20-250 kbps, every byte matters, 2) Battery savings - radio transmission is power-expensive, smaller packets = longer battery life, 3) Network efficiency - can fit more messages in same bandwidth, 4) Lower latency - less time to transmit, 5) Cost savings - cellular IoT charges per byte. Example: Sending 1000 sensor readings/day: CoAP = 4KB headers, HTTP = 100KB headers (96KB saved = $$ and battery life). For powerful devices with broadband, HTTP’s 100-byte overhead is negligible.

Question 4: When would you choose HTTP over CoAP for an IoT device?

Explanation: Choose HTTP when: 1) Web browser access required - users need to access device UI directly, 2) Existing infrastructure - company already has HTTP APIs, load balancers, authentication, 3) Powerful devices - Raspberry Pi, industrial gateway (not battery/MCU constrained), 4) Complex authentication - OAuth2, JWT tokens (easier with HTTP), 5) Cloud services - Most cloud APIs are HTTP REST, 6) Developer familiarity - team knows HTTP well. Example: Smart thermostat with web UI for configuration = HTTP. Tiny battery sensor node = CoAP.

1225.10 What’s Next

Now that you understand CoAP methods, multicast, and key features, the next chapter explores CoAP Security and Applications where you’ll learn about:

  • Security with DTLS encryption
  • Real-world applications (smart energy, building automation, industrial IoT)
  • Implementation patterns and best practices
  • Common pitfalls and troubleshooting