UNPKG

node-red-contrib-mobius-flow-thingsboard

Version:

Node-RED nodes to work with MOBiUSFlow and ThingsBoard.io

163 lines (155 loc) 6.4 kB
"use strict"; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); /* 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. */ const events_1 = require("events"); const mqtt = __importStar(require("mqtt")); class IThingsboardMQTTGateway extends events_1.EventEmitter { constructor(config) { super(); this.slowReconnectCounter = 0; this.config = config; if (this.config.keepAlive === 0) { this.config.keepAlive = 60; } if (this.config.reconnectPeriod === 0) { this.config.reconnectPeriod = 30; } if (this.config.slowReconnectPeriod === 0) { this.config.slowReconnectPeriod = 30; } } /** * 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 */ connect() { return this.disconnect() .then(() => { const clientOptions = { clean: false, clientId: `${this.config.accessToken}-${this.config.gatewayId}`, keepalive: this.config.keepAlive, password: '', reconnectPeriod: this.config.reconnectPeriod * 1000, rejectUnauthorized: true, username: `${this.config.accessToken}`, }; this.reconnectTimeout = setInterval(() => { if (this.isConnected()) { this.slowReconnectCounter = 0; } else { this.slowReconnectCounter++; if (this.slowReconnectCounter >= this.config.slowReconnectPeriod) { this._reconnect(); } } }, 60000); return new Promise((resolve, reject) => { let connectString = `mqtts://${this.config.site}:8883`; if (this.config.isLocal === true) { connectString = `mqtt://${this.config.site}:1883`; } this.mqttClient = mqtt.connect(connectString, clientOptions); this.mqttClient.on('connect', () => { this.emit('connected'); resolve(`Connected to ssl://${this.config.site}:8883`); }); this.mqttClient.on('error', (error) => { reject(error); }); this.mqttClient.on('offline', () => { this.emit('disconnected'); }); this.mqttClient.on('reconnect', () => { this.emit('connecting'); }); }); }); } /** * Disconnect from the Thingsboard instance * @param {boolean} [force = false] - Set true to force an immediate disconnects or false to wait for all * pending messages to complete before disconnecting * @returns A Promise which resolves when the connection has ended */ disconnect(force = false) { return new Promise((resolve) => { if (this.reconnectTimeout !== undefined) { clearInterval(this.reconnectTimeout); } if (this.mqttClient === undefined) { resolve(); } else { this.mqttClient.end(force, () => { resolve(); }); } }); } /** * Publish a device event to the Thingsboard instance * @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(); } }); }); } /** * Force a reconnect if the connection is down for too long */ _reconnect() { this.emit('connecting'); this.connect() .catch((err) => { // tslint:disable-next-line:no-console console.log(`Error during extended auto reconnect: ${err}`); }); } } exports.IThingsboardMQTTGateway = IThingsboardMQTTGateway;