CoAP client and server

What is CoAP?

CoAP stands for Constrained Application Protocol and together with MQTT is one of the most popular M2M and IoT standards. It is a specialised web transfer protocol and ideal for use within constrained networks and environments. It’s built for multicast support, low overhead and simplicity.

Both CoAP and HTTP are built on the REST model. You’ll find that CoAP easily translates to HTTP for integration with the web. CoAP used in a variety of smart products from home automation to industrial applications.

Why is CoAP important for connectivity?

CoAP is specifically designed to use minimal resources. This makes it ideal for the IoT. It works with MCUs with footprints as low as 10 KiB of RAM and 100 KiB of space. It utilises UDP on IP. This means, unlike TCP, no protocol handshakes or error corrections. Making it light and ideal for unreliable networks.

CoAP and Mongoose Embedded Web Server

Mongoose Embedded Web Server supports CoAP. In fact, it supports both embedded CoAP Client and embedded CoAP Server.

For an embedded CoAP client, call mg_set_protocol_coap for a connection and you are all set. It’s now a CoAP connection. Next, use mg_coap_compose to create a message, mg_coap_send_message to send etc.

Looking for an embedded CoAP server? It’s just as simple. Call mg_set_protocol_coap for a listening connection and your handler will start to receive CoAP specific events like MG_EV_COAP_ACK.

And of course, Mongoose ships with examples for embedded CoAP server and client.

CoAP server example

Create listening connection:

c = mg_bind(&mgr, "udp://5683", ev_handler);
mg_set_protocol_coap(c);

An handle COAP events:

void ev_handler(struct mg_connection *c, int ev, void *ev_data) {
  switch (ev) {
    case MG_EV_COAP_CON:
      ...
See full example.

CoAP client example

Make a connection to the CoAP server:

c = mg_connect(&mgr, "udp://my.server:5683", ev_handler);
mg_set_protocol_coap(c);

An handle COAP events:

void ev_handler(struct mg_connection *c, int ev, void *ev_data) {
  switch (ev) {
    case MG_EV_CONNECT:
      ...
    case MG_EV_COAP_ACK:
      ...
See full example.

All examples

SEE ALL EXAMPLES DOWNLOAD SOURCE CODE