Chapters

Stack and Trace Contracts: CoAP Lab Reference

Return to the parent chapter.

Start With the Decision

A client sends GET /temperature to read a named resource: an item exposed by a server. The supplied server returns 22.5. The same client then sends PUT /config to change a setting, but the base server has no /config route. A working read does not establish a working write.

Your task is to locate the failed boundary and choose the next test. A trace is a record of requests and replies. Keep the destination, method, path, response code and payload (message content) together; use a readback to check whether a claimed update changed state.

Route Overview

This is part 1 of 2. Continue with CoAP Lab: Message Construction.

Part Objectives

  • Trace one CoAP request and its response through the client and server, including errors and Observe updates.
  • Validate arduino esp32 coap client with a concrete scenario and pass criteria.
In 60 Seconds

Carry One Request Into a Checked Result

Start with the simulated temperature, then try to change the reporting interval. GET reads a resource; PUT asks to update one. A response code describes the server’s result, but the handler determines what actually happened.

The base /temperature PUT handler prints its input and returns 2.04 Changed; its GET handler still returns the constant 22.5. A success code alone therefore cannot prove that a setting changed. The later /config handler keeps state in memory, so reading it back gives a stronger check.

Complete the Python request, failed-route and readback sequence before comparing the ESP32 code. The serial simulator prints a model; the hardware client needs its own response evidence.

Start With One Working Sensor

Use one record throughout the lab: destination, method, path, sent bytes, received code, received bytes and observed state. Start with the fixed 22.5 reading, change /config from interval 60 to 30, then transfer the same checks to /readings.

Separate predictions from observations. The outputs below follow from the source; they are not fresh execution receipts. No tested aiocoap, Arduino core or coap-simple version is established here.

Chapter Roadmap
  • In 60 Seconds

  • Start With One Working Sensor

  • Key Concepts

  • Prerequisites

  • Related Chapters

  • For Beginners: How to Use These Labs

  • Continue: CoAP Implementation Stack and Trace Contracts

  • Python CoAP Server

  • Putting Numbers to It

  • Interactive Calculator: CoAP vs HTTP Message Overhead

  • Interactive Calculator: Battery Life Estimator

  • Interactive Tool: CoAP Response Code Lookup

  • Try It: CoAP Resource Tree Explorer

  • Checkpoint: Server Resource Contract

  • Python CoAP Client

  • Try It: Observe Pattern Timeline Simulator

  • Try It: CoAP-Style REST Sensor on ESP32

  • Checkpoint: Client Exchange Evidence

  • Arduino ESP32 CoAP Client

  • First: run the base /temperature resource; record which paths are absent before adding handlers.

  • Then: compare GET, PUT and POST results with the registered paths and handler bodies. Treat Observe as an extension until a changing observable resource exists.

  • Next: inspect the ESP32 callback and distinguish what it prints from fields that would require a packet trace.

  • Finally: use response codes, Token-versus-MID correlation, and the consolidation checks to decide whether the lab is ready for constrained-network testing.

Checkpoints pause after each implementation layer; collapsed deep dives and interactives are optional evidence builders.

Learning Objectives

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

  • Diagnose a missing path separately from an unsupported method or a transport failure.
  • Assemble the Python fragments and verify a configuration update by reading it back.
  • Explain why a success response from a print-only handler proves no stored record.
  • Match responses using a Token and acknowledgements using a Message ID in the timeline model.
  • Transfer the request-and-state checks to an ESP32 client without treating serial output as packet evidence.
  • Count explicitly modelled application bytes without turning that count into a battery-life claim.

Key Concepts

  • CoAP: Constrained Application Protocol. These examples use its request/response messages over UDP, a datagram transport.
  • Resource contract: the path, supported methods, payload rules and response behavior a server implements.
  • Handler: the function called for a method on a registered resource.
  • Response code: a class and detail, such as 2.05 Content. The examples use class 2 for success, 4 for client errors and 5 for server errors.
  • Confirmable (CON): a message that requests acknowledgement. An ACK acknowledges that message; read the response code and application state separately.
  • Non-confirmable (NON): a message that does not request an ACK. Its arrival is not guaranteed.
  • Token: a value used to match responses to a request, including its Observe notifications.
  • Message ID (MID): identifies a message for acknowledgement and duplicate handling; it is not an Observe subscription identifier.
  • Observe: an extension for receiving later representations of a resource after registration.
  • Content-Format: identifies how to interpret payload bytes; these snippets use 0 for text and 50 for JSON, a structured text data format.
  • DTLS: Datagram Transport Layer Security. These plaintext examples do not configure it.

Prerequisites

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

  • CoAP Methods and Patterns: Understanding of GET/POST/PUT/DELETE methods and CON/NON message types
  • CoAP Fundamentals: Knowledge of CoAP message structure, tokens, and options
  • Python asyncio basics: Familiarity with async/await syntax for the aiocoap examples
  • Arduino development: Basic ESP32 programming for the embedded examples

CoAP Series:

Practical Development:

If you can install Python packages:

  1. Prepare a lab folder and a Python environment with aiocoap already available, or arrange installation before the lab. The commands below are learner setup instructions; they were not executed in this offline review.
  2. Record python --version and python -m pip show aiocoap. Keep the package version with your trace; no tested version is claimed here.
  3. Save the complete server as coap_server.py and the complete GET client as get_temperature.py. Run them in separate terminals using the same environment.
  4. For each later client fragment, start a separate file with import asyncio and from aiocoap import *, then paste that fragment including its final asyncio.run(...). The fragments otherwise lack those imports.
  5. If you cannot run Python, trace the source and label your results predictions. The browser tools and serial sketch are models; they do not substitute for a UDP exchange.

async def declares an asynchronous handler. await protocol.request(request).response waits for a response; the returned code can still report an error. Stop a waiting client with Control-C before changing the server.

Continue: CoAP Implementation Stack and Trace Contracts

The main lab below stays focused on runnable Python and ESP32 examples. For the deeper implementation contract behind stack selection, URI+method handler mapping, response-code and payload evidence, Token-based correlation, CON/NON policy, proxy freshness, and DTLS session reuse, continue to CoAP Implementation Stack and Trace Contracts.

Python CoAP Server

This server exposes a /temperature resource that returns a simulated reading:

Step 1: Start the CoAP resource on localhost

  1. Save the complete block below as coap_server.py. In terminal A, use the install/run commands below if installation is needed and permitted in your environment.
  2. Expect CoAP server started on port 5683 and Resources: /temperature (GET, PUT). These print lines announce startup; Step 2 tests the exchange.
  3. Keep the server running. If startup fails, record the exception and check the Python environment and listening address before running clients. For an occupied port, use a separate lab environment; do not stop another user’s service.
  4. Record the actual bind and destination addresses. The code uses the library’s default bind, not an explicitly loopback-only listener. Use an isolated lab network and synthetic data.

The base server has no /config, /readings, discovery handler or changing Observe resource. Its PUT handler logs bytes without applying them.

import asyncio
from aiocoap import *
import aiocoap.resource as resource

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

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

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

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

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

        # In real implementation, parse and apply config
        return Message(code=Code.CHANGED)  # 2.04 Changed

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

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

    # Start server on default CoAP port (5683)
    await Context.create_server_context(root)

    print("CoAP server started on port 5683")
    print("Resources: /temperature (GET, PUT)")

    # Keep server running
    await asyncio.get_running_loop().create_future()

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

Knowledge check · self-test

Knowledge check

Test your understanding.

The code quiz is a handler fragment: read_sensor() is a placeholder, unlike the complete server’s fixed value. The class must extend resource.Resource, and the response payload must be bytes; that is why the two selected answers fit this API. Neither answer adds a route or verifies a physical sensor.

Install and run (learner environment; record the installed version; not executed here):

pip install aiocoap
python coap_server.py

For a smaller byte-count example, use /temp rather than the runnable server’s /temperature. Count only application messages. This simplified response omits the Content-Format option that the Python server sets, so these totals are not a capture prediction for that server.

Message overhead analysis:

  • CoAP request: 4-byte header + 2-byte token + 5-byte Uri-Path option (1-byte header + 4-byte temp value) = 11 bytes
  • Response: 4-byte header + 2-byte token + 1-byte marker + 4-byte payload (22.5) = 11 bytes
  • Total exchange: 22 bytes

Compare to HTTP:

  • HTTP request: GET /temp HTTP/1.1\r\nHost: server\r\n\r\n = 36 bytes
  • Response: HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\n22.5 = 42 bytes
  • Total: 78 bytes (about 3.55 times the CoAP total)

Ideal application-byte transmission time (assumed 250 kbps link, excluding transport framing, handshakes, losses and idle listening):

  • CoAP: tCoAP=22×8250,000=0.704t_{CoAP} = \frac{22 \times 8}{250,000} = 0.704 ms
  • HTTP: tHTTP=78×8250,000=2.496t_{HTTP} = \frac{78 \times 8}{250,000} = 2.496 ms

Transmit charge model (assume constant 20 mA while sending):

  • CoAP: 20×0.704/3600=0.0039120 \times 0.704 / 3600 = 0.00391 microamp-hours per exchange.
  • HTTP: 20×2.496/3600=0.0138720 \times 2.496 / 3600 = 0.01387 microamp-hours per exchange.
  • At one reading per minute, multiply by 1,440: about 5.63 and 19.97 microamp-hours per day.

This treats all request and response bytes as transmitted at one current and rate. A real endpoint also receives, wakes, computes and sleeps; retries, framing and battery ageing add costs. Measure those before estimating service life. The message calculator defaults to the longer temperature path; the charge calculator uses this smaller 22/78-byte model.

Maths · guided foundations

A 4x Advantage That Is Really a Modeling Choice

Check the quantities and assumptions.

A revised model gives a 13-byte CoAP request and 15-byte response. A captured CoAP exchange totals 32 bytes. What should you do before reporting a counting error?

Compare the capture’s path, token length and options with the 28-byte model.

Correct. 13 + 15 = 28, but a different path or options can change the captured size. Identify the extra bytes before reporting an error.

Interactive Calculator: CoAP vs HTTP Message Overhead

Try This:

  1. Leave payload at 4 and path length at 11, representing temperature. Expected: 29 CoAP bytes and 85 HTTP bytes for the simplified exchange. The response omits the Python server’s Content-Format option.
  2. Change path length to 4. Expected: 22 and 78, matching the /temp arithmetic above. If your trace differs, check the actual path, token length and options before comparing totals.
  3. Turn headers off only to inspect the model. That setting is not a valid HTTP/1.1 request. Restore defaults before comparing another case.
Interactive Calculator: Ideal Transmit-Only Charge

Try This:

  1. Double readings/hour from 60 to 120. Expected: daily modelled charge doubles and the displayed quotient halves. If comparing runs, hold the other controls fixed.
  2. Restore 60. The model uses 22/78 bytes, matching the smaller /temp example rather than the calculator’s default /temperature path.
  3. Treat the displayed days as a capacity divided by transmit-only charge, not battery life. No real cell or hardware power measurement is represented.
Interactive Tool: CoAP Response Code Lookup

Try This:

  1. Select 4.04 when a path has no registered resource; compare that with 4.05 for a method missing on an existing resource.
  2. Select 2.04 for the configuration update, then verify interval 30 by GET. The code label alone does not establish state.
  3. Read the HTTP labels as rough analogies, not exact mappings. Use the actual CoAP response and handler contract to diagnose this lab.

Adding Multiple Resources

Read the write path before running it: ConfigResource starts with interval 60, decodes JSON and merges it into an in-memory dictionary. GET serializes that dictionary; PUT returns Code.CHANGED. The handler catches exceptions but does not validate a schema, ranges or the request’s Content-Format.

ReadingsResource decodes and prints JSON, then returns Code.CREATED. The database line is a comment. Use this as the transfer case: what extra evidence would establish that a reading was stored?

To assemble the extension, place both class definitions above main() in coap_server.py. Insert the two root.add_resource(...) calls inside main(), after root = resource.Site() and before Context.create_server_context(root). They are placement instructions, not top-level runnable statements. Steps 3–4 first test the missing routes, then use this extension.

class ConfigResource(resource.Resource):
    """Configuration resource with GET and PUT"""

    def __init__(self):
        super().__init__()
        self.config = {"interval": 60, "threshold": 25.0}

    async def render_get(self, request):
        import json
        payload = json.dumps(self.config).encode('utf-8')
        return Message(
            code=Code.CONTENT,
            payload=payload,
            content_format=50  # application/json
        )

    async def render_put(self, request):
        import json
        try:
            new_config = json.loads(request.payload.decode('utf-8'))
            self.config.update(new_config)
            print(f'Config updated: {self.config}')
            return Message(code=Code.CHANGED)
        except Exception as e:
            return Message(code=Code.BAD_REQUEST)

class ReadingsResource(resource.Resource):
    """POST-only resource to receive sensor readings"""

    async def render_post(self, request):
        import json
        try:
            reading = json.loads(request.payload.decode('utf-8'))
            print(f'New reading: {reading}')
            # Store reading in database...
            return Message(code=Code.CREATED)  # 2.01 Created
        except Exception:
            return Message(code=Code.BAD_REQUEST)  # 4.00 Bad Request

# In main():
root.add_resource(['config'], ConfigResource())
root.add_resource(['readings'], ReadingsResource())
Try It: CoAP Resource Tree Explorer

Enter /sensors/temperature and inspect the generated two-segment Python registration. This preview changes only the diagram; it does not register a route in your running server.

The tree shows paths and method labels so you can compare them with actual handlers. Its discovery label does not create /.well-known/core; the supplied Python server registers no discovery resource.

Bex guides the message review.Checkpoint: Server Resource Contract

  • Predict the response to PUT /config before registration, then compare it with your run.
  • Point to the route registration and render_put method needed to repair that path.
  • State what GET /config must show after interval 30 is applied. A response code without this readback leaves state unverified.

With the server mapped, the client examples become trace recipes: request, response code, payload, and failure branch.

Python CoAP Client

Basic GET Request

Step 2: Send GET and inspect the response

  1. In terminal B, run python get_temperature.py with terminal A’s base server running. Expected lines include Response Code: 2.05 Content and Temperature: 22.5°C; exact code formatting can vary by library version.
  2. Record coap://localhost/temperature, GET, the returned code and decoded payload. The fixed source value explains 22.5; it is not a physical measurement.
  3. Deliberately change the path in your client copy to /missing and run again. Expect 4.04 Not Found rather than temperature output. A transport error instead means no response was obtained; check the destination and server before diagnosing a route.
  4. Restore /temperature and rerun. The original content should return. Save both results and recovery. This client does not print Token, MID or Content-Format; do not claim those fields were observed without extra trace instrumentation.
  5. To separate a missing method from a missing path, keep /temperature but change Code.GET to Code.POST in your test copy. Expect 4.05 Method Not Allowed: the resource exists but has no render_post. Restore GET afterward. If you get 4.04, check which path and server you actually reached.
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 and wait for response
        response = await protocol.request(request).response

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

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

# Run client
asyncio.run(get_temperature())

PUT Request for Configuration

Step 3: Match the PUT path to a registered handler

  1. Assemble put_config.py from the fragment below with the shared imports described in the beginner panel. Run python put_config.py against the base server. Expected: Update failed: with 4.04 Not Found, because /config has no route.
  2. Stop only your server with Control-C. Add the classes and registrations from Adding Multiple Resources as described there, then restart python coap_server.py.
  3. Run the unchanged PUT client again. Expect a 2.04 Changed result and Configuration updated successfully. Terminal A should log interval 30 in Config updated:.
  4. In a copy of the GET client, change the URI to coap://localhost/config and label its payload as configuration rather than temperature. Run it and inspect the JSON: interval must be 30 and threshold 25.0. Success without the readback leaves the update unverified.
  5. If 4.04 persists, check that the registration is inside the executed main() before context creation and that you restarted the correct process. If the dictionary cannot be read, check GET dispatch and decoding separately.

For a payload failure test, change the PUT payload in your copy to b'{'. The registered handler should return 4.00 Bad Request because decoding fails. Restore b'{"interval": 30}', resend, and read back interval 30. A missing-route result instead means the request has not reached this parser.

The payload is JSON but this PUT fragment does not set Content-Format 50; the supplied permissive handler accepts it anyway. That is a limitation to fix in a stricter contract, not evidence of format validation. Restarting this in-memory server resets interval to 60.

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}')

    if response.code.is_successful():
        print('Configuration updated successfully')
    else:
        print(f'Update failed: {response.code}')

asyncio.run(update_config())

POST Request to Send Data

Step 4: Register and verify the reading endpoint

  1. Assemble post_reading.py using the shared imports and the fragment below. Against the base server, expect Submission failed: with 4.04 Not Found.
  2. Run it against the extended server from Step 3. Expect Reading submitted successfully and a server New reading: line containing sensor ID temp-001. If still missing, check the /readings registration and render_post method.
  3. Compare the payload with the source: its timestamp is fixed sample text. The handler parses JSON but validates neither sensor identity nor timestamp and stores no database record.
  4. Transfer the readback test: can you retrieve a stored record after POST? With this code you cannot. Record parsed and printed, not persisted. A durable-storage extension must write a record and provide a way to verify it before claiming persistence.
  5. Restore the extended server after any deliberate missing-route test. Preserve failed and repaired results as separate observations.
import json

async def send_reading():
    """POST a sensor reading to the server"""

    protocol = await Context.create_client_context()

    reading = {
        "sensor_id": "temp-001",
        "temperature": 23.5,
        "humidity": 65.2,
        "timestamp": "2025-10-24T23:30:00Z"
    }

    request = Message(
        code=Code.POST,
        uri='coap://localhost/readings',
        payload=json.dumps(reading).encode('utf-8')
    )
    request.opt.content_format = 50  # application/json

    response = await protocol.request(request).response

    if response.code == Code.CREATED:
        print('Reading submitted successfully')
    else:
        print(f'Submission failed: {response.code}')

asyncio.run(send_reading())

Observe Pattern (Subscribe to Updates)

Step 5: Add a real observable resource before subscribing

  1. Trace the client below: observe=0 requests registration, then it prints the initial response and waits for later notifications. Add the shared imports if saving it as a separate file.
  2. Inspect the server before running this client. The supplied TemperatureResource is a plain Resource whose GET returns a constant; no notification producer is implemented. Do not treat Waiting for updates... as proof that an observation was accepted.
  3. Use the timeline below for this page’s bounded exercise. To build a live extension later, you need an ObservableResource, mutable reading state used by GET, calls to updated_state() on change, and task cancellation and context shutdown. Those pieces are not a complete runnable procedure here.
  4. For that future extension, require evidence of accepted registration, changed values and matching Token across notifications, followed by explicit cancellation. The supplied loop has no timeout or cancellation branch; stop your own waiting process with Control-C if you started it.
async def observe_temperature():
    """Subscribe to temperature updates using Observe"""

    protocol = await Context.create_client_context()

    request = Message(
        code=Code.GET,
        uri='coap://localhost/temperature',
        observe=0  # Register for notifications
    )

    request_handle = protocol.request(request)

    # Get initial response
    response = await request_handle.response
    print(f'Initial temperature: {response.payload.decode("utf-8")}C')

    # Wait for notifications (runs until cancelled)
    print('Waiting for updates...')
    async for response in request_handle.observation:
        print(f'Update: {response.payload.decode("utf-8")}C')
        # In real code, add break condition or timeout

asyncio.run(observe_temperature())
Try It: Observe Pattern Timeline Simulator

Visualize the message exchange sequence between a CoAP client and server during an Observe subscription.

The timeline is a generated diagram, not a UDP capture. It holds the Token fixed and assigns new MIDs to notifications; a CON notification’s ACK uses that notification’s MID. Use those fields to decide which messages belong together.

  1. Keep six notifications and “Mixed”, with CON every fifth notification. Expected: the initial request, initial reply, six notifications and one notification ACK give nine messages in the local timeline.
  2. Change to “All NON”. Expected: eight messages; no notification ACKs. If counts differ, check the controls and include the initial exchange in your count.
  3. Change to “All CON”. Expected: fourteen messages, because each of six notifications adds an ACK. Restore Mixed afterward.

The separate workbench below models registration, freshness and cancellation. Its Event Trace is model evidence; neither tool proves a live server’s behavior. The generated temperatures and short delays are illustrative.

Simulation · interactive

CoAP Observe Workbench

Explore how the system behaves.

Objective: Run a serial simulation of CoAP-like GET, PUT, and Observe patterns on ESP32. This sketch prints illustrative exchanges; it does not send UDP packets or implement a CoAP server.

Step 6: Inspect the ESP32 serial sketch as a model

  1. Inspect the sketch below before using the optional ESP32 editor. It calls local functions and prints strings; it never starts a UDP CoAP endpoint.
  2. Trace GET /nonexistent: the local lookup fails and prints 4.04 Not Found. Trace PUT /config/interval with 30.0, then its GET: the array value changes and is printed back. This is the same readback idea as Step 3, within one program.
  3. If you run it, set Serial Monitor to 115200 baud. Source-derived expectations are a discovery list, GET/PUT labels, and ten Observe-style updates; every fifth is labelled CON. No current browser build or runtime has been verified here.
  4. If the serial output is unreadable, check the baud setting; if compilation fails, record board/core/library versions and the error. A working Python exchange does not establish Arduino build compatibility.
  5. Save any log as CoAP-style print simulation. Stop your own simulation when finished. An “ACK received” print comes from the sketch itself, not another client.

Paste this code into the Wokwi editor:

#include <WiFi.h>

// Simulated CoAP resource registry
struct CoapResource {
  const char* path;
  float value;
  bool observable;
  int observeCount;
};

CoapResource resources[] = {
  {"/temperature", 22.5, true, 0},
  {"/humidity", 65.0, true, 0},
  {"/config/interval", 60.0, false, 0},
  {"/led", 0.0, false, 0}
};
const int NUM_RESOURCES = 4;

// CoAP response codes (RFC 7252)
const char* COAP_205_CONTENT = "2.05 Content";
const char* COAP_204_CHANGED = "2.04 Changed";
const char* COAP_201_CREATED = "2.01 Created";
const char* COAP_404_NOT_FOUND = "4.04 Not Found";
const char* COAP_405_NOT_ALLOWED = "4.05 Method Not Allowed";

unsigned long lastObserve = 0;
int messageId = 1000;

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

  Serial.println("=== CoAP Resource Contract Simulation ===");
  Serial.println("Printing CoAP-style methods on ESP32; no UDP packets are sent.\n");

  // Show resource discovery (/.well-known/core)
  discoverResources();

  // Demonstrate GET requests
  Serial.println("\n--- GET Requests ---");
  coapGet("/temperature");
  coapGet("/humidity");
  coapGet("/config/interval");
  coapGet("/nonexistent");

  // Demonstrate PUT requests
  Serial.println("\n--- PUT Requests (Update Resources) ---");
  coapPut("/config/interval", 30.0);
  coapPut("/led", 1.0);
  coapGet("/config/interval");  // Verify change

  // Demonstrate POST (create reading)
  Serial.println("\n--- POST Request (Submit Reading) ---");
  coapPost("/readings", 23.7);

  // Demonstrate Observe pattern
  Serial.println("\n--- Observe Pattern (Subscribe to Updates) ---");
  Serial.println("Registering observer for /temperature...");
  Serial.println("MID=" + String(messageId++) + " Token=0xAB | Observe=0 (Register)");
  Serial.println("Response: " + String(COAP_205_CONTENT) + " | Observe=1\n");

  Serial.println("Sending notifications every 2 seconds...\n");
}

void loop() {
  // Simulate Observe notifications
  if (millis() - lastObserve > 2000) {
    lastObserve = millis();

    // Update sensor values with drift
    resources[0].value += random(-10, 11) * 0.1;
    resources[1].value += random(-5, 6) * 0.1;
    resources[0].observeCount++;

    Serial.printf("Observe #%d | MID=%d | /temperature = %.1f C\n",
                  resources[0].observeCount, messageId++,
                  resources[0].value);

    // Show CON vs NON comparison
    if (resources[0].observeCount % 5 == 0) {
      Serial.println("  ^ CON (Confirmable) - requires ACK");
      Serial.println("    Client ACK received (MID=" + String(messageId - 1) + ")");
    } else {
      Serial.println("  ^ NON (Non-confirmable) - no ACK needed");
    }

    // Show message size comparison
    if (resources[0].observeCount == 3) {
      Serial.println("\n--- Protocol Overhead Comparison ---");
      Serial.println("Illustrative GET /temperature exchange: CoAP 18B request + 11B response = 29B");
      Serial.println("Literal HTTP/1.1 exchange: 43B request + 42B response = 85B");
      Serial.printf("CoAP application bytes: %.0f%% fewer in this example\n\n",
                    (1.0 - 29.0 / 85.0) * 100);
    }

    if (resources[0].observeCount >= 10) {
      Serial.println("\nDeregistering observer (Observe=1)...");
      Serial.println("Observer removed. Server stops notifications.\n");
      Serial.println("=== CoAP Demo Complete ===");
      while (1) delay(1000);
    }
  }
}

void discoverResources() {
  Serial.println("GET /.well-known/core (Resource Discovery)");
  Serial.println("Response: " + String(COAP_205_CONTENT));
  Serial.println("Content-Format: application/link-format\n");
  for (int i = 0; i < NUM_RESOURCES; i++) {
    Serial.printf("  <%s>;rt=\"sensor\";if=\"core.s\"",
                  resources[i].path);
    if (resources[i].observable) Serial.print(";obs");
    Serial.println();
  }
}

CoapResource* findResource(const char* path) {
  for (int i = 0; i < NUM_RESOURCES; i++) {
    if (strcmp(resources[i].path, path) == 0) return &resources[i];
  }
  return NULL;
}

void coapGet(const char* path) {
  Serial.printf("GET %s | MID=%d\n", path, messageId++);
  CoapResource* res = findResource(path);
  if (res) {
    Serial.printf("  Response: %s | %.1f\n", COAP_205_CONTENT, res->value);
  } else {
    Serial.printf("  Response: %s\n", COAP_404_NOT_FOUND);
  }
}

void coapPut(const char* path, float value) {
  Serial.printf("PUT %s | MID=%d | Payload: %.1f\n", path, messageId++, value);
  CoapResource* res = findResource(path);
  if (res) {
    res->value = value;
    Serial.printf("  Response: %s | Updated to %.1f\n", COAP_204_CHANGED, value);
  } else {
    Serial.printf("  Response: %s\n", COAP_404_NOT_FOUND);
  }
}

void coapPost(const char* path, float value) {
  Serial.printf("POST %s | MID=%d | Payload: {temp: %.1f}\n",
                path, messageId++, value);
  Serial.printf("  Response: %s | Location: /readings/1\n", COAP_201_CREATED);
}

What to Observe:

  1. Discovery: the sketch prints its four local entries. It does not discover a remote server or expose /.well-known/core over a network.
  2. State: PUT changes /config/interval from 60.0 to 30.0, and the next GET prints it. POST only prints a Created label; it creates no stored reading.
  3. Notifications: the loop prints updates after roughly two-second checks, with every fifth labelled CON. Those strings prove no packet delivery or acknowledgement.
  4. Byte model: the sketch prints 29 CoAP versus 85 HTTP application bytes for a simplified /temperature exchange, about 66% fewer. This uses a longer path than the /temp arithmetic above and omits transport and Content-Format option costs.

Bex guides the message review.Checkpoint: Client Exchange Evidence
  • Keep one successful GET, the missing /config result and the repaired configuration readback together.
  • Explain why POST’s success print does not establish a stored record.
  • Identify which evidence came from source, a model or your own network run. No live Observe or ESP32 result follows from the Python GET.

Transfer the same diagnostic sequence to a different client stack: establish the destination, inspect the reply and check application state. A Wi-Fi join is only a prerequisite.

Arduino ESP32 CoAP Client

This example uses the coap-simple library for ESP32:

Step 7: Verify the ESP32 packet path on your own hardware

  1. Inspect the sketch and record the Arduino core and coap-simple versions you would use. No tested board/library combination or hardware run is established here. Configure only your own lab server and Wi-Fi credentials in your local copy.
  2. For an optional hardware run, start the Python server on an isolated network reachable from the ESP32 and set serverIP accordingly. localhost on the board would refer to the board itself. Open Serial Monitor at 115200 baud.
  3. Expect the sketch to join Wi-Fi, print GET /temperature sent, MID:, and process responses through coap.loop(). A matching callback should print payload 22.5 and Code: 2.5; the code prints the detail without zero padding. A send line alone is not a received reply.
  4. If Wi-Fi joins but no reply arrives, compare server address, UDP port 5683, reachability and /temperature registration. If a 4.04 arrives, inspect routing; if payload differs, inspect the handler and destination. Keep the failure and the corrected reply.
  5. The callback prints IP, payload and code, but no Token or response MID. A separate packet trace would be needed to match those fields; no trace is supplied here. Do not infer them from the send log.
  6. sendConfig() and sendReading() below are helper functions, absent from loop(). They send nothing until explicitly called in your copy, and require the extended Python server. Test one at a time; verify interval 30 by GET and keep the POST persistence limitation from Step 4.
  7. Stop your own clients and server with Control-C, stop the simulation or disconnect your test board, and run deactivate in shells where you activated a virtual environment. Confirm the terminals return. Restart your server and repeat GET to recover; in-memory configuration starts at 60 again.
#include <WiFi.h>
#include <coap-simple.h>

// WiFi credentials
const char* ssid = "YourWiFi";
const char* password = "YourPassword";

// CoAP client instance
Coap coap;

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

// Callback for CoAP responses
void callback_response(CoapPacket &packet, IPAddress ip, int port) {
  // Extract payload
  char payload[packet.payloadlen + 1];
  memcpy(payload, packet.payload, packet.payloadlen);
  payload[packet.payloadlen] = '\0';

  Serial.print("Response from ");
  Serial.print(ip);
  Serial.print(": ");
  Serial.println(payload);

  // Check response code
  Serial.print("Code: ");
  Serial.print(packet.code >> 5);  // Class (2=Success, 4=Client Error, 5=Server Error)
  Serial.print(".");
  Serial.println(packet.code & 0x1F);  // Detail
}

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

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

  Serial.println("\nWiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  // Register response callback
  coap.response(callback_response);

  // Start CoAP client
  coap.start();
}

void loop() {
  // Send GET request every 10 seconds
  static unsigned long lastRequest = 0;

  if (millis() - lastRequest > 10000) {
    int msgid = coap.get(serverIP, serverPort, "temperature");
    Serial.print("GET /temperature sent, MID: ");
    Serial.println(msgid);
    lastRequest = millis();
  }

  // Process incoming responses
  coap.loop();
}

ESP32 PUT Request Example

void sendConfig() {
  // Build JSON payload
  char payload[64];
  snprintf(payload, sizeof(payload), "{\"interval\": %d}", 30);

  // Send PUT request
  int msgid = coap.put(
    serverIP,
    serverPort,
    "config",
    payload,
    strlen(payload)
  );

  Serial.print("PUT /config sent, MID: ");
  Serial.println(msgid);
}

ESP32 POST Request Example

void sendReading() {
  // Read sensor (simulated)
  float temperature = 22.5 + (random(-10, 10) / 10.0);
  float humidity = 60.0 + (random(-50, 50) / 10.0);

  // Build JSON payload
  char payload[128];
  snprintf(payload, sizeof(payload),
    "{\"temp\": %.1f, \"hum\": %.1f}",
    temperature, humidity);

  // Send POST request
  int msgid = coap.post(
    serverIP,
    serverPort,
    "readings",
    payload,
    strlen(payload)
  );

  Serial.print("POST /readings sent: ");
  Serial.println(payload);
}

Continue to the Next Part

Carry this evidence into CoAP Lab: Message Construction, which begins with Try It: CoAP Message Byte Builder.

Hi, I’m Broker Bex. What do you need?

Find help

Let’s find what you need

Find a lesson or return to your module guide.

Give feedback

Help improve this chapter

Tell us what helped or what needs fixing.

Tips

Try a small next step

A few ways to get more from this chapter.

Ask AI

Continue the conversation

Take the conversation further with your preferred assistant.

AI help is available in supported modules when enabled in Settings.

No live person answers on independent study. Feedback does not promise a personal reply.

For welfare or safety concerns, follow your school’s procedures outside IoTClass.