Thursday, December 19, 2024
ExplainerInternet of ThingsIoT Software&Tools

What is CoAP Protocol | CoAP Protocol Introduction | Overview

What is CoAP Protocol ?

CoAP-Constrained Application Protocol is a specialized Internet Application Protocol for constrained devices, as defined in RFC 7252. It enables devices to communicate over the Internet. It is defined as Contrained Application Protocol, and is a protocol intended to be used in very simple hardware. The protocol is especially targeted for constrained hardware such as 8-bits microcontrollers, low power sensors and similar devices that can’t run on HTTP or TLS. It is a simplification of the HTTP protocol running on UDP, that helps save bandwidth. It is designed for use between devices on the same constrained network (e.g., low-power, lossy networks), between devices and general nodes on the Internet, and between devices on different constrained networks both joined by an internet. CoAP is also being used via other mechanisms, such as SMS on mobile communication networks.

The Internet Engineering Task Force Constrained RESTful environments (IETF CoRE) Working Group has done the major standardization work for CoAP. The core of the protocol is specified in RFC 7252, which means that CoAP is still not a standard protocol.

Two new features designed specifically for Internet of Things and M2M are:

  • Observe at new events happened on sensors or actuators.
  • Device management and discoverability from external devices.

The main features of this protocol are:

  • Web protocol used in M2M with constrained requirements
  • Asynchronous message exchange
  • Low overhead and very simple to parse
  • URI and content-type support
  • Proxy and caching capabilities

When to use

Some of the specific cases in which CoAP are useful are:

  • Your hardware cannot run HTTP or TLS: If this is the case then running CoAP and DTLS can practically do the same as HTTP. If one is an expert on HTTP APIs, then the migration will be simple. You receive GET for reading and POST, PUT and DELETE for mutations and the security runs on DTLS.
  • Your hardware uses battery: If this is ones problem then running CoAP will improve the battery performance when compared with HTTP over TCP/IP. UDP saves some bandwidth and makes the protocol more efficient.
  • A subscription is necessary: If one cannot run MQTT and HTTP polling is impossible then CoAP is a solution

You may like also : MQTT Public Brokers List

You may like also: How To Create Secure MQTT Broker


Some features of CoAP Prtocols are very similar to HTTP even if CoAP must not be considered a compressed HTTP protocol because it is specifically designed for IoT and in more details for M2M so it is very optimized for this task.

From the abstraction protocol layer, CoAP can be represented as:

Coap layer

In this above diagram you can see there are two different layers that make CoAp protocol: Message and Request/Response. The Messages layer deals with UDP and with asynchronous messages. The Request/Response layer manages request/response interaction based on request/response messages.

CoAP Protocol supports four different message types:

  • Confirmable
  • Non-confirmable
  • Acknowledgment
  • Reset

Now We discuss some term related CoAP Protocol.

Endpoint: An entity that participates in the CoAP protocol. Usually, an Endpoint is identified with a host

Sender: The entity that sends a message

Recipient: The destination of a message

Client: The entity that sends a request and the destination of the response

Server: The entity that receives a request from a client and sends back a response to the client

CoAP Message Model

CoAP Message is lowest layer and deals with UDP exchanging messages between endpoints. CoAP message  has unique ID and three parts:

  • a binary header
  • a compact options
  • payload

CoAP protocol uses two kinds of messages:

  • Confirmable message
  • Non-confirmable message

A CoAP confirmable message is a reliable message. During exchanging messages between two endpoints, these messages can be reliable. In the CoAP protocol, a reliable message is obtained using a Confirmable message (CON). Using this kind of message, the client can be sure that the message will arrive at the server. A CoAP Confirmable message is sent again and again until the other party sends an acknowledge message (ACK). The ACK message contains the same ID of the confirmable message (CON).

CoAP Protocol

In the above diagram, you can see communication but If the server has troubles managing the incoming request it can send back a Rest message (RST) instead of the Acknowledge message (ACK).

Non-confirmable (NON) messages that don’t require an Acknowledge by the server. These mesages are unreliable messages means do not contain critical information that must be delivered to the server. To this category belongs messages that contain values read from sensors. Even if these messages are unreliable, they have a unique ID.

CoAp Request/Response Model

This is Second layer in the abstraction layer. Here request is sent using a Confirmable (CON) or Non-Confirmable (NON) message. There are several scenarios depending on if the server can answer immediately to the client request or the answer if not available:

  • If the server can answer immediately to the client request then if the request is carried using a Confirmable message (CON) then the server sends back to the client an Acknowledge message containing the response or the error code:

request/response

Here Token is different from the Message ID and it is used to match the request and the response.

  • If the server can’t answer to the request, then server sends an Acknowledge with an empty response. As soon as the response is available then the server sends a new Confirmable message to the client containing the response. At this point the client sends back an Acknowledge message:

Coap communication

If the request coming from the client is carried using a NON-confirmable message then the server answer using a NON-confirmable message.

CoAp Message Format

A message is made by several parts:

coap message format

Where:

Ver: It is a 2 bit unsigned integer indicating the version

T: it is a 2 bit unsigned integer indicating the message type: 0 confirmable, 1 non-confirmable

TKL: Token Length is the token 4 bit length

Code: It is the code response (8 bit length)

Message ID: It is the message ID expressed with 16 bit

Use CoAP with NodeJS

node-coap is a client and server library for CoAP modeled after the http module.

This library follows:

It does not parse the protocol but it use CoAP-packet instead.

If you need a command line interface for CoAP, check out coap-cli.

node-coap is an OPEN Open Source Project, see the Contributing section to find out what this means.

Installation

$ npm install coap --save

Basic Example

The following example opens a UDP server and sends a CoAP message to it:

var coap        = require('coap')
, server      = coap.createServer()
server.on('request', function(req, res) {
res.end('Hello ' + req.url.split('/')[1] + '\n')
})
// the default CoAP port is 5683
server.listen(function() {
var req = coap.request('coap://localhost/Matteo')
req.on('response', function(res) {
res.pipe(process.stdout)
res.on('end', function() {
process.exit(0)
})
})
req.end()
})

How To Use – Visithttps://www.npmjs.com/package/coap

Implementations

CoAP Protocol is simple enough to implement from scratch for a simple application. For applications where that is not desirable, generic implementations are becoming available for a variety of platforms. Many of these implementations stay private, but some are published with liberal open-source licenses such as the Apache 2.0 or the MIT license

Visit – http://coap.technology/impls.html

COAP vs MQTT

Both MQTT and CoAP:

  • Are open standards
  • Are better suited to constrained environments than HTTP
  • Provide mechanisms for asynchronous communication
  • Run on IP
  • Have a range of implementations

mqtt vs coap

Following table compares various features of COAP vs MQTT and tabulates difference between CoAP and MQTT protocols.

Features CoAP MQTT
Full Form Constrained Application Protocol Message Queue Telemetry Transport
Model used for communication Request-Response, Publish-Subscribe Publish-Subscribe
RESTful Yes No
Transport layer Preferably UDP, TCP can also be used. Preferably TCP, UDP can also be used (MQTT-S).
Header Size 4 Bytes 2 Bytes
Number of message types used 4 16
Messaging Asynchronous & Synchronous Asynchronous
Application Reliability 2 Levels 3 Levels
Security IPSEC or DTLS Not defined in the standard
Intermediaries YES YES (MQTT-S)
LLN Suitability (thousand nodes) Excellent Fair
Application success stories Utility Field Area Networks Extending enterprise messaging into IoT applications

Comparison

MQTT and CoAP are both useful as IoT protocols, but have fundamental differences.

MQTT is a many-to-many communication protocol for passing messages between multiple clients through a central broker. It decouples producer and consumer by letting clients publish and having the broker decide where to route and copy messages. While MQTT has some support for persistence, it does best as a communications bus for live data.

CoAP is, primarily, a one-to-one protocol for transferring state information between client and server. While it has support for observing resources, CoAP is best suited to a state transfer model, not purely event based.

MQTT clients make a long-lived outgoing TCP connection to a broker. This usually presents no problem for devices behind NAT. CoAP clients and servers both send and receive UDP packets. In NAT environments, tunnelling or port forwarding can be used to allow CoAP, or devices may first initiate a connection to the head-end as in LWM2M.

MQTT provides no support for labelling messages with types or other metadata to help clients understand it. MQTT messages can be used for any purpose, but all clients must know the message formats up-front to allow communication. CoAP, conversely, provides inbuilt support for content negotiation and discovery allowing devices to probe each other to find ways of exchanging data.

Both protocols have pros and cons, choosing the right one depends on your application.


Recommended:


Buy now : Raspberry PI 3 Model B+ Motherboard

I hope you like this post. Do you have any questions? Leave a comment down below!

Thanks for reading. If you like this post probably you might like my next ones, so please support me by subscribing my blog.

Harshvardhan Mishra

Hi, I'm Harshvardhan Mishra. Tech enthusiast and IT professional with a B.Tech in IT, PG Diploma in IoT from CDAC, and 6 years of industry experience. Founder of HVM Smart Solutions, blending technology for real-world solutions. As a passionate technical author, I simplify complex concepts for diverse audiences. Let's connect and explore the tech world together! If you want to help support me on my journey, consider sharing my articles, or Buy me a Coffee! Thank you for reading my blog! Happy learning! Linkedin

One thought on “What is CoAP Protocol | CoAP Protocol Introduction | Overview

Leave a Reply

Your email address will not be published. Required fields are marked *