Chapters

CoAP Advanced Features: Reference

Return to the parent chapter.

Start With the Almost-Too-Large Update

Prove the Update Through a Broken Link

Picture a street sensor that needs a software fix over a weak radio link. The update is too large for one message, and the device may sleep before every part arrives. A safe release needs a clear final result, not a pile of successful sends.

Follow the opening case from its first sign to a careful next step.

Firmware is the software installed on a device. An over-the-air (OTA) update delivers replacement firmware through the network. CoAP, the Constrained Application Protocol, exchanges requests and responses for named resources.

Work through the street sensor’s update before choosing an extension. The existing tour uses a 2,048-byte image and 256-byte pieces: 2,048 / 256 = eight blocks, numbered 0 through 7. If a client sends those bytes in PUT requests to the sensor, use Block1, the option for request bodies. If the sensor requests them with GET and receives the bytes in responses, use Block2, the option for response bodies. The direction of the body decides the option; the word “firmware” does not.

Suppose the acknowledgment for block 2 is lost. Retry that exchange and check that the receiver stores its bytes once. Block 7 has the more flag cleared, but that alone does not prove the image is authentic or installed. Check the complete image, its trusted source, and the device’s reported running version before approving the update.

Start an update, lose one block, repeat another, delay the last block, and restart the device. It must keep the old safe version or accept one complete new version. The service must show which outcome occurred.

A restart adds a different question: did the implementation persist enough state to continue with the same image? Block-wise transfer does not promise persistent recovery after power loss. Carry that question through discovery, transport selection, and the fleet example below.

In 60 Seconds

For the sensor update, choose Block1 for request bodies or Block2 for response bodies. Discovery lists advertised resource links. Datagram Transport Layer Security (DTLS) can protect a UDP exchange between its security endpoints; a terminating proxy creates a separate protection boundary. None of these features alone proves that the device installed the intended image.

Chapter Roadmap

First, use Block1 and Block2 for payloads that do not fit one datagram. Then use /.well-known/core instead of hard-coded resources. Next, decide when UDP, TCP, WebSockets, or DTLS changes the design. Finally, pressure-test NAT, timeout, proxy, and OTA evidence. Checkpoints summarize each layer; Deep-dive sections are optional.

Learning Objectives

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

  • Implement Block-wise Transfer: Apply RFC 7959 to handle large payloads (firmware updates) over CoAP’s UDP transport.
  • Configure Resource Discovery: Construct .well-known/core endpoints with CoRE Link Format attributes.
  • Evaluate CoAP Transport Options: Select between UDP, TCP, and WebSockets based on network constraints and device requirements.
  • Analyze DTLS Security Overhead: Calculate handshake RTT costs and justify security mode selection for constrained deployments.
  • Diagnose Block Transfer Failures: Distinguish between timeout cascade, packet loss, and NAT expiry failure modes.
Quick Check: Advanced Feature Choice
  • CoAP: A resource request/response protocol; the base specification uses UDP, and RFC 8323 defines reliable transports.
  • Confirmable Message (CON): Requests an acknowledgment and supports bounded retransmission; an ACK alone does not establish successful application processing.
  • Non-confirmable Message (NON): Fire-and-forget UDP datagram — lowest latency, no delivery guarantee.
  • Observe Option: CoAP extension enabling publish/subscribe: client registers to receive notifications on resource changes.
  • Block-wise Transfer: Application-layer transfer of a representation in numbered pieces, distinct from IP fragmentation.
  • Token: Client-generated value matching responses to requests — enables concurrent request/response pairing.
  • DTLS: Datagram TLS — CoAP’s security layer providing encryption and authentication over UDP.

For Beginners: CoAP Advanced Features

Beyond basic request-response messaging, CoAP offers features like resource observation (automatic notifications when data changes), block transfers (sending large data in chunks), and resource discovery (finding what services a device offers). These features make CoAP a powerful, lightweight communication tool for constrained IoT devices.

The dashboard needs repeated readings; the updater needs a large body. These are different problems. Observe maintains a notification relationship for a resource, while block-wise transfer carries pieces of a representation.

For the eight-block street-sensor update, retrying block 2 repeats its 256-byte payload. The receiver must handle the repeat without adding those bytes twice. Discovery can help the updater find an advertised resource, but it neither provisions credentials nor proves that every device is reachable.

Prerequisites

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

Before choosing an extension, use the figure in the parent chapter to separate the three problems that advanced CoAP features solve: repeated updates, payloads too large for one datagram, and one-to-many operations.

In the figure in the parent chapter, Observe replaces repeated polling with notifications when data changes. Block-wise transfer splits a large representation into bounded pieces. Multicast sends one request towards a group. Each is a separate extension. Choose the one that fits the traffic problem instead of treating “advanced CoAP” as one bundle. The next section covers the size problem. Use the linked Observe material for rules about the notification lifecycle.

Continue: CoAP Block Transfer and Discovery Contracts

The main chapter below stays focused on the advanced-feature tour. For the deeper contract behind Block1 and Block2 sizing, NUM/M/SZX encoding, retry and resume evidence, CoRE Link Format discovery, Max-Age, ETag revalidation, and proxy caching, continue to CoAP Block Transfer and Discovery Contracts.

Block-wise Transfer (RFC 7959)

The first problem is size. CoAP exchanges are intentionally small, so firmware images and log uploads need reviewable pieces.

Minimum Viable Understanding: Block-wise Transfer

Core Concept: The path maximum transmission unit (MTU) limits packet size without fragmentation. Headers and security consume part of that budget. Block-wise transfer divides a representation into pieces; the implementation must reconstruct and validate the result.

Why It Matters: The sensor can retry a piece rather than restarting the whole image. It still needs a policy for duplicate blocks, interrupted transfers, and final acceptance.

Key Takeaway: Use Block2 for large response payloads (downloads), Block1 for large request payloads (uploads). Each block includes block number, more-flag, and size.

Block2: Large Response Payloads

A large server response, such as a firmware image, cannot safely be treated as one oversized datagram. Use the figure in the parent chapter to see which state must survive while the client assembles that representation piece by piece.

Read the figure in the parent chapter with these corrections: a token correlates a request with its response; subsequent block requests may use different tokens. Representation consistency is a separate check: compare ETags when supplied and reject blocks from a changed representation rather than mixing versions. Validate each response’s block number, decoded size, payload length, and representation metadata, then place its payload at offset NUM × decoded block size. Track covered byte ranges so duplicates do not add bytes and reordered responses do not change placement; appending each distinct arrival once is insufficient.

Before accepting the image, require complete byte coverage through the final block and a consistent total length. For this updater, verification of the complete image against a trusted expected hash is an application acceptance policy, not a guarantee supplied by RFC 7959.

Block2 option format:

  • NUM: Block number (0-based sequence).
  • M: More flag (1 = more blocks follow, 0 = last block).
  • SIZE: Decoded block size in bytes (16, 32, 64, 128, 256, 512, 1024). The encoded SZX field is a size exponent, not a byte count.

Block1: Large Request Payloads

Used when client sends large data to server (e.g., uploading logs):

Client -> Server: PUT /logs/daily
                  Block1: NUM=0, M=1, SIZE=512
                  Payload: [first 512 bytes]

Server -> Client: 2.31 Continue
                  Block1: NUM=0, M=1, SIZE=512

Client -> Server: PUT /logs/daily
                  Block1: NUM=1, M=1, SIZE=512
                  Payload: [next 512 bytes]

... until final block with M=0 ...

Server -> Client: 2.04 Changed

Implementation with Reliability

async def download_firmware(uri, output_file):
    block_num = 0
    block_size = 1024
    consecutive_failures = 0

    with open(output_file, 'wb') as f:
        while True:
            # Adaptive timeout with exponential backoff
            timeout = min(2.0 * (1.5 ** consecutive_failures), 30.0)

            try:
                request = Message(
                    code=GET,
                    uri=uri,
                    msg_type=CON,  # Reliable for each block
                    block2=(block_num, False, block_size)
                )
                response = await protocol.request(request, timeout=timeout).response

                # Write block to file
                f.write(response.payload)
                consecutive_failures = 0

                # Check if more blocks available
                if response.opt.block2.more:
                    block_num += 1
                else:
                    break  # Last block received

            except TimeoutError:
                consecutive_failures += 1
                if consecutive_failures > 10:
                    raise TransferFailed(f"Failed at block {block_num}")

    print(f"Downloaded {block_num + 1} blocks")

The code above is a sketch, not a verified library procedure. It assumes a fixed block size and appends each response without validating its block number or representation identity. Before using this pattern, check the installed library API, returned offsets, changed block sizes, duplicate handling, and final integrity. Its file is opened afresh; it does not implement recovery after reboot.

Performance Analysis

Scenario: An illustrative 256 KiB firmware image over LoRaWAN, with an assumed 10% loss rate. KiB means 1,024 bytes; the table identifies the radio constraints missing from a CoAP-only estimate.

ApproachBlocksRetransmissionsTimeSuccess Rate
Single 256 KiB payloadNot a valid LoRaWAN application payload; split into regional-size fragments—Depends on regional data rate and duty restrictions—
1 KiB blocks (NON)Each 1 KiB block must be further fragmented to fit the regional LoRaWAN application-payload limitNo CoAP retransmissionCalculate from fragmentation and radio scheduleIncomplete if fragments are lost
1 KiB blocks + CONEach block requires further LoRaWAN fragmentationDepends on fragment retriesCalculate from regional payload and radio scheduleDepends on retry and integrity policy
512 byte blocks + CONEach block still requires LoRaWAN fragmentationDepends on fragment retriesCalculate from regional payload and radio scheduleDepends on retry and integrity policy

Assume each whole block attempt independently succeeds with probability 1−p1-p, and ignore acknowledgment loss. Without retries, all nn blocks arrive with probability:

Psuccess=(1−p)nP_{\text{success}} = (1 - p)^n

For 1KB blocks (256 blocks total) without confirmations (NON):

P1KB NON=(1−0.10)256=0.9256≈1.93×10−12≈0%P_{1\text{KB NON}} = (1 - 0.10)^{256} = 0.9^{256} \approx 1.93 \times 10^{-12} \approx 0\%

Under an idealized unlimited-retry model, the expected attempts per block are:

E[transmissions]=11−p=10.9≈1.11E[\text{transmissions}] = \frac{1}{1-p} = \frac{1}{0.9} \approx 1.11

Total time for 256 blocks at 200 ms per confirmed block:

Ttotal=256×0.2×1.11≈56.8 secondsT_{\text{total}} = 256 \times 0.2 \times 1.11 \approx 56.8 \text{ seconds}

For 512-byte blocks, there are 512 blocks. At the same independent loss probability, each attempt still succeeds with probability 0.9. Smaller blocks reduce payload bytes repeated per retry, but more blocks reduce the probability of completing without any loss. The time product above includes idealized retry attempts but excludes acknowledgment loss, backoff, radio fragmentation, airtime restrictions, and receive windows. It is not a LoRaWAN completion-time estimate.

Key insight: Without retries, more fragments mean more chances for loss. With capped retries, compute completion probability from all radio fragments and the retry policy; smaller blocks can reduce bytes retransmitted after a loss.

Bex guides the message review.Checkpoint: Block-wise Transfer

You now know:

  • Block2 handles large responses; Block1 handles large requests.
  • The block option carries NUM, M, and a block size such as 512 or 1024 bytes. In the 256 KiB, 10% packet-loss example, both 1 KiB and 512-byte CoAP blocks require smaller LoRaWAN fragments; transfer time must be recalculated for the chosen region, data rate, duty limit, acknowledgments, and retry policy.

You need to send a 10 KiB firmware update over a lossy CoAP/UDP path (15% datagram loss). After allowing for CoAP headers, token, options, payload marker, and network/security overhead, the path permits up to 1024 payload bytes per block without fragmentation, but the priority is to limit bytes resent after loss while detecting failed delivery. Which listed block-wise configuration best fits?

256-byte blocks with CON messages for reliability

Correct. Among these options, 256-byte CON blocks detect failed delivery and limit each block retry to 256 payload bytes instead of 1024. The smaller blocks add exchanges, so a full transfer budget still needs measurement.

A 1,800-byte update crosses a path limited to 300-byte CoAP payloads. Which legal block size fits without exceeding the limit, and how many data blocks are needed?

Use 256-byte blocks and send eight data blocks.

Correct. 256 is the largest power-of-two CoAP block size below 300; ceil(1800/256) is eight.

Interactive: Block-wise Transfer Time Calculator

Try It:

  1. Keep image size and loss fixed; reduce block size. Expect more blocks and a lower displayed NON first-pass success rate. A higher rate would contradict this model’s independent fixed-loss assumption.
  2. Compare the displayed time with a trace. This estimate assumes unlimited independent attempts; real CON exchanges have bounded retries and backoff.
  3. Treat the recommendation label as a heuristic. It cannot establish an optimal size or radio feasibility.
Interactive: Block Size Optimizer

Key Principle: The optimizer uses assumed loss thresholds and a 12-byte CoAP allowance. It does not measure a path or include all network and security headers. Its MTU clamp can return a value outside the legal block sizes. Choose a legal size that fits the full packet budget, then measure completion and retry cost; the displayed “optimal” label is not evidence.

See why the tempting answer fails.

Resource Discovery (RFC 6690)

Once payloads can move safely, the next question is how a client knows which resources exist. Discovery replaces guessed URIs with an inventory.

Minimum Viable Understanding: CoAP Resource Discovery

Core Concept: A CoAP server that implements RFC 6690 discovery exposes /.well-known/core, which returns selected resource links in CoRE Link Format. The server chooses which links and attributes to include.

Why It Matters: A client can inspect advertised links instead of guessing paths. It still needs a reachable server, permission, and an application agreement about what each resource means.

Key Takeaway: Implement /.well-known/core (RFC 7252 §7.2 says servers SHOULD) and tag links with rt= (resource type), if= (interface) and obs (observable, RFC 7641 §6).

Discovery Request-Response

Client Request:
GET coap://sensor.local/.well-known/core

Server Response (Link Format, Content-Format: 40):
</sensors/temp>;rt="temperature";if="sensor";obs,
</sensors/humidity>;rt="humidity";if="sensor";obs,
</sensors/pressure>;rt="pressure";if="sensor",
</actuators/led>;rt="light";if="actuator",
</config/interval>;rt="config";if="parameter"

Filtered Discovery

Request only specific resource types:

# Find all temperature sensors
GET coap://sensor.local/.well-known/core?rt=temperature

Response:
</sensors/temp>;rt="temperature";if="sensor";obs,
</sensors/temp_outdoor>;rt="temperature";if="sensor";obs

# Find all observable resources
GET coap://sensor.local/.well-known/core?obs

Multicast Discovery

Multicast discovery asks every eligible node the same resource question without sending one request per address. Send a NON GET to the link-local CoAP multicast group and /.well-known/core; each server then returns its own unicast response after a randomized Leisure delay. NON avoids an acknowledgment storm, while the delayed unicast replies reduce collisions and let the client associate each discovery record with one endpoint. The result is efficient inventory evidence, not reliable group command delivery.

GET coap://[FF02::FD]/.well-known/core

# All CoAP devices respond with their resource list
Device 1: </temp>;rt="temperature"
Device 2: </humidity>;rt="humidity"
Device 3: </pressure>;rt="pressure"
Bex guides the message review.Checkpoint: Discovery Contracts

You now know:

  • /.well-known/core returns CoRE Link Format instead of guessed paths.
  • rt, if, ct, sz, obs, and title describe resources and behavior.
  • Multicast discovery can query coap://[FF02::FD]/.well-known/core, but the client still initiates the request.

CoAP over TCP (RFC 8323)

Why CoAP-over-TCP?

Problem: Suppose the street-sensor updater cannot use its UDP route. Check whether policy blocks UDP, whether a NAT mapping has expired, and whether a supported TCP service is reachable. UDP carries separate datagrams; TCP provides an ordered byte stream. Stream order does not prove application execution order or successful installation.

Solution: RFC 8323 defines CoAP over reliable transports (TCP, TLS, WebSockets).

Protocol Differences

FeatureCoAP/UDPCoAP/TCP
TransportUnreliable UDPReliable TCP
Message TypesCON, NON, ACK, RSTNo message type field; requests, responses, and signaling messages
ReliabilityApplication (CON/ACK)Transport (TCP)
Message IDRequiredAbsent
ConnectionNoneTCP 3-way handshake
Default Port5683 (coap://)5683 (coap+tcp://)
Secure Port5684 (coaps://)5684 (coaps+tcp://) by default

Header Format Changes

CoAP/UDP header (4 bytes):

|Ver| T |  TKL  |      Code     |          Message ID           |

CoAP/TCP framing (at least 2 bytes before any token/options):

| Len | TKL | Extended Length (if any) | Code | Token (if any) |

Key changes:

  • No Message ID (TCP sequence numbers handle ordering).
  • No Type field (TCP reliability eliminates CON/NON/ACK).
  • Length field (for framing over stream).

Interactive: CoAP Transport Selector

Decision Framework: Test the selector with both “Firewall blocks UDP” and “Battery-powered device” checked. Its heuristic can still recommend UDP. That result conflicts with the blocked route: reject it and verify a supported permitted path. NAT presence alone does not require TCP, and battery cost needs measurement.

When to Use

Use a reliable transport when the endpoints support it and the permitted path requires it. WebSockets need matching service support too; an open web port alone is insufficient. For the street sensor, compare reconnect cost and idle energy on the actual path before choosing TCP or UDP. TCP does not provide multicast, and connection setup matters when devices sleep between transfers.

You’re deploying CoAP sensors in a factory. IT blocks UDP port 5683, will not approve a UDP exception, and confirms that a suitable TCP 443 route is available. Which listed solution keeps CoAP methods while fitting that policy?

Use CoAP over TCP per RFC 8323 via the approved TCP 443 route.

Correct. RFC 8323 defines CoAP over TCP. On the permitted TCP route, it retains CoAP methods while replacing UDP message-layer CON/NON/ACK handling with reliable transport. TCP 443 still needs the intended CoAP service and firewall configuration.

Factory IT approves UDP 5683 for these sensors and has no usable TCP route. Which transport keeps standard CoAP methods within this policy?

CoAP over the approved UDP 5683 path

Correct. UDP 5683 is now permitted and reachable, so ordinary CoAP datagrams fit the stated route.

DTLS Security

Transport and security answer separate questions: can the peers exchange traffic, and can they protect it? A permitted TCP path still needs a suitable service and security configuration. DTLS protects datagrams between its endpoints.

CoAP uses DTLS (Datagram TLS) for security over UDP:

Security Modes

ModeDescriptionUse Case
NoSecNo securityDevelopment only
PreSharedKeySymmetric keys pre-installedFactory provisioning
RawPublicKeyAsymmetric without certificatesLightweight devices
CertificateFull X.509 certificatesEnterprise deployments

DTLS Handshake

Securing a datagram transport requires a handshake that can tolerate loss without letting an unauthenticated sender consume unlimited server state. the figure in the parent chapter shows where the DTLS cookie challenge fits before keys protect application traffic.

This figure depicts a DTLS 1.2-style certificate exchange, not a universal sequence for every version or credential mode. Follow the figure in the parent chapter downward. The first ClientHello prompts a stateless cookie challenge; the client proves return reachability by repeating ClientHello with that cookie. Only then do the server parameters, certificate and key exchange, and Finished messages establish the protected session. Encrypted application data starts after this exchange, which explains the setup cost explored by the calculator next.

Interactive: DTLS Handshake Overhead Calculator

Key Insight: DTLS setup cost varies with cookie exchange, profile, and loss. The calculator uses deployment-measured full-handshake and resumed-handshake setup RTTs; message-flight counts are not RTT counts. Measure both paths on the target link before estimating reconnection cost.

Bex guides the message review.Checkpoint: Transport and Security

You now know:

  • CoAP/UDP uses CON, NON, ACK, RST, and Message IDs; CoAP/TCP removes those message types.
  • A supported CoAP/TCP service may fit a permitted TCP route. Verify policy and measure device cost; TCP does not provide multicast.
  • NoSec provides no DTLS protection. PSK, raw public keys, and certificates require different credential arrangements. Measure full and resumed setup on the target link.

A measured DTLS full handshake took 600 ms and session resumption took 200 ms on this link. How much measured setup time was saved?

400 ms

Correct. These are deployment measurements, not DTLS-required RTT counts; 600 ms minus 200 ms equals 400 ms saved.

On this link, a full DTLS setup measured 750 ms and a resumed setup measured 180 ms. How much setup time does resumption save?

570 ms

Correct. Subtracting resumed setup from full setup gives 570 ms.

Common Pitfalls

Pitfall: Block-Wise Transfer Timeout Cascade

The mistake: Using fixed CoAP timeout settings for a long block-wise transfer can cause repeated retries or an abandoned transfer on a lossy link.

Why It Happens: A timeout may reflect loss, a slow response, or lost path state. The default initial ACK timeout is not a deadline for an entire multi-block transfer. Restarting the whole image after one failed exchange is an implementation policy, not a block-wise requirement.

The Fix: Implement adaptive timeouts and resumable transfers:

def download_with_resume(uri, resume_from=0):
    block_num = resume_from
    consecutive_failures = 0
    base_timeout = 2.0

    while True:
        timeout = min(base_timeout * (1.5 ** consecutive_failures), 30.0)

        try:
            response = coap_get(uri, block2=(block_num, 0, 1024), timeout=timeout)
            save_progress(block_num, response.payload)
            consecutive_failures = 0

            if response.block2.more:
                block_num += 1
            else:
                return assemble_firmware()

        except TimeoutError:
            consecutive_failures += 1
            if consecutive_failures > 10:
                save_resume_point(block_num)
                raise TransferSuspended(block_num)
Pitfall: Assuming CoAP Works Through NAT Like HTTP

The Mistake: Assuming a network address translation (NAT) gateway preserves a UDP return path throughout a long idle period. Mapping lifetimes depend on the gateway and policy; the page has no measurements supporting a universal interval.

The Fix:

  • Test UDP connectivity before design.
  • Measure mapping expiry and test a keepalive interval against both that lifetime and the device energy budget.
  • Consider CoAP over TCP for NAT-hostile networks.
  • Compare measured DTLS full and resumed setup costs after connectivity is restored; resumption does not repair an expired NAT mapping.
Interactive: CoAP Block-Wise Transfer Animation

CoAP block-wise transfer narrated tour

Play silently with captions on provisional storyboard timing; narration audio is pending. Production pacing is not device or protocol time. Choose Reduced motion for a complete still at each beat.

Play the tour to open the workbench. Pause, replay a beat, or read the full transcript below. Calculations or situations this teaching model cannot show keep the existing frame and provide captions only.

Full transcript — CoAP block-wise transfer (8 beats)

B1 — Street sensor update
You are the engineer sending a software fix to a street sensor over a weak radio link. The sensor may sleep before every part arrives. It needs to keep its old safe software or accept a complete new version. How can the update travel in manageable pieces?

Model caption: You are sending a street sensor a software fix over a weak link. It may sleep before all parts arrive. It must retain its old safe software or accept a complete new version. The model demonstrates transfer pieces.

B2 — Upload and download
Constrained Application Protocol, or CoAP, gives small devices a compact way to make requests. Its block transfer splits a large message body into numbered pieces. Block one carries an upload in request messages. Block two carries a download in response messages. Your sensor receives the fix as a Block one upload.

Model caption: Constrained Application Protocol, or CoAP, uses requests for small devices. Numbered blocks split a large body. Block1 carries uploads in requests; Block2 carries downloads in responses. The fix is a Block1 upload.

B3 — Number, more flag, size
Each block has a number, a more flag, and a size. Numbering starts at zero. The more flag is one when more blocks follow, and zero for the final block. The number identifies the piece; the flag tells whether another piece follows.

Model caption: Numbering starts at zero. Every block has a number, a more flag and a size. More flag one means another block follows; zero marks the final block.

B4 — Negotiate smaller blocks
For our example, the update contains two thousand forty-eight bytes. The client requests blocks of five hundred twelve bytes, but the server accepts at most two hundred fifty-six. The model takes the smaller value, two hundred fifty-six bytes. Smaller blocks make retries cheaper, while requiring more exchanges.

Model caption: The update has 2048 bytes. Requested size is 512 bytes; server maximum is 256. The smaller value, 256 bytes, is used. Smaller pieces make retries cheaper and require more exchanges.

B5 — Eight numbered pieces
Divide two thousand forty-eight by two hundred fifty-six to get eight. Rounding up still gives eight, and choosing the larger of one and eight leaves eight blocks. So the update travels as eight pieces of two hundred fifty-six bytes each, numbered zero through seven.

Model caption: 2048 divided by 256 is 8. Rounding up leaves 8; the larger of 1 and 8 is 8. Eight 256-byte pieces carry the update, numbered 0 through 7.

B6 — Confirmable exchanges
The client sends block zero, and the server replies that it can continue. The more flag is one. Block one follows. We use Confirmable messages: if an acknowledgement is lost, the exchange can time out and the client can retry the same block.

Model caption: Block 0 is sent and receives Continue with more flag 1; block 1 follows. Confirmable messages allow the same exchange to be retried after a timeout if its acknowledgement is lost.

B7 — Retry only block two
Now the model loses the acknowledgement for block two, the third piece. A tempting mistake is to restart the entire update after that loss. That wastes work because the Confirmable exchange retries only block two. The repeated request carries two hundred fifty-six bytes, rather than the whole update.

Model caption: The model loses the acknowledgement for block 2, the third piece. Restarting the whole update wastes work: Confirmable recovery retries only block 2, repeating its 256-byte request payload.

B8 — Upload complete
After the retry, the upload reaches block seven. Its more flag is zero, and the model finishes with eight of eight blocks transferred. Split the body into numbered pieces, and a retry can repeat a piece instead of the whole body.

Model caption: After the retry, block 7 is the last piece: more flag 0 and eight of eight blocks transferred. Split the body into numbered pieces, and a retry can repeat a piece instead of the whole body.

Interactive: CoAP Proxy Operation Animation

Simulation · interactive

CoAP Proxy Workbench

Explore how the system behaves.

Worked Example: OTA Firmware Update for 500 Street Lights

The pieces now meet one operational question: can block transfer, frame limits, packet loss, and gateway parallelism finish inside a fixed maintenance window?

Transfer example: A council proposes a 128 KiB image for 500 lights in a two-hour window. Apply the street-sensor rule: identify which peer requests the image, choose the body option, and count the blocks. At 128 bytes per block, 131,072 / 128 = 1,024 blocks.

The calculations retained below are a hypothetical planning worksheet. The assumed 242-byte radio allowance, 12-byte CoAP allowance, 1.5-second exchanges, eight concurrent streams, gateway prices, and labor costs are unverified premises. A radio chip model does not establish a LoRaWAN application-payload limit or downlink concurrency. Region, data rate, receive class, security overhead, airtime restrictions, and gateway transmit scheduling must be checked before using this worksheet for a rollout.

Step 1: Calculate block count and transfer time per device

Firmware size: 128 KB = 131,072 bytes
Block size: 128 bytes (leaving room for CoAP headers within 242-byte limit)
  CoAP header + Block2 option: ~12 bytes
  Total per-message payload: 128 + 12 = 140 bytes (fits in 242-byte LoRaWAN frame)

Block count: 131,072 / 128 = 1,024 blocks per device

Here the device requests image blocks with GET, so the firmware is in Block2 responses. Assume a 1.5-second exchange only to inspect the worksheet arithmetic; it is not a measured Class C timing. The extra 8% below is a one-pass retry allowance, not the expected attempts under repeated independent loss:

Optimistic transfer time: 1,024 blocks x 1.5 seconds = 1,536 seconds = 25.6 minutes
With 8% packet loss and 1 retry per loss:
  Expected retransmissions: 1,024 x 0.08 = ~82 extra blocks
  Adjusted time: (1,024 + 82) x 1.5 = 1,659 seconds = 27.7 minutes per device

Step 2: Assess parallelism constraints

For arithmetic only, suppose a scheduler could maintain eight independent streams at the assumed 28-minute completion time. Receive-channel count does not establish simultaneous downlink capacity:

Devices per gateway: 8 parallel streams
Time per batch: 28 minutes
Batches needed: 500 / 8 = 62.5 -> 63 batches
Total time with 1 gateway: 63 x 28 = 1,764 minutes = 29.4 hours

Under those assumptions the worksheet exceeds two hours. Its gateway-count calculation is conditional; adding gateways does not by itself remove shared airtime or scheduling constraints:

Available time: 120 minutes
Batches possible per gateway: 120 / 28 = 4.3 -> 4 batches
Devices per gateway: 4 batches x 8 channels = 32 devices
Gateways needed: 500 / 32 = 15.6 -> 16 gateways

Step 3: Design the update strategy with CoAP Block-wise features

Design DecisionChoiceRationale
Block size128 bytesFits LoRaWAN frame with CoAP headers
Message typeCONACK and bounded retry improve delivery; final hash and install checks still decide integrity
Resume supportPersist validated transfer stateRecovery also needs image identity, offsets, and stored bytes; saving a number alone is insufficient
Integrity checkVerify complete image against trusted metadataA hash detects mismatch; trusted provenance and installation checks remain separate
Rollback planKeep previous firmware in secondary flash partitionThe bootloader/update policy must detect failure and select that fallback; demonstrate recovery after a failed update

Step 4: Cost analysis

Option A: Sequential update (1 gateway, no parallelism)
  Time: 500 devices x 28 min = 14,000 minutes = 9.7 days
  Gateway cost: 1 x $1,500 = $1,500
  Labor: 0 (unattended)
  Risk: Very slow, devices run outdated firmware for days

Option B: Parallel update (16 gateways, 2-hour window)
  Time: 2 hours (single maintenance window)
  Gateway cost: 16 x $1,500 = $24,000 (but gateways serve normal traffic too)
  Labor: 1 technician x 2 hours = $100
  Risk: Low, all devices updated simultaneously

Option C: Incremental rollout (4 gateways, 4 nights)
  Time: 4 maintenance windows x 2 hours = 8 hours total
  Gateway cost: 4 x $1,500 = $6,000
  Devices per night: 128
  Risk: Medium -- staged rollout catches firmware bugs before full deployment

Decision: Do not approve a gateway purchase from these figures. First demonstrate one complete update, interruption recovery, and an observed installed version. Then measure a pilot under the actual radio schedule and estimate fleet capacity from that evidence. Staged deployment limits exposure, but neither the proposed nightly count nor completion window is established here. Resume after power loss requires persisted implementation state and validation that the image has not changed.

  1. Record body direction, negotiated size, block offsets, and image identity. Expect 1,024 payload blocks for this fixed-size image; a different count needs an explanation such as renegotiated size.
  2. Interrupt and repeat an exchange, then reboot the receiver. Expect no duplicated stored bytes and either verified recovery or a clean restart; an unexplained offset indicates lost or inconsistent state.
  3. Verify the complete image against trusted update metadata, install it under the device’s update policy, and read its running version. A final block or matching hash alone does not establish trusted origin or successful installation.

Bex guides the message review.Checkpoint: OTA Rollout Evidence

You now know:

  • The 128 kB firmware image becomes 1,024 blocks at 128 bytes each.
  • The worksheet gives 29.4 hours only under its assumed eight-stream scheduler and 28-minute batches. Actual gateway capacity remains unverified.
  • The accepted design is not just faster transfer; it needs resume state, SHA-256 verification, rollback, staged rollout, and gateway capacity evidence.

Knowledge Check: Concept Matching

Choose which feature addresses each update-path problem. Match by body direction, discovery need, credential arrangement, or permitted transport; one feature does not establish the others.

Label the Diagram

Knowledge check · self-test

Knowledge check

Test your understanding.

Code Challenge

Knowledge check · self-test

Knowledge check

Test your understanding.

Order the Steps

Knowledge check · self-test

Knowledge check

Test your understanding.

Maths · guided foundations

Block Airtime and the Retransmission Penalty

Check the quantities and assumptions.

Bridge a constrained observation into enterprise work without merging protocol guarantees in the diagram the chapter figure.

Read the chapter figure from the cold-room sensor to the edge. CoAP discovery finds the resource, and Max-Age gives the gateway a bounded cache rather than a timeless truth. The gateway then publishes into an AMQP exchange whose binding selects a durable queue for enterprise work. At the consumer, acknowledgement policy defines the remaining failure trade: at-most-once may lose work, while at-least-once may repeat it. The bridge preserves both contracts explicitly, so a CoAP response or AMQP broker acceptance is not mistaken for proof that the final application acted.

Summary

For an update, locate the body first: Block1 carries request bodies; Block2 carries response bodies. Choose a legal block size within the complete packet budget, calculate the block count, and inspect duplicates, retries, and restart state.

Discovery gives advertised links, a reachable transport carries exchanges, and security protects the relevant endpoints. Each addresses a different failure. Approve the update only with complete-image checks, trusted provenance, and installation evidence. Use measured radio and gateway capacity before transferring a one-device result to a fleet.

Concept Relationships

Advanced CoAP features connect to:

Foundation Concepts:

Review the message format first to locate the block options and payload marker, then compare Observe as a different way to move resource data.

Practical Applications:

Start with firmware updates to see where block transfer is used, then examine 6LoWPAN to place CoAP on a constrained network.

Security:

Read the DTLS guide for transport protection, then compare the security modes available to a CoAP deployment.

  • DTLS for IoT - Securing CoAP communications.
  • CoAP Security Modes - NoSec, PSK, certificates.

See Also

Standards:

Read the block transfer rules first. Then use the link format rules to find resources.

Implementation:

Use the block and discovery contracts for the detailed rules, then try the lab to trace those rules on a device.

Comparison:

Compare CoAP with HTTP for the transport choice, then read the chunking rationale for the large payload case.

What’s Next

ChapterFocusWhy Read It
CoAP Block Transfer and Discovery ContractsBlock option encoding, per-block retries, discovery metadata, and proxy cache evidenceTurn the feature overview into a reviewable implementation contract
CoAP API DesignRESTful resource modeling and URI designApply the resource discovery patterns from this chapter to design well-structured CoAP APIs
CoAP Decision FrameworkWhen to use CoAP vs MQTT vs HTTPEvaluate trade-offs using the transport and security knowledge built here
CoAP Fundamentals and ArchitectureCore CoAP message model and architectureReinforce the foundation that all advanced features extend
OTA Firmware UpdatesProduction firmware update workflowsSee Block-wise Transfer applied end-to-end in a real OTA update pipeline
DTLS and SecurityDTLS handshake mechanics and cipher suitesDeepen understanding of the security modes introduced in this chapter
6LoWPAN OverviewIPv6 adaptation for constrained networksUnderstand the network layer that CoAP block transfer and discovery operate over

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.