Chapters

CoAP Methods and Multicast: Reference

Related reference: CoAP message types.

This page preserves the original supporting material for CoAP Methods and Multicast. The five figure blocks remain in that chapter in their original order; the five multiple-choice checks are collected on the standalone check page. Original walkthroughs and runtime cells below are retained without revision.

Start With the Device Menu

Choose the Action Before the Method

A caretaker reads a tank level, sets an alarm limit, and creates a calibration record. These are three different operations on resources: named items a client can read or change. The client is the requester; the server owns the resource and answers.

Work through this illustrative exchange with no other writer changing the configuration. The existing resource coap://tank.local/config/alarm-limit stores 80 percent; the caretaker wants 90 percent. GET reads without requesting a change. PUT to that URI with payload 90 changes the stored limit from 80 to 90. A fresh PUT with the same URI and value leaves the intended limit at 90.

The client sends that PUT as a Confirmable (CON) message, which requests an acknowledgement (ACK), with Message ID 100 and Token a1. The Message ID identifies a message for acknowledgement and duplicate handling; the Token correlates a response with its request. The server first sends an empty ACK: code 0.00, Message ID 100, and no Token. This acknowledges the request message, not successful storage. Later, in this example, it sends a separate CON response: 2.04 Changed, Message ID 101, Token a1. The client acknowledges that response with an empty ACK carrying Message ID 101. The separate response has its own Message ID but echoes the request Token.

If the separate response is lost, the empty ACK alone leaves completion uncertain. A fresh same-value PUT still leaves the intended limit at 90; correlate its successful 2.04 Changed response with that fresh request, then GET the resource and check a fresh 2.05 Content readback containing 90 before reporting that the setting is stored. This establishes stored configuration, not whether a physical alarm operates correctly.

Contrast a POST to coap://tank.local/calibrations with illustrative payload offset=2. Suppose no record for this operation exists initially and the server creates /calibrations/17. A lost response leaves creation uncertain; a fresh POST may create another record. A received 2.01 Created response with Location-Path identifying /calibrations/17, followed by that record’s readback, would identify the result. With the response missing, resolve the operation through an application lookup that uniquely associates it with a stored record, or a documented application deduplication key whose retained result returns that same record on repeat. Without such evidence or a deduplication contract, do not blindly issue a fresh POST. Message ID and Token do not supply durable application deduplication.

By the end, choose a method for a new operation, predict its repeat effect, and name the response and device-state evidence needed to report success.

The panels show a tank reading and a change to its alarm limit. They show why a repeated request must keep the same meaning.

Constrained Application Protocol (CoAP) supplies request and response rules for named resources. This page follows its UDP transport: datagrams sent without a TCP connection. A method specifies the requested action; a response reports the server’s result.

For the tank, record the resource address, action, authorized caller, expected response, and repeat rule. Test a normal request, a missing resource, a denied change, and a lost reply. Check the resulting device state as well as the response. Later, apply the same record to a thermostat and to discovery across a group.

Phoebe’s Field Notes: When a Full CR2032 Cannot Supply the Pulse

The mathematical gist. The calculator assumes 2,430 J at 3.00 V. Under the illustrative relation Vload=Voc−IRV_{load}=V_{oc}-IR, a 20 mA pulse across 15 ohm loses 0.30 V; across 100 ohm it loses 2.00 V. These are assumed resistances, not measurements of a particular cell. Its 0.0864 mJ message cost gives 28,125 days at 1,000 messages/day, about 77.1 years. That result omits shelf life, other loads, and whether the cell can supply the pulse.

Math Bridge · guided foundationsHow can a 77-year message budget fail in one pulse?Let Eddie connect nominal joules, internal resistance, cutoff, and shelf life.
Chapter Roadmap

This chapter moves from verbs to deployment choices:

  1. First map GET, POST, PUT, and DELETE to sensor resources.
  2. Then test those methods in Python and ESP32 examples.
  3. Next compare CoAP, MQTT, and HTTP with the byte and battery calculators.
  4. Finally add multicast, discovery, Observe, and CON/NON evidence.

Checkpoint callouts pause the tour; Deep-dive sections and calculation audits are optional support on a first pass.

Learning Objectives

  • Choose GET, POST, PUT, or DELETE from the intended resource change and explain what a repeat may do.
  • Diagnose the gap between a successful response and a verified device state in the Python and ESP32 examples.
  • Use scoped multicast discovery to find candidate resources without assuming every server replied.
  • Choose Observe for change reporting while checking freshness and notification overhead.
  • Audit byte and energy assumptions before using a calculator result in a protocol decision.
Key Concepts
  • CoAP: A resource request/response protocol; this page uses its UDP binding.
  • Idempotent: Repeating the same operation has the same intended effect as applying it once. Responses may differ.
  • Confirmable (CON): A message that requests acknowledgement and supports bounded retransmission. Delivery can still fail.
  • Non-confirmable (NON): A message without message-layer acknowledgement or retransmission.
  • Token: A client-selected value used to correlate a response with a request.
  • Message ID: A value used for duplicate detection and matching an ACK or reset to a message.
  • Observe: A GET-based registration for subsequent resource notifications.
  • Block-wise transfer: An extension that moves a representation in blocks.
  • DTLS: Datagram Transport Layer Security, providing a security layer for UDP exchanges.

In 60 Seconds

CoAP supports four REST methods mirroring HTTP: GET (retrieve), POST (create), PUT (update/create), and DELETE (remove), with GET, PUT, and DELETE being idempotent. Beyond basic REST, CoAP adds multicast support for group operations (e.g., turning off all lights), resource discovery via /.well-known/core, and the Observe extension that enables server-push notifications, which can reduce repeated polling traffic when resource changes are infrequent.

For Beginners: What is CoAP?

For the tank panel, the address identifies the alarm-limit resource and PUT carries its desired value. The server answers with a response code, which the panel must inspect. If the response is missing, the panel needs a retry and verification rule.

The four-byte base header is only the start of a CoAP message. Tokens, options describing the resource, payload framing, and the payload add bytes. Network and security layers add more. A compact header helps a byte budget; it does not establish device battery life.

CoAP Request Methods and Multicast

Now extend the tank example to several sensors. Multicast sends a request to a group address rather than one server. It reduces outgoing requests, while each responding sensor still contributes traffic. For the illustrative group of fifty, replacing fifty requests with one removes 49/50, or 98%, of outgoing requests; it does not remove 98% of the whole exchange.

Use a non-confirmable group GET for discovery, then collect individual unicast replies. Missing replies leave uncertainty about which devices are present. A group command also needs an authorization and outcome rule for each device.

Continue: CoAP Method Codes and Multicast Contracts

The main chapter below stays focused on the core methods and feature tour. For the deeper contract behind compact method and response codes, safe/idempotent retry behavior, multicast discovery, Location options, Token correlation, and Leisure response spreading, continue to CoAP Method Codes and Multicast Contracts.

CoAP Methods

Return to the lost tank reply. Repeating the same fixed-limit PUT preserves the intended setting; issuing another create-record POST may add another record. Idempotency names this distinction in intended effects, not identical response codes. Safe means the client is not requesting a state change: GET is safe, while PUT and DELETE can change state.

Distinguish a protocol retransmission from a new application request. Duplicate handling of a retransmitted message does not give every fresh POST an idempotency guarantee. Use this table after predicting the operation:

MethodPurposeHTTP EquivalentIdempotent
GETRetrieve resourceGETYes
POSTProcess supplied data; may create a subordinate resource or trigger an actionPOSTNot guaranteed
PUTUpdate/CreatePUTYes
DELETERemove resourceDELETEYes

Examples

Read the examples by the state transition each method promises. GET retrieves the current /temperature representation without changing it. POST sends a new reading to the /readings collection, allowing the server to create a subordinate resource. PUT replaces the known /config representation with the supplied interval, so an identical retry has the same intended state. DELETE removes /readings/old. URI, method, payload, and expected response code should be reviewed together before any of these exchanges is implemented.

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

Bex guides the message review.Checkpoint: Method Semantics

You now know:

  • CoAP carries the same four REST verbs as HTTP: GET, POST, PUT, and DELETE.
  • GET, PUT, and DELETE have idempotent semantics; POST has no general guarantee for a fresh repeat.
  • Transfer the tank rule to the thermostat below: read temperature, set a fixed target, and invoke a reset. A reset action still needs a repeat policy.

Code Examples

Read the snippets as partial examples. They are preserved here for inspection, not presented as a tested end-to-end configuration lab. The Python server refers to resource without an explicit import, mounts only /temperature, and its PUT handler prints bytes without storing a setting. The client’s /config PUT therefore has no matching resource in that server. A Changed response from a handler that only prints does not prove the requested setting was saved.

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())

Knowledge check · self-test

Knowledge check

Test your understanding.

Install: pip install aiocoap

Python CoAP Client

The executed GET targets the mounted /temperature resource. The separate update_config() function is defined but never called by the final line. To evaluate an update implementation, inspect both the response and a subsequent read of stored state; these snippets do not supply that storage contract.

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())

Arduino ESP32 CoAP Client

This client requests temperature and prints received payloads. It waits ten seconds before servicing coap.loop(), so it is not evidence of prompt response handling or complete retry behavior. Its Message ID printout alone cannot establish a matching successful response.

#include <WiFi.h>
#include <coap-simple.h>

// WiFi credentials
const char* ssid = "YourWiFi";
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 WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("\nWiFi 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();
}

Interactive Comparison: CoAP vs MQTT vs HTTP

The chart uses fixed illustrative values. Its battery years, latency and complexity scores have no measurement evidence here. Its header bars also compare different amounts of framing. Use the controls to inspect the assumptions; do not use the ranking as a benchmark or a battery forecast.

Key Insights

CoAP Advantages:

  • A four-byte base header supports compact resource messages, before other fields and layers.
  • GET and PUT make reads and desired-state settings explicit.
  • UDP avoids TCP connection setup for this binding; security and application exchanges can still add setup work.

When CoAP Wins:

For the tank panel, directly addressable resources and short datagram exchanges are reasons to evaluate CoAP. Measure the complete exchange on the target device before accepting an energy or latency requirement.

When to Choose Alternatives:

  • MQTT: Evaluate brokered publication when several consumers need the same events.
  • HTTP: Evaluate the required web interfaces, tooling and transport before comparing costs.

The simulator comparisons become a protocol choice only after interaction pattern and device constraints are considered together. Use the figure in the parent chapter to turn those observations into a repeatable selection route.

Read the figure in the parent chapter from the interaction question at the top. Small operations on named resources lead toward CoAP when sleep cycles, UDP, and tight headers matter; brokered fan-out leads toward MQTT; a full web API and proxy ecosystem leads toward HTTP. The branches describe fit, not a universal winner. Having chosen an interaction model, the next question is what that choice costs on the wire.

Interactive Tool: CoAP Message Size Calculator

Audit a simplified byte model. It fixes CoAP token/options at eight bytes and UDP/IPv4 at 28 bytes; it does not encode the actual resource. The URI-length control changes only MQTT. HTTP includes an assumed setup cost, while MQTT setup is excluded. Security, responses, retries and link framing are omitted. If the eight-byte allowance contains only token/options, the CoAP payload marker is also missing. The displayed totals therefore are not packet captures or complete exchange costs.

Message Size Optimization

At a fixed payload, identify which bytes the model counts before comparing totals. For the tank, a longer resource path can add CoAP option bytes even though this calculator leaves them fixed.

Use a capture of the intended request, response, security and retry policy to replace the model’s constants. Fewer bytes can reduce airtime under otherwise equal conditions; battery life also depends on receive, idle and sleep work.

Battery Life Calculator: CON vs NON Messages

Delivery policy changes radio work, so use the interactive battery-life calculator below before treating CON or NON as a default. Set the daily message rate first, then switch message type and compare size, daily energy, and the modeled battery-life bars.

The preserved interactive calculator uses an inconsistent 12-byte ACK allowance: its CON cards and bars are not valid UDP/IPv4 totals. For the corrected model, assume an IPv4 header without options (20 bytes), a UDP header (8 bytes), and an empty CoAP ACK (4 bytes, with no Token, options or payload). The ACK therefore adds 20 + 8 + 4 = 32 bytes to the illustrative 45-byte request, giving 77 bytes across both directions before link-layer framing, security or retries. This models one request and one empty ACK; an application response would add traffic.

At 1,000 exchanges/day, applying the calculator’s 250,000 bit/s, 20 mA and 3 V assumptions uniformly to counted bytes gives 0.0864 J/day for 45 bytes and 0.14784 J/day for 77 bytes. Dividing its assumed 2,430 J budget by these costs and by 365 gives 77.05 and 45.03 years respectively. These are equivalent transmit-energy calculations across both directions, not a device measurement: a sending device receives the ACK, and its receive current and listening time need separate accounting. The calculator’s CON output retains the old allowance; use the corrected arithmetic here rather than its CON cards or bars. Neither result forecasts product battery life.

Critical Battery Life Insights

NON vs CON Performance:

Read these points as one illustrative byte-count comparison: NON sends a 45-byte request and CON plus an empty ACK exchanges 77 bytes, a 32-byte increase under the IPv4 assumptions above. Radio energy also depends on the receive window, retries, and sleep schedule. Use CON when acknowledgment and retry matter, while planning for failure after the retry limit. This transmit-only accounting excludes receive energy, idle current, security, self-discharge and pulse capability; its years are not a service-life prediction.

  • NON messages skip acknowledgment; this model counts 45 bytes versus 77 bytes for CON plus an empty ACK (32/77 ≈ 42% fewer bytes)
  • CON messages request an ACK and may retry; the corrected 77-byte exchange is 32/45 ≈ 71% more than NON before retries
  • Battery-life change depends on the full device energy budget
  • Use CON when acknowledgment and bounded retries are needed

Bex guides the message review.Checkpoint: Message Cost

You now know:

  • CoAP’s base header is four bytes; the HTTP numbers here are chosen accounting assumptions.
  • For the 5-byte temperature example, the chapter’s model gives 45 bytes for CoAP and 425 bytes for HTTP.
  • Under the stated IPv4 assumptions, an empty ACK adds 4 CoAP + 8 UDP + 20 IPv4 = 32 bytes, giving a 77-byte request-plus-ACK model. The preserved calculator still uses 12 bytes; its CON output is inconsistent with that framing and is not a device measurement.

Interactive Simulator: CoAP-Style UDP Communication

What This Simulates: An embedded ESP32 UDP example. The remote simulation has not been verified here; use the checks below to establish which CoAP fields it actually exposes.

Before starting the simulator, inspect the figure in the parent chapter to predict which endpoint owns each resource and which identifiers should match when the response returns.

Read the diagram in the figure in the parent chapter from the ESP32 client across UDP port 5683 to the sensor server. GET selects /temperature, while PUT targets /led; the server maps each method and path to resource behavior. On the return path, Message IDs support the exchange and Tokens correlate responses with requests. Use those predicted fields as checkpoints while the serial trace runs.

How to Use:

  1. Start the simulation and locate a request’s method and resource path in the serial output. Expect GET /temperature or PUT /led only if implemented; a missing path means the trace cannot verify resource dispatch.
  2. Compare the response Token with the request Token, and an ACK’s Message ID with the acknowledged message. Missing identifiers mean correlation is unverified; UDP text alone is insufficient.
  3. Inspect the response code and resulting resource state. An ACK without a success response does not prove an update. Record unavailable fields rather than inferring them from elapsed time.

Learning Points

Use the diagram to predict the exchange before reading a trace. A Token correlates the response; a Message ID handles message-level matching and duplicates. An empty ACK can arrive before the separate resource response.

What You’ll Observe:

  1. UDP traffic, if the simulation exposes it.
  2. A CoAP header only if actual encoded fields are available.
  3. Method/path dispatch only if the trace shows it.
  4. Message IDs and Tokens with different matching roles.
  5. No TCP handshake for this UDP binding; this does not rule out security setup.

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:

The preserved illustration below compares byte counts, not power. Its packet sizes have not been established for this simulator and must not be used as evidence of energy savings.

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

Multicast Support

Once a single exchange is clear, scale the same resource model to a group. Multicast helps discovery without changing what GET means.

CoAP supports multicast for group communication:

IPv4 Multicast

224.0.1.187

IPv6 Multicast

FF0X::FD

Use cases:

  • Discover devices on network
  • Broadcast commands to group
  • Query multiple sensors simultaneously

Example:

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

This address identifies the example group and scope; X in the address pattern is a scope placeholder. A multicast GET is NON. Only reachable, participating servers that choose to answer contribute replies; the request does not establish that every device received it.

Multicast Efficiency Calculator

The calculator assumes 24-byte requests, 12-byte responses, and a reply from every device. Its fixed 10 ms multicast time does not include a verified collection window or paced reply delays; the displayed “faster” percentage is not a completion-time result.

Use the calculator to compare request amplification, not to assume multicast makes every operation safe. Set Number of Devices first, then switch Communication Type between Unicast (individual) and Multicast (group). Unicast increases request count and sequential time with every device; multicast holds the outbound request count at one but still receives one response per participating endpoint. That distinction explains why discovery benefits from multicast while state-changing commands still need per-device authorization, outcome tracking, and retry decisions.

Bex guides the message review.Checkpoint: Discovery and Observe

You now know:

  • Multicast can send one discovery request instead of contacting 50 sensors one by one.
  • Polling 50 sensors every 5 seconds creates 600 request cycles per minute even when values stay stable.
  • Observe can avoid unchanged-value polls, but registration lifetime, notification pacing and freshness still need checking.

CoAP Features

Return to the tank: discovery finds an advertised alarm resource, GET reads its representation, PUT sets the desired limit, and Observe can report later state changes. Each feature answers a different question. Discovery does not authorize a change, and a notification does not prove a physical alarm operated.

Key Features
  1. Reduced Overhead: Four-byte base header, plus other fields and layers.
  2. URI Support: An address identifies the resource.
  3. Content-Format: Identifies the payload representation, such as text or JSON.
  4. Resource Discovery: Query /.well-known/core for advertised links.
  5. Observe Pattern: Register for subsequent resource notifications.
  6. Caching: Max-Age describes response freshness for reuse.
  7. Block-wise Transfer: Transfer representations in blocks.
  8. Security: Configure protection and peer identity separately; UDP examples can use DTLS.

Resource Discovery

Query a known server for its advertised resources. In this example, /temperature advertises text (ct=0) and /config JSON (ct=50). Select the path and representation before issuing the operation; the listing alone proves neither permission nor implementation behavior:

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

Response:

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

What This Simulates: An embedded discovery example whose remote behavior is unverified here. Check for the request and response rather than assuming automatic device enrollment.

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. Start the simulation and look for a GET to /.well-known/core and a returned link list. Without both, discovery is not demonstrated.
  2. Select an advertised path and inspect its attributes. Expect the request to use that path; a different path can produce a missing-resource error.
  3. GET the selected resource and compare the representation with its advertised format. A mismatch is a contract defect.
  4. If testing Observe, check that registration was accepted before expecting notifications. Silence alone cannot distinguish a stable value from a failed registration or lost connection.

Learning Points

Treat discovery as a negotiation, not merely a directory listing. First request /.well-known/core, then parse each link into its resource path and attributes. The resource type says what the endpoint represents, the interface says how a client should interact with it, content format says what representation to expect, and obs advertises notification support. Only after those claims are understood should the client issue a request. The experiments below summarize ways to change that contract; each change should be checked in both the advertisement and the behavior of the discovered resource.

What You’ll Observe:

  1. Discovery Request - A client queries a known server or a reachable group.
  2. Standard Endpoint - /.well-known/core returns advertised links (the page cites RFC 6690).
  3. Resource Attributes - Metadata describes expected resource and interface behavior.
  4. Verification - A subsequent request tests the advertised behavior.
  5. Enrollment - Identity and permission still require separate handling.

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:

Resource discovery is useful only if a client can interpret an advertisement rather than merely find a URI. Inspect the figure in the parent chapter to decode the example from the path outward through its link-format attributes.

In the figure in the parent chapter, start with /temp, the resource a client can request. Then read rt as its semantic resource type, if as the interaction interface, ct=0 as the representation’s content-format, and obs as an advertisement of Observe support that the client must verify during registration. Those attributes let discovery feed a compatible client action, which is why the application examples below can find capabilities without hard-coded endpoint catalogs.

Real-World Applications:

  1. Smart Building - HVAC units discover sensors automatically
  2. Industrial IoT - Factory machines advertise capabilities
  3. Home Automation - A hub discovers advertised resources from responding devices; enrollment is a separate application mechanism
  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:

The following sketch assumes multicast reachability and successful replies. “Finds all devices” and “adapts” describe the sketch’s intended outcome, not a guarantee. A missing server may be asleep, unreachable, unauthorized to answer, or lost in transit.

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:

  • Fewer manually maintained resource paths when advertisements are usable.
  • Discovery of responding devices within the selected network scope.
  • Metadata to guide later requests, with identity, permissions and actual behavior verified separately.
Knowledge Check: Match and Sequence

Match each CoAP concept to its correct definition or use case:

Use the tank workflow: discover a candidate path, select a compatible representation, then register only if change reports are needed. The matching answers distinguish each action from the evidence it still requires.

Arrange the following steps of a CoAP resource discovery and subscription workflow in the correct order:

The order matters because a client needs a target URI before registration, and must verify acceptance before relying on notifications. Discovery replies identify candidates; they are not an inventory completeness guarantee.

Knowledge check · self-test

Knowledge check

Test your understanding.

Label the Diagram

Knowledge check · self-test

Knowledge check

Test your understanding.

Protocol Comparison

For the tank design, compare interactions before byte totals. The tables below describe this page’s UDP CoAP, HTTP over TCP, and brokered MQTT examples; they are not exhaustive transport specifications or measured benchmarks.

CoAP vs HTTP: Concrete Performance Numbers

FeatureCoAPHTTPCoAP Advantage
TransportUDPTCPNo handshake overhead
Base Header Size in this example4 bytes100–200 bytes of illustrative HTTP headers96–98% fewer header bytes before CoAP options
Illustrative Total On-Wire Size40–60 bytes250–600 bytes76–93% fewer bytes across the stated endpoints
Connection SetupNone (UDP)3-way handshakeSaves 1+ RTT + ~180 bytes
MethodsGET, POST, PUT, DELETESame + moreFocused on IoT needs
DiscoveryAdvertised links at /.well-known/coreDepends on the applicationCompare actual enrollment and discovery requirements
MulticastYes (FF0X::FD)NoOne-to-many efficiency
ObserveResource notificationsApplication may use Server-Sent EventsSavings depend on polling and notification policies
SecurityDTLSTLSUDP-optimized

Real Numbers Example - Temperature Reading:

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

Putting Numbers to It

This is an illustrative accounting exercise, using the calculator’s incomplete framing allowance. It is not a complete on-wire capture. Here HH means counted overhead and PP means payload bytes:

Btotal=Hprotocol+Htransport+PB_{\text{total}} = H_{\text{protocol}} + H_{\text{transport}} + P

CoAP message: Bc=4 (header)+8 (token+options)+28 (UDP/IP)+5 (payload)=45B_c = 4\text{ (header)} + 8\text{ (token+options)} + 28\text{ (UDP/IP)} + 5\text{ (payload)} = 45 bytes

HTTP message: Bh=200 (headers)+40 (TCP/IP)+5 (payload)+180 (handshake)=425B_h = 200\text{ (headers)} + 40\text{ (TCP/IP)} + 5\text{ (payload)} + 180\text{ (handshake)} = 425 bytes

Assume 1,000 daily readings, 3 V, 200 mA transmit current and 250 kbps effective link rate. These are selected model inputs, not measured ESP32 behavior; the earlier battery calculator uses 20 mA instead: Ec=1000×45×8250,000×0.2A×3V=0.86 J/dayE_c = 1000 \times \frac{45 \times 8}{250,000} \times 0.2\text{A} \times 3\text{V} = 0.86\text{ J/day}

Eh=1000×425×8250,000×0.2A×3V=8.16 J/dayE_h = 1000 \times \frac{425 \times 8}{250,000} \times 0.2\text{A} \times 3\text{V} = 8.16\text{ J/day}

Dividing an assumed 675 mWh = 2,430 J energy budget by these transmit-only costs yields about 7.7 years versus 0.8 years. This division does not establish that a CR2032 can supply the assumed radio current. The 9.4× overhead ratio translates directly to a 9.4× difference in radio energy per day. Note: real-world battery life will be shorter due to sleep/idle current, MCU processing, and other loads; this model isolates the protocol overhead contribution.

The arithmetic above becomes easier to audit when bytes, energy, and lifetime stay on one scale. Use the figure in the parent chapter to check that each stage preserves the same overhead ratio.

Read the figure in the parent chapter from on-wire bytes to daily energy and finally to TX-only battery life. The example’s 45-versus-425-byte traffic becomes 0.86 versus 8.16 joules per day under the same radio assumptions, so the lifetime bars reverse in length. Because sleep current, computation, retries, and battery behavior are excluded, carry forward the comparative conclusion—protocol overhead matters—not the projected years as a deployment promise.

Maths · guided foundations

The Efficiency Claim Reduces to Counting Bytes

Check the quantities and assumptions.

Bex guides the message review.Checkpoint: Protocol Selection

You now know:

  • CoAP keeps REST-style GET, POST, PUT, and DELETE while avoiding TCP setup.
  • In the chapter model, 1,000 daily readings produce 0.86 J/day for CoAP and 8.16 J/day for HTTP radio transmission.
  • The isolated protocol-overhead model yields 7.7 years versus 0.8 years of TX-only battery life before other loads are counted.

CoAP vs MQTT

FeatureCoAPMQTT
PatternRequest/ResponsePublish/Subscribe
TransportUDPTCP
DiscoveryBuilt-inExternal
QoSVia message type3 levels (0,1,2)
BrokerOptionalRequired
Best ForRESTful IoTEvent-driven IoT
Order Multicast Discovery

Put these four steps in order: choose a scoped group address, send a NON multicast GET, let eligible servers evaluate the request, then collect paced unicast replies.

Knowledge check · self-test

Knowledge check

Test your understanding.

CON and NON Pattern Evidence

Choose the CoAP message type per interaction, not per deployment. The method tells the server what operation to perform; CON or NON tells the protocol how much delivery evidence is worth paying for.

InteractionPreferReason
Periodic temperature or humidity readingNONThe next reading replaces the missing one, so avoiding ACK traffic usually matters more than perfect delivery
User-initiated configuration PUTCON, plus response/state checksRetry message loss; inspect the operation response and verify the saved value
Door unlock, alarm, valve close, or safety threshold alertCON, with application outcome verificationBounded retries can still fail; missing completion must trigger the application’s failure policy
High-frequency heartbeatNON, with application-level missing-heartbeat detectionMissing one heartbeat is tolerable; several missing heartbeats become the signal
Firmware block transferCON in this example, plus completeness checksDetect missing blocks and verify the completed representation

For constrained sensors, a hybrid policy is often the measurable answer: routine telemetry as NON, rare commands and critical alerts as CON. Record the tolerated loss rate, expected message frequency, and retry budget so the battery and reliability tradeoff can be checked in tests.

See Also

Review the method code contract first, then the message types used to carry those requests and responses.

A thermostat target is 18 C. You need it stored as 21 C, with no other writer. Your first request receives only an empty ACK; its separate response is lost. A fresh same-value request later returns 2.04 Changed, and a fresh GET returns 2.05 Content with 21 C. Which method, repeat prediction, and success report fit?

PUT /target with 21 C; a fresh identical repeat preserves 21 C. Report the stored setting after the correlated 2.04 Changed and fresh 21 C readback, not from the empty ACK alone.

Correct. PUT expresses fixed desired state, so a fresh same-value repeat preserves its intended effect. The empty ACK confirms message receipt; the correlated success response and fresh readback establish the stored setting.

A facility manager has 200 CoAP sensors from three manufacturers on the same link-local multicast scope. Each supports CoRE resource discovery, and identity enrollment is handled separately. The installer wants to discover their resource addresses without manually entering each IP. Which feature fits?

Resource discovery at /.well-known/core using a multicast query

Correct. A NON multicast GET to the link-local CoAP group at /.well-known/core can discover responses from reachable devices that implement CoRE Link Format. The client must handle missing or delayed responses, and discovery does not replace identity enrollment.

An IoT architect is designing a smart parking system. Sensors report infrequent car-presence changes and need individually addressable maintenance resources. There is no broker, and the device design requires short datagram exchanges without TCP connection setup or a persistent session. Five-year battery life remains a target to verify. Which listed protocol best fits?

CoAP for sparse device updates and individually addressable resources.

Correct. CoAP provides compact resource-oriented exchanges over UDP without a broker, fitting the stated datagram design and addressable maintenance resources. Choose CON or NON from the consequence of a missed state change, and measure whole-device energy before accepting the five-year target.

Summary

For the tank, GET reads, PUT sets a fixed alarm limit, and POST can create a calibration record. Predict a repeat’s intended effect before retrying after a lost reply. Discovery identifies candidate resources; Observe can reduce repeated reads. Neither feature establishes successful actuation. Keep response codes, correlation fields and resulting state as separate evidence.

Key Takeaway

Choose the method from the intended action, the delivery policy from the cost of loss, and the success claim from the response and verified state. Use byte models to ask what to measure, then transfer that rule to the next resource.

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.