Overview

更新时间:
2024-03-04
下载文档

Overview

CoAP is a protocol developed by the IETF to meet the Internet of Things and M2M scenarios, with the following characteristics:

  • Similar to HTTP, based on the REST model: Servers present Resources in the form of URIs, and clients can access them through methods such as GET, PUT, POST, and DELETE, but they reduce complexity compared to simplified HTTP implementations (smaller code and smaller packets).
  • Used in resource-constrained environments (memory, storage, no good source of randomness), such as 8-bit single-chip microcomputer with CPU, memory 32Kb, FLASH 256Kb.
  • For applications with low service performance requirements: low rate (10s of kbit / s), low power consumption.

CoAP protocol features:

  • Client / Server-like interaction model based on UDP.
  • The client sends a Request (carrying different methods) to request operations on the resource (represented by the URI), and the Server returns a Response (representation carrying the resource) and a status code.

JSRE supports the basic CoAP protocol, as well as the Observer mode. The implementation of the CoAP protocol includes a client and a server. You can visit the following documents for API description:

User can use the following code to import the coap module and access CoapClient and CoapServer .

var coap = require('coap');

RESTful-Style

CoAP is based on the basic RESTful-style request / response mode. CoAP supports 4 methods: 'GET', 'POST', 'PUT', 'DELETE'.

Base examples of requests:

  • Client
var client = coap.request('coap://192.168.7.31:5683', function (client) {
  client.on('response', function (client, res) {
    console.log('Recv message:', res.payload.toString());
  });
}, {method: 'POST'}); // Set request method and other options.

client.end('Hello world!'); // Set payload data.
  • Server
server.on('request', function (req, res) {
  console.log('Recv message:', req.payload.toString());
  res.end('Hello, world.');
});

CoAP Message is used to carry the Request / Response model. There are two modes:

  • Reliability Mode
    • Confirmable request message need response acknowledgement message.
    • Confirmable message and acknowledgement Message match by message ID.
  • Non-Reliability Mode
    • Non-Confirmable Message does not require acknowledgement Message confirmation(The message was returned in our server implementation, but it is unreliable and may be lost).

JSRE-CoAP internally handles Reliability Mode and Non-Reliability Mode automatically, users do not need to pay attention to their details. The user only needs to care: When reliable messages need to be transmitted, Reliability Mode should be selected, otherwise Non-Reliability Mode should be selected. The client's default request is Reliability Mode. Examples of them are:

  • A reliability request example:
var client = coap.request('coap://192.168.7.31:5683', callback,  {confirm: true}); // Set reliability request.

client.end('Hello world!', /* {confirm: true} */); // The same as set at `request`.
  • A non-reliability request example:
var client = coap.request('coap://192.168.7.31:5683', callback,  {confirm: false}); // Set non-reliability request.

client.end('Hello world!', /* {confirm: false} */); // The same as set at `request`.

Reliable Transmission

Due to the unreliability of the UDP protocol, the transmitted messages may be lost. In the Reliability Mode of CoAP, reliable transmission of messages is achieved through an exponential backoff-based retransmission mechanism. The process is as follows:

		Client                 Server
		  |                      |
		  |    CON [oxbc90]      |
		  | -------------------> |
		  |                      |
		  |                      |
		  |    ACK [0xbc90]      |
		  | <------------------- |
		  |                      |
  • CON(Confirmable Message): The message that needs to be confirmed. The Receipt party must reply to the message.
  • ACK(Acknowledgement Message): Used to confirm to the Sender that a Confirmable Message has been received and can carry a Piggybacked Response.
  • 0xbc90(Message ID): ID used for pairing is a reliable transmission process and supports repeated detection.

The reliable transmission of message is initiated by a confirmable msg;

The server receives a confirmable msg, and the processing result is: reply with an acknowledgement msg (carrying a matching message ID);

If the client does not receive the ACK message from the server within the limited time (RetryTimeout), the client will resend the CON message. The client will resend multiple times (RetryTimes) until it receives an ACK message from the server. The timeout time of each retransmission message will be twice as long as the previous one (RetryTimeout * (1 + 2 + .. 2 ^ (n-1))). If the ACK message is not received after the retransmission of RetryTimes times, Transmission failed.

The reliable transmission mechanism is implemented internally by JSRE-CoAP. Users only need to pay attention to the parameters related to reliable transmission:

OptionDescriptionDefault
RetryTimeoutThe first retry timeout.10s
RetryTimesThe retry times.3
PeriodTimeoutThe server response timeout.60s

Observe Model

This base CoAP does not work well when a client is interested in having a current representation of a resource over a period of time. Existing approaches from HTTP, such as repeated polling or HTTP long polling, generate significant complexity and/or overhead and thus are less applicable in a constrained environment.

The protocol extends the CoAP core protocol with a mechanism for a CoAP client to "observe" a resource on a CoAP server: the client retrieves a representation of the resource and requests this representation be updated by the server as long as the client is interested in the resource.

Observing a resource in CoAP:

                Client              Server
                 |                    |
                 | GET /temperature   |
                 | Token: 0x4a        | Registration
                 | Observe: 0         |
                 +------------------->|
                 |                    |
                 | 2.05 Content       |
                 | Token: 0x4a        | Notification of
                 | Observe: 12        | the current state
                 | Payload: 22.9 Cel  |
                 |<-------------------+
                 |                    |
                 | 2.05 Content       |
                 | Token: 0x4a        | Notification upon
                 | Observe: 44        | a state change
                 | Payload: 22.8 Cel  |
                 |<-------------------+
                 |                    |
                 | 2.05 Content       |
                 | Token: 0x4a        | Notification upon
                 | Observe: 60        | a state change
                 | Payload: 23.1 Cel  |
                 |<-------------------+
                 |                    |
  • Token: Token is the identity of the resource.
  • Observe: The larger the value of observe, the newer the state of the resource data obtained.

The reliable transmission mechanism is implemented internally by JSRE-CoAP. Users only need to pay attention to the parameters related to reliable transmission:

Observe-Model is implemented internally by JSRE-CoAP, so users don't have to pay attention to implementation details. The user only needs to understand the Observe-Model interface.

  • Observe-Model request example:
var client = coap.request('coap://192.168.7.31:5683', function (client) {
  client.on('response', function (client, res) {
    console.log('Coap recv:', res.payload.toString());
  }); // Client can receive notify from server repeatedly.

  client.on('end', function (client) {
    console.log('Coap observe end.');
  });

}, { observe: true, token: Buffer.from('ABC123')}); // Set observe model and token identifies the subscribed resource.
  • Observe-Model server example:
server.on('request', function (req, res) {
  var timer = undefined;
  if (req.isObserve()) { // Observe request.
    timer = setInterval(function (res) {
      res.send({ temperature: 35 }); // Notify client when temperature changes.
    }, 1000, res);
  }
});
文档内容是否对您有所帮助?
有帮助
没帮助