node-red-contrib-mobius-flow-thingsboard
Version:
Node-RED nodes to work with MOBiUSFlow and ThingsBoard.io
210 lines (202 loc) • 8.03 kB
JavaScript
;
/*
Copyright (c) 2018, IAconnects Technology Limited
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be
used to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ThingsboardMqttClient = void 0;
const events_1 = require("events");
const mqtt = __importStar(require("mqtt"));
class ThingsboardMqttClient extends events_1.EventEmitter {
constructor(siteURL, gatewayId, accessToken, allowSelfCert) {
super();
this.slowReconnectCounter = 0;
this.siteURL = siteURL;
this.gatewayId = gatewayId;
this.accessToken = accessToken;
this.allowSelfCert = allowSelfCert;
this.connect();
this.reconnectTimeout = setInterval(() => {
if (this.isConnected()) {
this.slowReconnectCounter = 0;
}
else {
this.slowReconnectCounter++;
if (this.slowReconnectCounter >= 12) {
this.connect();
}
}
}, 10000);
}
async closeMqttConnection() {
clearInterval(this.reconnectTimeout);
await this.disconnect();
}
updateDeviceClientAttributes(deviceName, attributes) {
return new Promise((resolve, reject) => {
if (!this.isConnected) {
reject(new Error('Not connected to Thingsboard'));
}
else {
this.publish('v1/gateway/attributes', JSON.stringify({ [deviceName]: attributes }), 1)
.then(() => {
resolve(null);
})
.catch((err) => {
reject(err);
});
}
});
}
updateDeviceTelemetry(deviceName, timestamp, telemetry) {
return new Promise((resolve, reject) => {
if (!this.isConnected) {
reject(new Error('Not connected to Thingsboard'));
}
else {
this.publish('v1/gateway/telemetry', JSON.stringify({
[deviceName]: [
{
ts: timestamp,
values: telemetry,
},
],
}), 1)
.then(() => {
resolve(null);
})
.catch((err) => {
reject(err);
});
}
});
}
registerDeviceAsConnected(deviceName) {
this.publish('v1/gateway/connect', JSON.stringify({ device: deviceName }), 1);
}
registerDeviceAsDisconnected(deviceName) {
this.publish('v1/gateway/disconnect', JSON.stringify({ device: deviceName }), 1);
}
/**
* Get the state of the MQTT connection
* @returns true if connected to the Thingsboard instance, else false
*/
isConnected() {
return this.mqttClient !== undefined ? this.mqttClient.connected : false;
}
/**
* Connect to the Thingsboard instance
* @returns A Promise which resolves if a connection is established, or rejects with the error if a connection fails
*/
async connect() {
await this.disconnect();
this.emit('connecting');
const clientOptions = {
clean: false,
clientId: `${this.accessToken}-${this.gatewayId}`,
keepalive: 60,
password: '',
reconnectPeriod: 30000,
rejectUnauthorized: !this.allowSelfCert,
username: `${this.accessToken}`,
};
const connectString = `mqtts://${this.siteURL}:8883`;
this.mqttClient = mqtt.connect(connectString, clientOptions);
this.mqttClient.on('connect', () => {
this.emit('connected');
this.mqttClient.subscribe('v1/gateway/attributes', { qos: 1 });
});
this.mqttClient.on('error', (error) => {
this.emit('disconnected');
});
this.mqttClient.on('offline', () => {
this.emit('disconnected');
});
this.mqttClient.on('reconnect', () => {
this.emit('connecting');
});
this.mqttClient.on('message', (topic, message) => {
if (topic.endsWith('attributes')) {
this.emit('attributes', topic, JSON.parse(message.toString()));
}
});
}
/**
* Disconnect from the Thingsboard instance
* @returns A Promise which resolves when the connection has ended
*/
disconnect() {
this.emit('disconnected');
return new Promise((resolve) => {
if (this.mqttClient === undefined) {
resolve(null);
}
else {
this.mqttClient.removeAllListeners();
this.mqttClient.end(true, () => {
resolve(null);
});
}
});
}
/**
* Publish a device event to the Thingsboard instance
* @param {string} topic - The event topic
* @param {string} payload - The event payload
* @param {mqtt.QoS} qos - The QoS to use when publishing
*/
publish(topic, payload, qos) {
return new Promise((resolve, reject) => {
this.mqttClient.publish(topic, payload, { qos }, (err) => {
if (err) {
throw reject(err);
}
else {
resolve(null);
}
});
});
}
}
exports.ThingsboardMqttClient = ThingsboardMqttClient;