Skip to content

MQTT Client

Giovanni Foiani edited this page Jul 5, 2018 · 8 revisions

Import MQTT Client

var MqttClient = require('spacebunny').MqttClient;

Connection parameters

Prerequisites: you must have created a device through the Space Bunny's web interface. You also have at least one enabled channel, e.g. 'data' (name is not mandatory, but we'll use this for our example). See our Getting Started for a quick introduction to Space Bunny's base concepts. Once everything is set up get your device's Device key from Space Bunny's web application: on the web interface, go to devices section and create or pick an existing device. Click on the 'SHOW CONFIGURATION' link, copy the Device key and substitute it here:

var connectionParams = { deviceKey: 'your-device-key' };

You can also provide the endpointUrl key to use a different endpoint, default points to our Live Application.

You can also provide full manual configuration, all information can be retrieved from the 'SHOW CONFIGURATION' view on Space Bunny web interface. With the following configuration the SDK will not contact the endpoint for configurations.

var connectionParams = {
  deviceId: 'device-id',
  secret: 'device-secret',
  host: 'hostname',
  port: 1883, // default for MQTT
  vhost: 'organization-id',
  channels: [ 'data', 'alarms' ],
  endpoint: {
    host: 'api.spacebunny.io',
    port: 3000
  }
};

You can also customize endpoint passing a complete URL:

var connectionParams = {
  deviceId: 'device-id',
  endpoint: {
    url: 'http://mycustomendpoint.com'
  }
};

Secure connection

If you want to connect using an encrypted channel, you must enable TLS and provide the client and CA certificates path. Default port for MQTTS connections is 8883. Certificates paths are not mandatory, if not provided the platform just creates an encrypted communication channel without peer verification.

var connectionParams = {
  deviceKey: 'your-device-key',
  tls: true,
  ca: '/path/to/ca_certificate.pem',
  cert: '/path/to/client_certificate.pem',
  key: '/path/to/client_key.pem'
};

Instantiate the client

var mqttClient = new MqttClient(connectionParams);

At this point the SDK is auto-configured and ready to use. Configurations are automatically fetched by the SDK.

Receive messages

When a message is sent on the inbox channel of the current device, the callback function will be called.

// callback called when a message is received
var messageCallback = function(topic, message) {
  console.log(topic + ':' + message);
};
mqttClient.connect().then(function() {
  mqttClient.onReceive(messageCallback).then(function(res) {
    console.log('Start receiving..');
  }).catch(function(reason) {
    console.error(reason);
  });
}).catch(function(reason) {
  console.error(reason);
});

Receive options

It is possible to specify some options to modify message reception behaviour:

  • qos (default 1): The MQTT Client supports QoS 0 (at most once) and QoS 1 (at least once) semantics. In MQTT QoS relates to transport assurance as well as persistence. While clients are permitted to request QoS 2 subscriptions, the SDK will only grant subscriptions up to QoS 1. QoS 0 messages are stored in transient queues while QoS 1 messages are stored in permanent queues.
var receiveOpts = { ... };
mqttClient.connect().then(function() {
  mqttClient.onReceive(messageCallback, receiveOpts).then(function(res) {
    console.log('Start receiving..');
  }).catch(function(reason) {
    console.error(reason);
  });
}).catch(function(reason) {
  console.error(reason);
});

Send messages

publish function takes two mandatory arguments (channel's name and payload) and a variety of options:

  • retain (default false): A retained message is a normal MQTT message with the retained flag set to true. The broker will store the last retained message and the corresponding QoS for that topic. Each client that subscribes to a topic pattern, which matches the topic of the retained message, will receive the message immediately after subscribing. For each topic only one retained message will be stored by the broker.
var payload = { some: 'json' };
var publishOpts = { ... };
mqttClient.connect().then(function() {
  mqttClient.publish('data', payload, publishOpts).then(function(res) {
    console.log('Message sent!');
  }).catch(function(reason) {
   console.error(reason);
  });
}).catch(function(reason) {
  console.error(reason);
});

The platform can manage the sending and receiving of data in any format. The default format is JSON.