node-red-contrib-mobius-flow-thingsboard
Version:
Node-RED nodes to work with MOBiUSFlow and ThingsBoard.io
229 lines (221 loc) • 9.31 kB
JavaScript
;
/*
Copyright (c) 2017, 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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const thingsboard_http_client_v2_1 = require("../thingsboard-http-client-v2");
const thingsboard_mqtt_client_v2_1 = require("../thingsboard-mqtt-client-v2");
module.exports = (RED) => {
RED.nodes.registerType('mobius thingsboard connection v2', function (configuration) {
RED.nodes.createNode(this, configuration);
// eslint-disable-next-line @typescript-eslint/no-this-alias
const node = this;
const users = {};
let mqttConnected = false;
let registeredDevices = new Map();
let registeredAssets = new Map();
const httpClient = new thingsboard_http_client_v2_1.ThingsboardHttpClient(configuration.site, configuration.customerId, configuration.username, configuration.password);
const mqttClient = new thingsboard_mqtt_client_v2_1.ThingsboardMqttClient(configuration.site, configuration.gatewayId, configuration.gatewayAccessToken, configuration.allowSelfCert);
RED.nodes.eachNode((n) => {
if (n.id !== node.id && n.type === 'mobius thingsboard connection v2' && n.gatewayAccessToken === configuration.gatewayAccessToken) {
node.error('Multiple connections with this Access Token exist: This will cause stability issues in all connections using this.');
}
});
node.on('close', (done) => {
httpClient.closeHttpConnection();
mqttClient.closeMqttConnection();
done();
});
node.getHttpClient = () => {
return httpClient;
};
node.getMqttClient = () => {
return mqttClient;
};
/**
* Register a new Mobius node with this config node
* @param {Object} mobiusNode - The new node to register
*/
node.register = function (mobiusNode) {
users[mobiusNode.id] = mobiusNode;
if (mqttConnected) {
users[mobiusNode.id].status({
fill: 'green',
shape: 'dot',
text: 'Connected',
});
}
};
/**
* Deregister a previously registered Thingsboard node
* @param thingsboardNode The node to deregister
* @param done A callback to be run by the node after it has been deregistered
*/
node.deregister = (thingsboardNode, done) => {
delete users[thingsboardNode.id];
done();
};
/**
* Clear the registered devices list
*/
node.clearRegisteredDevices = () => {
if (mqttConnected) {
registeredDevices.forEach((id, name) => {
mqttClient.registerDeviceAsDisconnected(name);
});
}
registeredDevices.clear();
};
/**
* Refresh the registered devices list
*/
node.refreshRegisteredDevices = () => {
return new Promise((resolve, reject) => {
this.clearRegisteredDevices();
httpClient.Ready.then(() => {
httpClient
.getRegisteredDevices()
.then((devices) => {
registeredDevices = devices;
registeredDevices.forEach((id, name) => {
mqttClient.registerDeviceAsConnected(name);
});
resolve(registeredDevices.size);
})
.catch((err) => {
reject(err);
});
});
});
};
node.addDeviceToRegister = (name, deviceId) => {
registeredDevices.set(name, { id: deviceId });
};
/**
* Check if a device is registered
* @param name The device name
*/
node.deviceIsRegistered = (name) => {
return registeredDevices.has(name);
};
node.getDeviceId = (name) => {
var _a;
return (_a = registeredDevices.get(name)) === null || _a === void 0 ? void 0 : _a.id;
};
/**
* Clear the registered assets list
*/
node.clearRegisteredAssets = () => {
registeredAssets.clear();
};
/**
* Refresh the registered assets list
*/
node.refreshRegisteredAssets = () => {
return new Promise((resolve, reject) => {
this.clearRegisteredAssets();
httpClient.Ready.then(() => {
httpClient
.getRegisteredAssets()
.then((assets) => {
registeredAssets = assets;
resolve(registeredAssets.size);
})
.catch((err) => {
reject(err);
});
});
});
};
node.addAssetToRegister = (name, assetId) => {
registeredAssets.set(name, { id: assetId });
};
/**
* Check if an asset is registered
* @param name The device name
*/
node.assetIsRegistered = (name) => {
return registeredAssets.has(name);
};
node.getAssetId = (name) => {
var _a;
return (_a = registeredAssets.get(name)) === null || _a === void 0 ? void 0 : _a.id;
};
// ***** HTTP CONNECTION FUNCTIONS *****/
httpClient.on('connectionError', () => {
node.error('Invalid HTTP Connection: Likely the Site, CustomerId, Username or Password is incorrect. Note: This will not effect sending telemetry of updating attributes if MQTT is connected. Manipulation of the Thingsboard configuration will not be possible until the HTTP connection is also made.');
for (const id in users) {
if (users.hasOwnProperty(id)) {
users[id].status({
fill: 'yellow',
shape: 'ring',
text: 'HTTP Connection Error',
});
}
}
});
// ***** MQTT CONNECTION FUNCTIONS *****/
mqttClient.on('connecting', () => {
mqttConnected = false;
for (const id in users) {
if (users.hasOwnProperty(id)) {
users[id].status({
fill: 'yellow',
shape: 'dot',
text: 'Connecting',
});
}
}
});
mqttClient.on('disconnected', () => {
mqttConnected = false;
for (const id in users) {
if (users.hasOwnProperty(id)) {
users[id].status({
fill: 'red',
shape: 'ring',
text: 'Disconnected',
});
}
}
});
mqttClient.on('connected', async () => {
mqttConnected = true;
for (const id in users) {
if (users.hasOwnProperty(id)) {
users[id].status({
fill: 'green',
shape: 'dot',
text: 'Connected',
});
}
}
try {
await this.refreshRegisteredDevices();
await this.refreshRegisteredAssets();
}
catch (err) {
node.error(err.message);
}
});
});
};