SimCor SimCor - 2 days ago 4
Javascript Question

how to register a new option with coap.registerOption

I'm using node-coap in order to send data to a coap server, I need to use a custom option in the packet so I'm running this code:

var req = {
hostname:"localhost",
method:"PUT",
pathname:"create1",
}
var coapReq = coap.request(req)
coap.registerOption('newOption',toBinary,toString)
coapReq.setOption('newOption',b.from('Hello World'))
coapReq.end()


The function toBinary and toString are defined as follow:

function toBinary(data){
return b.from(data)
}

function toString(data){
return data.toString()
}


This piece of code is not working. What is the correct way to use the registerOption method?

Answer

In the node-coap readme, an example of setOption uses a numeric name for the custom option.

var coap = require('coap')

function toBinary(text){
  return new Buffer(text);
}

function toString(data){
  return data.toString()
}

coap.registerOption("555", toBinary, toString)

server = coap.createServer()

server.on('request', function(req, res) {
  console.log(req.options);
  res.end()
})

// the default CoAP port is 5683
server.listen(function() {
  var req = {
    hostname:"localhost",
    method:"PUT",
    pathname:"create1",
  }
  var coapReq = coap.request(req)
  coapReq.setOption('555', "Hello World")

  coapReq.on('response', function(res) {
    res.pipe(process.stdout)
    res.on('end', function() {
      process.exit(0)
    })
  })

  coapReq.end()
})

And the options were:

[ { name: 'Uri-Path', value: <Buffer 63 72 65 61 74 65 31> },
{ name: '555', value: 'Hello World' } ]

It is not possible to pass a alphabetic option name as node-coap uses coap-packet module where option name is parsed like integer:

https://github.com/mcollina/coap-packet/blob/master/index.js#L342

I'd recommend you to create an issue/PR at node-coap github repo to make more clear explanation of this at README.