CoAP - Node.js style
node-coap is a client and server library for CoAP modeled after the
httpmodule.
What is CoAP?
Constrained Application Protocol (CoAP) is a software protocol intended to be used in very simple electronics devices that allows them to communicate interactively over the Internet. - Wikipedia
This library follows: * draft-18 of CoAP. * observe-11 for the observe specification. * block-14 for the blockwise specification.
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.
$ npm install coap --save
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() })
or on IPv6:
var coap = require('coap') , server = coap.createServer({ type: 'udp6' })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://[::1]/Matteo')
req.on('response', function(res) { res.pipe(process.stdout) res.on('end', function() { process.exit(0) }) })
req.end() })
The library now comes with the ability to behave as a COAP proxy for other COAP endpoints. In order to activate the proxy features, create the server with the
proxyoption activated.
A proxy-enabled service behaves as usual for all requests, except for those coming with the
Proxy-Urioption. This requests will be redirected to the URL specified in the option, and the response from this option will, in turn, be redirected to the caller. In this case, the proxy server handler is not called at all (redirection is automatic).
You can find an example of how this mechanism works in
examples/proxy.js. This example features one target server that writes all the information it receives along with the origin port and a proxy server. Once the servers are up:
The example shows that the target server sees the last ten requests as coming from the same port (the proxy), while the first ten come from different ports.
coap.request()
coap.createServer()
IncomingMessage
OutgoingMessage
ObserveReadStream
ObserveWriteStream
coap.registerOption()
coap.ignoreOption()
coap.registerFormat()
coap.Agent
coap.globalAgent
coap.globalAgentIPv6
coap.updateTiming
coap.defaultTiming
Execute a CoAP request.
urlcan be a string or an object. If it is a string, it is parsed using
require('url').parse(url). If it is an object:
host: A domain name or IP address of the server to issue the request to. Defaults to
'localhost'.
hostname: To support
url.parse()
hostnameis preferred over
host
port: Port of remote server. Defaults to 5683.
method: A string specifying the CoAP request method. Defaults to
'GET'.
confirmable: send a CoAP confirmable message (CON), defaults to
true.
observe: send a CoAP observe message, allowing the streaming of updates from the server.
pathname: Request path. Defaults to
'/'. Should not include query string
query: Query string. Defaults to
''. Should not include the path, e.g. 'a=b&c=d'
options: object that includes the CoAP options, for each key-value pair the setOption() will be called.
headers: alias for
options, but it works only if
optionsis missing.
agent: Controls
Agentbehavior. Possible values:
undefined(default): use
globalAgent, a single socket for all concurrent requests.
Agentobject: explicitly use the passed in
Agent.
false: opts out of socket reuse with an
Agent, each request uses a new UDP socket.
proxyUri: adds the Proxy-Uri option to the request, so if the request is sent to a proxy (or a server with proxy features) the request will be forwarded to the selected URI. The expected value is the URI of the target. E.g.: 'coap://192.168.5.13:6793'
multicast: If set to
true, it forces request to be multicast. Several
responseevents will be emitted for each received response. It's user's responsibility to set proper multicast
hostparameter in request configuration. Default
false.
multicastTimeout: time to wait for multicast reponses in milliseconds. It is only applicable in case if
multicastis
true. Default
20000 ms.
retrySend: overwrite the default maxRetransmit, useful when you want to use a custom retry count for a request
coap.request()returns an instance of
OutgoingMessage
.
If you need
to add a payload, just pipeinto it. Otherwise, you must call
endto submit the request.
If
hostnameis a IPv6 address then the payload is sent through a IPv6 UDP socket, dubbed in node.js as
'udp6'.
function (response) { }
Emitted when a response is received.
responseis an instance of
IncomingMessage
.
If the
observeflag is specified, the
'response'event will return an instance of
ObserveReadStream
.
Which represent the updates coming from the server, according to the
observe spec.
Returns a new CoAP Server object.
The
requestListeneris a function which is automatically added to the
'request'event.
The constructor can be given an optional options object, containing one of the following options: *
type: indicates if the server should create IPv4 connections (
udp4) or IPv6 connections (
udp6). Defaults to
udp4. *
proxy: indicates that the server should behave like a proxy for incoming requests containing the
Proxy-Uriheader. An example of how the proxy feature works, refer to the example in the
/examplesfolder. Defaults to
false. *
multicastAddress: Optional. Use this in order to force server to listen on multicast address *
multicastInterface: Optional. Use this in order to force server to listen on multicast interface. This is only applicable if
multicastAddressis set. If absent, server will try to listen
multicastAddresson all available interfaces *
piggybackReplyMs: set the number of milliseconds to wait for a piggyback response. Default 50. *
sendAcksForNonConfirmablePackets: Optional. Use this to suppress sending ACK messages for non-confirmable packages
function (request, response) { }
Emitted each time there is a request.
requestis an instance of
IncomingMessage
and responseis an instance of
OutgoingMessage
.
If the
observeflag is specified, the
responsevariable will return an instance of
ObserveWriteStream
.
Each write(data)to the stream will cause a new observe message sent to the client.
Begin accepting connections on the specified port and hostname. If the hostname is omitted, the server will accept connections directed to any IPv4 or IPv6 address by passing
nullas the address to the underlining socket.
To listen to a unix socket, supply a filename instead of port and hostname.
A custom socket object can be passed as a
portparameter. This custom socket must be an instance of
EventEmitterwhich emits
message,
errorand
closeevents and implements
send(msg, offset, length, port, address, callback)function, just like
dgram.Socket. In such case, the custom socket must be pre-configured manually, i.e. CoAP server will not bind, add multicast groups or do any other configuration.
This function is asynchronous.
Closes the server.
This function is synchronous, but it provides an asynchronous callback for convenience.
An
OutgoingMessageobject is returned by
coap.requestor emitted by the
coap.createServer
'response'event. It may be used to access response status, headers and data.
It implements the Writable Stream interface, as well as the following additional properties, methods and events.
The CoAP code of the message. It is HTTP-compatible, as it can be passed
404.
(same as message.code)
Sets a single option value. All the options are in binary format, except for
'Content-Format',
'Accept',
'Max-Age'and
'ETag'. See
registerOption
to know how to register more.
Use an array of buffers if you need to send multiple options with the same name.
If you need to pass a custom option, pass a string containing a a number as key and a
Bufferas value.
Example:
message.setOption("Content-Format", "application/json");
or
message.setOption("555", [Buffer.from('abcde'),Buffer.from('ghi')]);
setOptionis also aliased as
setHeaderfor HTTP API compatibility.
Also,
'Content-Type'is aliased to
'Content-Format'for HTTP compatibility.
Since v0.7.0, this library supports blockwise transfers, you can trigger them by adding a
req.setOption('Block2', Buffer.of(0x2))to the output of request.
See the spec for all the possible options.
Returns a Reset COAP Message to the sender. The RST message will appear as an empty message with code
0.00and the reset flag set to
trueto the caller. This action ends the interaction with the caller.
Functions somewhat like
http's
writeHead()function. If
codeis does not match the CoAP code mask of
#.##, it is coerced into this mask.
headersis an object with keys being the header names, and values being the header values.
Emitted when the request does not receive a response or acknowledgement within a transaction lifetime.
Errorobject with message
No reply in XXXsand
retransmitTimeoutproperty is provided as a parameter.
Emitted when an error occurs. This can be due to socket error, confirmable message timeout or any other generic error.
Errorobject is provided, that describes the error.
An
IncomingMessageobject is created by
coap.createServeror
coap.requestand passed as the first argument to the
'request'and
'response'event respectively. It may be used to access response status, headers and data.
It implements the Readable Stream interface, as well as the following additional methods and properties.
The full payload of the message, as a Buffer.
All the CoAP options, as parsed by CoAP-packet.
All the options are in binary format, except for
'Content-Format',
'Accept'and
'ETag'. See
registerOption()
to know how to register more.
See the spec for all the possible options.
All the CoAP options that can be represented in a human-readable format. Currently they are only
'Content-Format',
'Accept'and
'ETag'. See to know how to register more.
Also,
'Content-Type'is aliased to
'Content-Format'for HTTP compatibility.
The CoAP code of the message.
The method of the message, it might be
'GET',
'POST',
'PUT',
'DELETE'or
null. It is null if the CoAP code cannot be parsed into a method, i.e. it is not in the '0.' range.
The URL of the request, e.g.
'coap://localhost:12345/hello/world?a=b&b=c'.
The sender informations, as emitted by the socket. See the
dgramdocs for details
Information about the socket used for the communication (address and port).
An
ObserveReadStreamobject is created by
coap.requestto handle observe requests. It is passed as the first argument to the
'response'event. It may be used to access response status, headers and data as they are sent by the server. Each new observe message from the server is a new
'data'event.
It implements the Readable Stream and IncomingMessage interfaces, as well as the following additional methods, events and properties.
Closes the stream.
The sender's information, as emitted by the socket. See the
dgramdocs for details
Information about the socket used for the communication (address and port).
An
ObserveWriteStreamobject is emitted by the
coap.createServer
'response'event as a response object. It may be used to set response status, headers and stream changing data to the client.
Each new
write()call is a new message being sent to the client.
It implements the Writable Stream and OutgoingMessage interfaces, as well as the following additional methods and properties.
Emitted when the client is not sending 'acks' anymore for the sent messages.
Returns a Reset COAP Message to the sender. The RST message will appear as an empty message with code
0.00and the reset flag set to
trueto the caller. This action ends the interaction with the caller.
Register a new option to be converted to string and added to the
message.headers.
toBinaryis a function that accept a string and returns a
Buffer.
toStringis a function that accept a
Bufferand returns a
String.
Explicitly ignore an option; useful for compatibility with
http-based modules.
Register a new format to be interpreted and sent in CoAP
Content-Formatoption. Each format is identified by a number, see the Content-Format registry.
These are the defaults formats:
js registerFormat('text/plain', 0) registerFormat('application/link-format', 40) registerFormat('application/xml', 41) registerFormat('application/octet-stream', 42) registerFormat('application/exi', 47) registerFormat('application/json', 50)
An Agent encapsulate an UDP Socket. It uses a combination of
messageIdand
tokento distinguish between the different exchanges. The socket will auto-close itself when no more exchange are in place.
By default, no UDP socket are open, and it is opened on demand to send the messages.
Opts is an optional object with the following optional properties:
type:
'udp4'or
'udp6'if we want an Agent on an IPv4 or IPv6 UDP socket.
socket: use existing socket instead of creating a new one.
Agentfor IPv4.
Agentfor IPv6.
You can update the CoAP timing settings, take a look at the examples:
var coapTiming = { ackTimeout:0.25, ackRandomFactor: 1.0, maxRetransmit: 3, maxLatency: 2, piggybackReplyMs: 10 }; coap.updateTiming(coapTiming);
Reset the CoAP timings to the default values
node-coap is an OPEN Open Source Project. This means that:
Individuals making significant and valuable contributions are given commit-access to the project to contribute as they see fit. This project is more like an open wiki than a standard guarded open source project.
See the CONTRIBUTING.md file for more details.
node-coap is only possible due to the excellent work of the following contributors:
Matteo Collina | GitHub/mcollina | Twitter/@matteocollina |
---|---|---|
Nguyen Quoc Dinh | GitHub/nqd | Twitter/@nqdinh |
Daniel Moran Jimenez | GitHub/dmoranj | Twitter/@erzeneca |
Ignacio Martín | GitHub/neich | Twitter/@natxupitxu |
Christopher Hiller | GitHub/boneskull | Twitter/@b0neskull |
MIT, see LICENSE.md file.