How CoAP Works: Simple Explanation and Example
CoAP (Constrained Application Protocol) works as a lightweight web transfer protocol designed for simple devices in IoT. It uses UDP to send requests and responses similar to HTTP but optimized for low power and low bandwidth environments.Syntax
The basic CoAP message structure includes a header, token, options, and payload. The header defines the message type (Confirmable, Non-confirmable, Acknowledgement, Reset), method (GET, POST, PUT, DELETE), and message ID for matching requests and responses.
CoAP messages are sent over UDP, making them lightweight and fast for constrained networks.
plaintext
Header: 4 bytes - Version (2 bits) - Type (2 bits): CON, NON, ACK, RST - Token Length (4 bits) - Code (8 bits): Method or response code - Message ID (16 bits) Token: 0-8 bytes Options: variable length Payload: optional data after a 0xFF byte separator
Example
This example shows a simple CoAP GET request from a client to a server to read a resource, and the server's response.
python
import asyncio from aiocoap import * async def main(): protocol = await Context.create_client_context() request = Message(code=GET, uri='coap://localhost/sensor/temp') try: response = await protocol.request(request).response print('Response Code:', response.code) print('Payload:', response.payload.decode('utf-8')) except Exception as e: print('Failed to fetch resource:', e) if __name__ == '__main__': asyncio.run(main())
Output
Response Code: 2.05 Content
Payload: 22.5
Common Pitfalls
- Using TCP instead of UDP: CoAP is designed for UDP; using TCP breaks its lightweight nature.
- Ignoring message types: Not handling Confirmable (CON) messages properly can cause lost messages.
- Not matching Message IDs: Responses must match request IDs to avoid confusion.
- Large payloads: CoAP is for small messages; large payloads should be avoided or split.
plaintext
Wrong (using TCP): # CoAP does not support TCP natively Right (using UDP): # Use UDP sockets or CoAP libraries that use UDP under the hood
Quick Reference
| CoAP Term | Description |
|---|---|
| CON | Confirmable message requiring ACK |
| NON | Non-confirmable message, no ACK needed |
| ACK | Acknowledgement message |
| RST | Reset message indicating error |
| GET | Request to read a resource |
| POST | Request to create or update a resource |
| PUT | Request to update a resource |
| DELETE | Request to delete a resource |
Key Takeaways
CoAP uses UDP for lightweight, fast communication in IoT devices.
Messages have types like CON and NON to manage reliability.
CoAP methods mirror HTTP but are optimized for constrained networks.
Always match message IDs to pair requests and responses correctly.
Avoid large payloads to keep CoAP efficient and reliable.