COAP、HTTP 与 LwM2M:物联网协议的演进、关联及 COAP Options 详解
In the family of IoT communication protocols, COAP (Constrained Application Protocol) is often referred to as “the IoT version of HTTP”. This is not only because they share similar design philosophies, but more importantly, COAP has completely borrowed and optimized the request/response model of HTTP, allowing it to operate efficiently in resource-constrained IoT environments. Meanwhile, LwM2M is an IoT device management protocol built on top of COAP, forming a lightweight protocol evolution chain of “HTTP→COAP→LwM2M”.
1. The Homogeneity of the Request/Response Model
COAP and HTTP‘s request/response models are like identical twins, with a completely consistent core structure:
Client initiates request → Server processes request → Server returns response
This “question-and-answer” interaction mode allows developers familiar with HTTP to quickly understand how COAP works. Both use URI to identify resources (e.g., coap://device/temp corresponds to http://server/temp), define operation types using method verbs, and represent processing results through status codes.
2. The IoT Transformation of the HTTP Model by COAP
If HTTP is designed as a “heavy truck” for PCs and servers, then COAP is a “lightweight motorcycle” tailored for IoT devices, making three key optimizations while retaining the core model:
1. Lightweight Transport Layer Choices
HTTP is based on the TCP protocol, which requires a “line to be connected” before communication, suitable for large data transfers but with significant overhead; COAP, on the other hand, is based on UDP, similar to sending a text message, allowing communication without establishing a connection, with a minimum data packet size of only 4 bytes, making it particularly suitable for devices with limited computing power, such as sensors.
2. Simplified Adaptation of Method Verbs
COAP retains the four core methods from HTTP:
· GET: Read resource (e.g., query temperature and humidity)
· PUT: Create or replace resource (e.g., set device threshold)
· POST: Process resource (e.g., trigger device action)
· DELETE: Delete resource (e.g., clear historical data)
These methods are semantically identical to those in HTTP, but are more concise in transmission details.
3. Correspondence and Extension of Status Codes
COAP’s status codes are designed with three digits, corresponding to the concept of status codes in HTTP:
· 1xx: Informational response (e.g., 102 means continue)
· 2xx: Successful response (e.g., 205 means content updated)
· 4xx: Client error (e.g., 404 means resource not found)
· 5xx: Server error (e.g., 503 means service unavailable)
This design allows developers to directly apply their HTTP error handling experience.
3. Unique Enhanced Features of COAP
To adapt to IoT scenarios, COAP adds three “superpowers” on top of the HTTP model:
1. Asynchronous Observation Mechanism
Similar to a subscription feature, clients can listen for resource changes through the “Observe” option. When sensor data updates, the server actively pushes new values, eliminating the need for clients to repeatedly query, significantly reducing communication overhead.
2. Group Communication Support
Through the “Blockwise” option, COAP can split large messages into smaller chunks for transmission; it also supports multicast requests to multiple devices, suitable for batch control scenarios.
3. Built-in Security Layer
COAP provides encrypted communication through the DTLS (Datagram Transport Layer Security) protocol, corresponding to HTTPS in HTTP, forming the “CoAPS” secure communication method.
4. COAP Options: The Protocol’s “Extension Toolbox”
The Options field in COAP is similar to the request/response headers in HTTP, serving as the protocol’s “extension interface”—by carrying additional information, it enables core capabilities such as resource location, data format declaration, and functional extension. Its design follows the principle of “lightweight and compact”, with each Option consisting of “number + length + value”, supporting flexible addition and removal, and only carrying when necessary to avoid redundant overhead.
Common Core Options Classification and Description
1. Resource Location: Locating the Key URI Resource
· Uri-Path (Number: 11) is one of the most commonly used options, used to concatenate resource paths, similar to the path portion in HTTP URI. It supports multi-segment concatenation; for example, when accessing coap://device/sensor/temp, it will be split into two Uri-Path options: “sensor” and “temp”. Example: When the client sends a GET request, it specifies access to the “temp” resource through Uri-Path: “temp”.
· Uri-Query (Number: 15) corresponds to the query parameters in HTTP URI, used to pass resource filtering, condition limiting, and other information, formatted as “key=value”. It supports multiple Query concatenation; for example, Uri-Query: “type=indoor”, Uri-Query: “limit=10”. Example: When registering an LwM2M device, it passes the device identifier through Uri-Query: “ep=mydevice123”.
· Uri-Host (Number: 3) specifies the hostname or IP address where the resource is located, similar to the Host header in HTTP, usually used for proxy forwarding or multi-domain scenarios. Example: Uri-Host: “iot-gateway.local”
· Uri-Port (Number: 7) specifies the COAP server port (default 5683, CoAPS default 5684), used for communication on non-default ports. Example: Uri-Port: 5685 (specifying the server listens on port 5685).
2. Data Format: Declaring the “Language” of Data
· Content-Format (Number: 12) is used to declare the data format of the Payload, similar to the Content-Type in HTTP, simplifying transmission through “media type number” (rather than strings). Common numbers correspond to:
o 0: text/plain (plain text)
o 50: application/json (JSON format)
o 110: application/vnd.oma.lwm2m+tlv (LwM2M TLV format) Example: When the server returns JSON data, it carries Content-Format: 50.
· Accept (Number: 17) is used by the client when sending a request to declare the expected data format returned by the server, similar to the Accept header in HTTP, also using media type numbers. Example: When the client expects to receive TLV format data, it carries Accept: 110.
3. Functional Extension: COAP’s “Special Capabilities”
· Observe (Number: 6) implements the core “asynchronous observation mechanism” of COAP: when the client sends a GET request, it carries Observe: 0 to indicate “subscribe to resource”; the server will actively push responses when the resource updates, identifying the update sequence with an incrementing number (e.g., Observe: 123). Example: When subscribing to a temperature and humidity sensor, the client carries Observe: 0, and after the server data updates, it returns Observe: 45 (the 45th update).
· Block2 (Number: 23) and Block1 (Number: 27) implement the “block transfer” function, used to split large messages (when exceeding MTU):
o Block2: Used to split the Payload (response data) sent from the server to the client;
o Block1: Used to split the Payload (request data) sent from the client to the server; both value formats are “block number; block size”, for example, Block2: 0/16 (the 0th block, each block 16 bytes).
Example: When transferring a 100-byte firmware fragment, it indicates Block1: 2/32 (the 2nd block, each block 32 bytes).
· Max-Age (Number: 8) declares the “validity period” of the resource, similar to Cache-Control in HTTP, measured in seconds. When the server returns the resource, it carries this option to indicate that “the client can cache this data for N seconds without needing to repeat the request”.
Example: Max-Age: 30 (resource data is valid for 30 seconds).
4. Security and Control: Ensuring Communication Reliability
· If-Match (Number: 1) and If-None-Match (Number: 5) are used for “conditional operations”, similar to the same-named headers in HTTP, to avoid concurrent modification conflicts:
o If-Match: Carries the resource’s ETag (entity tag), and the operation (e.g., PUT update) is executed only if the current resource’s ETag matches the specified value;
o If-None-Match: The operation is executed only if the resource does not exist (e.g., PUT create). Example: When updating device configuration, the client carries If-Match: “a1b2c3” (current resource ETag), ensuring the configuration has not been modified by others.
· No-Response (Number: 258) allows the client to declare that “no response from the server is needed” when sending a request, reducing communication overhead for low-priority operations (e.g., periodically reporting non-critical data). Example: When a sensor periodically reports ordinary data, it carries No-Response: 0 (indicating no response is needed).
5. LwM2M Dedicated Extension Class
LwM2M extends dedicated fields based on COAP Options for device management scenarios:
· LwM2M-Result (Number: 263) carries the operation result code when the device responds to management operations (e.g., “200” means success, “400” means parameter error).
· LwM2M-Info (Number: 264) conveys additional information for device management (e.g., firmware update progress, error details).
Rules for Using Options
1. Orderliness: Options must be sorted by “number from smallest to largest” to reduce parsing complexity;
2. Necessity: Only carry necessary options (e.g., do not carry Uri-Port if the port does not need to be specified);
3. Compatibility: Unknown numbered Options will be ignored and will not affect the core protocol flow.
5. Parsing the COAP Message Format
COAP message structure adopts a compact design, with a minimum size of 4 bytes, consisting of four parts:
plaintext
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 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|Token (if any, TKL bytes) …
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|Options (if any) … // Options fields are here
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|1 1 1 1 1 1 1 1| Payload (if any) …
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Actual Message Example (Including Options)
The client sends a GET request to subscribe to the temperature resource
plaintext
COAP layer:
Ver: 1 (01)
T: Confirmable (00)
TKL: 2 (0010)
Code: 0.01 (GET request)
Message ID: 0x1234
Token: 0xAB CD
Options:// Core Options fields
Uri-Path: “sensor” // First segment of the path
Uri-Path: “temp” // Second segment of the path (full path: /sensor/temp)
Observe: 0 // Subscribe to resource
Accept: 50 // Expecting to return JSON format
Payload: None
The server returns a temperature update response
plaintext
COAP layer:
Ver: 1 (01)
T: Acknowledgment (10)
TKL: 2 (0010)
Code: 2.05 (Content success response)
Message ID: 0x1234 (same as request)
Token: 0xAB CD (same as request)
Options:
Content-Format: 50 // Declaring return in JSON format
Observe: 15 // Identifying the 15th update
Max-Age: 10 // Data valid for 10 seconds
Payload:
0xFF (separator)
{