Skip to content

moleike/node-lwm2m

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

node-lwm2m

build coverage status gitter

node-lwm2m is an implementation of the Open Mobile Alliance's Lightweight M2M protocol (LWM2M).

Install

npm install --save lwm2m

Synopsis

var server = require('lwm2m').createServer()

server.on('register', function(params, accept) {
  setImmediate(function() {
     
    // read device related information
    server.read(params.ep, '3/0')
      .then(function(device) {
        console.log(JSON.stringify(device, null, 4))
      })
      
    // monitor device battery level
    server.observe(params.ep, '/3/0/9')
      .then(function(stream) {
        stream.on('data', function(value) {
          console.log('battery level: %d%', value)
        })
      })
  })
  accept()
})

server.listen(5683)

Contribute

Please report bugs via the github issue tracker.

API

Table of Contents

schemas

Schemas for OMA-defined objects. See oma.

createServer

Returns Server object

bootstrap#createServer

Returns bootstrap#Server object

Resource

Schema resource type definition

Type: Object

Properties

  • type ("String" | "Integer" | "Float" | "Boolean" | "Opaque" | "Time" | ["type"])
  • id number Resource ID
  • required boolean? resource is mandatory. Defaults to false
  • enum Array?
  • range object?

Schema

Schema constructor.

An Schema describes the shape of an LwM2M Object and the type of its resources. Schemas are used throghout the API for generating/parsing payloads from/to JavaScript values.

See oma directory for default definitions. See also thermostat.js for an example of a composite schema.

Note

LwM2M types will be coerced to JavaScript types and viceversa, e.g. Time will return a Date(), Opaque a Buffer(), and Integer/Float a number.

Parameters

Examples

// IPSO light controller
var lightControlSchema = new Schema({
  onOff: {
    type: 'Boolean',
    id : 5850,
    required: true
  },
  dimmer: {
    type: 'Integer',
    id: 5851,
    range: { min: 0, max: 100 }
  },
  units: {
    type: 'String',
    id: 5701,
  }
});

// an object literal matching the schema above
var lightControl = {
  onOff: true,
  dimmer: 40,
}

// Bad schema
var schema = new Schema({
  a: { type: 'String', id: 0 },
  b: { type: 'Error', id: 1 },
}); // throws TypeError
  • Throws any Will throw an error if fails to validate

validate

validates obj with schema.

Parameters

Examples

var schema = new Schema({
  a: { type: String, id: 0 },
  b: { type: Buffer, id: 1 },
});

schema.validate({
  a: 'foo',
  b: Buffer.from('bar'),
}); // OK

schema.validate({
  a: 'foo',
  b: 'bar',
}); // Throws error
  • Throws any Will throw an error if fails to validate

Server

Extends EventEmitter

Server constructor.

Events:

  • register: device registration request.
  • update: device registration update.
  • unregister: device unregistration.

Parameters

  • options Object?
    • options.type string IPv4 (udp4) or IPv6 (udp6) connections (optional, default 'upd6')
    • options.piggybackReplyMs number milliseconds to wait for a piggyback response (optional, default 50)
    • options.registry Registry impl. of CoRE Resource Directory (optional, default Registry)

read

Read path on device with endpoint name endpoint. The optional callback is given the two arguments (err, res), where res is parsed using schema.

Note:

If no schema is provided will return a Buffer if the payload is TLV-encoded or opaque, or an String otherwise.

Parameters

  • endpoint String client endpoint name
  • path String either an LWM2M Object instance or resource
  • options Object?
    • options.format string media type. (optional, default 'text')
    • options.schema Schema defining resources.
  • callback Function?

Examples

var schema = Schema({
  test: { id: 1, type: Number }
});

var options = { 
  schema: schema, 
  format: 'json',
};

server.read('test', '/1024/11', options, function(err, res) {
  assert(res.hasOwnProperty('test'));
  assert(typeof res.test == 'number');
});

Returns Promise<(Object | string | Buffer | number)> a promise of the eventual value

write

Write value into path of device with endpoint name endpoint. For writing Object Instances, an schema is required.

Note:

schemas can be globally added to lwm2m.schemas.

Parameters

Examples

var schema = Schema({
  foo : { 
    id: 5, 
    type: 'String' 
  },
  bar : { 
    id: 6, 
    type: 'Number' 
  },
});

var options = { 
  schema: schema, 
  format: 'json',
};

var value = {
  foo: 'test',
  bar: 42,
};

var promise = server.write('test', '/42/0', value, options)
var promise = server.write('test', '/42/0/5', 'test')
var promise = server.write('test', '/42/0/6', 42)

// add schema for Object ID 42 globally.
lwm2m.schemas[42] = schema;

var promise = server.write('test', '/42/0', value)

Returns Promise

execute

Makes an Execute operation over the designed resource ID of the selected device.

Parameters

Returns Promise

discover

Execute a discover operation for the selected resource.

Parameters

Returns Promise<string> a promise with an strng in link-format

writeAttributes

Write attributes into path of endpoint endpoint.

Parameters

Examples

var attr = {
  "pmin": 5,
  "pmax": 10
};

server.writeAttributes('dev0', '3303/0/5700', attr, function(err, res) {
   assert.ifError(err);
});

Returns Promise

create

Create a new LWM2M Object for path, where path is an Object ID.

Parameters

Returns Promise

delete

Deletes the LWM2M Object instance in path of endpoint endpoint

Parameters

Returns Promise

observe

Observe changes in path of device with endpoint name endpoint. The notification behaviour, e.g. periodic or event-triggered reporting, is configured with the writeAttributes method. The callback is given the two arguments (err, stream), where stream is a Readable Stream. To stop receiving notifications close() the stream and (optionally) call cancel() on the same endpoint and path and .

Parameters

  • endpoint String client endpoint name
  • path String
  • options
    • options.format string media type. (optional, default 'text')
    • options.schema Schema defining resources.
  • callback Function?

Examples

server.observe('dev0', '/1024/10/1', function(err, stream) {
  stream.on('data', function(value) {
    console.log('new value %s', value);
  });

  stream.on('end', function() {
    console.log('stopped observing');
  });
});

Returns Promise

cancel

Cancel an observation for path of device endpoint.

Parameters

Returns Promise

bootstrap#Server

Extends EventEmitter

Server constructor.

Events

  • bootstrapRequest: device bootstrap request.

Parameters

  • options Object?
    • options.type string IPv4 (udp4) or IPv6 (udp6) connections (optional, default 'upd6')
    • options.piggybackReplyMs number milliseconds to wait for a piggyback response (optional, default 50)

Examples

var bootstrap = require('lwm2m').bootstrap;
var server = bootstrap.createServer();

server.on('error', function(err) {
  throw err;
});

server.on('close', function() {
  console.log('server is done');
});

server.on('bootstrapRequest', function(params, accept) {
  console.log('endpoint %s contains %s', params.ep, params.payload);
  accept();
});

// the default CoAP port is 5683
server.listen();

write

Makes a Write operation over the designed resource ID of the selected device.

Parameters

Examples

var schema = Schema({
  foo : { 
    id: 5, 
    type: 'String' 
  },
  bar : { 
    id: 6, 
    type: 'Number' 
  },
});

var options = { 
  schema: schema, 
  format: 'json',
};

var value = {
  foo: 'test',
  bar: 42,
};

var promise = server.write('test', '/42/3', value, options)

Returns Promise

delete

Deletes the LWM2M Object instance in path of endpoint endpoint

Parameters

Returns Promise

finish

Terminate the Bootstrap Sequence previously initiated

Parameters

Returns Promise

Registry

Extends EventEmitter

Registry for clients. Default implementation is in-memory.

For production use, extend Registry class and give new implementations to _get, _find, _save, _update and _delete.

See examples for a MongoDB-backed registry.

_find

get client by endpoint name

Parameters

  • endpoint string
  • callback Function callback is given the two arguments (err, client)

_get

get client by location in the registry

Parameters

  • location string
  • callback Function callback is given the two arguments (err, client)

_save

store a new client in the registry

Parameters

  • client Object
  • callback Function callback is given the two arguments (err, location)

_update

update a client in the registry

Parameters

  • location string
  • params Object
  • callback Function callback is given the two arguments (err, location)

_delete

delete client from the registry

Parameters

  • location string
  • callback Function callback is given the two arguments (err, client)