CoAP is a HTTP-like protocol intended to be used in devices with constrained memory and limited communication capabilities. Messages are transmitted using UDP instead of TCP, which allows the use of multicast. As in HTTP, it can work using the request-response model, but unlike it, messages can be sent without receiving back a confirmation/response, or receiving responses anytime a given path is updated (Observe mode). The message format is binary and defined to be very light. To give an example, that’s the basic format of CoAP’s header defined on the protocol’s RFC:
Options are equivalent to HTTP header fields, and just as in HTTP, can have a variable number.
One of the basic types in Elixir is binary, which is just a sequence of bytes. What is very nice about it is that the language allows you to do pattern matching with them. For instance, that is part of the code responsible for parsing the CoAP fields of a binary (
header) message in coapex:
For me that’s very clean and intuitive. You can see the code and easily understand what is what in the received message. What is also interesting, is that you can use extracted fields on the following matches. In this case, we extract
token_length at the beginning of the message, and use it later on to extract the received
Afterwards, in the parser code, the
rest of the message is recursively parsed to extract any options available and, finally, its content.
The other way around, or serializing the message back to binary, is also very simple:
hdr is a Struct containing all the attributes of the CoAP message. On the code, I’m declaring what will go in that position (i.e.
hdr.version) and how it will be transformed (2 bits, unsigned, with
Apart from the unit tests, a Server/Client example can be found here.
- Services Version Lock with Docker and Jenkins
- Blockchains as Part of the IoT Architecture
- Tips for your Distributed Project Inception or Meeting
- Problems with Branches per Environment
- Integration testing for nginx Routes
- Secure Configuration Management for Microservices
- Nested Structures on Elixir, and Other Simple Tricks
- Efficient Timer using a Circular Buffer
- Erlang, Elixir and a simple Supervisor
- RFID, Dryers, and IoT