UNPKG

node-red-contrib-mobius-flow-thingsboard

Version:

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

286 lines (278 loc) 13.6 kB
"use strict"; /* 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 }); module.exports = (RED) => { RED.nodes.registerType('mobius thingsboard manager', function (configuration) { RED.nodes.createNode(this, configuration); const node = this; const serviceConn = RED.nodes.getNode(configuration.connection); node.status({ fill: 'green', shape: 'dot', text: 'Ready', }); serviceConn.register(node); function isArrayOfMobiusObjects(value) { return Array.isArray(value) && value.every((item) => item.hasOwnProperty('uri')); } function provisionDevice(element) { return new Promise((resolve, reject) => { const attributes = {}; const telemetry = {}; if (element.hasOwnProperty('resources')) { for (const resource of Array.isArray(element.resources) ? element.resources : Object.values(element.resources)) { if (resource.hasOwnProperty('settings') && resource.settings.hasOwnProperty('tags') && resource.settings.tags.hasOwnProperty('attribute') && resource.settings.tags.attribute === 'true') { attributes[resource.name] = resource.pv; } if (!(resource.hasOwnProperty('settings') && resource.settings.hasOwnProperty('tags') && resource.settings.tags.hasOwnProperty('attribute') && resource.settings.tags.attribute === 'true')) { telemetry[resource.name] = resource.pv; } } } const httpClient = serviceConn.getHttpClient(); if (element.hasOwnProperty('uri') && element.hasOwnProperty('profileName') && element.hasOwnProperty('description')) { (async () => { try { const objectData = await httpClient.addDevice(element.uri, element); setTimeout(async () => { await httpClient.updateDeviceClientAttributes(objectData.id.id, attributes); await httpClient.updateDeviceTelemetry(objectData.id.id, Date.now(), telemetry); resolve(null); }, 1000); } catch (err) { if (err.hasOwnProperty('statusCode') && err.hasOwnProperty('errorMessage')) { node.error(`${err.statusCode} - ${err.errorMessage}`); reject(`${err.statusCode} - ${err.errorMessage}`); } else { node.error(`${element.uri} - API call failed`); reject(`${element.uri} - API call failed`); } } })(); } else { node.error(`${element.uri} - Input format error`); reject(`${element.uri} - Input format error`); } }); } function provisionAsset(element) { return new Promise((resolve, reject) => { const telemetry = {}; if (element.hasOwnProperty('resources')) { for (const resource of Array.isArray(element.resources) ? element.resources : Object.values(element.resources)) { if (!(resource.hasOwnProperty('settings') && resource.settings.hasOwnProperty('tags') && resource.settings.tags.hasOwnProperty('attribute') && resource.settings.tags.attribute === 'true')) { telemetry[resource.name] = resource.pv; } } } const httpClient = serviceConn.getHttpClient(); if (element.hasOwnProperty('uri') && element.hasOwnProperty('profileName') && element.hasOwnProperty('description')) { (async () => { try { const objectData = await httpClient.addAsset(element.uri, element); setTimeout(async () => { await httpClient.updateAssetTelemetry(objectData.id.id, Date.now(), telemetry); resolve(null); }, 1000); } catch (err) { if (err.hasOwnProperty('statusCode') && err.hasOwnProperty('errorMessage')) { node.error(`${err.statusCode} - ${err.errorMessage}`); reject(`${err.statusCode} - ${err.errorMessage}`); } else { node.error(`${element.uri} - API call failed`); reject(`${element.uri} - API call failed`); } } })(); } else { node.error(`${element.uri} - Input format error`); reject(`${element.uri} - Input format error`); } }); } node.on('input', async (msg, done) => { try { switch (msg.topic) { case 'clear-registered-objects': serviceConn.clearRegisteredObjects(); node.send({ topic: msg.topic, payload: 'OK', }); node.status({ fill: 'green', shape: 'dot', text: 'Cleared objects', }); break; case 'register-objects': if (!isArrayOfMobiusObjects(msg.payload)) { node.status({ fill: 'red', shape: 'dot', text: 'Input format error.', }); node.send({ topic: msg.topic, payload: 'Fault', }); } else { msg.payload.forEach((element) => { serviceConn.registerObject(element.uri); }); node.status({ fill: 'green', shape: 'dot', text: 'Registered objects', }); node.send({ topic: msg.topic, payload: 'OK', }); } break; case 'get-registered-objects': node.send({ topic: msg.topic, payload: serviceConn.getRegisteredObjects(), }); node.status({ fill: 'green', shape: 'dot', text: 'Ready', }); break; case 'provision-devices': case 'provision-assets': if (!isArrayOfMobiusObjects(msg.payload)) { node.status({ fill: 'red', shape: 'dot', text: 'Input format error.', }); node.send({ topic: msg.topic, payload: 'Fault', }); } else { node.status({ fill: 'yellow', shape: 'dot', text: 'Busy', }); try { const delay = function () { return new Promise((resolve) => { setTimeout(() => { resolve(null); }, 1000); }); }; for (let lp = 0; lp < msg.payload.length; lp++) { if (msg.topic === 'provision-devices') { await provisionDevice(msg.payload[lp]); } if (msg.topic === 'provision-assets') { await provisionAsset(msg.payload[lp]); } serviceConn.registerObject(msg.payload[lp].uri); await delay(); } if (msg.topic === 'provision-devices') { node.status({ fill: 'green', shape: 'dot', text: 'Provisioned devices', }); } if (msg.topic === 'provision-assets') { node.status({ fill: 'green', shape: 'dot', text: 'Provisioned assets', }); } node.send({ topic: msg.topic, payload: 'OK', }); } catch (err) { node.status({ fill: 'yellow', shape: 'dot', text: 'One or more failures', }); node.send({ topic: msg.topic, payload: 'Fault', }); if (done) { done(); } } } break; } } catch (err) { this.error(`Failed to add device to Thingsboard: ${err.message}`); } finally { if (done) { done(); } } }); node.on('close', (done) => { serviceConn.deregister(node, done); done(); }); }); };