evrythng-pubsub.js

The evrythng-pubsub.js SDK is a plugin to be used in combination with evrythng.js to allow applications to directly subscribe and publish to MQTT topics for each resource.

These plugins help communicate with the Pub/Sub Broker instead of the usual HTTP REST API.

📘

Note

evrythng-pubsub.js is compatible with Node.js and browsers, choosing WS or MQTT or a combination.


Installation

Installation of evrythng-pubsub.js is like evrythng.js, but the library name is evrythng-pubsub instead of evrythng.

📘

Note

You must install evrythng.js before you can use this plugin.

Install with Dependencies

<!-- evrythng.js SDK -->
<script src="https://d10ka0m22z5ju5.cloudfront.net/js/evrythng/5.2.0/evrythng-5.2.0.js"></script>

<!-- evrythng-pubsub.js SDK -->
<script src="https://d10ka0m22z5ju5.cloudfront.net/js/evrythng-pubsub/1.0.0/evrythng-pubsub-1.0.0.js"></script>

Including the library in a Node.js application and performing initialization is identical to including and initilizing evrythng.js. However, because this is a plugin, be sure to apply it to the base SDK using use():

const evrythng = require('evrythng');
const PubSub = require('evrythng-pubsub');

evrythng.use(PubSub);

Setup

Before the MQTT or WebSocket connection can be used, be sure to choose the right options using PubSub.setup(). Clients must always connect to the mqtts://mqtt.evrythng.com domain for MQTT or wss://ws.evrythng.com domain for Web Sockets.

PubSub.setup({
  apiUrl: 'mqtts://mqtt.evrythng.com:8883/mqtt',
  reconnectPeriod: 1000,
  keepAlive: 50
});

Function Reference

The evrythng-pubsub.js SDK adds new methods to existing resources, accessed through the same scopes. These are:

.subscribe(callback);  // Subscribe to resource updates.

.unsubscribe();  // Unsubscribe from a resource.

.publish(value);  // Publish a new value or object to a resource.

We show some common examples below to help illustrate this pattern:

const thngId = 'UGM4xF47eDsaQKRwRhdHpnbg';
const key = 'temperature_celsius';
const actionType = 'scans';

const thngResource = operator.thng(thngId);

// Update a Thng
thngResource.publish({ name: 'Some New Name' });

// Subscribe to a Thng property's updates
thngResource.property(key).subscribe(console.log);

// Update a Thng property's value
thngResource.property(key).publish(23.5);

// Create a Thng action
thngResource.action(actionType).publish();

// Subscribe to all actions
operator.action('all').subscribe(console.log);

// Unsubscribe from Thng property updates
thngResource.property(key).unsubscribe();