Stack and Trace Contracts: CoAP Lab Reference
More
Depth: Practitioner
Progress saves as you read. Mark sections complete as you go; your progress appears in the sidebar.
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.
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.
-
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
/temperatureresource; 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
0for text and50for 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:
- CoAP Methods and Patterns - Tradeoffs and design decisions
- Message Construction Lab - Continue from handler behavior to message construction
- CoAP Comprehensive Review - Assessment and quiz
Practical Development:
- Prototyping Hardware - ESP32 setup guide
- Network Design - Testing tools
- MQTT Implementation - Compare with MQTT patterns
If you can install Python packages:
- Prepare a lab folder and a Python environment with
aiocoapalready available, or arrange installation before the lab. The commands below are learner setup instructions; they were not executed in this offline review. - Record
python --versionandpython -m pip show aiocoap. Keep the package version with your trace; no tested version is claimed here. - Save the complete server as
coap_server.pyand the complete GET client asget_temperature.py. Run them in separate terminals using the same environment. - For each later client fragment, start a separate file with
import asyncioandfrom aiocoap import *, then paste that fragment including its finalasyncio.run(...). The fragments otherwise lack those imports. - 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
- 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. - Expect
CoAP server started on port 5683andResources: /temperature (GET, PUT). These print lines announce startup; Step 2 tests the exchange. - 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.
- 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
tempvalue) = 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: ms
- HTTP: ms
Transmit charge model (assume constant 20 mA while sending):
- CoAP: microamp-hours per exchange.
- HTTP: 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.
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())
Checkpoint: Server Resource Contract
- Predict the response to PUT
/configbefore registration, then compare it with your run. - Point to the route registration and
render_putmethod needed to repair that path. - State what GET
/configmust show after interval30is 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
- In terminal B, run
python get_temperature.pywith terminal A’s base server running. Expected lines includeResponse Code: 2.05 ContentandTemperature: 22.5°C; exact code formatting can vary by library version. - Record
coap://localhost/temperature, GET, the returned code and decoded payload. The fixed source value explains22.5; it is not a physical measurement. - Deliberately change the path in your client copy to
/missingand run again. Expect4.04 Not Foundrather than temperature output. A transport error instead means no response was obtained; check the destination and server before diagnosing a route. - Restore
/temperatureand 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. - To separate a missing method from a missing path, keep
/temperaturebut changeCode.GETtoCode.POSTin your test copy. Expect4.05 Method Not Allowed: the resource exists but has norender_post. Restore GET afterward. If you get4.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
- Assemble
put_config.pyfrom the fragment below with the shared imports described in the beginner panel. Runpython put_config.pyagainst the base server. Expected:Update failed:with4.04 Not Found, because/confighas no route. - 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. - Run the unchanged PUT client again. Expect a
2.04 Changedresult andConfiguration updated successfully. Terminal A should log interval30inConfig updated:. - In a copy of the GET client, change the URI to
coap://localhost/configand label its payload as configuration rather than temperature. Run it and inspect the JSON: interval must be30and threshold25.0. Success without the readback leaves the update unverified. - If
4.04persists, check that the registration is inside the executedmain()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
- Assemble
post_reading.pyusing the shared imports and the fragment below. Against the base server, expectSubmission failed:with4.04 Not Found. - Run it against the extended server from Step 3. Expect
Reading submitted successfullyand a serverNew reading:line containing sensor IDtemp-001. If still missing, check the/readingsregistration andrender_postmethod. - 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.
- 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.
- 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
- Trace the client below:
observe=0requests registration, then it prints the initial response and waits for later notifications. Add the shared imports if saving it as a separate file. - Inspect the server before running this client. The supplied
TemperatureResourceis a plainResourcewhose GET returns a constant; no notification producer is implemented. Do not treatWaiting for updates...as proof that an observation was accepted. - 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 toupdated_state()on change, and task cancellation and context shutdown. Those pieces are not a complete runnable procedure here. - 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())
Checkpoint: Client Exchange Evidence
- Keep one successful GET, the missing
/configresult 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
- 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.
- For an optional hardware run, start the Python server on an isolated network reachable from the ESP32 and set
serverIPaccordingly.localhoston the board would refer to the board itself. Open Serial Monitor at115200baud. - Expect the sketch to join Wi-Fi, print
GET /temperature sent, MID:, and process responses throughcoap.loop(). A matching callback should print payload22.5andCode: 2.5; the code prints the detail without zero padding. A send line alone is not a received reply. - If Wi-Fi joins but no reply arrives, compare server address, UDP port
5683, reachability and/temperatureregistration. If a4.04arrives, inspect routing; if payload differs, inspect the handler and destination. Keep the failure and the corrected reply. - 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.
sendConfig()andsendReading()below are helper functions, absent fromloop(). They send nothing until explicitly called in your copy, and require the extended Python server. Test one at a time; verify interval30by GET and keep the POST persistence limitation from Step 4.- Stop your own clients and server with Control-C, stop the simulation or disconnect your test board, and run
deactivatein shells where you activated a virtual environment. Confirm the terminals return. Restart your server and repeat GET to recover; in-memory configuration starts at60again.
#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.



