Search code examples
node.jsiotcoapcbor

Can CoAP be used when preserving data order is required?


I am trying to transmit sensor data from an IoT device via CoAP using node-coap. The order of the data, as it arrives to the CoAP server, is important to me. I can not find a way to preserve the sequence of data, even when using the confirmable request option.

I have a small program below that shows what I mean.

Can CoAP not be used if order/sequence of data is important? If it can, what am I doing wrong?

'use strict';

const coap = require('coap'),
  cbor = require('cbor'),
  server = coap.createServer();

const sequentialData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let incomingData = [];
let numResponses = sequentialData.length;

server.on('request', (req, res) => {
  const obj = cbor.decodeFirstSync(req.payload);
  incomingData.push(obj.data);
  res.end();
});

server.listen(() => {
  const reqOpts = {
    hostname: 'localhost',
    method: 'POST',
    pathname: '/sequential',
    options: {
      Accept: 'application/cbor'
    }
  };

  sequentialData.forEach((item) => {
    const req = coap.request(reqOpts);
    req.write(cbor.encode({
      data: item
    }));

    req
      .on('response', (res) => {
        res.pipe(process.stdout);
        res.on('end', () => {
          if (--numResponses === 0) {
            console.log(`got data in this order`, incomingData);
            process.exit();
          }
        })
      });

    req.end();
  });
});

Node Program above will output a different order each time ran.


Solution

  • It can't as long you are using UDP as transport.

    As per RFC7252:

    As CoAP is bound to unreliable transports such as UDP, CoAP messages may arrive out of order, appear duplicated, or go missing without notice. For this reason, CoAP implements a lightweight reliability mechanism, without trying to re-create the full feature set of a transport like TCP. It has the following features:

    • Simple stop-and-wait retransmission reliability with exponential back-off for Confirmable messages.
    • Duplicate detection for both Confirmable and Non-confirmable messages.

    https://www.rfc-editor.org/rfc/rfc7252

    There are some efforts to make CoAP-over-HTTP in different implementations but it does not belong to CoAP RFC itself.

    You may try to dig in this way if you absolutely forced to use CoAP.