From d289a99d07058bca3082ed3d149f9a078baaa12e Mon Sep 17 00:00:00 2001 From: rasta5man Date: Tue, 14 May 2024 16:29:11 +0200 Subject: [PATCH 1/9] new switching line functionality - in progress --- flow/cmd_manager.js | 2660 ++++++++++++++++++++++----------------- flow/dido_controller.js | 9 +- flow/modbus_reader.js | 10 +- 3 files changed, 1485 insertions(+), 1194 deletions(-) diff --git a/flow/cmd_manager.js b/flow/cmd_manager.js index 3c18f1d..b3f9871 100644 --- a/flow/cmd_manager.js +++ b/flow/cmd_manager.js @@ -19,15 +19,15 @@ exports.html = `
RPC - run RPC calls

-
@(User)
-
-
-
@(Password)
-
-
-
@(My edge)
-
-
+
@(User)
+
+
+
@(Password)
+
+
+
@(My edge)
+
+
`; @@ -43,38 +43,49 @@ const bitwise = require('bitwise'); var SunCalc = require('./helper/suncalc.js'); const DataToTbHandler = require('./helper/DataToTbHandler.js'); const ErrorToServiceHandler = require('./helper/ErrorToServiceHandler.js'); -const { promisifyBuilder } = require('./helper/db_helper.js'); +const { promisifyBuilder, makeMapFromDbResult} = require('./helper/db_helper.js'); const { sendNotification, initNotifications, ERRWEIGHT } = require('./helper/notification_reporter.js'); +const dbNodes = TABLE("nodes"); +const dbRelays = TABLE("relays"); +const dbSettings = TABLE("settings"); + //https://github.com/log4js-node/log4js-node/blob/master/examples/example.js //file: { type: 'file', filename: path.join(__dirname, 'log/file.log') } - var path = require('path'); var log4js = require("log4js"); const process = require('process'); -log4js.configure({ - appenders: { - errLogs: { type: 'file', compress:true, daysToKeep: 2, maxLogSize: 1048576, backups: 1, keepFileExt: true, filename: path.join(__dirname + "/../", 'err.txt') }, - monitorLogs: { type: 'file', compress:true, daysToKeep: 2, maxLogSize: 1048576, backups: 1, keepFileExt: true, filename: path.join(__dirname + "/../", 'monitor.txt') }, - console: { type: 'console' } - }, - categories: { - errLogs: { appenders: ['console', 'errLogs'], level: 'error' }, - monitorLogs: { appenders: ['console', 'monitorLogs'], level: 'trace' }, - //another: { appenders: ['console'], level: 'trace' }, - default: { appenders: ['console'], level: 'trace' } - } -}); +//TODO - to remove? +// runTasks intervals +const SHORT_INTERVAL = 50; +const LONG_INTERVAL = 500; -const errLogger = log4js.getLogger("errLogs"); -const logger = log4js.getLogger(); -const monitor = log4js.getLogger("monitorLogs"); +//send data to following instances: +const SEND_TO = { + debug: 0, + tb: 1, + http_response: 2, + dido_controller: 3, + infoSender: 4 +} -//USAGE -//logger.debug("text") -//monitor.info('info'); -//errLogger.error("some error"); +const PRIORITY_TYPES = { + terminal: 0, + fw_detection: 1,//reserved only for FW detection - FLOW.OMS_masterNodeIsResponding + high_priority: 2,//reserverd only for: read dimming / brightness (after set dimming from platform) + relay_profile: 3, + node_broadcast: 4, + node_profile: 5, + node_cmd: 6 +} + +//list of command calls to process. Processing in runTasks function +let tasks = []; + +let interval = null;//timeout for procesing tasks +let refFlowdata = null;//holds reference to httprequest flowdata +let refFlowdataObj = {}; //load from settings let latitude = 48.70826502;//48.682255758; @@ -111,15 +122,9 @@ priorities["8"] = minutes; priorities["3"] = minutes; priorities["89"] = minutes; -//prikazy kt sa budu spustat na dany node - see config.js in terminal-oms.app +//prikazy kt sa budu spustat na dany node - see config.js in terminal-oms.app. (1 - dimming) let listOfCommands = [0,1,3,6,7,8,74,75,76,77,78,79,80,84,87,89]; -//1 - dimming - -const dbNodes = TABLE("nodes"); -const dbRelays = TABLE("relays"); -const dbSettings = TABLE("settings"); - const errorHandler = new ErrorToServiceHandler(); let rotary_switch_state = "Off"; @@ -133,6 +138,35 @@ let nodesData = {};//key is node, value data from db //helper container for counting resolved group of commands (commands related to set profile) let cmdCounter = {};//key is node, value is counter let cmdNOKNodeCounter = {};//key is node, value is counter + +//END OF VARIABLE SETTINGS +//-------------------------------- + + +log4js.configure({ + appenders: { + errLogs: { type: 'file', compress:true, daysToKeep: 2, maxLogSize: 1048576, backups: 1, keepFileExt: true, filename: path.join(__dirname + "/../", 'err.txt') }, + monitorLogs: { type: 'file', compress:true, daysToKeep: 2, maxLogSize: 1048576, backups: 1, keepFileExt: true, filename: path.join(__dirname + "/../", 'monitor.txt') }, + console: { type: 'console' } + }, + categories: { + errLogs: { appenders: ['console', 'errLogs'], level: 'error' }, + monitorLogs: { appenders: ['console', 'monitorLogs'], level: 'trace' }, + //another: { appenders: ['console'], level: 'trace' }, + default: { appenders: ['console'], level: 'trace' } + } +}); + +const errLogger = log4js.getLogger("errLogs"); +const logger = log4js.getLogger(); +const monitor = log4js.getLogger("monitorLogs"); + +//USAGE +//logger.debug("text") +//monitor.info('info'); +//errLogger.error("some error"); + + function cmdCounterResolve(address) { if(cmdCounter.hasOwnProperty(address)) @@ -141,13 +175,12 @@ function cmdCounterResolve(address) let result = cmdCounter[address]; if(result == 0) delete cmdCounter[address]; - return result; } - return -1; } + function getParams(priority) { let params = {}; @@ -163,25 +196,25 @@ function getParams(priority) params.rw = 0;//0: read, 1: write //other values - //params.type = "cmd"; "relay" "cmd-terminal" + //params.type = "cmd"; "relay" "cmd-terminal" "set_node_profile" "process_profiles" "edge_date_time" "number_of_luminaires" //params.tbname = tbname; - params.priority = priorityTypes.node_cmd;//default priority - params.timestamp = 0;//execution time + params.priority = PRIORITY_TYPES.node_cmd; //default priority - if more tasks with the same timestamp, we sort them based on priority + params.timestamp = 0; //execution time - if timestamp < Date.now(), the task is processed if(priority != undefined ) { params.timestamp = priority; params.priority = priority; } - params.addMinutesToTimestamp = 0;//repeat if > 0, + params.addMinutesToTimestamp = 0;//repeat task if value is > 0, - //params.isDusk = false; - //params.isDawn = false; + //params.timePointName = "luxOff" // "luxOn", "dusk", "dawn", "profileTimepoint" //params.info = ""; return params; } + async function loadSettings() { let responseSettings = await promisifyBuilder(dbSettings.find()); @@ -200,12 +233,10 @@ async function loadSettings() //logger.debug('settings', responseSettings[0]); - //FLOW.OMS_tem - //rvo_name:string|lang:string|temperature_adress:string|latitude:number|longitude:number - initNotifications(); } + //nastav profil nodu function processNodeProfile(node) { @@ -246,13 +277,13 @@ function processNodeProfile(node) logger.debug("processNodeProfile", node, line, nodeObj, nodeProfile); //return; - //let timestamp = priorityTypes.node_cmd; + //let timestamp = PRIORITY_TYPES.node_cmd; //let now = new Date(); //now.setSeconds(now.getSeconds() + 10); //let timestamp = now.getTime(); - let timestamp = priorityTypes.node_cmd; + let timestamp = PRIORITY_TYPES.node_cmd; //nodeProfile = undefined; removeTask({type: "set_node_profile", address: node}); @@ -270,7 +301,7 @@ function processNodeProfile(node) logger.debug("turn off profile"); - let params = getParams(priorityTypes.node_cmd); + let params = getParams(PRIORITY_TYPES.node_cmd); params.type = "set_node_profile"; params.address = node; params.byte1 = 0; @@ -288,7 +319,7 @@ function processNodeProfile(node) tasks.push(params); - //sendNotification("CMD Manager: process cmd", relaysData[0].tbname, ERRWEIGHT.NOTICE, "Master node is working again", "", instanceSendTo.tb, instance ); + //sendNotification("CMD Manager: process cmd", relaysData[0].tbname, ERRWEIGHT.NOTICE, "Master node is working again", "", SEND_TO.tb, instance ); } else { @@ -296,10 +327,10 @@ function processNodeProfile(node) //cmdCounter[node] = tasksProfile.length; //tasks.push(tasksProfile); - //let timestamp = priorityTypes.node_cmd; + //let timestamp = PRIORITY_TYPES.node_cmd; - //vypneme profil - Zapísať hodnotu 32 do registra Time Schedule Settings – reset profilu - let params = getParams(priorityTypes.node_cmd); + //vypneme profil - Zapísať hodnotu 32 do registra Time Schedule Settings – reset profilu + let params = getParams(PRIORITY_TYPES.node_cmd); params.type = "set_node_profile"; params.address = node; params.byte1 = 0; @@ -335,7 +366,7 @@ function processNodeProfile(node) Prázdny profil je vtedy keď časový bod obsahuje hodnotu 0xFFFFFFFF (táto hodnota sa zapíše do registrov keď sa aktivuje reset profilu do registru 8). Páry sa prechádzajú časovo zoradené takže teoreticky je jedno v akom poradí sa zapisujú ale je lepšie ich zapisovať v chronologickom poradí od 13:00. Časový bod má formát: - Byte 3: hodiny Byte 2: minúty Byte 1: sekundy Byte 0 – rezervované + Byte 3: hodiny Byte 2: minúty Byte 1: sekundy Byte 0 – rezervované Register úrovne má rovnaký formát ako dimming register (Reg 1). */ @@ -353,7 +384,7 @@ function processNodeProfile(node) logger.debug("processNodeProfile: TS1 Time point ", (i + 1), node); - params = getParams(priorityTypes.node_cmd); + params = getParams(PRIORITY_TYPES.node_cmd); params.type = "set_node_profile"; params.address = node; params.byte1 = parseInt(t[0]);//hh @@ -372,7 +403,7 @@ function processNodeProfile(node) register++; timestamp++; - params = getParams(priorityTypes.node_cmd); + params = getParams(PRIORITY_TYPES.node_cmd); params.type = "set_node_profile"; params.address = node; params.byte1 = 0; @@ -407,7 +438,7 @@ function processNodeProfile(node) logger.debug("processNodeProfile: Threshold lux level for DUSK/DAWN", node); - let params = getParams(priorityTypes.node_cmd); + let params = getParams(PRIORITY_TYPES.node_cmd); params.type = "set_node_profile"; params.address = node; params.register = 96; @@ -445,7 +476,7 @@ function processNodeProfile(node) logger.debug("processNodeProfile: DUSK/DAWN max. adjust period", node); - let params = getParams(priorityTypes.node_cmd); + let params = getParams(PRIORITY_TYPES.node_cmd); params.type = "set_node_profile"; params.address = node; params.register = 97; @@ -482,12 +513,12 @@ function processNodeProfile(node) { //Statický offset pre časy úsvitu a súmraku. Byte 1 je pre DUSK, Byte 0 je pre DAWN. Formát: - //Bity 0 – 6: hodnota v minútach - //Bit 7: znamienko (1 – mínus) + //Bity 0 – 6: hodnota v minútach + //Bit 7: znamienko (1 – mínus) logger.debug("processNodeProfile: Static offset", node); - let params = getParams(priorityTypes.node_cmd); + let params = getParams(PRIORITY_TYPES.node_cmd); params.type = "set_node_profile"; params.address = node; params.register = 98; @@ -527,7 +558,7 @@ function processNodeProfile(node) logger.debug("Time schedule settings - turn on", node); - params = getParams(priorityTypes.node_cmd); + params = getParams(PRIORITY_TYPES.node_cmd); params.type = "set_node_profile"; params.address = node; params.register = 8; @@ -556,7 +587,7 @@ function processNodeProfile(node) //Bit 5 – zápis 1 spôsobí reset nastavení profilu (nastavenie prázdneho profilu) bits.push(0); - //Bity 6-7 - zatiaľ nepoužité + //Bity 6-7 - zatiaľ nepoužité bits.push(0); bits.push(0); @@ -607,53 +638,29 @@ function processNodeProfile(node) } -const instanceSendTo = { - debug: 0, - tb: 1, - http_response: 2, - dido_controller: 3, - infoSender: 4 -} - -const priorityTypes = { - terminal: 0, - fw_detection: 1,//reserved only for FW detection - FLOW.OMS_masterNodeIsResponding - high_priority: 2,//reserverd only for: read dimming / brightness (after set dimming from platform) - relay_profile: 3, - node_broadcast: 4, - node_profile: 5, - node_cmd: 6 -} - - -let interval = null;//timeout for procesing tasks -let refFlowdata = null;//holds reference to httprequest flowdata -let refFlowdataObj = {}; function cleanUpRefFlowdataObj() { - let now = new Date(); - let timestamp = now.getTime(); + let now = new Date(); + let timestamp = now.getTime(); - //clear old refFlowdata references - let keys = Object.keys(refFlowdataObj); - for(let i = 0; i < keys.length; i++) - { - let timestampKey = keys[i]; + //clear old refFlowdata references + let keys = Object.keys(refFlowdataObj); + for(let i = 0; i < keys.length; i++) + { + let timestampKey = keys[i]; - if((timestamp - timestampKey) > 60*1000 ) - { - console.log("cleanUpRefFlowdataObj delete", timestampKey); - delete refFlowdataObj[ timestampKey ]; - } - } + if((timestamp - timestampKey) > 60*1000 ) + { + console.log("cleanUpRefFlowdataObj delete", timestampKey); + delete refFlowdataObj[ timestampKey ]; + } + } } -let tasks = [];//list of command calls to process function removeTask(obj) { - let keys = Object.keys(obj); tasks = tasks.filter((task) => { @@ -665,25 +672,41 @@ function removeTask(obj) { if(task[key] == obj[key]) counter++; } - } if(counter == keys.length) return false; return true; - }); - } -//TODO - to remove? -const shortIterval = 10; -const longInterval = 100; - loadSettings(); + exports.install = function(instance) { + let now = new Date(); + console.log("CMD Manager installed", now.toLocaleString("sk-SK")); + + const tbHandler = new DataToTbHandler(SEND_TO.tb); + tbHandler.setSender(exports.title); + + //FLOW.OMS_projects_id, name: FLOW.OMS_rvo_name + //const errorHandler = new ErrorToServiceHandler(instance, SEND_TO.infoSender); + errorHandler.setProjectsId(FLOW.OMS_projects_id); + //const errorHandler = new ErrorToServiceHandler(instance); + //errorHandler.sendMessageToService("ahoj", 0); + + let sunCalcResult = calculateDuskDawn(); + + let reportDuskDawn = { + dusk_time: sunCalcResult.dusk_time, + dawn_time: sunCalcResult.dawn_time, + dusk_time_reported: undefined, + dawn_time_reported: undefined + }; + + process.on('uncaughtException', function (err) { //TODO send to service @@ -697,253 +720,170 @@ exports.install = function(instance) { //te();//force error - const tbHandler = new DataToTbHandler(instanceSendTo.tb); - tbHandler.setSender(exports.title); - //FLOW.OMS_projects_id, name: FLOW.OMS_rvo_name - //const errorHandler = new ErrorToServiceHandler(instance, instanceSendTo.infoSender); - errorHandler.setProjectsId(FLOW.OMS_projects_id); - //const errorHandler = new ErrorToServiceHandler(instance); - //errorHandler.sendMessageToService("ahoj", 0); - - - async function loadRelaysData(line) + function processAllNodeProfilesOnLine(line) { - logger.debug("loadRelaysData", line); - - //ak zapiname liniu, mali by sme skontrolovat kde processed je false - //nodes.table: node:number|tbname:string|line:number|profile:string|processed:boolean - //vyselektujem vsetky nodes a spracujem profil - - return new Promise((resolve, reject) => { - - dbRelays.find().make(function(builder) { - builder.callback(function(err, response) { - - if(err != null) reject(err); - - let relaysDataTmp = {}; - for(let i = 0; i < response.length; i++) - { - let record = response[i]; - let line = record["line"]; - relaysDataTmp[ record["line"] ] = record; - - //porovname predchadzajuce hodnoty - //ak record.contactor == 1, a aktualna hodnota record.contactor == 0 - //to znamena, ze sa zmenil stav - linia bola vypnuta - - let prevData = relaysData[ record["line"] ]; - - //ugly but do not remove!!! - relaysData[ record["line"] ] = record; - - let state = "";//on, off or empty (no change) - if(prevData != undefined) - { - /* - if(prevData.contactor == 1 && record.contactor == 0) - { - state = "off"; - reportOfflineNodeStatus(line); - } - - if(prevData.contactor == 0 && record.contactor == 1) - { - state = "on"; - reportOnlineNodeStatus(line); - } - */ - - } - else - { - //start flowu - state = "start"; - } - - if(line != undefined) - { - //ak sa jedna o update profilu linie - pozor di_co_controller posiela command pre loadRelaysData - if(line != record["line"] ) continue; - } - - //je zapnuta linia? contactor = 1 a processed = false, spracujeme profil - if(record.contactor == 1) - { - - //nespracovany profil, zapisem do nodu - //rotary_switch_state = Automatic - profilu pre nody sa vykonavaju - //ak je spracovany, a automatic - tak ho zapnem - - if(rotary_switch_state == "Automatic") - { - //prejs nodes - nacitame vsetky nody z pre danu liniu - for (let k in nodesData) { - //node:number|tbname:string|line:number|profile:string|processed:boolean - - //potrebujem nody k danej linii - if(record.line == nodesData[k].line) - { - let node = nodesData[k].node; - let processed = nodesData[k].processed; - - if(!processed) - { - processNodeProfile(node); - } - else{ - //logger.debug( `node ${node} profile for line ${nodesData[k].line} was already processed`); - } - } - } - - } - else - { - logger.debug("unable to process profile - rotary_switch_state is", rotary_switch_state); - } - - } - } - - relaysData = {...relaysDataTmp}; - - resolve("OK"); - - }); - }); - //resolve(stdout); - //reject(error); - - }) + + for (let k in nodesData) { + //node:number|tbname:string|line:number|profile:string|processed:boolean + + if(line == nodesData[k].line) + { + let node = nodesData[k].node; + let processed = nodesData[k].processed; + + if(!processed) + { + processNodeProfile(node); + } + else + { + logger.debug( `Node ${node} profile for line ${nodesData[k].line} was already processed`); + } + } + } } + + async function loadRelaysData(line) { + + relaysData = await promisifyBuilder(dbRelays.find()); + relaysData = makeMapFromDbResult(relaysData, "line"); + + for (const [key, value] of Object.entries(relaysData)) + { + if(key == "0") continue; + if(line != undefined) + { + //ak sa jedna o update profilu linie - pozor di_co_controller posiela command pre loadRelaysData + if(line != value.line ) continue; + } + + if(value.contactor == 1) processAllNodeProfilesOnLine(value.line); + } + +// console.log('.........', relaysData); + } + + function reportOnlineNodeStatus(line) { - //broadcast cas, o 1-2 sek neskor - status, brightness - + //broadcast cas, o 3 sek neskor - status, brightness //Po zapnutí línie broadcastovo aktualizovať predtým čas. logger.debug("--->reportOnlineNodeStatus for line", line); //return; + + //run broadcast //Actual time + addMinutesToTimestamp = 0; + let params = {}; + + let recipient = 2;//2 broadcast, address = 0 + let address = 0;//0 + if(recipient === 2) { - //run broadcast //Actual time - addMinutesToTimestamp = 0; - - let params = {}; - - let recipient = 2;//2 broadcast, address = 0 - let address = 0;//0 - if(recipient === 2) - { - address = 0xffffffff;//Broadcast - } - - var d = new Date(); - let hours = d.getHours(); - let minutes = d.getMinutes(); - let seconds = d.getSeconds(); - - params.address = address;//broadcast - params.byte1 = hours;//h - params.byte2 = minutes;//m - params.byte3 = seconds;//s - params.byte4 = 0; - params.recipient = recipient; - params.register = 87;//Actual time - params.rw = 1;//write - - let timestampStart = priorityTypes.node_broadcast; - - //other values - params.type = "cmd"; - //params.tbname = tbname; - params.timestamp = timestampStart; - params.addMinutesToTimestamp = addMinutesToTimestamp; - params.info = "run broadcast: Actual time"; - - tasks.push(params); - - let sec = 3; - setTimeout(function(){ - //Po zapnutí línie - spraviť hromadný refresh stavu práve zapnutých svietidiel - - for (let k in nodesData) { - - //potrebujem nody k danej linii - if(line == nodesData[k].line || line == undefined) - { - let tbname = nodesData[k].tbname; - let node = nodesData[k].node; - - //prud, vykon - current, input power pre liniu pre vsetky nody - - //a pridame aj vyreportovanie dimmingu - { - let params = getParams(priorityTypes.high_priority); - - params.type = "cmd"; - params.tbname = tbname; - params.address = node; - params.register = 1;//dimming - params.recipient = 1;//slave - params.rw = 0;//read - params.timestamp = priorityTypes.high_priority; - params.info = 'read dimming / brightness (after set dimming from platform)'; - //params.debug = true; - - tasks.push(params); - } - - //Prúd - { - let params = getParams(priorityTypes.high_priority); - - params.type = "cmd"; - params.tbname = tbname; - params.address = node; - params.register = 75;//prud - params.recipient = 1;//slave - params.rw = 0;//read - params.timestamp = priorityTypes.high_priority; - params.info = 'read current (after set dimming from platform)'; - //params.debug = true; - - tasks.push(params); - } - - //výkon - { - let params = getParams(priorityTypes.high_priority); - - params.type = "cmd"; - params.tbname = tbname; - params.address = node; - params.register = 76;//výkon - params.recipient = 1;//slave - params.rw = 0;//read - params.timestamp = priorityTypes.high_priority; - params.info = 'read power (after set dimming from platform)'; - //params.debug = true; - - tasks.push(params); - } - - } - } - - },sec*1000); - + address = 0xffffffff;//Broadcast } + var d = new Date(); + let hours = d.getHours(); + let minutes = d.getMinutes(); + let seconds = d.getSeconds(); + + params.address = address;//broadcast + params.byte1 = hours;//h + params.byte2 = minutes;//m + params.byte3 = seconds;//s + params.byte4 = 0; + params.recipient = recipient; + params.register = 87;//Actual time + params.rw = 1;//write + + let timestampStart = PRIORITY_TYPES.node_broadcast; + + //other values + params.type = "cmd"; + //params.tbname = tbname; + params.timestamp = timestampStart; + params.addMinutesToTimestamp = addMinutesToTimestamp; + params.info = "run broadcast: Actual time"; + + tasks.push(params); + + let sec = 3; + setTimeout(function(){ + //Po zapnutí línie - spraviť hromadný refresh stavu práve zapnutých svietidiel + + for (let k in nodesData) { + + //potrebujem nody k danej linii + if(line == nodesData[k].line || line == undefined) + { + let tbname = nodesData[k].tbname; + let node = nodesData[k].node; + + //prud, vykon - current, input power pre liniu pre vsetky nody + + //a pridame aj vyreportovanie dimmingu + { + let params = getParams(PRIORITY_TYPES.high_priority); + + params.type = "cmd"; + params.tbname = tbname; + params.address = node; + params.register = 1;//dimming + params.recipient = 1;//slave + params.rw = 0;//read + params.timestamp = PRIORITY_TYPES.high_priority; + params.info = 'read dimming'; + //params.debug = true; + + tasks.push(params); + } + + //Prúd + { + let params = getParams(PRIORITY_TYPES.high_priority); + + params.type = "cmd"; + params.tbname = tbname; + params.address = node; + params.register = 75;//prud + params.recipient = 1;//slave + params.rw = 0;//read + params.timestamp = PRIORITY_TYPES.high_priority; + params.info = 'read current'; + //params.debug = true; + + tasks.push(params); + } + + //výkon + { + let params = getParams(PRIORITY_TYPES.high_priority); + + params.type = "cmd"; + params.tbname = tbname; + params.address = node; + params.register = 76;//výkon + params.recipient = 1;//slave + params.rw = 0;//read + params.timestamp = PRIORITY_TYPES.high_priority; + params.info = 'read power'; + //params.debug = true; + + tasks.push(params); + } + } + } + },sec*1000); } + function reportOfflineNodeStatus(line) { - logger.debug("--->reportOfflineNodeStatus for line", line); values = {}; @@ -970,7 +910,7 @@ exports.install = function(instance) { ] } - //instance.send(instanceSendTo.tb, dataToTb); + //instance.send(SEND_TO.tb, dataToTb); tbHandler.sendToTb(dataToTb, instance); } } @@ -982,40 +922,35 @@ exports.install = function(instance) { //values["status"] = "OFFLINE";//prúd } - let now = new Date(); - console.log("CMD Manager installed", now.toLocaleString("sk-SK")); function turnOnLine(line, info) { let obj = { - line: line, - command: "turnOn", - info: info + line: line, + command: "turnOn", + info: info }; logger.debug("linia", line, obj); - - instance.send(instanceSendTo.dido_controller, obj); + instance.send(SEND_TO.dido_controller, obj); } function turnOffLine(line, info) { let obj = { - line: line, - command: "turnOff", - info: info - }; + line: line, + command: "turnOff", + info: info + }; - logger.debug("linia", line, obj); - - instance.send(instanceSendTo.dido_controller, obj); + logger.debug("linia", line, obj); + instance.send(SEND_TO.dido_controller, obj); } + function detectIfResponseIsValid(bytes) { - //ak sa odpoved zacina 0 - je to v poriadku, inak je NOK - let type = "RESPONSE"; if(bytes[4] == 0) type = "RESPONSE"; else if(bytes[4] == 1) type = "ERROR"; @@ -1033,7 +968,7 @@ exports.install = function(instance) { //CRC_ERROR message = "NOK"; error = "CRC_ERROR c1"; - instance.send(instanceSendTo.debug, "CRC_ERROR c1"); + instance.send(SEND_TO.debug, "CRC_ERROR c1"); } if(c2 != bytes[10]) @@ -1041,16 +976,16 @@ exports.install = function(instance) { //CRC_ERROR message = "NOK"; error = "CRC_ERROR c2"; - instance.send(instanceSendTo.debug, "CRC_ERROR c2"); + instance.send(SEND_TO.debug, "CRC_ERROR c2"); } //crc error if(type != "RESPONSE") { - instance.send(instanceSendTo.debug, bytes); - instance.send(instanceSendTo.debug, "RESPONSE " + type + " - " + bytes[4]); + instance.send(SEND_TO.debug, bytes); + instance.send(SEND_TO.debug, "RESPONSE " + type + " - " + bytes[4]); - //logger.debug(instanceSendTo.debug, "RESPONSE " + type + " - " + bytes[4], bytes); + //logger.debug(SEND_TO.debug, "RESPONSE " + type + " - " + bytes[4], bytes); error = "type is: " + type; @@ -1060,16 +995,16 @@ exports.install = function(instance) { return {message: message, type: type, error: error}; } + + //BUILD TASKS// function buildTasks(params) { - //report FLOW.OMS_edge_fw_version as fw_version //report date as startdate monitor.info("buildTasks - params", params); let processLine; //defined line - let init = false; let processLineProfiles = true; let processBroadcast = true; @@ -1079,7 +1014,6 @@ exports.install = function(instance) { { init = true; tasks = []; - logger.debug("-->buildTasks clear tasks"); } else @@ -1103,12 +1037,12 @@ exports.install = function(instance) { let keys = Object.keys(relaysData); for(let i = 0; i < keys.length; i++) { - let line = keys[i];//line is turned off by default + let line = parseInt(keys[i]); //line is turned off by default let profilestr = relaysData[line].profile; //Reset linii let resetLine = false; - if(FLOW.OMS_rvo_name == "Kovalov RVO 2" && line != '0' && init == true) resetLine = true; + if(FLOW.OMS_rvo_name == "Kovalov RVO 2" && line != 0 && init == true) resetLine = true; if(resetLine) { @@ -1116,18 +1050,18 @@ exports.install = function(instance) { Takže v Koválove sú nastavené offesty pre dusk a dawn nasledovne: - DUSK: offset +20 minút – teda napr. namiesto 17:00 bude 17:20 a reštart by sa robil v čase 17:19, teda o minútu skôr. Tak aby keď budeš robiť zapnutie o 17:20 tak na RVO1 sa svietidlá zapnú v rovnakom čase. Teda: vypnutie v čase DUSK_TIME + 19 minút, zapnutie v čase DUSK_TIME + 20 minút + DUSK: offset +20 minút – teda napr. namiesto 17:00 bude 17:20 a reštart by sa robil v čase 17:19, teda o minútu skôr. Tak aby keď budeš robiť zapnutie o 17:20 tak na RVO1 sa svietidlá zapnú v rovnakom čase. + Teda: vypnutie v čase DUSK_TIME + 19 minút, zapnutie v čase DUSK_TIME + 20 minút DAWN: offset -30 minút – teda napr. namiesto 7:00 bude 6:30 a reštart by sa robil v čase 6:30, tak aby sa svietidlá zhasli rovnako s RVO1. Zapnutie by bolo 6:31. - - Teda: vypnutie v čase DAWN_TIME -30 minút, zapnutie v čase DAWN_TIME -29 minút + Teda: vypnutie v čase DAWN_TIME -30 minút, zapnutie v čase DAWN_TIME -29 minút Vždy po reštarte asi 30 sekúnd po zapnutí treba poslať aktuálny čas na nody. */ - //function calculateDuskDown(date, line, duskOffset = 0, dawnOffset = 0) + //function calculateDuskDawn(date, line, duskOffset = 0, dawnOffset = 0) let duskOffset = 20; let dawnOffset = -30; - let sunCalcResult = calculateDuskDown(new Date(), undefined, duskOffset, dawnOffset); + let sunCalcResult = calculateDuskDawn(new Date(), undefined, duskOffset, dawnOffset); console.log(sunCalcResult); monitor.info("--> dusk - dawn", sunCalcResult); @@ -1141,13 +1075,11 @@ exports.install = function(instance) { //vypneme liniu a o minitu zapneme { let value = 0;//vypneme liniu - let isDusk = true; - let isDawn = false; let dusk_time = sunCalcResult.dusk_time; if(dusk_time < now.getTime()) dusk_time = dusk_time + 24*60*60*1000;//1den - let params = getParams(priorityTypes.relay_profile); + let params = getParams(PRIORITY_TYPES.relay_profile); params.type = "relay"; params.line = line; params.value = value; @@ -1160,8 +1092,7 @@ exports.install = function(instance) { params.addMinutesToTimestamp = 24*60; //this will be recalculated - params.isDusk = isDusk; - params.isDawn = isDawn; + params.timePointName = "dusk" if(params.value == 0) params.info = "reset - KOVALOV - force turn off line: " + line; else if(params.value == 1) params.info = "reset - KOVALOV - force turn on line: " + line; @@ -1177,13 +1108,11 @@ exports.install = function(instance) { //a o minutu zapneme { let value = 1;//zapneme liniu - let isDusk = true; - let isDawn = false; let dusk_time = sunCalcResult.dusk_time + 60*1000;//o minutu neskor po vypnuti zapneme if(dusk_time < now.getTime()) dusk_time = dusk_time + 24*60*60*1000;//1den - let params = getParams(priorityTypes.relay_profile); + let params = getParams(PRIORITY_TYPES.relay_profile); params.type = "relay"; params.line = line; params.value = value; @@ -1196,8 +1125,7 @@ exports.install = function(instance) { params.addMinutesToTimestamp = 24*60; //this will be recalculated - params.isDusk = isDusk; - params.isDawn = isDawn; + params.timePointName = "dusk" if(params.value == 0) params.info = "reset - KOVALOV - force turn off line: " + line; else if(params.value == 1) params.info = "reset - KOVALOV - force turn on line: " + line; @@ -1218,13 +1146,11 @@ exports.install = function(instance) { //vypneme liniu a o minitu zapneme { let value = 0;//vypneme liniu - let isDusk = false; - let isDawn = true; let dawn_time = sunCalcResult.dawn_time; if(dawn_time < now.getTime()) dawn_time = dawn_time + 24*60*60*1000;//1den - let params = getParams(priorityTypes.relay_profile); + let params = getParams(PRIORITY_TYPES.relay_profile); params.type = "relay"; params.line = line; params.value = value; @@ -1238,8 +1164,7 @@ exports.install = function(instance) { params.addMinutesToTimestamp = 24*60; //this will be recalculated - params.isDusk = isDusk; - params.isDawn = isDawn; + params.timePointName = "dawn"; if(params.value == 0) params.info = "reset - KOVALOV - force turn off line: " + line; else if(params.value == 1) params.info = "reset - KOVALOV - force turn on line: " + line; @@ -1255,13 +1180,11 @@ exports.install = function(instance) { //a o minitu zapneme { let value = 1;//vypneme liniu - let isDusk = false; - let isDawn = true; let dawn_time = sunCalcResult.dawn_time + 1000*60;//o minutu neskor po vypnuti zapneme if(dawn_time < now.getTime()) dawn_time = dawn_time + 24*60*60*1000;//1den - let params = getParams(priorityTypes.relay_profile); + let params = getParams(PRIORITY_TYPES.relay_profile); params.type = "relay"; params.line = line; params.value = value; @@ -1275,8 +1198,7 @@ exports.install = function(instance) { params.addMinutesToTimestamp = 24*60; //this will be recalculated - params.isDusk = isDusk; - params.isDawn = isDawn; + params.timePointName = "dawn"; if(params.value == 0) params.info = "reset - KOVALOV - force turn off line: " + line; else if(params.value == 1) params.info = "reset - KOVALOV - force turn on line: " + line; @@ -1300,11 +1222,11 @@ exports.install = function(instance) { if(processLine != line) continue; } - try{ + try { - if(profilestr === "") throw ("profile is not defined"); + if(profilestr === "") throw ("Profile is not defined"); let profile = JSON.parse(profilestr); - if(Object.keys(profile).length === 0) throw ("profile is not defined"); + if(Object.keys(profile).length === 0) throw ("Profile is empty"); monitor.info("buildTasks: profile for line", line); monitor.info("profile:", profile); @@ -1312,52 +1234,61 @@ exports.install = function(instance) { let time_points = profile.time_points; if(time_points == undefined) time_points = profile.intervals; + // add name to regular profile timepoint and delete unused end_time key: + time_points.forEach(point => { + point.name = "profileTimepoint" + delete point.end_time; + }); + //monitor.info("buildTasks: time_points", time_points); let currentValue = 0; - if(time_points.length > 0) currentValue = time_points[ time_points.length - 1].value; + if(time_points.length > 0) currentValue = time_points[time_points.length - 1].value; - //create task for tun on + turn off, calculate dusk/down + /** + * if astro_clock is true, we create timepoints, that switch on/off relays accordingly. + * we need to manage, astro clock timepoints has the greatest priority - normal timepoints will not switch off/on lines before dusk or dawn + * if dawn/dusk_lux_sensor is true, it has higher priority than astro_clock switching + */ if(profile.astro_clock == true) { - //let now = new Date().toLocaleString("en-US", {timeZone: "Europe/Bratislava"}); - let sunCalcResult = calculateDuskDown(new Date(), line); - // monitor.info("dusk and dawn sunCalcResult", line, sunCalcResult); + // if astro clock true, we remove all regular profile points + time_points = []; - //add to timpoints - if(profile.dawn_lux_sensor == false) time_points.push( {"start_time": sunCalcResult["dawn"], "value": 1, "isDawn": true} ); - if(profile.dusk_lux_sensor == false) time_points.push( {"start_time": sunCalcResult["dusk"], "value": 0, "isDusk": true} ); + let sunCalcResult = calculateDuskDawn(new Date(), line); - //aby nam to neostalo svietit + // adding dusk dawn to timpoints + if(profile.dawn_lux_sensor == false) time_points.push({"start_time": sunCalcResult["dawn"], "value": 0, "name":"dawn"}); + if(profile.dusk_lux_sensor == false) time_points.push({"start_time": sunCalcResult["dusk"], "value": 1, "name":"dusk"}); + + //if dusk/dawn is true, lines will switch on/off according to lux_sensor value. In case it fails, we create lux_timepoints, to make sure lines will switch on/off (aby nam to nezostalo svietit) + //force to turn off after timestamp: dawn + dawn_lux_sensor_time_window if(profile.dawn_lux_sensor == true) { - //force to turn off after timestamp: dawn + dawn_lux_sensor_time_window let [ahours, aminutes, aseconds] = sunCalcResult["dawn"].split(':'); - let ad = new Date(); - ad.setHours( parseInt(ahours) ); - ad.setMinutes( parseInt(aminutes) + profile.dawn_lux_sensor_time_window ); + ad.setHours(parseInt(ahours)); + ad.setMinutes(parseInt(aminutes) + profile.dawn_lux_sensor_time_window); ad.setSeconds(0); let strDate = ad.getHours() + ":" + ad.getMinutes(); - time_points.push( {"value": 0, "start_time": strDate} ); + time_points.push({"value": 0, "start_time": strDate, "name": "luxOff"}); } if(profile.dusk_lux_sensor == true) { - //force to turn off after timestamp: dawn + dawn_lux_sensor_time_window let [ahours, aminutes, aseconds] = sunCalcResult["dusk"].split(':'); - let ad = new Date(); - ad.setHours( parseInt(ahours) ); - ad.setMinutes( parseInt(aminutes) + profile.dawn_lux_sensor_time_window ); + ad.setHours(parseInt(ahours)); + ad.setMinutes(parseInt(aminutes) + profile.dusk_lux_sensor_time_window); ad.setSeconds(0); let strDate = ad.getHours() + ":" + ad.getMinutes(); - time_points.push( {"value": 1, "start_time": strDate} ); + time_points.push({"value": 1, "start_time": strDate, "name": "luxOn"}); + //time_points.push({"value": 1, "start_time": "15:19", "name": "luxOn"}); //testing } } @@ -1380,76 +1311,57 @@ exports.install = function(instance) { return ad.getTime() - bd.getTime(); }); + console.log("line timepoints ........", time_points); + monitor.info("-->comming events turn on/off lines:"); for(let t = 0; t < time_points.length; t++) { let start_time = new Date(); + let [hours, minutes, seconds] = time_points[t].start_time.split(':'); - let isDusk = false; - let isDawn = false; - if(time_points[t].hasOwnProperty("isDusk")) isDusk = time_points[t].isDusk; - if(time_points[t].hasOwnProperty("isDawn")) isDawn = time_points[t].isDawn; - - if(isDusk) time_points[t].value = 1;//sumrak - zapneme svetlo - if(isDawn) time_points[t].value = 0;//vychod - vypneme svetlo - - if(time_points[t].hasOwnProperty("start_time")) - { - let [hours, minutes, seconds] = time_points[t].start_time.split(':'); - - start_time.setHours( parseInt(hours) ); - start_time.setMinutes( parseInt(minutes) ); - start_time.setSeconds(0); - } + start_time.setHours( parseInt(hours) ); + start_time.setMinutes( parseInt(minutes) ); + start_time.setSeconds(0); //task is the past if(now.getTime() > start_time.getTime()) { currentValue = time_points[t].value; - //je v minulosti, pridame 24h + //timepoint is in past, we add 24 hours start_time.setDate(start_time.getDate() + 1); } - let params = getParams(priorityTypes.relay_profile); + let params = getParams(PRIORITY_TYPES.relay_profile); params.type = "relay"; - params.line = line; + params.line = parseInt(line); params.value = time_points[t].value; params.tbname = relaysData[line].tbname; params.timestamp = start_time.getTime(); params.addMinutesToTimestamp = 0; - //once a day - if(!isDusk && !isDawn) params.addMinutesToTimestamp = 24*60; + // it timepoints are not calculated (dawn, dusk, lux_timepoint), but static points in line profile, we just repeat the task every day + if(time_points[t].name == "profileTimepoint") params.addMinutesToTimestamp = 24*60; - //inak sa cas vypocita dynamicky + //astro timepoints will be recalculated dynamically: + params.timePointName = time_points[t].name; - //this will be recalculated - params.isDusk = isDusk; - params.isDawn = isDawn; - - //if(profile.astro_clock == true && profile.dusk_lux_sensor == false && profile.dawn_lux_sensor == false) - - if(params.value == 0) + // if astro timepoint, we save time window: + if(['luxOn', 'luxOff', 'dusk','dawn'].includes(params.timePointName)) { - params.info = "turn off line: " + line; - if(isDusk) params.info = "dusk: turn off line: " + line; - if(isDawn) params.info = "dawn: turn off line: " + line; - } - else if(params.value == 1) - { - params.info = "turn on line: " + line; - if(isDusk) params.info = "dusk: turn on line: " + line; - if(isDawn) params.info = "dawn: turn on line: " + line; + params.dawn_lux_sensor_time_window = profile.dawn_lux_sensor_time_window; + params.dusk_lux_sensor_time_window = profile.dusk_lux_sensor_time_window; } + if(params.value == 0) params.info = `${params.timePointName}: turn off line: ` + line; + else if(params.value == 1) params.info = `${params.timePointName}: turn on line: ` + line; + params.debug = true; //turn on/off line tasks.push(params); - monitor.info(params.info, start_time); } @@ -1457,15 +1369,13 @@ exports.install = function(instance) { monitor.info("-->time_points final", line, time_points); //ensure to turn on/off according to calculated value - let params = getParams(priorityTypes.terminal); + let params = getParams(PRIORITY_TYPES.terminal); params.type = "relay"; params.line = parseInt(line); params.tbname = relaysData[line].tbname; params.value = currentValue; - params.isDusk = false; - params.isDawn = false; - params.timestamp = priorityTypes.terminal; + params.timestamp = PRIORITY_TYPES.terminal; params.addMinutesToTimestamp = 0; params.debug = true; @@ -1478,7 +1388,6 @@ exports.install = function(instance) { tasks.push(params); - } catch (error) { if(profilestr !=="" ) { @@ -1509,7 +1418,7 @@ exports.install = function(instance) { // addMinutesToTimestamp = 60*5; addMinutesToTimestamp = 60 * 3; //kazde 3 hodiny zisti novy dusk - let params = getParams(priorityTypes.node_broadcast); + let params = getParams(PRIORITY_TYPES.node_broadcast); let recipient = 2;//2 broadcast, address = 0 let address = 0;//0 @@ -1518,7 +1427,7 @@ exports.install = function(instance) { address = 0xffffffff;//Broadcast } - let sunCalcResult = calculateDuskDown(); + let sunCalcResult = calculateDuskDawn(); let dusk_hours = sunCalcResult["dusk_hours"]; let dusk_minutes = sunCalcResult["dusk_minutes"]; @@ -1531,7 +1440,7 @@ exports.install = function(instance) { params.register = 6;//Time of dusk - Reg 6 params.rw = 1;//write - let timestampStart = priorityTypes.node_broadcast; + let timestampStart = PRIORITY_TYPES.node_broadcast; //other values params.type = "cmd"; @@ -1550,7 +1459,7 @@ exports.install = function(instance) { // addMinutesToTimestamp = 60*5; addMinutesToTimestamp = 60 * 3; //kazde 3 hodiny zisti novy dawn - let params = getParams(priorityTypes.node_broadcast); + let params = getParams(PRIORITY_TYPES.node_broadcast); let recipient = 2;//2 broadcast, address = 0 let address = 0;//0 @@ -1559,7 +1468,7 @@ exports.install = function(instance) { address = 0xffffffff;//Broadcast } - let sunCalcResult = calculateDuskDown(); + let sunCalcResult = calculateDuskDawn(); let dawn_hours = sunCalcResult["dawn_hours"]; let dawn_minutes = sunCalcResult["dawn_minutes"]; @@ -1572,7 +1481,7 @@ exports.install = function(instance) { params.register = 7;//Time of dawn - Reg 6 params.rw = 1;//write - let timestampStart = priorityTypes.node_broadcast; + let timestampStart = PRIORITY_TYPES.node_broadcast; //other values params.type = "cmd"; @@ -1589,7 +1498,7 @@ exports.install = function(instance) { //run broadcast //Actual time addMinutesToTimestamp = 5; - let params = getParams(priorityTypes.node_broadcast); + let params = getParams(PRIORITY_TYPES.node_broadcast); let recipient = 2;//2 broadcast, address = 0 let address = 0;//0 @@ -1612,7 +1521,7 @@ exports.install = function(instance) { params.register = 87;//Actual time params.rw = 1;//write - let timestampStart = priorityTypes.node_broadcast; + let timestampStart = PRIORITY_TYPES.node_broadcast; //other values params.type = "cmd"; @@ -1631,7 +1540,7 @@ exports.install = function(instance) { //Do tohto registra posiela riadiaca jednotka hodnotu intenzity osvetlenia ktorú meria jej senzor pre potreby riadenia časov súmraku resp. úsvitu podľa intenzity osvetlenia. //Byty 0 (LSB) a 1 obsahujú 16 bitový integer s luxami. - let params = getParams(priorityTypes.node_broadcast); + let params = getParams(PRIORITY_TYPES.node_broadcast); addMinutesToTimestamp = 15; @@ -1646,7 +1555,7 @@ exports.install = function(instance) { //16 bitový integer s luxami params.byte3 = lux_sensor; params.byte4 = lux_sensor; - params.timestamp = priorityTypes.node_broadcast; + params.timestamp = PRIORITY_TYPES.node_broadcast; params.addMinutesToTimestamp = addMinutesToTimestamp; params.info = "run broadcast: Actual Lux level from cabinet"; params.register = 95;//Actual Lux level from cabinet @@ -1671,7 +1580,7 @@ exports.install = function(instance) { { register = listOfCommands[i]; - let params = getParams(priorityTypes.node_cmd); + let params = getParams(PRIORITY_TYPES.node_cmd); //core rpc values params.address = address; @@ -1685,7 +1594,7 @@ exports.install = function(instance) { let addMinutesToTimestamp = priorities[register]; - let timestampStart = priorityTypes.node_cmd; //run imediatelly in function runTasks + let timestampStart = PRIORITY_TYPES.node_cmd; //run imediatelly in function runTasks if(addMinutesToTimestamp > 1) { timestampStart = timestampStart + addMinutesToTimestamp * 60000; @@ -1724,12 +1633,12 @@ exports.install = function(instance) { //Adresa mastera je 0. V prípade že kedykoľvek nastane situácia že Master Node neodpovedá (napríklad pri vyčítaní telemetrie z nodu nevráti žiadne dáta), //tak treba vyreportovať string "NOK". { - let params = getParams(priorityTypes.fw_detection); + let params = getParams(PRIORITY_TYPES.fw_detection); params.type = "cmd"; params.register = 4; params.address = 0; - let timestampStart = priorityTypes.fw_detection; + let timestampStart = PRIORITY_TYPES.fw_detection; params.timestamp = timestampStart; params.addMinutesToTimestamp = 5; params.tbname = FLOW.OMS_edgeName; @@ -1743,10 +1652,10 @@ exports.install = function(instance) { //kazdu hodinu skontrolovat nastavenie profilov { - let params = getParams(priorityTypes.fw_detection); + let params = getParams(PRIORITY_TYPES.fw_detection); params.type = "process_profiles"; - let timestampStart = priorityTypes.relay_profile; + let timestampStart = PRIORITY_TYPES.relay_profile; params.timestamp = timestampStart; params.addMinutesToTimestamp = 60;//60 = every hour params.info = "detekcia nespracovaných profilov linie a nodov"; @@ -1758,10 +1667,10 @@ exports.install = function(instance) { { //edge_date_time - let params = getParams(priorityTypes.node_cmd); + let params = getParams(PRIORITY_TYPES.node_cmd); params.type = "edge_date_time"; - let timestampStart = priorityTypes.node_cmd; + let timestampStart = PRIORITY_TYPES.node_cmd; params.timestamp = timestampStart; params.addMinutesToTimestamp = 1; params.tbname = FLOW.OMS_edgeName; @@ -1773,10 +1682,10 @@ exports.install = function(instance) { { //edge_date_time - let params = getParams(priorityTypes.node_cmd); + let params = getParams(PRIORITY_TYPES.node_cmd); params.type = "number_of_luminaires"; - let timestampStart = priorityTypes.node_cmd + 1; + let timestampStart = PRIORITY_TYPES.node_cmd + 1; params.timestamp = timestampStart; params.addMinutesToTimestamp = 1; params.tbname = FLOW.OMS_edgeName; @@ -1788,6 +1697,7 @@ exports.install = function(instance) { monitor.info("tasks created:", tasks.length); } + function turnOnOffLinesAccordingToLuxSensor(lux_sensor_value) { //let dusk_hours = sunCalcResult["dusk_hours"]; @@ -1832,7 +1742,7 @@ exports.install = function(instance) { if(profile.astro_clock == true) { - let sunCalcResult = calculateDuskDown(now, line); + let sunCalcResult = calculateDuskDawn(now, line); //dawn: usvit/vychod - lux je nad hranicou - vypnem //dusk: zapad pod hranicou - zapnem @@ -1905,14 +1815,6 @@ exports.install = function(instance) { } } - let sunCalcResult = calculateDuskDown(); - - let reportDuskDawn = { - dusk_time: sunCalcResult.dusk_time, - dawn_time: sunCalcResult.dawn_time, - dusk_time_reported: undefined, - dawn_time_reported: undefined - }; async function upateNodeStatus(node, status) { @@ -1937,10 +1839,10 @@ exports.install = function(instance) { }); } } - + async function runTasks() { - + clearInterval(interval); let currentTimestamp = Date.now(); @@ -1954,7 +1856,7 @@ exports.install = function(instance) { //reportovali sme? if(reportDuskDawn.dusk_time_reported != sunCalcResult.dusk_time) { - sendNotification("CMD Manager: calculated Time of dusk", FLOW.OMS_edgeName, "dusk_has_occured", {value: sunCalcResult["dusk"]}, "", instanceSendTo.tb, instance); + sendNotification("CMD Manager: calculated Time of dusk", FLOW.OMS_edgeName, "dusk_has_occured", {value: sunCalcResult["dusk"]}, "", SEND_TO.tb, instance); reportDuskDawn.dusk_time_reported = sunCalcResult.dusk_time; } } @@ -1962,7 +1864,7 @@ exports.install = function(instance) { var nextDay = new Date(); nextDay.setDate(nextDay.getDate() + 1); - sunCalcResult = calculateDuskDown(nextDay); + sunCalcResult = calculateDuskDawn(nextDay); reportDuskDawn.dusk_time = sunCalcResult.dusk_time; } @@ -1974,7 +1876,7 @@ exports.install = function(instance) { //reportovali sme? if(reportDuskDawn.dawn_time_reported != sunCalcResult.dawn_time) { - sendNotification("CMD Manager: calculated Time of dawn", FLOW.OMS_edgeName, "dawn_has_occured", {value: sunCalcResult["dawn"]}, "", instanceSendTo.tb, instance); + sendNotification("CMD Manager: calculated Time of dawn", FLOW.OMS_edgeName, "dawn_has_occured", {value: sunCalcResult["dawn"]}, "", SEND_TO.tb, instance); reportDuskDawn.dawn_time_reported = sunCalcResult.dawn_time; } } @@ -1982,39 +1884,32 @@ exports.install = function(instance) { var nextDay = new Date(); nextDay.setDate(nextDay.getDate() + 1); - sunCalcResult = calculateDuskDown(nextDay); + sunCalcResult = calculateDuskDawn(nextDay); reportDuskDawn.dawn_time = sunCalcResult.dawn_time; } //-------------------------------------------------------- - //sort tasks - //tasks.sort((a,b) => a.timestamp - b.timestamp ); - + //sort tasks based on timestamp tasks.sort(function (a, b) { - if(a.timestamp <= currentTimestamp && b.timestamp <= currentTimestamp) { return a.priority - b.priority; } - return a.timestamp - b.timestamp; }); if(tasks.length == 0 ) { - instance.send(instanceSendTo.debug, "no tasks created"); - interval = setInterval(runTasks, longInterval); - + instance.send(SEND_TO.debug, "no tasks created"); + interval = setInterval(runTasks, LONG_INTERVAL); return; } if(!rsPort.isOpen) { - instance.send(instanceSendTo.debug, "!rsPort.isOpen"); + instance.send(SEND_TO.debug, "!rsPort.isOpen"); //await rsPort.open(); - - //continue } let currentTask = tasks[0]; @@ -2028,47 +1923,36 @@ exports.install = function(instance) { { let params = {...tasks[0]}; - if(FLOW.OMS_maintenance_mode) + //allow terminal commands + if(FLOW.OMS_maintenance_mode && params.type !== "cmd-terminal") { - - //allow terminal commands - if(params.type == "cmd-terminal"); - else - { - interval = setInterval(runTasks, longInterval); - return; - } + interval = setInterval(runTasks, LONG_INTERVAL); + return; } let type = params.type; let tbname = params.tbname; let nodeKey = params.address; - let useProfile = params.useProfile; - if(useProfile === undefined) useProfile = true; - let duskOffset = params.duskOffset; - let dawnOffset = params.dawnOffset; - let line = null; + //rpc related if(nodesData[nodeKey] !== undefined) line = nodesData[nodeKey].line; if(params.line !== undefined) line = params.line; let repeatTask = false; - if(params.addMinutesToTimestamp > 0) repeatTask = true; - if(params.isDawn || params.isDusk) repeatTask = true; + if(params.addMinutesToTimestamp > 0 || params.timePointName) repeatTask = true; if(repeatTask) { - if(type == "cmd") + if(type === "cmd") { //set next start time automatically tasks[0].timestamp = currentTimestamp + tasks[0].addMinutesToTimestamp * 60000; - } + } } else { - //terminal data... tasks.shift(); } @@ -2114,17 +1998,16 @@ exports.install = function(instance) { ] } - //instance.send(instanceSendTo.tb, dataToTb); + //instance.send(SEND_TO.tb, dataToTb); tbHandler.sendToTb(dataToTb, instance); - interval = setInterval(runTasks, shortIterval); + interval = setInterval(runTasks, SHORT_INTERVAL); return; } } - //kontrola nespracovanych profilov nodov if(type == "process_profiles") { @@ -2160,7 +2043,7 @@ exports.install = function(instance) { //vsetky linie kt. su zapnute, a spracuju sa nespracovane profily nodov loadRelaysData(); - interval = setInterval(runTasks, shortIterval); + interval = setInterval(runTasks, SHORT_INTERVAL); return; } @@ -2186,10 +2069,10 @@ exports.install = function(instance) { tasks[0].timestamp = currentTimestamp + tasks[0].addMinutesToTimestamp * 60000; - //instance.send(instanceSendTo.tb, dataToTb); + //instance.send(SEND_TO.tb, dataToTb); tbHandler.sendToTb(dataToTb, instance); - interval = setInterval(runTasks, shortIterval); + interval = setInterval(runTasks, SHORT_INTERVAL); return; } @@ -2198,56 +2081,69 @@ exports.install = function(instance) { if(type == "relay") { - //ak je dusk, alebo dawn, vypocitame si dynamicky nove values - if(params.isDawn || params.isDusk) + const timePointName = params.timePointName; + const value = params.value; + + // used just in Kovalov RVO 2 + const useProfile = params.useProfile; + + let date = new Date(); + date.setDate(date.getDate() + 1);//next day + + let sunCalcResult; + if(!useProfile) { - let date = new Date(); - date.setDate(date.getDate() + 1);//next day - - let sunCalcResult; - if(useProfile) sunCalcResult = calculateDuskDown(date, params.line); - else - { - //do not use profile, line is there for undefined - sunCalcResult = calculateDuskDown(date, undefined, duskOffset, dawnOffset); - } - - if(params.isDawn) - { - tasks[0].timestamp = sunCalcResult.dawn_time; - } - - if(params.isDusk) - { - tasks[0].timestamp = sunCalcResult.dusk_time; - } + sunCalcResult = calculateDuskDawn(date, params.line); } else { - if(tasks[0].addMinutesToTimestamp == 0);// tasks.shift(); - else tasks[0].timestamp = currentTimestamp + tasks[0].addMinutesToTimestamp * 60000; + //do not use profile, line is there for undefined + sunCalcResult = calculateDuskDawn(date, undefined, params.duskOffset, params.dawnOffset); } + if(timePointName == "dawn") + { + tasks[0].timestamp = sunCalcResult.dawn_time; + } + else if(timePointName == "dusk") + { + tasks[0].timestamp = sunCalcResult.dusk_time; + } + else if(timePointName == "luxOn") + { + tasks[0].timestamp = sunCalcResult.dusk_time + params.dusk_lux_sensor_time_window * 60000; + } + else if(timePointName == "luxOff") + { + tasks[0].timestamp = sunCalcResult.dawn_time + params.dawn_lux_sensor_time_window * 60000; + } + else if(timePointName == "profileTimepoint") + { + tasks[0].timestamp = currentTimestamp + tasks[0].addMinutesToTimestamp * 60000; + } + + //monitor.info("new relay timepoint sunCalcResult ,,,,,,,,,,", sunCalcResult); + let info; - if(useProfile) info = "aplikovaný bod profilu"; - else info = params.info; + if(!useProfile) info = "aplikovaný bod profilu"; + else info = params.info; //kovalov rvo params.info let message = ""; - if(params.value == 1) + if(value == 1) { turnOnLine(params.line, info); message = "on"; } - else if(params.value == 0) + else if(value == 0) { turnOffLine(params.line, info); message = "off"; } - //sendNotification("CMD Manager: process cmd", relaysData[0].tbname, ERRWEIGHT.INFO, "aplikovaný bod profilu línie " + params.line + " - stav: " + message, "", instanceSendTo.tb, instance, null ); - if(useProfile) sendNotification("CMD Manager: process cmd", FLOW.OMS_edgeName, "switching_profile_point_applied_to_line", {line: params.line, value: message}, "", instanceSendTo.tb, instance ); + //sendNotification("CMD Manager: process cmd", relaysData[0].tbname, ERRWEIGHT.INFO, "aplikovaný bod profilu línie " + params.line + " - stav: " + message, "", SEND_TO.tb, instance, null ); + if(!useProfile) sendNotification("CMD Manager: process cmd", FLOW.OMS_edgeName, "switching_profile_point_applied_to_line", {line: params.line, value: message}, "", SEND_TO.tb, instance ); - interval = setInterval(runTasks, shortIterval); + interval = setInterval(runTasks, SHORT_INTERVAL); return; } @@ -2285,11 +2181,11 @@ exports.install = function(instance) { if(!disconnectedReport[tbname]) { - //instance.send(instanceSendTo.tb, dataToTb); + //instance.send(SEND_TO.tb, dataToTb); tbHandler.sendToTb(dataToTb, instance); } - interval = setInterval(runTasks, shortIterval); + interval = setInterval(runTasks, SHORT_INTERVAL); return; } @@ -2310,10 +2206,9 @@ exports.install = function(instance) { if(stop) { - interval = setInterval(runTasks, longInterval); + interval = setInterval(runTasks, LONG_INTERVAL); return; } - } let relayStatus = 1; @@ -2341,17 +2236,16 @@ exports.install = function(instance) { ] } - //instance.send(instanceSendTo.tb, dataToTb); + //instance.send(SEND_TO.tb, dataToTb); tbHandler.sendToTb(dataToTb, instance); - interval = setInterval(runTasks, shortIterval); - + interval = setInterval(runTasks, SHORT_INTERVAL); return; } if(!rsPort.isOpen) { - interval = setInterval(runTasks, longInterval); + interval = setInterval(runTasks, LONG_INTERVAL); return; } @@ -2370,15 +2264,14 @@ exports.install = function(instance) { params.byte4 = 0; } - //set dusk/down for broadcast - + //SET DUSK/DAWN FOR BROADCAST //Time of dusk if(params.register == 6 && params.recipient === 2) { if(params.type != "cmd-terminal") { - let sunCalcResult = calculateDuskDown(); + let sunCalcResult = calculateDuskDawn(); let dusk_hours = sunCalcResult["dusk_hours"]; let dusk_minutes = sunCalcResult["dusk_minutes"]; @@ -2389,7 +2282,7 @@ exports.install = function(instance) { //TODO astrohodiny let dusk = "Time of dusk: " + sunCalcResult["dusk"]; - //sendNotification("CMD Manager: calculated Time of dusk", relaysData[0].tbname, ERRWEIGHT.INFO, dusk, "", instanceSendTo.tb, instance, null ); + //sendNotification("CMD Manager: calculated Time of dusk", relaysData[0].tbname, ERRWEIGHT.INFO, dusk, "", SEND_TO.tb, instance, null ); } } @@ -2398,7 +2291,7 @@ exports.install = function(instance) { { if(params.type != "cmd-terminal") { - let sunCalcResult = calculateDuskDown(); + let sunCalcResult = calculateDuskDawn(); let dawn_hours = sunCalcResult["dawn_hours"]; let dawn_minutes = sunCalcResult["dawn_minutes"]; @@ -2409,7 +2302,7 @@ exports.install = function(instance) { //TODO astrohodiny let dawn = "Time of dawn: " + sunCalcResult["dawn"]; - //sendNotification("CMD Manager: calculated Time of dusk", relaysData[0].tbname, ERRWEIGHT.INFO, dawn, "", instanceSendTo.tb, instance, null ); + //sendNotification("CMD Manager: calculated Time of dusk", relaysData[0].tbname, ERRWEIGHT.INFO, dawn, "", SEND_TO.tb, instance, null ); } } @@ -2417,26 +2310,14 @@ exports.install = function(instance) { let register = params.register; - instance.send(instanceSendTo.debug, "address: " + params.address + " register:" + params.register + "type: " + params.type); + instance.send(SEND_TO.debug, "address: " + params.address + " register:" + params.register + "type: " + params.type); var startTime, endTime; startTime = new Date(); let resp = com_generic(params.address, params.recipient, params.rw, params.register, params.name, params.byte1, params.byte2, params.byte3, params.byte4); - let readBytes = 11; - //if broadcast WRITE - do not read - //if(params.recipient == 2) readBytes = 0; - - //WRITE + BROADCAST = readBytes = 0; - // if(params.rw == 1 && params.recipient == 2) readBytes = 0; - - if(params.hasOwnProperty("debug")) - { - //console.log("--->readBytes", readBytes, params); - } - await writeData(rsPort, resp, readBytes).then(function (data) { endTime = new Date(); @@ -2496,7 +2377,7 @@ exports.install = function(instance) { builder.callback(function(err, response) { - sendNotification("CMD Manager: process cmd", FLOW.OMS_edgeName, "dimming_profile_was_successfully_received_by_node", {node: params.address}, "", instanceSendTo.tb, instance ); + sendNotification("CMD Manager: process cmd", FLOW.OMS_edgeName, "dimming_profile_was_successfully_received_by_node", {node: params.address}, "", SEND_TO.tb, instance ); logger.debug( "--> profil úspešne odoslaný na node č. " + params.address); nodesData[params.address].processed = true; @@ -2524,17 +2405,17 @@ exports.install = function(instance) { if(params.address == 0) { - //sendNotification("CMD Manager: process cmd", relaysData[0].tbname, ERRWEIGHT.NOTICE, "Master node is working again", "", instanceSendTo.tb, instance, "rvo_status" ); - //sendNotification("CMD Manager: process cmd", relaysData[0].tbname, "master_node_is_responding_again", {}, "", instanceSendTo.tb, instance, "rvo_status" ); - sendNotification("CMD Manager: process cmd", FLOW.OMS_edgeName, "master_node_is_responding_again", {}, "", instanceSendTo.tb, instance, "rvo_status" ); + //sendNotification("CMD Manager: process cmd", relaysData[0].tbname, ERRWEIGHT.NOTICE, "Master node is working again", "", SEND_TO.tb, instance, "rvo_status" ); + //sendNotification("CMD Manager: process cmd", relaysData[0].tbname, "master_node_is_responding_again", {}, "", SEND_TO.tb, instance, "rvo_status" ); + sendNotification("CMD Manager: process cmd", FLOW.OMS_edgeName, "master_node_is_responding_again", {}, "", SEND_TO.tb, instance, "rvo_status" ); FLOW.OMS_masterNodeIsResponding = true; } //odoslanie príkazu z terminálu - dáta if(params.type == "cmd-terminal") { - //sendNotification("CMD Manager: process cmd", relaysData[0].tbname, ERRWEIGHT.DEBUG, "odoslanie príkazu z terminálu", params, instanceSendTo.tb, instance, null ); - sendNotification("CMD Manager: process cmd", FLOW.OMS_edgeName, "command_was_sent_from_terminal_interface", {}, params, instanceSendTo.tb, instance ); + //sendNotification("CMD Manager: process cmd", relaysData[0].tbname, ERRWEIGHT.DEBUG, "odoslanie príkazu z terminálu", params, SEND_TO.tb, instance, null ); + sendNotification("CMD Manager: process cmd", FLOW.OMS_edgeName, "command_was_sent_from_terminal_interface", {}, params, SEND_TO.tb, instance ); } if(params.debug) @@ -2553,7 +2434,7 @@ exports.install = function(instance) { ] } - //instance.send(instanceSendTo.tb, dataToTb); + //instance.send(SEND_TO.tb, dataToTb); tbHandler.sendToTb(dataToTb, instance); } @@ -2574,11 +2455,11 @@ exports.install = function(instance) { responseObj["bytes"] = data; //params.refFlowdata.data = responseObj; - //instance.send(instanceSendTo.http_response, params.refFlowdata); + //instance.send(SEND_TO.http_response, params.refFlowdata); let refFlowdata = refFlowdataObj[ params.refFlowdataKey ]; refFlowdata.data = responseObj; - instance.send(instanceSendTo.http_response, refFlowdata); + instance.send(SEND_TO.http_response, refFlowdata); } else @@ -2607,13 +2488,13 @@ exports.install = function(instance) { responseObj["bytes"] = data; //params.refFlowdata.data = responseObj; - //instance.send(instanceSendTo.http_response, params.refFlowdata); + //instance.send(SEND_TO.http_response, params.refFlowdata); let refFlowdata = refFlowdataObj[ params.refFlowdataKey ]; if(refFlowdata !== undefined) { refFlowdata.data = responseObj; - instance.send(instanceSendTo.http_response, refFlowdata); + instance.send(SEND_TO.http_response, refFlowdata); } @@ -2634,7 +2515,7 @@ exports.install = function(instance) { responseObj["bytes"] = data; params.refFlowdata.data = responseObj; - instance.send(instanceSendTo.http_response, params.refFlowdata); + instance.send(SEND_TO.http_response, params.refFlowdata); } } @@ -2642,8 +2523,8 @@ exports.install = function(instance) { if(params.address == 0) { - //sendNotification("CMD Manager: process cmd", relaysData[0].tbname, ERRWEIGHT.ALERT, "Master node not responding", "", instanceSendTo.tb, instance, "rvo_status"); - sendNotification("CMD Manager: process cmd", FLOW.OMS_edgeName, "master_node_is_not_responding", {}, "", instanceSendTo.tb, instance, "rvo_status"); + //sendNotification("CMD Manager: process cmd", relaysData[0].tbname, ERRWEIGHT.ALERT, "Master node not responding", "", SEND_TO.tb, instance, "rvo_status"); + sendNotification("CMD Manager: process cmd", FLOW.OMS_edgeName, "master_node_is_not_responding", {}, "", SEND_TO.tb, instance, "rvo_status"); logger.debug("master_node_is_not_responding", params); FLOW.OMS_masterNodeIsResponding = false; } @@ -2655,8 +2536,8 @@ exports.install = function(instance) { logger.debug( "profil nebol úspešne odoslaný na node č. ", params, result, resp); - //sendNotification("CMD Manager: process cmd", tbname, ERRWEIGHT.ALERT, "profil nebol úspešne odoslaný na node č. " + params.address, "", instanceSendTo.tb, instance, null ); - sendNotification("CMD Manager: process cmd", tbname, "configuration_of_dimming_profile_to_node_failed", {node: params.address}, "", instanceSendTo.tb, instance ); + //sendNotification("CMD Manager: process cmd", tbname, ERRWEIGHT.ALERT, "profil nebol úspešne odoslaný na node č. " + params.address, "", SEND_TO.tb, instance, null ); + sendNotification("CMD Manager: process cmd", tbname, "configuration_of_dimming_profile_to_node_failed", {node: params.address}, "", SEND_TO.tb, instance ); } //is it node? @@ -2682,11 +2563,11 @@ exports.install = function(instance) { ] } - //instance.send(instanceSendTo.tb, dataToTb); + //instance.send(SEND_TO.tb, dataToTb); tbHandler.sendToTb(dataToTb, instance); } - //instance.send(instanceSendTo.debug, result); + //instance.send(SEND_TO.debug, result); if(params.hasOwnProperty("debug")) { @@ -2716,13 +2597,13 @@ exports.install = function(instance) { responseObj["message"] = "ERROR WRITE FAILED: " + reason;// //params.refFlowdata.data = responseObj; - //instance.send(instanceSendTo.http_response, params.refFlowdata); + //instance.send(SEND_TO.http_response, params.refFlowdata); let refFlowdata = refFlowdataObj[ params.refFlowdataKey ]; if(refFlowdata !== undefined) { refFlowdata.data = responseObj; - instance.send(instanceSendTo.http_response, refFlowdata); + instance.send(SEND_TO.http_response, refFlowdata); } @@ -2742,7 +2623,7 @@ exports.install = function(instance) { //responseObj["bytes"] = data; params.refFlowdata.data = responseObj; - instance.send(instanceSendTo.http_response, params.refFlowdata); + instance.send(SEND_TO.http_response, params.refFlowdata); //refFlowdata = undefined; } @@ -2766,8 +2647,8 @@ exports.install = function(instance) { if(params.address == 0) { - //sendNotification("CMD Manager: process cmd", relaysData[0].tbname, ERRWEIGHT.ALERT, "Master node not responding", "", instanceSendTo.tb, instance, "rvo_status"); - sendNotification("CMD Manager: process cmd", FLOW.OMS_edgeName, "master_node_is_not_responding", {}, "", instanceSendTo.tb, instance, "rvo_status"); + //sendNotification("CMD Manager: process cmd", relaysData[0].tbname, ERRWEIGHT.ALERT, "Master node not responding", "", SEND_TO.tb, instance, "rvo_status"); + sendNotification("CMD Manager: process cmd", FLOW.OMS_edgeName, "master_node_is_not_responding", {}, "", SEND_TO.tb, instance, "rvo_status"); logger.debug("master_node_is_not_responding", params); FLOW.OMS_masterNodeIsResponding = false; @@ -2780,8 +2661,8 @@ exports.install = function(instance) { logger.debug( "profil nebol úspešne odoslaný na node č. ", params, resp); - //sendNotification("CMD Manager: process cmd", tbname, ERRWEIGHT.ALERT, "odosielanie profilu na node č. " + params.address + " zlyhalo", "", instanceSendTo.tb, instance, null ); - sendNotification("CMD Manager: process cmd", tbname, "configuration_of_dimming_profile_to_node_failed", {node: params.address}, "", instanceSendTo.tb, instance ); + //sendNotification("CMD Manager: process cmd", tbname, ERRWEIGHT.ALERT, "odosielanie profilu na node č. " + params.address + " zlyhalo", "", SEND_TO.tb, instance, null ); + sendNotification("CMD Manager: process cmd", tbname, "configuration_of_dimming_profile_to_node_failed", {node: params.address}, "", SEND_TO.tb, instance ); } //is it node? @@ -2807,7 +2688,7 @@ exports.install = function(instance) { ] } - //instance.send(instanceSendTo.tb, dataToTb); + //instance.send(SEND_TO.tb, dataToTb); tbHandler.sendToTb(dataToTb, instance); FLOW.OMS_masterNodeIsResponding = false; @@ -2829,11 +2710,11 @@ exports.install = function(instance) { ] } - instance.send(instanceSendTo.tb, dataToTb); + instance.send(SEND_TO.tb, dataToTb); } */ - instance.send(instanceSendTo.debug, reason); + instance.send(SEND_TO.debug, reason); }); } @@ -2845,615 +2726,584 @@ exports.install = function(instance) { logger.debug("currentTask is not processed - task is in the future", currentTask); } - interval = setInterval(runTasks, longInterval); + interval = setInterval(runTasks, LONG_INTERVAL); return; } //console.log("----->runTasks - setInterval", new Date()); - interval = setInterval(runTasks, shortIterval); + interval = setInterval(runTasks, SHORT_INTERVAL); } + //! rsPort LM = "/dev/ttymxc4", rsPort UNIPI = "/dev/ttyUSB0" - // const rsPort = new SerialPort("/dev/ttymxc4", { autoOpen: false }); //LM - // const rsPort = new SerialPort("/dev/ttyUSB0", { autoOpen: false }); // UNIPI + // const rsPort = new SerialPort("/dev/ttymxc4", { autoOpen: false }); //LM + // const rsPort = new SerialPort("/dev/ttyUSB0", { autoOpen: false }); // UNIPI - if(FLOW.OMS_serial_port == "") FLOW.OMS_serial_port = "ttymxc4"; - if(FLOW.OMS_serial_port == undefined) FLOW.OMS_serial_port = "ttymxc4"; - if(FLOW.OMS_serial_port.length === 1) FLOW.OMS_serial_port = "ttymxc4"; - - const rsPort = new SerialPort(`/dev/${FLOW.OMS_serial_port}`, { autoOpen: false }); + if(FLOW.OMS_serial_port == "" || FLOW.OMS_serial_port == undefined || FLOW.OMS_serial_port.length === 1) FLOW.OMS_serial_port = "ttymxc4"; + const rsPort = new SerialPort(`/dev/${FLOW.OMS_serial_port}`, { autoOpen: false }); //(node:16372) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 13 data listeners added to [SerialPort]. Use emitter.setMaxListeners() to increase limit //rsPort.setMaxListeners(0); - rsPort.on('open', async function() { + rsPort.on('open', async function() { logger.debug("CMD manager - rsPort opened sucess"); - await loadRelaysData(); + loadRelaysData(); - await runSyncExec(`stty -F /dev/${FLOW.OMS_serial_port} 115200 min 1 time 5 ignbrk -brkint -icrnl -imaxbel -opost -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke`).then(function (status) { - instance.send(instanceSendTo.debug, "RPC runSyncExec - Promise Resolved:" + status); + await runSyncExec(`stty -F /dev/${FLOW.OMS_serial_port} 115200 min 1 time 5 ignbrk -brkint -icrnl -imaxbel -opost -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke`).then(function (status) { + instance.send(SEND_TO.debug, "RPC runSyncExec - Promise Resolved:" + status); - logger.debug(0, "RPC runSyncExec - Promise Resolved:" + status); + logger.debug(0, "RPC runSyncExec - Promise Resolved:" + status); - //APP START - let dataToInfoSender = {id: FLOW.OMS_projects_id, name: FLOW.OMS_rvo_name}; - dataToInfoSender.fw_version = FLOW.OMS_edge_fw_version; - dataToInfoSender.startdate = new Date().toISOString().slice(0, 19).replace('T', ' '); - dataToInfoSender.__force__ = true; - - instance.send(instanceSendTo.infoSender, dataToInfoSender); + //APP START + let dataToInfoSender = {id: FLOW.OMS_projects_id, name: FLOW.OMS_rvo_name}; + dataToInfoSender.fw_version = FLOW.OMS_edge_fw_version; + dataToInfoSender.startdate = new Date().toISOString().slice(0, 19).replace('T', ' '); + dataToInfoSender.__force__ = true; + + instance.send(SEND_TO.infoSender, dataToInfoSender); - logger.debug(0, "---------------------------->START message send to service", dataToInfoSender); + logger.debug(0, "---------------------------->START message send to service", dataToInfoSender); - //---- + }).catch(function (reason) { + instance.send(SEND_TO.debug, "CMD manager - RPC runSyncExec - promise rejected:" + reason); + }); + }); - nodesData = {}; - - dbNodes.find().make(function(builder) { - builder.callback(function(err, response) { - - for(let i = 0; i < response.length; i++) - { - let node = response[i]; - let key = node["node"]; - - nodesData[ key ] = node; - } - - //buildTasks(); - //interval = setInterval(runTasks, longInterval); - // console.log('******** nodesData',nodesData); - - }); - }); - - }).catch(function (reason) { - instance.send(instanceSendTo.debug, "CMD manager - RPC runSyncExec - promise rejected:" + reason); - }); - - }); - - rsPort.on('error', function(err) { + rsPort.on('error', function(err) { //TODO report to service!!! //errLogger.error(exports.title, "unable to open port", FLOW.OMS_serial_port, err.message); errorHandler.sendMessageToService([exports.title, "unable to open port", FLOW.OMS_serial_port, err.message], 0); - instance.send(instanceSendTo.debug, err.message); + instance.send(SEND_TO.debug, err.message); }); - rsPort.on("close", () => { - rsPort.close(); - }); + rsPort.on("close", () => { + rsPort.close(); + }); //loadRelaysData(); rsPort.open(); - instance.on("close", () => { + instance.on("close", () => { clearInterval(interval); - rsPort.close(); - }); + rsPort.close(); + }); + - //onData instance.on("data", async function(flowdata) { - //instance.on("data", (data) => { - //instance.send(instanceSendTo.debug, "on Data"); - //instance.send(instanceSendTo.debug, flowdata); - - //logger.debug(flowdata.data); + //instance.send(SEND_TO.debug, "on Data"); + //instance.send(SEND_TO.debug, flowdata); + + //logger.debug(flowdata.data); - //just testing functions - if(flowdata.data == "open") - { - if(!rsPort.isOpen) rsPort.open(); - return; - } - else if(flowdata.data == "close") - { - rsPort.close(); - return; - } - else if(flowdata.data == "clean") - { - tasks = []; - return; - } - else if(flowdata.data == "buildtasks") - { - //build & run - return; - } - else if(flowdata.data == "run") - { - //durations = []; + //just testing functions + if(flowdata.data == "open") + { + if(!rsPort.isOpen) rsPort.open(); + return; + } + else if(flowdata.data == "close") + { + rsPort.close(); + return; + } + else if(flowdata.data == "clean") + { + tasks = []; + return; + } + else if(flowdata.data == "buildtasks") + { + //build & run + return; + } + else if(flowdata.data == "run") + { + //durations = []; - if(tasks.length == 0) + if(tasks.length == 0) + { + + buildTasks(); + + if(rsPort.isOpen) { - - buildTasks(); - - if(rsPort.isOpen) - { - interval = setInterval(runTasks, 100); - } - else - { - instance.send(instanceSendTo.debug, "port is not opened!!!"); - } + interval = setInterval(runTasks, 100); + } + else + { + instance.send(SEND_TO.debug, "port is not opened!!!"); } } - else + } + else + { + //terminal data - object + //logger.debug("flowdata", flowdata.data); + + if(typeof flowdata.data === 'object') { - //terminal data - object - //logger.debug("flowdata", flowdata.data); - - if(typeof flowdata.data === 'object') + //logger.debug("dido", flowdata.data); + if(flowdata.data.hasOwnProperty("sender")) { - //logger.debug("dido", flowdata.data); - if(flowdata.data.hasOwnProperty("sender")) + //data from dido_controller + if(flowdata.data.sender == "dido_controller") { - //data from dido_controller - if(flowdata.data.sender == "dido_controller") + + if(flowdata.data.hasOwnProperty("cmd")) { + let cmd = flowdata.data.cmd; - if(flowdata.data.hasOwnProperty("cmd")) + + if(cmd == "buildTasks") { - let cmd = flowdata.data.cmd; + clearInterval(interval); + logger.debug("-->CMD MANAGER - BUILD TASKS"); + buildTasks(); + + //logger.debug("tasks:"); + //logger.debug(tasks); + + logger.debug("-->CMD MANAGER - RUN TASKS"); + interval = setInterval(runTasks, LONG_INTERVAL); + } + else if(cmd == "reload_relays") + { + loadRelaysData(flowdata.data.line); + + if(flowdata.data.dataChanged) + { + if(!flowdata.data.value) + { + reportOfflineNodeStatus(flowdata.data.line); + } + else + { + reportOnlineNodeStatus(flowdata.data.line); + } + } - if(cmd == "buildTasks") + } + else if(cmd == "rotary_switch_state") + { + //state was changed + if(rotary_switch_state != flowdata.data.value) { - clearInterval(interval); - - logger.debug("-->CMD MANAGER - BUILD TASKS"); - buildTasks(); - - //logger.debug("tasks:"); - //logger.debug(tasks); - - logger.debug("-->CMD MANAGER - RUN TASKS"); - interval = setInterval(runTasks, longInterval); - } - else if(cmd == "reload_relays") - { - await loadRelaysData(flowdata.data.line); - - if(flowdata.data.dataChanged) + if(rotary_switch_state == "Off") { - if(!flowdata.data.value) - { - reportOfflineNodeStatus(flowdata.data.line); - } - else - { - reportOnlineNodeStatus(flowdata.data.line); - } + //vyreportovat vsetky svietdla + reportOfflineNodeStatus(); } - + else reportOnlineNodeStatus(); + } - else if(cmd == "rotary_switch_state") + + rotary_switch_state = flowdata.data.value; + } + else if(cmd == "lux_sensor") + { + lux_sensor = parseInt(flowdata.data.value); + + //process profiles + turnOnOffLinesAccordingToLuxSensor(lux_sensor); + } + else if(cmd == "state_of_breaker") + { + //istic linie + let value = flowdata.data.value; + let line = parseInt(flowdata.data.line); + + let dataChanged = false; + if(state_of_breaker[line] != value) dataChanged = true; + + state_of_breaker[line] = value; + + let status = "OK"; + let weight = ERRWEIGHT.NOTICE; + let message = `zapnutý istič línie č. ${line}`; + if(value == "Off") { - //state was changed - if(rotary_switch_state != flowdata.data.value) + weight = ERRWEIGHT.ERROR; + message = `vypnutý istič línie č. ${line}`; + status = "NOK"; + } + + if(dataChanged) { + + if(relaysData.hasOwnProperty(line)) { - if(rotary_switch_state == "Off") - { - //vyreportovat vsetky svietdla - reportOfflineNodeStatus(); - } - else reportOnlineNodeStatus(); + let tbname = relaysData[line].tbname; - } + if(value == "Off") sendNotification("CMD Manager: onData", tbname, "circuit_breaker_was_turned_off_line", {line: line}, "", SEND_TO.tb, instance, "circuit_breaker"); + else sendNotification("CMD Manager: onData", tbname, "circuit_breaker_was_turned_on_line", {line: line}, "", SEND_TO.tb, instance, "circuit_breaker"); - rotary_switch_state = flowdata.data.value; - } - else if(cmd == "lux_sensor") - { - lux_sensor = parseInt(flowdata.data.value); - - //process profiles - turnOnOffLinesAccordingToLuxSensor(lux_sensor); - } - else if(cmd == "state_of_breaker") - { - //istic linie - let value = flowdata.data.value; - let line = parseInt(flowdata.data.line); - - let dataChanged = false; - if(state_of_breaker[line] != value) dataChanged = true; - - state_of_breaker[line] = value; - - let status = "OK"; - let weight = ERRWEIGHT.NOTICE; - let message = `zapnutý istič línie č. ${line}`; - if(value == "Off") - { - weight = ERRWEIGHT.ERROR; - message = `vypnutý istič línie č. ${line}`; - status = "NOK"; - } - - if(dataChanged) { - - if(relaysData.hasOwnProperty(line)) - { - let tbname = relaysData[line].tbname; - - if(value == "Off") sendNotification("CMD Manager: onData", tbname, "circuit_breaker_was_turned_off_line", {line: line}, "", instanceSendTo.tb, instance, "circuit_breaker"); - else sendNotification("CMD Manager: onData", tbname, "circuit_breaker_was_turned_on_line", {line: line}, "", instanceSendTo.tb, instance, "circuit_breaker"); - - //report status liniu - let values = { - "status": status - }; - - let dataToTb = { - [tbname]: [ - { - "ts": Date.now(), - "values": values - } - ] - } - - //instance.send(instanceSendTo.tb, dataToTb); - tbHandler.sendToTb(dataToTb, instance); - - //current value - if(value == "Off") - { - //vyreportovat vsetky svietdla na linii - reportOfflineNodeStatus(line); + //report status liniu + let values = { + "status": status + }; + + let dataToTb = { + [tbname]: [ + { + "ts": Date.now(), + "values": values + } + ] } - else reportOnlineNodeStatus(line); - } + + //instance.send(SEND_TO.tb, dataToTb); + tbHandler.sendToTb(dataToTb, instance); + //current value + if(value == "Off") + { + //vyreportovat vsetky svietdla na linii + reportOfflineNodeStatus(line); + } + else reportOnlineNodeStatus(line); } + } - else{ - logger.debug("undefined cmd", cmd); - } + } + else{ + logger.debug("undefined cmd", cmd); } } - - return; } - //data from worksys - if(flowdata.data.hasOwnProperty("topic")) + return; + } + + //data from worksys + if(flowdata.data.hasOwnProperty("topic")) + { + + let data = flowdata.data.content.data; + + let command = data.params.command; + let method = data.method; + let profile = data.params.payload; + if(profile == undefined) profile = ""; + let entity = data.params.entities[0]; + let entity_type = entity.entity_type; + let tbname = entity.tb_name; + + instance.send(SEND_TO.debug, flowdata.data); + logger.debug("--->worksys", flowdata.data, data.params, entity, entity_type, command, method); + logger.debug("----------------------------"); + + if(entity_type == "street_luminaire"|| entity_type === "street_luminaire_v4_1" || entity_type === "street_luminaire_v4_1cez" || entity_type === "street_luminaire_v4") { - - let data = flowdata.data.content.data; - - let command = data.params.command; - let method = data.method; - let profile = data.params.payload; - if(profile == undefined) profile = ""; - let entity = data.params.entities[0]; - let entity_type = entity.entity_type; - let tbname = entity.tb_name; - - instance.send(instanceSendTo.debug, flowdata.data); - logger.debug("--->worksys", flowdata.data, data.params, entity, entity_type, command, method); - logger.debug("----------------------------"); - - if(entity_type == "street_luminaire"|| entity_type === "street_luminaire_v4_1" || entity_type === "street_luminaire_v4_1cez" || entity_type === "street_luminaire_v4") + if(method == "set_command") { - if(method == "set_command") + + //let command = data.params.command; + let value = data.params.payload.value; + + if(command == "dimming") { - //let command = data.params.command; - let value = data.params.payload.value; - - if(command == "dimming") - { - - let nodeWasFound = false; - let keys = Object.keys(nodesData); - - //logger.debug("-----", keys); - - for(let i = 0; i < keys.length; i++) - { - let node = keys[i]; - //logger.debug( node, nodesData[node], tbname); - - if(tbname == nodesData[node].tbname.trim()) - { - let params = getParams(priorityTypes.high_priority); - - value = parseInt(value); - if(value > 0) value = value + 128; - - //set dimming - LUM1_13 - 647 je node linie 1 kt. dobre vidime - params.type = "cmd"; - params.tbname = tbname; - params.address = node; - params.register = 1;//dimming - params.recipient = 1;//slave - params.byte4 = value; - params.rw = 1;//write - params.timestamp = priorityTypes.high_priority; - params.info = 'set dimming from platform'; - //params.debug = true; - - //ak linia je - - //debug(params); - logger.debug("dimming", params); - - tasks.push(params); - - setTimeout(function(){ - - //spustime o 4 sekundy neskor, s prioritou priorityTypes.high_priority - //a pridame aj vyreportovanie dimmingu - { - let params = getParams(priorityTypes.high_priority); - - params.type = "cmd"; - params.tbname = tbname; - params.address = node; - params.register = 1;//dimming - params.recipient = 1;//slave - params.rw = 0;//read - params.timestamp = priorityTypes.high_priority; - params.info = 'read dimming (after set dimming from platform)'; - params.debug = true; - - tasks.push(params); - } - - //pridame aj vyreportovanie - vykon - { - let params = getParams(priorityTypes.high_priority); - - params.type = "cmd"; - params.tbname = tbname; - params.address = node; - params.register = 76; - params.recipient = 1;//slave - params.rw = 0;//read - params.timestamp = priorityTypes.high_priority; - params.info = 'read Input Power (after set dimming from platform)'; - params.debug = true; - - tasks.push(params); - } - - //pridame aj vyreportovanie - prud svietidla - { - let params = getParams(priorityTypes.high_priority); - - params.type = "cmd"; - params.tbname = tbname; - params.address = node; - params.register = 75; - params.recipient = 1;//slave - params.rw = 0;//read - params.timestamp = priorityTypes.high_priority; - params.info = 'read Input Current (after set dimming from platform)'; - params.debug = true; - - tasks.push(params); - } - - //pridame aj vyreportovanie - power faktor - ucinnik - { - let params = getParams(priorityTypes.high_priority); - - params.type = "cmd"; - params.tbname = tbname; - params.address = node; - params.register = 77; - params.recipient = 1;//slave - params.rw = 0;//read - params.timestamp = priorityTypes.high_priority; - params.info = 'read power factor - Cos phi (after set dimming from platform)'; - params.debug = true; - - tasks.push(params); - } - - },4000); - - - nodeWasFound = true; - - break; - } - } - - if(!nodeWasFound) - { - logger.debug("set dimming from platform", "unable to find tbname", tbname); - } - } - else - { - instance.send(instanceSendTo.debug, "undefined command " + command); - logger.debug("undefined command", command); - } - - return; - - } - else if(method == "set_profile") - { - //nastav profil nodu - logger.debug("-->set_profile for node", data.params); - logger.debug("------profile data", profile); - //instance.send(instanceSendTo.debug, "set_profile" + command); - + let nodeWasFound = false; let keys = Object.keys(nodesData); + + //logger.debug("-----", keys); + for(let i = 0; i < keys.length; i++) { let node = keys[i]; + //logger.debug( node, nodesData[node], tbname); + if(tbname == nodesData[node].tbname.trim()) { + let params = getParams(PRIORITY_TYPES.high_priority); - if(profile != "") profile = JSON.stringify(profile); - dbNodes.modify({ processed: false, profile: profile }).where("node", node).make(function(builder) { + value = parseInt(value); + if(value > 0) value = value + 128; - builder.callback(function(err, response) { + //set dimming - LUM1_13 - 647 je node linie 1 kt. dobre vidime + params.type = "cmd"; + params.tbname = tbname; + params.address = node; + params.register = 1;//dimming + params.recipient = 1;//slave + params.byte4 = value; + params.rw = 1;//write + params.timestamp = PRIORITY_TYPES.high_priority; + params.info = 'set dimming from platform'; + //params.debug = true; - logger.debug("worksys - update node profile done", profile); - if(profile === "") logger.debug("worksys - update node profile done - profile is empty"); + //ak linia je - //profil úspešne prijatý pre node č. xx - //sendNotification("CMD manager", tbname, ERRWEIGHT.INFO, `profil úspešne poslaný z platformy na RVO pre node č. ${node}`, profile, instanceSendTo.tb, instance, null ); - sendNotification("CMD manager", tbname, "dimming_profile_was_processed_for_node", {node: node}, profile, instanceSendTo.tb, instance ); + //debug(params); + logger.debug("dimming", params); - nodesData[node].processed = false; - nodesData[node].profile = profile; + tasks.push(params); - let line = nodesData[node].line; - processNodeProfile(node); + setTimeout(function(){ - }); - }); + //spustime o 4 sekundy neskor, s prioritou PRIORITY_TYPES.high_priority + //a pridame aj vyreportovanie dimmingu + { + let params = getParams(PRIORITY_TYPES.high_priority); + + params.type = "cmd"; + params.tbname = tbname; + params.address = node; + params.register = 1;//dimming + params.recipient = 1;//slave + params.rw = 0;//read + params.timestamp = PRIORITY_TYPES.high_priority; + params.info = 'read dimming (after set dimming from platform)'; + params.debug = true; + + tasks.push(params); + } + + //pridame aj vyreportovanie - vykon + { + let params = getParams(PRIORITY_TYPES.high_priority); + + params.type = "cmd"; + params.tbname = tbname; + params.address = node; + params.register = 76; + params.recipient = 1;//slave + params.rw = 0;//read + params.timestamp = PRIORITY_TYPES.high_priority; + params.info = 'read Input Power (after set dimming from platform)'; + params.debug = true; + + tasks.push(params); + } + + //pridame aj vyreportovanie - prud svietidla + { + let params = getParams(PRIORITY_TYPES.high_priority); + + params.type = "cmd"; + params.tbname = tbname; + params.address = node; + params.register = 75; + params.recipient = 1;//slave + params.rw = 0;//read + params.timestamp = PRIORITY_TYPES.high_priority; + params.info = 'read Input Current (after set dimming from platform)'; + params.debug = true; + + tasks.push(params); + } + + //pridame aj vyreportovanie - power faktor - ucinnik + { + let params = getParams(PRIORITY_TYPES.high_priority); + + params.type = "cmd"; + params.tbname = tbname; + params.address = node; + params.register = 77; + params.recipient = 1;//slave + params.rw = 0;//read + params.timestamp = PRIORITY_TYPES.high_priority; + params.info = 'read power factor - Cos phi (after set dimming from platform)'; + params.debug = true; + + tasks.push(params); + } + + },4000); + + + nodeWasFound = true; + + break; } } + + if(!nodeWasFound) + { + logger.debug("set dimming from platform", "unable to find tbname", tbname); + } } else { - - instance.send(instanceSendTo.debug, "unknown method " + method); - logger.debug("unknown method", method); - - return; - } - - } - - //nastav profil linie z platformy - else if(entity_type == "edb_line" || entity_type == "edb" || entity_type == "edb_line_ver4" || entity_type == "edb_ver4_se") - { - //profil linie - //relays.table line:number|tbname:string|contactor:number|profile:string - //najdeme line relaysData - - if(method == "set_profile") - { - - logger.debug("-->set_profile for line", data.params); - logger.debug("profile data:", profile); - - let keys = Object.keys(relaysData); - for(let i = 0; i < keys.length; i++) - { - let line = keys[i]; - if(tbname == relaysData[line].tbname) - { - //zmazeme tasky - removeTask({type: "relay", line: line}); - - if(profile != "") profile = JSON.stringify(profile); - dbRelays.modify({ profile: profile }).where("line", line).make(function(builder) { - - builder.callback(function(err, response) { - - //update profile - logger.debug("worksys - update relay profile done:", profile); - instance.send(instanceSendTo.debug, "worksys - update relay profile done"); - - loadRelaysData(line).then(function (data) { - logger.debug("loadRelaysData DONE for line", line); - buildTasks({processLineProfiles: true, line: line}); - }); - - sendNotification("CMD manager - set profile from worksys", tbname, "switching_profile_was_processed_for_line", {line: line}, profile, instanceSendTo.tb, instance ); - - }); - }); - - break; - } - } - } - else if(method == "set_command") - { - let value = data.params.payload.value; - - if(command === "switch") - { - - // if we receive rpc from platform, to switch maintenance mode, we set OMS_maintenance_mode flow variable to value; - if(entity_type === "edb" || entity_type === "edb_ver4_se") FLOW.variables.OMS_maintenance_mode = value; - - let responseRelays = await promisifyBuilder(dbRelays.find().where("tbname", tbname)); - - let line = 0; - if(responseRelays.length == 1) line = responseRelays[0].line; - - if(value == false) turnOffLine(line, "command received form platform"); - else turnOnLine(line, "command received form platform"); - } - - } - else - { - instance.send(instanceSendTo.debug, "undefined method " + method); - logger.debug("undefined method", method); + instance.send(SEND_TO.debug, "undefined command " + command); + logger.debug("undefined command", command); } return; - - } - else{ - instance.send(instanceSendTo.debug, "UNKNOW entity_type " + entity_type); - logger.debug("UNKNOW entity_type", entity_type); } + else if(method == "set_profile") + { + //nastav profil nodu + logger.debug("-->set_profile for node", data.params); + logger.debug("------profile data", profile); + //instance.send(SEND_TO.debug, "set_profile" + command); - return; + let keys = Object.keys(nodesData); + for(let i = 0; i < keys.length; i++) + { + let node = keys[i]; + if(tbname == nodesData[node].tbname.trim()) + { + + if(profile != "") profile = JSON.stringify(profile); + dbNodes.modify({ processed: false, profile: profile }).where("node", node).make(function(builder) { + + builder.callback(function(err, response) { + + logger.debug("worksys - update node profile done", profile); + if(profile === "") logger.debug("worksys - update node profile done - profile is empty"); + + //profil úspešne prijatý pre node č. xx + //sendNotification("CMD manager", tbname, ERRWEIGHT.INFO, `profil úspešne poslaný z platformy na RVO pre node č. ${node}`, profile, SEND_TO.tb, instance, null ); + sendNotification("CMD manager", tbname, "dimming_profile_was_processed_for_node", {node: node}, profile, SEND_TO.tb, instance ); + + nodesData[node].processed = false; + nodesData[node].profile = profile; + + let line = nodesData[node].line; + processNodeProfile(node); + + }); + }); + } + } + } + else + { + + instance.send(SEND_TO.debug, "unknown method " + method); + logger.debug("unknown method", method); + + return; + } } - //terminal - if(!rsPort.isOpen) await rsPort.open(); - - let params = flowdata.data.body; - if(params == undefined) + //nastav profil linie z platformy + else if(entity_type == "edb_line" || entity_type == "edb" || entity_type == "edb_line_ver4" || entity_type == "edb_ver4_se") { - //logger.debug("CMD manager flowdata.data.body is undefined"); + //profil linie + //relays.table line:number|tbname:string|contactor:number|profile:string + //najdeme line relaysData + + if(method == "set_profile") + { + + logger.debug("-->set_profile for line", data.params); + logger.debug("profile data:", profile); + + let keys = Object.keys(relaysData); + for(let i = 0; i < keys.length; i++) + { + let line = keys[i]; + if(tbname == relaysData[line].tbname) + { + //zmazeme tasky + removeTask({type: "relay", line: line}); + + if(profile != "") profile = JSON.stringify(profile); + dbRelays.modify({ profile: profile }).where("line", line).make(function(builder) { + + builder.callback(function(err, response) { + + //update profile + logger.debug("worksys - update relay profile done:", profile); + instance.send(SEND_TO.debug, "worksys - update relay profile done"); + + loadRelaysData(line).then(function (data) { + logger.debug("loadRelaysData DONE for line", line); + buildTasks({processLineProfiles: true, line: line}); + }); + + sendNotification("CMD manager - set profile from worksys", tbname, "switching_profile_was_processed_for_line", {line: line}, profile, SEND_TO.tb, instance ); + + }); + }); + break; + } + } + } + else if(method == "set_command") + { + let value = data.params.payload.value; + + if(command === "switch") + { + + // if we receive rpc from platform, to switch maintenance mode, we set OMS_maintenance_mode flow variable to value; + if(entity_type === "edb" || entity_type === "edb_ver4_se") FLOW.variables.OMS_maintenance_mode = value; + + let responseRelays = await promisifyBuilder(dbRelays.find().where("tbname", tbname)); + + let line = 0; + if(responseRelays.length == 1) line = responseRelays[0].line; + + if(value == false) turnOffLine(line, "command received form platform"); + else turnOnLine(line, "command received form platform"); + } + } + else + { + instance.send(SEND_TO.debug, "undefined method " + method); + logger.debug("undefined method", method); + } + return; } - - params.priority = priorityTypes.terminal; - params.type = "cmd-terminal"; - params.tbname = ""; - params.timestamp = priorityTypes.terminal; - params.addMinutesToTimestamp = 0;// do not repeat task!!! - params.debug = true; - - let timestamp = Date.now(); - params.refFlowdataKey = timestamp; - //params.refFlowdata = flowdata; - //refFlowdata = flowdata; - - //console.log("flowdata", flowdata); - - cleanUpRefFlowdataObj(); - - refFlowdataObj[ timestamp ] = flowdata; - - //fix - //params.address = params.adress; - logger.debug("received from terminal", params); - logger.debug("date/time:", new Date()); - logger.debug("tasks length:", tasks.length); - - //tasks = []; - - //add to tasks - tasks.push(params); - + else + { + instance.send(SEND_TO.debug, "UNKNOW entity_type " + entity_type); + logger.debug("UNKNOW entity_type", entity_type); + } + return; } + + //terminal + if(!rsPort.isOpen) await rsPort.open(); + + let params = flowdata.data.body; + if(params == undefined) + { + //logger.debug("CMD manager flowdata.data.body is undefined"); + return; + } + + params.priority = PRIORITY_TYPES.terminal; + params.type = "cmd-terminal"; + params.tbname = ""; + params.timestamp = PRIORITY_TYPES.terminal; + params.addMinutesToTimestamp = 0;// do not repeat task!!! + params.debug = true; + + let timestamp = Date.now(); + params.refFlowdataKey = timestamp; + //params.refFlowdata = flowdata; + //refFlowdata = flowdata; + + //console.log("flowdata", flowdata); + + cleanUpRefFlowdataObj(); + + refFlowdataObj[ timestamp ] = flowdata; + + //fix + //params.address = params.adress; + logger.debug("received from terminal", params); + logger.debug("date/time:", new Date()); + logger.debug("tasks length:", tasks.length); + + //tasks = []; + + //add to tasks + tasks.push(params); + } - }) + } + }) } // end of instance.export @@ -3586,7 +3436,7 @@ setCorrectPlcTimeOnceADay(); ///helper functions -function calculateDuskDown(date, line, duskOffset = 0, dawnOffset = 0) +function calculateDuskDawn(date, line, duskOffset = 0, dawnOffset = 0) { if(date === undefined) date = new Date(); @@ -3611,7 +3461,7 @@ function calculateDuskDown(date, line, duskOffset = 0, dawnOffset = 0) let dusk_astro_clock_offset = duskOffset;//minutes let dawn_astro_clock_offset = dawnOffset;//minutes - try{ + try { let profile = JSON.parse(profilestr); if(Object.keys(profile).length === 0) throw ("profile is not defined"); @@ -3671,6 +3521,7 @@ function calculateDuskDown(date, line, duskOffset = 0, dawnOffset = 0) return result; } + function processResponse(register, bytes) { @@ -3796,56 +3647,56 @@ function processResponse(register, bytes) //naklon if(register == 84) { - let temp; - if(byte3 >= 128) - { - temp = (byte3 - 128) * (-1); - } - else - { - temp = byte3; - } + let temp; + if(byte3 >= 128) + { + temp = (byte3 - 128) * (-1); + } + else + { + temp = byte3; + } - let inclination_x; - if(byte2 >= 128) - { - inclination_x = (byte2 - 128) * (-1); - } - else - { - inclination_x = byte2; - } + let inclination_x; + if(byte2 >= 128) + { + inclination_x = (byte2 - 128) * (-1); + } + else + { + inclination_x = byte2; + } - let inclination_y; - if(byte1 >= 128) - { - inclination_y = (byte1 - 128) * (-1); - } - else - { - inclination_y = byte1; - } + let inclination_y; + if(byte1 >= 128) + { + inclination_y = (byte1 - 128) * (-1); + } + else + { + inclination_y = byte1; + } - let inclination_z; - if(byte0 >= 128) - { - inclination_z = (byte0 - 128) * (-1); - } - else - { - inclination_z = byte0; - } + let inclination_z; + if(byte0 >= 128) + { + inclination_z = (byte0 - 128) * (-1); + } + else + { + inclination_z = byte0; + } - values["temperature"] = temp; + values["temperature"] = temp; - //náklon x - values["inclination_x"] = inclination_x; + //náklon x + values["inclination_x"] = inclination_x; - //náklon y - values["inclination_y"] = inclination_y; + //náklon y + values["inclination_y"] = inclination_y; - //náklon z - values["inclination_z"] = inclination_z; + //náklon z + values["inclination_z"] = inclination_z; } let h = byte3; @@ -3868,7 +3719,6 @@ function processResponse(register, bytes) timestamp = d.getTime(); } - //aktuálny čas if(register == 87) { @@ -3900,13 +3750,13 @@ function processResponse(register, bytes) if(register == 89) { //formát: "Byte3: Byte2.Byte1 (Byte0)" - values["fw_version"] = byte3 + ":" + byte2 + "." + byte1 + "(" + byte0 + ")"; } return values; } + //byte1 MSB = data3, byte2 = data2, byte3 = data1, byte4 = data0 LSB function com_generic(adresa, rec, rw, register, name, byte1, byte2, byte3, byte4) { let resp = []; @@ -3921,7 +3771,7 @@ function com_generic(adresa, rec, rw, register, name, byte1, byte2, byte3, byte4 if (rw === 0) { - cmd = cmd + 0x8000; + cmd = cmd + 0x8000; } //master @@ -3935,24 +3785,24 @@ function com_generic(adresa, rec, rw, register, name, byte1, byte2, byte3, byte4 //recipient if (rec === 3) { - resp.push(0xFF); - resp.push(0xFF); - resp.push(0xFF); - resp.push(0xFF); - resp.push( adresa & 0xFF );//band + resp.push(0xFF); + resp.push(0xFF); + resp.push(0xFF); + resp.push(0xFF); + resp.push( adresa & 0xFF );//band } else { - resp.push( (adresa >> 24) & 0xFF);//rshift - resp.push( (adresa >> 16) & 0xFF); - resp.push( (adresa >> 8) & 0xFF); - resp.push( adresa & 0xFF ); + resp.push( (adresa >> 24) & 0xFF);//rshift + resp.push( (adresa >> 16) & 0xFF); + resp.push( (adresa >> 8) & 0xFF); + resp.push( adresa & 0xFF ); - if (rec === 2) - { - resp.push(0xFF); - } - else resp.push(0); + if (rec === 2) + { + resp.push(0xFF); + } + else resp.push(0); } resp.push( (cmd >> 8) & 0xFF);//rshift @@ -3980,3 +3830,441 @@ function com_generic(adresa, rec, rw, register, name, byte1, byte2, byte3, byte4 + + + +const lineTimepointsExample1 = +[ + { start_time: '05:17', value: 0, name: 'dawn' }, + { value: 0, end_time: '13:00', start_time: '05:30' }, + { value: 0, end_time: '20:00', start_time: '13:00' }, + { value: 1, end_time: '05:30', start_time: '20:00' }, + { start_time: '20:19', value: 1, name: 'dusk' } +] + + + +const lineTimepointsExample2 = +[ + { value: 0, end_time: '13:00', start_time: '05:30' }, + { value: 0, start_time: '5:47', name: 'luxOff' }, + { value: 0, end_time: '20:00', start_time: '13:00' }, + { value: 1, end_time: '05:30', start_time: '20:00' }, + { value: 1, start_time: '20:49', name: 'luxOn' } +] + + + + +// SAMPLE DATA + + +const relaysDataExample = +{ + '0': { + line: 0, + tbname: 'jbN4q7JPZmexgdnz2yKbWGDYAWwO0Q3BMX6ERLoV', + contactor: 1, + profile: '' + }, + '1': { + line: 1, + tbname: 'MgnK93rkoAazbqdQ4yB2Q0yZ1YXGx6pmwBeVEP2O', + contactor: 1, + profile: '{"intervals":[{"value":1,"end_time":"13:00","start_time":"13:00"}],"astro_clock":false,"dawn_lux_sensor":false,"dusk_lux_sensor":false,"dawn_lux_sensor_value":5,"dusk_lux_sensor_value":5,"dawn_astro_clock_offset":0,"dusk_astro_clock_offset":0,"dawn_lux_sensor_time_window":30,"dusk_lux_sensor_time_window":30,"dawn_astro_clock_time_window":60,"dusk_astro_clock_time_window":60}' + }, + '2': { + line: 2, + tbname: 'jBL12pg63eX4N9P7zy0lJLyEJKmlbkGwZMx0avQV', + contactor: 1, + profile: '{"intervals":[{"value":1,"end_time":"13:00","start_time":"13:00"}],"astro_clock":false,"dawn_lux_sensor":false,"dusk_lux_sensor":false,"dawn_lux_sensor_value":5,"dusk_lux_sensor_value":5,"dawn_astro_clock_offset":0,"dusk_astro_clock_offset":0,"dawn_lux_sensor_time_window":30,"dusk_lux_sensor_time_window":30,"dawn_astro_clock_time_window":60,"dusk_astro_clock_time_window":60}' + }, + '3': { + line: 3, + tbname: 'aAOzENGrvpbe0VoK7D6E1a819PZmdg3nl24JLQMk', + contactor: 1, + profile: '{"intervals":[{"value":1,"end_time":"13:00","start_time":"13:00"}],"astro_clock":false,"dawn_lux_sensor":false,"dusk_lux_sensor":false,"dawn_lux_sensor_value":5,"dusk_lux_sensor_value":5,"dawn_astro_clock_offset":0,"dusk_astro_clock_offset":0,"dawn_lux_sensor_time_window":30,"dusk_lux_sensor_time_window":30,"dawn_astro_clock_time_window":60,"dusk_astro_clock_time_window":60}' + } +} + + +// [2024-05-08T11:43:33.055] [DEBUG] default - --->reportOfflineNodeStatus for line 2 +// [2024-05-08T11:43:33.055] [DEBUG] default - --->reportOfflineNodeStatus for line 3 +// [2024-05-08T11:43:35.737] [DEBUG] default - -->CMD MANAGER - BUILD TASKS +// [2024-05-08T11:43:35.742] [INFO] monitorLogs - buildTasks - params undefined +// [2024-05-08T11:43:35.743] [DEBUG] default - -->buildTasks clear tasks +// [2024-05-08T11:43:35.744] [INFO] monitorLogs - buildTasks: profile for line 1 +// [2024-05-08T11:43:35.745] [INFO] monitorLogs - profile: { +// intervals: [ { value: 1, end_time: '13:00', start_time: '13:00' } ], +// astro_clock: false, +// dawn_lux_sensor: false, +// dusk_lux_sensor: false, +// dawn_lux_sensor_value: 5, +// dusk_lux_sensor_value: 5, +// dawn_astro_clock_offset: 0, +// dusk_astro_clock_offset: 0, +// dawn_lux_sensor_time_window: 30, +// dusk_lux_sensor_time_window: 30, +// dawn_astro_clock_time_window: 60, +// dusk_astro_clock_time_window: 60 +// } +// [2024-05-08T11:43:35.747] [INFO] monitorLogs - -->comming events turn on/off lines: +// [2024-05-08T11:43:35.748] [INFO] monitorLogs - turn on line: 1 2024-05-08T11:00:00.747Z +// [2024-05-08T11:43:35.749] [INFO] monitorLogs - -->time_points final 1 [ { value: 1, end_time: '13:00', start_time: '13:00' } ] +// [2024-05-08T11:43:35.751] [INFO] monitorLogs - -->currentValue for relay 1 1 +// +// +// typ paramu ...... / cmd + + + +const rpcSwitchOffLine = +{ + "topic": "v1/gateway/rpc", + "content": { + "device": "jbN4q7JPZmexgdnz2yKbWGDYAWwO0Q3BMX6ERLoV", + "data": { + "id": 8, + "method": "set_command", + "params": { + "entities": [ + { + "entity_type": "edb_line", + "tb_name": "MgnK93rkoAazbqdQ4yB2Q0yZ1YXGx6pmwBeVEP2O" + } + ], + "command": "switch", + "payload": { + "value": false + } + } + } + } +} + +const rpcSetNodeDimming = +{ + "topic": "v1/gateway/rpc", + "content": { + "device": "jbN4q7JPZmexgdnz2yKbWGDYAWwO0Q3BMX6ERLoV", + "data": { + "id": 10, + "method": "set_command", + "params": { + "entities": [ + { + "entity_type": "street_luminaire", + "tb_name": "jbN4q7JPZmexgdnz2yKbWdDYAWwO0Q3BMX6ERLoV" + } + ], + "command": "dimming", + "payload": { + "value": 5 + } + } + } + } +} + +const rpcLineProfile = +{ + "topic": "v1/gateway/rpc", + "content": { + "device": "jbN4q7JPZmexgdnz2yKbWGDYAWwO0Q3BMX6ERLoV", + "data": { + "id": 9, + "method": "set_profile", + "params": { + "entities": [ + { + "entity_type": "edb_line", + "tb_name": "MgnK93rkoAazbqdQ4yB2Q0yZ1YXGx6pmwBeVEP2O" + } + ], + "payload": { + "intervals": [ + { + "value": 0, + "end_time": "20:00", + "start_time": "13:00" + }, + { + "value": 1, + "end_time": "05:30", + "start_time": "20:00" + }, + { + "value": 0, + "end_time": "13:00", + "start_time": "05:30" + } + ], + "astro_clock": true, + "dawn_lux_sensor": false, + "dusk_lux_sensor": false, + "dawn_lux_sensor_value": 5, + "dusk_lux_sensor_value": 5, + "dawn_astro_clock_offset": 0, + "dusk_astro_clock_offset": 0, + "dawn_lux_sensor_time_window": 30, + "dusk_lux_sensor_time_window": 30, + "dawn_astro_clock_time_window": 60, + "dusk_astro_clock_time_window": 60 + } + } + } + } +} + + +const rpcNodeProfile = +{ + "topic": "v1/gateway/rpc", + "content": { + "device": "jbN4q7JPZmexgdnz2yKbWGDYAWwO0Q3BMX6ERLoV", + "data": { + "id": 11, + "method": "set_profile", + "params": { + "entities": [ + { + "entity_type": "street_luminaire", + "tb_name": "jbN4q7JPZmexgdnz2yKbWdDYAWwO0Q3BMX6ERLoV" + } + ], + "payload": { + "intervals": [ + { + "cct": 3000, + "value": 0, + "end_time": "17:50", + "start_time": "13:00" + }, + { + "cct": 3000, + "value": 100, + "end_time": "21:30", + "start_time": "17:50" + }, + { + "cct": 3000, + "value": 0, + "end_time": "13:00", + "start_time": "07:10" + }, + { + "cct": 3000, + "value": 50, + "end_time": "00:00", + "start_time": "21:30" + }, + { + "cct": 3000, + "value": 10, + "end_time": "04:30", + "start_time": "00:00" + }, + { + "cct": 3000, + "value": 100, + "end_time": "07:10", + "start_time": "04:30" + } + ], + "astro_clock": true, + "dawn_lux_sensor": false, + "dusk_lux_sensor": false, + "dawn_lux_sensor_value": 5, + "dusk_lux_sensor_value": 5, + "dawn_astro_clock_offset": 30, + "dusk_astro_clock_offset": 20, + "dawn_lux_sensor_time_window": 30, + "dusk_lux_sensor_time_window": 30, + "dawn_astro_clock_time_window": 60, + "dusk_astro_clock_time_window": 60 + } + } + } + } +} + + + + const sunCalcExample = { + dusk_no_offset: '20:18', + dawn_no_offset: '05:19', + dusk: '20:18', + dusk_hours: 20, + dusk_minutes: 18, + dawn: '05:19', + dawn_hours: 5, + dawn_minutes: 19, + dusk_time: 1715278688962, + dawn_time: 1715224744357, + dusk_astro_clock_offset: 0, + dawn_astro_clock_offset: 0 +} + + +// TODO - in runTasks function, when processing tasks, wrong task gets updated +/* +[2024-05-09T20:48:00.200] [DEBUG] default - currentTask is not processed - task is in the future { + address: 0, + byte1: 0, + byte2: 0, + byte3: 0, + byte4: 0, + recipient: 0, + register: -1, + rw: 0, + priority: 3, + timestamp: 1715280480204, + addMinutesToTimestamp: 0, + type: 'relay', + line: 1, + value: 1, + tbname: 'MgnK93rkoAazbqdQ4yB2Q0yZ1YXGx6pmwBeVEP2O', + timePointName: 'luxOn', + dawn_lux_sensor_time_window: 30, + dusk_lux_sensor_time_window: 30, + info: 'luxOn: turn on line: 1', + debug: true +} +[2024-05-09T20:48:00.302] [INFO] monitorLogs - pparrams ************* { + address: 0, + byte1: 0, + byte2: 0, + byte3: 0, + byte4: 0, + recipient: 0, + register: -1, + rw: 0, + priority: 3, + timestamp: 1715280480204, + addMinutesToTimestamp: 0, + type: 'relay', + line: 1, + value: 1, + tbname: 'MgnK93rkoAazbqdQ4yB2Q0yZ1YXGx6pmwBeVEP2O', + timePointName: 'luxOn', + dawn_lux_sensor_time_window: 30, + dusk_lux_sensor_time_window: 30, + info: 'luxOn: turn on line: 1', + debug: true +} +new relay task ............ { + address: 4292, + byte1: 0, + byte2: 0, + byte3: 0, + byte4: 0, + recipient: 1, + register: 1, + rw: 0, + priority: 6, + timestamp: 1715280540301, + addMinutesToTimestamp: 1, + type: 'cmd', + tbname: 'jbN4q7JPZmexgdnz2yKbWdDYAWwO0Q3BMX6ERLoV', + info: 'generated cmd - buildTasks (node)' +} +[2024-05-09T20:48:00.304] [INFO] monitorLogs - new relay task ............. { + address: 4292, + byte1: 0, + byte2: 0, + byte3: 0, + byte4: 0, + recipient: 1, + register: 1, + rw: 0, + priority: 6, + timestamp: 1715280540301, + addMinutesToTimestamp: 1, + type: 'cmd', + tbname: 'jbN4q7JPZmexgdnz2yKbWdDYAWwO0Q3BMX6ERLoV', + info: 'generated cmd - buildTasks (node)' +} +*/ + + + + +/* +~~~~~~~~~~~~~~~~~~~~~pp { + address: 0, + byte1: 0, + byte2: 0, + byte3: 0, + byte4: 0, + recipient: 0, + register: -1, + rw: 0, + priority: 0, + timestamp: 0, + addMinutesToTimestamp: 0, + type: 'relay', + line: 1, + tbname: 'MgnK93rkoAazbqdQ4yB2Q0yZ1YXGx6pmwBeVEP2O', + value: 0, + debug: true, + info: 'turn off line on startup: 1' +} +deleting task from tasks +++++++++++++++++++++ { + address: 0, + byte1: 0, + byte2: 0, + byte3: 0, + byte4: 0, + recipient: 0, + register: -1, + rw: 0, + priority: 0, + timestamp: 0, + addMinutesToTimestamp: 0, + type: 'relay', + line: 1, + tbname: 'MgnK93rkoAazbqdQ4yB2Q0yZ1YXGx6pmwBeVEP2O', + value: 0, + debug: true, + info: 'turn off line on startup: 1' +} +[2024-05-10T09:31:36.629] [INFO] monitorLogs - pparrams ************* { + address: 0, + byte1: 0, + byte2: 0, + byte3: 0, + byte4: 0, + recipient: 0, + register: -1, + rw: 0, + priority: 0, + timestamp: 0, + addMinutesToTimestamp: 0, + type: 'relay', + line: 1, + tbname: 'MgnK93rkoAazbqdQ4yB2Q0yZ1YXGx6pmwBeVEP2O', + value: 0, + debug: true, + info: 'turn off line on startup: 1' +} +else task in relay ????? should be ??? +[2024-05-10T09:31:36.631] [INFO] monitorLogs - new relay task ............. { + address: 0, + byte1: 0, + byte2: 0, + byte3: 0, + byte4: 0, + recipient: 0, + register: -1, + rw: 0, + priority: 0, + timestamp: 0, + addMinutesToTimestamp: 0, + type: 'relay', + line: 2, + tbname: 'jBL12pg63eX4N9P7zy0lJLyEJKmlbkGwZMx0avQV', + value: 1, + debug: true, + info: 'turn on line on startup: 2' +} +*/ diff --git a/flow/dido_controller.js b/flow/dido_controller.js index 60e3976..50bec74 100644 --- a/flow/dido_controller.js +++ b/flow/dido_controller.js @@ -60,7 +60,7 @@ state_of_contactor - podľa indexu stykača sa reportuje jeho stav, teda //globals //FIRMWARE version -FLOW.OMS_edge_fw_version = "2023-10-18";//rok-mesiac-den +FLOW.OMS_edge_fw_version = "2024-05-10";//rok-mesiac-den FLOW.OMS_edgeName = ""; FLOW.OMS_maintenance_mode = false; @@ -507,15 +507,18 @@ exports.install = function(instance) { ws.on('error', (err) => { + monitor.info('websocket error, reconnect') instance.send(instanceSendTo.debug, err.message); clearInterval(startRequests); - startRequests = null; + ws = null; + setTimeout(handleWebSocket, 1000); }) ws.onclose = function(){ // connection closed, discard old websocket and create a new one in 5s // stopRequests(); + monitor.info('websocket onclose, reconnect') clearInterval(startRequests); ws = null; console.log("ws is null now, reconnecting..."); @@ -705,7 +708,7 @@ exports.install = function(instance) { // if(!rsPort.isOpen && !ws) if(!rsPort && !ws) { - errLogger.error("di do controller - port or websocket is not opened"); + errLogger.error("dido controller - port or websocket is not opened"); return; } diff --git a/flow/modbus_reader.js b/flow/modbus_reader.js index fd1ac62..52a3af6 100644 --- a/flow/modbus_reader.js +++ b/flow/modbus_reader.js @@ -139,16 +139,16 @@ exports.install = function(instance) { obj.transformResponse(resp, register, obj.deviceAddress); - obj.error = 0; + obj.errors = 0; obj.index++; obj.readAnotherRegister(); }).catch (function () { - console.log("error pri citani modbus registra", register, obj.indexInDeviceConfig, tbName, tbAttribute); + console.log("errors pri citani modbus registra", register, obj.indexInDeviceConfig, tbName, tbAttribute); - obj.error++; - if(obj.error == obj.lengthOfActualDeviceStream) + obj.errors++; + if(obj.errors == obj.lengthOfActualDeviceStream) { instance.send(instanceSendTo.dido_controller, {status: "NOK-" + obj.device}); // NOK-em340, NOK-em111, NOK-twilight_sensor, NOK-thermometer @@ -168,7 +168,7 @@ exports.install = function(instance) { numberOfNotResponding[obj.device] = 1; } - obj.error = 0; + obj.errors = 0; numberOfNotResponding[obj.device] += 1; } From 54038a06f8820a126bc1e0d95c8d4a9bf66d5b34 Mon Sep 17 00:00:00 2001 From: rasta5man Date: Tue, 21 May 2024 15:49:42 +0200 Subject: [PATCH 2/9] major updated line switching version 2024-05-10 --- databases/modbus_config.js | 2 +- flow/cmd_manager.js | 401 ++++++++----------------------------- flow/dido_controller.js | 4 + flow/modbus_reader.js | 58 +++--- 4 files changed, 112 insertions(+), 353 deletions(-) diff --git a/databases/modbus_config.js b/databases/modbus_config.js index d63430f..574de9f 100644 --- a/databases/modbus_config.js +++ b/databases/modbus_config.js @@ -1,4 +1,4 @@ -const timeoutInterval = 300000; +const timeoutInterval = 150000; const deviceConfig = [ { device: "em340", diff --git a/flow/cmd_manager.js b/flow/cmd_manager.js index b3f9871..9216b4c 100644 --- a/flow/cmd_manager.js +++ b/flow/cmd_manager.js @@ -236,6 +236,17 @@ async function loadSettings() initNotifications(); } +loadSettings(); + + +async function loadNodes() +{ + const responseNodes = await promisifyBuilder(dbNodes.find()); + nodesData = makeMapFromDbResult(responseNodes, "node"); +} + +loadNodes(); + //nastav profil nodu function processNodeProfile(node) @@ -680,7 +691,6 @@ function removeTask(obj) } -loadSettings(); exports.install = function(instance) { @@ -1002,6 +1012,8 @@ exports.install = function(instance) { //report FLOW.OMS_edge_fw_version as fw_version //report date as startdate + //return; + monitor.info("buildTasks - params", params); let processLine; //defined line @@ -1224,6 +1236,10 @@ exports.install = function(instance) { try { + + /** + * we process line profiles: timepoints, astro clock, lux_sensor, offsets ... + */ if(profilestr === "") throw ("Profile is not defined"); let profile = JSON.parse(profilestr); if(Object.keys(profile).length === 0) throw ("Profile is empty"); @@ -1245,6 +1261,7 @@ exports.install = function(instance) { let currentValue = 0; if(time_points.length > 0) currentValue = time_points[time_points.length - 1].value; + /** * if astro_clock is true, we create timepoints, that switch on/off relays accordingly. * we need to manage, astro clock timepoints has the greatest priority - normal timepoints will not switch off/on lines before dusk or dawn @@ -1698,121 +1715,88 @@ exports.install = function(instance) { } + /** + * We process line profile, where "astro_clock": true + * example profile: + * + "dawn_lux_sensor": true, + "dusk_lux_sensor": true, + "dawn_lux_sensor_value": 5, + "dusk_lux_sensor_value": 5, + "dawn_astro_clock_offset": 0, + "dusk_astro_clock_offset": 10, + "dawn_lux_sensor_time_window": 30, + "dusk_lux_sensor_time_window": 30, + "dawn_astro_clock_time_window": 60, + "dusk_astro_clock_time_window": 60 + + * if dawn: if currentTimestamp is in timewindow "dawnTime + and - dawn_lux_sensor_time_window" and lux value >= lux_sensor_value, we switch off the line. + * if dusk: we do oposite + * + * dawn: usvit - lux je nad hranicou - vypnem + * dusk: sumrak - lux je pod hranicou - zapnem + */ function turnOnOffLinesAccordingToLuxSensor(lux_sensor_value) { - //let dusk_hours = sunCalcResult["dusk_hours"]; - //let dusk_minutes = sunCalcResult["dusk_minutes"]; - - let duskTimeStamp; - let downTimeStamp; - - //prejedme si line s profilom, kde mame "astro_clock": true - - /* - "dawn_lux_sensor": true, - "dusk_lux_sensor": true, - "dawn_lux_sensor_value": 5, - "dusk_lux_sensor_value": 5, - "dawn_astro_clock_offset": 0, - "dusk_astro_clock_offset": 10, - "dawn_lux_sensor_time_window": 30, - "dusk_lux_sensor_time_window": 30, - "dawn_astro_clock_time_window": 60, - "dusk_astro_clock_time_window": 60 - */ - - //ak sme pred/po vychode a lux value <= lux_sensor_value, liniu zapneme - - //ak sme pred/po zapade a lux_value <= lux_sensor_value, liniu zapneme let now = new Date(); let currentTimestamp = now.getTime(); - let keys = Object.keys(relaysData); + for(let i = 0; i < keys.length; i++) { - let line = keys[i];//line is turned off by default - let profilestr = relaysData[line].profile; - let contactor = relaysData[line].contactor; // 0 or 1 - vypnuta/zapnuta - try{ + let line = keys[i]; //line is turned off by default + let profilestr = relaysData[line].profile; + const contactor = relaysData[line].contactor; + + try { let profile = JSON.parse(profilestr); - if(Object.keys(profile).length === 0) throw ("profile is not defined"); + if(Object.keys(profile).length === 0) throw ("turnOnOffLinesAccordingToLuxSensor - profile is not defined"); if(profile.astro_clock == true) { - let sunCalcResult = calculateDuskDawn(now, line); + let sunCalcResult = calculateDuskDawn(now, line); - //dawn: usvit/vychod - lux je nad hranicou - vypnem - //dusk: zapad pod hranicou - zapnem + //usvit + if(profile.dawn_lux_sensor == true) + { + let lux_sensor_time_window1 = sunCalcResult.dawn_time - (parseInt( profile.dawn_lux_sensor_time_window ) * 1000 * 60); // LUX_SENSOR_TIME_WINDOW x 1000 x 60 --> dostaneme odpocet/pripocitanie minut + let lux_sensor_time_window2 = sunCalcResult.dawn_time + (parseInt( profile.dawn_lux_sensor_time_window ) * 1000 * 60); - //"dawn_lux_sensor_time_window": 30, - //"dusk_lux_sensor_time_window": 30, - - //vychod - // LUX_SENSOR_TIME_WINDOW x 1000 x 60 --> dostaneme odpocet/pripocitanie minut - if(profile.dawn_lux_sensor == true) + if(currentTimestamp >= lux_sensor_time_window1 && currentTimestamp <= lux_sensor_time_window2) { - let lux_sensor_time_window1 = sunCalcResult.dawn_time - (parseInt( profile.dawn_lux_sensor_time_window ) * 1000 * 60); - let lux_sensor_time_window2 = sunCalcResult.dawn_time + (parseInt( profile.dawn_lux_sensor_time_window ) * 1000 * 60); - //console.log('------>>>', new Date(lux_sensor_time_window1), new Date(lux_sensor_time_window2), lux_sensor_time_window1, lux_sensor_time_window2) - //console.log('++++-->>>', new Date(sunCalcResult.dusk_time), new Date(sunCalcResult.dawn_time)) - - if(currentTimestamp >= lux_sensor_time_window1 && currentTimestamp <= lux_sensor_time_window2) - { - //dawn: usvit/vychod - lux je nad hranicou - vypnem - if(lux_sensor_value > profile.dawn_lux_sensor_value) - { - //vypnem - if(contactor) turnOffLine(line, "profile: dawn - turnOff line according to lux sensor"); - } - // else - // { - // //zapnem - // if(!contactor) turnOnLine(line, "profile: dawn - turnOn line according to lux sensor"); - // } - - } - - //ak sme po vychode - if(currentTimestamp > lux_sensor_time_window2) - { - //vypneme - //urobime jednorazovy prikaz - } + if(lux_sensor_value > profile.dawn_lux_sensor_value) + { + if(contactor) turnOffLine(line, "Profile: dawn - turnOff line according to lux sensor"); + } } + } - //zapad - if(profile.dusk_lux_sensor == true) + //sumrak + if(profile.dusk_lux_sensor == true) + { + let lux_sensor_time_window1 = sunCalcResult.dusk_time - (parseInt( profile.dusk_lux_sensor_time_window ) * 1000 * 60); + let lux_sensor_time_window2 = sunCalcResult.dusk_time + (parseInt( profile.dusk_lux_sensor_time_window ) * 1000 * 60); + + if(currentTimestamp >= lux_sensor_time_window1 && currentTimestamp <= lux_sensor_time_window2) { - let lux_sensor_time_window1 = sunCalcResult.dusk_time - (parseInt( profile.dusk_lux_sensor_time_window ) * 1000 * 60); - let lux_sensor_time_window2 = sunCalcResult.dusk_time + (parseInt( profile.dusk_lux_sensor_time_window ) * 1000 * 60); - - if(currentTimestamp >= lux_sensor_time_window1 && currentTimestamp <= lux_sensor_time_window2) - { - //dusk: zapad pod hranicou - zapnem - if(lux_sensor_value < profile.dusk_lux_sensor_value) - { - //zapnem - if(!contactor) turnOnLine(line, "profile: dusk - turnOn line according to lux sensor"); - } - // else - // { - // //vypnem - // if(contactor) turnOffLine(line, "profile: dusk - turnOff line according to lux sensor"); - // } - - } + if(lux_sensor_value < profile.dusk_lux_sensor_value) + { + if(!contactor) turnOnLine(line, "Profile: dusk - turnOn line according to lux sensor"); + } } - + } } } catch (error) { - //if(profilestr !=="" ) logger.debug(profilestr, error); + if(profilestr !== "" ) monitor.info('Error parsing profile in turnOnOffLinesAccordingToLuxSensor', error); } + } + } @@ -1842,7 +1826,7 @@ exports.install = function(instance) { async function runTasks() { - + clearInterval(interval); let currentTimestamp = Date.now(); @@ -2049,19 +2033,14 @@ exports.install = function(instance) { if(type == "edge_date_time") { + const ts = Date.now(); - //var d = new Date(); - //let hours = addZeroBefore(d.getHours()); - //let minutes = addZeroBefore(d.getMinutes()); - //let seconds = addZeroBefore(d.getSeconds()); - //let values = {"edge_date_time": `${hours}:${minutes}:${seconds}`}; - - let values = {"edge_date_time": Date.now()}; + let values = {"edge_date_time": ts}; let dataToTb = { [tbname]: [ { - "ts": Date.now(), + "ts": ts, "values": values } ] @@ -2069,11 +2048,8 @@ exports.install = function(instance) { tasks[0].timestamp = currentTimestamp + tasks[0].addMinutesToTimestamp * 60000; - //instance.send(SEND_TO.tb, dataToTb); - tbHandler.sendToTb(dataToTb, instance); - + instance.send(SEND_TO.tb, dataToTb); interval = setInterval(runTasks, SHORT_INTERVAL); - return; } @@ -3832,33 +3808,8 @@ function com_generic(adresa, rec, rw, register, name, byte1, byte2, byte3, byte4 - -const lineTimepointsExample1 = -[ - { start_time: '05:17', value: 0, name: 'dawn' }, - { value: 0, end_time: '13:00', start_time: '05:30' }, - { value: 0, end_time: '20:00', start_time: '13:00' }, - { value: 1, end_time: '05:30', start_time: '20:00' }, - { start_time: '20:19', value: 1, name: 'dusk' } -] - - - -const lineTimepointsExample2 = -[ - { value: 0, end_time: '13:00', start_time: '05:30' }, - { value: 0, start_time: '5:47', name: 'luxOff' }, - { value: 0, end_time: '20:00', start_time: '13:00' }, - { value: 1, end_time: '05:30', start_time: '20:00' }, - { value: 1, start_time: '20:49', name: 'luxOn' } -] - - - - // SAMPLE DATA - const relaysDataExample = { '0': { @@ -3888,36 +3839,6 @@ const relaysDataExample = } -// [2024-05-08T11:43:33.055] [DEBUG] default - --->reportOfflineNodeStatus for line 2 -// [2024-05-08T11:43:33.055] [DEBUG] default - --->reportOfflineNodeStatus for line 3 -// [2024-05-08T11:43:35.737] [DEBUG] default - -->CMD MANAGER - BUILD TASKS -// [2024-05-08T11:43:35.742] [INFO] monitorLogs - buildTasks - params undefined -// [2024-05-08T11:43:35.743] [DEBUG] default - -->buildTasks clear tasks -// [2024-05-08T11:43:35.744] [INFO] monitorLogs - buildTasks: profile for line 1 -// [2024-05-08T11:43:35.745] [INFO] monitorLogs - profile: { -// intervals: [ { value: 1, end_time: '13:00', start_time: '13:00' } ], -// astro_clock: false, -// dawn_lux_sensor: false, -// dusk_lux_sensor: false, -// dawn_lux_sensor_value: 5, -// dusk_lux_sensor_value: 5, -// dawn_astro_clock_offset: 0, -// dusk_astro_clock_offset: 0, -// dawn_lux_sensor_time_window: 30, -// dusk_lux_sensor_time_window: 30, -// dawn_astro_clock_time_window: 60, -// dusk_astro_clock_time_window: 60 -// } -// [2024-05-08T11:43:35.747] [INFO] monitorLogs - -->comming events turn on/off lines: -// [2024-05-08T11:43:35.748] [INFO] monitorLogs - turn on line: 1 2024-05-08T11:00:00.747Z -// [2024-05-08T11:43:35.749] [INFO] monitorLogs - -->time_points final 1 [ { value: 1, end_time: '13:00', start_time: '13:00' } ] -// [2024-05-08T11:43:35.751] [INFO] monitorLogs - -->currentValue for relay 1 1 -// -// -// typ paramu ...... / cmd - - - const rpcSwitchOffLine = { "topic": "v1/gateway/rpc", @@ -4088,8 +4009,6 @@ const rpcNodeProfile = } } - - const sunCalcExample = { dusk_no_offset: '20:18', dawn_no_offset: '05:19', @@ -4104,167 +4023,3 @@ const rpcNodeProfile = dusk_astro_clock_offset: 0, dawn_astro_clock_offset: 0 } - - -// TODO - in runTasks function, when processing tasks, wrong task gets updated -/* -[2024-05-09T20:48:00.200] [DEBUG] default - currentTask is not processed - task is in the future { - address: 0, - byte1: 0, - byte2: 0, - byte3: 0, - byte4: 0, - recipient: 0, - register: -1, - rw: 0, - priority: 3, - timestamp: 1715280480204, - addMinutesToTimestamp: 0, - type: 'relay', - line: 1, - value: 1, - tbname: 'MgnK93rkoAazbqdQ4yB2Q0yZ1YXGx6pmwBeVEP2O', - timePointName: 'luxOn', - dawn_lux_sensor_time_window: 30, - dusk_lux_sensor_time_window: 30, - info: 'luxOn: turn on line: 1', - debug: true -} -[2024-05-09T20:48:00.302] [INFO] monitorLogs - pparrams ************* { - address: 0, - byte1: 0, - byte2: 0, - byte3: 0, - byte4: 0, - recipient: 0, - register: -1, - rw: 0, - priority: 3, - timestamp: 1715280480204, - addMinutesToTimestamp: 0, - type: 'relay', - line: 1, - value: 1, - tbname: 'MgnK93rkoAazbqdQ4yB2Q0yZ1YXGx6pmwBeVEP2O', - timePointName: 'luxOn', - dawn_lux_sensor_time_window: 30, - dusk_lux_sensor_time_window: 30, - info: 'luxOn: turn on line: 1', - debug: true -} -new relay task ............ { - address: 4292, - byte1: 0, - byte2: 0, - byte3: 0, - byte4: 0, - recipient: 1, - register: 1, - rw: 0, - priority: 6, - timestamp: 1715280540301, - addMinutesToTimestamp: 1, - type: 'cmd', - tbname: 'jbN4q7JPZmexgdnz2yKbWdDYAWwO0Q3BMX6ERLoV', - info: 'generated cmd - buildTasks (node)' -} -[2024-05-09T20:48:00.304] [INFO] monitorLogs - new relay task ............. { - address: 4292, - byte1: 0, - byte2: 0, - byte3: 0, - byte4: 0, - recipient: 1, - register: 1, - rw: 0, - priority: 6, - timestamp: 1715280540301, - addMinutesToTimestamp: 1, - type: 'cmd', - tbname: 'jbN4q7JPZmexgdnz2yKbWdDYAWwO0Q3BMX6ERLoV', - info: 'generated cmd - buildTasks (node)' -} -*/ - - - - -/* -~~~~~~~~~~~~~~~~~~~~~pp { - address: 0, - byte1: 0, - byte2: 0, - byte3: 0, - byte4: 0, - recipient: 0, - register: -1, - rw: 0, - priority: 0, - timestamp: 0, - addMinutesToTimestamp: 0, - type: 'relay', - line: 1, - tbname: 'MgnK93rkoAazbqdQ4yB2Q0yZ1YXGx6pmwBeVEP2O', - value: 0, - debug: true, - info: 'turn off line on startup: 1' -} -deleting task from tasks +++++++++++++++++++++ { - address: 0, - byte1: 0, - byte2: 0, - byte3: 0, - byte4: 0, - recipient: 0, - register: -1, - rw: 0, - priority: 0, - timestamp: 0, - addMinutesToTimestamp: 0, - type: 'relay', - line: 1, - tbname: 'MgnK93rkoAazbqdQ4yB2Q0yZ1YXGx6pmwBeVEP2O', - value: 0, - debug: true, - info: 'turn off line on startup: 1' -} -[2024-05-10T09:31:36.629] [INFO] monitorLogs - pparrams ************* { - address: 0, - byte1: 0, - byte2: 0, - byte3: 0, - byte4: 0, - recipient: 0, - register: -1, - rw: 0, - priority: 0, - timestamp: 0, - addMinutesToTimestamp: 0, - type: 'relay', - line: 1, - tbname: 'MgnK93rkoAazbqdQ4yB2Q0yZ1YXGx6pmwBeVEP2O', - value: 0, - debug: true, - info: 'turn off line on startup: 1' -} -else task in relay ????? should be ??? -[2024-05-10T09:31:36.631] [INFO] monitorLogs - new relay task ............. { - address: 0, - byte1: 0, - byte2: 0, - byte3: 0, - byte4: 0, - recipient: 0, - register: -1, - rw: 0, - priority: 0, - timestamp: 0, - addMinutesToTimestamp: 0, - type: 'relay', - line: 2, - tbname: 'jBL12pg63eX4N9P7zy0lJLyEJKmlbkGwZMx0avQV', - value: 1, - debug: true, - info: 'turn on line on startup: 2' -} -*/ diff --git a/flow/dido_controller.js b/flow/dido_controller.js index 50bec74..0952350 100644 --- a/flow/dido_controller.js +++ b/flow/dido_controller.js @@ -864,6 +864,10 @@ exports.install = function(instance) { { deviceStatuses["em"] = "OK"; } + else + { + return; + } const updateStatus = checkFinalRVOStatus(); if(updateStatus) values.status = "OK"; diff --git a/flow/modbus_reader.js b/flow/modbus_reader.js index 52a3af6..898816e 100644 --- a/flow/modbus_reader.js +++ b/flow/modbus_reader.js @@ -16,17 +16,12 @@ exports.readme = ` const modbus = require('jsmodbus') const SerialPort = require('serialport') - const { timeoutInterval, deviceConfig } = require("../databases/modbus_config"); - -const ErrorToServiceHandler = require('./helper/ErrorToServiceHandler'); -const errorHandler = new ErrorToServiceHandler(); - const { sendNotification } = require('./helper/notification_reporter'); const DELAY_BETWEEN_DEVICES = 10000; -const instanceSendTo = { +const SEND_TO = { debug: 0, dido_controller: 1, tb: 2 @@ -49,9 +44,9 @@ exports.install = function(instance) { this.index = 0; this.timeoutInterval = 5000; - // kedze potrebujeme ist stale dookola pre jednotlive zariadenia, potrebujeme ci uz index ako aj adresu zariadenia, a aj pocet registrov na vycitanie - this.deviceAddress = null; // adresa zariadenia (1 ma EM340 a 2 ma twilight_sensor) - this.indexInDeviceConfig = 0; // prvy item v deviceConfig + // we need to go always around for all devices. So we need index value, device address, as well as number of registers for single device + this.deviceAddress = null; // device address (1 - EM340 and 2 for twilight_sensor) + this.indexInDeviceConfig = 0; // first item in deviceConfig this.lengthOfActualDeviceStream = null; this.device = null; @@ -69,7 +64,7 @@ exports.install = function(instance) { // we create a client for every deviceAddress ( = address) in list and push them into dictionary for( let i = 0; i < deviceConfig.length; i++) { - this.clients[deviceConfig[i].deviceAddress] = new modbus.client.RTU(this.socket, deviceConfig[i].deviceAddress); + this.clients[deviceConfig[i].deviceAddress] = new modbus.client.RTU(this.socket, deviceConfig[i].deviceAddress, 2000); // 2000 is timeout in register request, default is 5000, which is too long } this.socket.on('error', function(e) { @@ -133,13 +128,13 @@ exports.install = function(instance) { { message = "twilight_sensor_ok"; } - message && sendNotification("modbus_reader: readRegisters", tbName, message, {}, "", instanceSendTo.tb, instance); + message && sendNotification("modbus_reader: readRegisters", tbName, message, {}, "", SEND_TO.tb, instance); delete numberOfNotResponding[obj.device]; } - obj.transformResponse(resp, register, obj.deviceAddress); + obj.transformResponse(resp, register); - obj.errors = 0; + //obj.errors = 0; obj.index++; obj.readAnotherRegister(); @@ -150,7 +145,7 @@ exports.install = function(instance) { obj.errors++; if(obj.errors == obj.lengthOfActualDeviceStream) { - instance.send(instanceSendTo.dido_controller, {status: "NOK-" + obj.device}); // NOK-em340, NOK-em111, NOK-twilight_sensor, NOK-thermometer + instance.send(SEND_TO.dido_controller, {status: "NOK-" + obj.device}); // NOK-em340, NOK-em111, NOK-twilight_sensor, NOK-thermometer //todo - neposlalo notification, ked sme vypojili twilight a neposle to do tb, ale do dido ?? if(!numberOfNotResponding.hasOwnProperty(obj.device)) @@ -164,7 +159,7 @@ exports.install = function(instance) { { message = "electrometer_nok"; } - message && sendNotification("modbus_reader: readingTimeouted", tbName, message, {}, "", instanceSendTo.tb, instance); + message && sendNotification("modbus_reader: readingTimeouted", tbName, message, {}, "", SEND_TO.tb, instance); numberOfNotResponding[obj.device] = 1; } @@ -176,6 +171,12 @@ exports.install = function(instance) { depth: null })) + // if reading out of device's last register returns error, we send accumulated allValues to dido_controller (if allValues are not an empty object) + if(obj.index + 1 >= obj.lengthOfActualDeviceStream) + { + if(!isObjectEmpty(obj.allValues)) instance.send(SEND_TO.dido_controller, {values: obj.allValues}); + obj.allValues = {}; + } obj.index++; obj.readAnotherRegister(); }) @@ -187,7 +188,7 @@ exports.install = function(instance) { else this.setNewStream(); } - transformResponse = (response, register, deviceAddress) => { + transformResponse = (response, register) => { for (let i = 0; i < this.lengthOfActualDeviceStream; i++) { @@ -198,11 +199,11 @@ exports.install = function(instance) { let multiplier = a.multiplier; let value = this.calculateValue(response, multiplier); - // console.log(deviceAddress, register, tbName, tbAttribute, response, a.multiplier, value); + // console.log(register, tbName, tbAttribute, response, a.multiplier, value); // if(tbName == undefined) return; - if(this.index + 1 + this.errors < this.lengthOfActualDeviceStream) + if(this.index + 1 < this.lengthOfActualDeviceStream) { this.allValues[tbAttribute] = value; return; @@ -215,7 +216,7 @@ exports.install = function(instance) { this.checkNullVoltage(values); - instance.send(instanceSendTo.dido_controller, {values: values}); + instance.send(SEND_TO.dido_controller, {values: values}); this.allValues = {}; break; @@ -227,8 +228,6 @@ exports.install = function(instance) { setNewStream = () => { - // console.log('------------',this.lengthOfActualDeviceStream, this.index); - // console.log('------------',this.indexInDeviceConfig, deviceConfig.length); if(this.lengthOfActualDeviceStream == this.index) { if(this.indexInDeviceConfig + 1 == deviceConfig.length) @@ -260,13 +259,13 @@ exports.install = function(instance) { // ] // }; - // instance.send(instanceSendTo.tb, dataToTB); + // instance.send(SEND_TO.tb, dataToTB); // const dataToDiDo = { // values: values // } - // instance.send(instanceSendTo.dido_controller, dataToDiDo); + // instance.send(SEND_TO.dido_controller, dataToDiDo); // } @@ -314,27 +313,28 @@ exports.install = function(instance) { if(values[singleValue] == 0) { FLOW.OMS_no_voltage.add(phase); - sendNotification("modbus_citys: checkNullVoltage", tbName, "no_voltage_on_phase", {phase: phase}, "", instanceSendTo.tb, instance, "voltage" + phase ); + sendNotification("modbus_citys: checkNullVoltage", tbName, "no_voltage_on_phase", {phase: phase}, "", SEND_TO.tb, instance, "voltage" + phase ); // console.log('no voltage') } else { FLOW.OMS_no_voltage.delete(phase); // console.log('voltage detected') - sendNotification("modbus_citys: checkNullVoltage", tbName, "voltage_on_phase_restored", {phase: phase}, "", instanceSendTo.tb, instance, "voltage" + phase); + sendNotification("modbus_citys: checkNullVoltage", tbName, "voltage_on_phase_restored", {phase: phase}, "", SEND_TO.tb, instance, "voltage" + phase); } } }) } - // we use dataToTbHandler. Therefore we need to check, if objects we send to dido_controller are not empty - isObjectEmpty = (objectName) => { - return Object.keys(objectName).length === 0 && objectName.constructor === Object; - } } + const isObjectEmpty = (objectName) => { + return Object.keys(objectName).length === 0 && objectName.constructor === Object; + } + setTimeout(() => { const newSocket = new SocketWithClients(); tbName = FLOW.OMS_rvo_tbname; }, 25000); } + From 2f659a164b2deb1553b6c824a5746b79068d3c62 Mon Sep 17 00:00:00 2001 From: Jakub Klena Date: Fri, 24 May 2024 01:19:34 +0200 Subject: [PATCH 3/9] Slack connector component --- flow/slack_connector.js | 112 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 flow/slack_connector.js diff --git a/flow/slack_connector.js b/flow/slack_connector.js new file mode 100644 index 0000000..b0be352 --- /dev/null +++ b/flow/slack_connector.js @@ -0,0 +1,112 @@ +exports.id = 'slack_connector'; +exports.title = 'Slack_Connector'; +exports.version = '1.0.0'; +exports.group = 'Worksys'; +exports.color = '#888600'; +exports.input = 1; +exports.output = 1; +exports.click = false; +exports.author = 'Jakub Klena'; +exports.icon = 'sign-out'; +exports.options = { slack_channel: "C071KN2Q8SK", bot_name: "Flow DEMO", bot_icon: ":totaljs:" }; +// Slack channel - where to post the messages, can be name like "backend-alerts" +// Bot Name - Name of the "user" that will post these messages, it should be based on which server it is running on. +// Bot Icon - We can use any slack icon (even custom ones uploaded by us) as the "user" profile picture + +exports.html = `
+
+
+
Slack Channel
+
+
+
+
+
Bot Name
+
+
+
Bot Icon
+
+
+
`; + +exports.readme = `Sends any string received on input to Slack Channel.`; + +var log4js = require("log4js"); +var path = require('path'); + +log4js.configure({ + appenders: { + errLogs: { type: 'file', compress:true, daysToKeep: 2, maxLogSize: 1048576, backups: 1, keepFileExt: true, filename: path.join(__dirname + "/../", 'err.txt') }, + monitorLogs: { type: 'file', compress:true, daysToKeep: 2, maxLogSize: 1048576, backups: 1, keepFileExt: true, filename: path.join(__dirname + "/../", 'monitor.txt') }, + console: { type: 'console' } + }, + categories: { + errLogs: { appenders: ['console', 'errLogs'], level: 'error' }, + monitorLogs: { appenders: ['console', 'monitorLogs'], level: 'trace' }, + //another: { appenders: ['console'], level: 'trace' }, + default: { appenders: ['console'], level: 'trace' } + } +}); + +const errLogger = log4js.getLogger("errLogs"); +const logger = log4js.getLogger(); +const monitor = log4js.getLogger("monitorLogs"); + +exports.install = function(instance) { + process.on('uncaughtException', function (err) { + errLogger.error('uncaughtException:', err.message); + errLogger.error(err.stack); + instance.error(err); + }); + + instance.on('data', function(data) { + let str = String(data); // Ensuring data get converted to string + let message = `{ + channel: ${instance.options.slack_channel}, + username: ${instance.options.bot_name}, + icon_emoji: ${instance.options.bot_icon}, + text: ${str} + }`; + let headers = { + 'Content-type': `application/json`, + 'Authorization': `Bearer xoxb-7060441089557-7144902656932-7IU6yMlvscrNtm5KrZxbm7Tf` + }; + + if (F.is4) { + let opt = { + 'method': 'post', + 'url': 'https://slack.com/api/chat.postMessage', + 'headers': { + 'Content-type': `application/json`, + 'Authorization': `Bearer xoxb-7060441089557-7144902656932-7IU6yMlvscrNtm5KrZxbm7Tf` + }, + 'cookies': null, + 'body': JSON.stringify(message), + 'type': 'json', + 'callback': function(err, response) { + if (response && !err) { + var msg = { data: response.body, status: response.status, headers: response.headers, host: response.host, cookies: response.cookies }; + instance.send2(msg); + } else if (err) + errLogger.error('Slack post failed - err:', err, '\n - response was:', response); + instance.error(err, response); + } + }; + REQUEST(opt); + + } else { + + U.request('https://slack.com/api/chat.postMessage', ['json', 'post'], JSON.stringify(message), function(err, data, status, headers, host) { + console.log("err: ", err); + console.log("resp: ", response); + if (response && !err) { + response.data = { data: data, status: status, headers: headers, host: host }; + instance.send2(response); + } else if (err) { + errLogger.error('Slack post failed - err:', err, '\n - response was:', response); + instance.error(err, response); + } + }, null, headers); + } + }); +} From 9e2ab3ccead41e3560902922f824d0e9e1664239 Mon Sep 17 00:00:00 2001 From: Jakub Klena Date: Fri, 24 May 2024 01:24:08 +0200 Subject: [PATCH 4/9] api key fix --- flow/slack_connector.js | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/flow/slack_connector.js b/flow/slack_connector.js index b0be352..ba8638a 100644 --- a/flow/slack_connector.js +++ b/flow/slack_connector.js @@ -8,7 +8,7 @@ exports.output = 1; exports.click = false; exports.author = 'Jakub Klena'; exports.icon = 'sign-out'; -exports.options = { slack_channel: "C071KN2Q8SK", bot_name: "Flow DEMO", bot_icon: ":totaljs:" }; +exports.options = { slack_channel: "C071KN2Q8SK", api_key: "", bot_name: "Flow DEMO", bot_icon: ":totaljs:" }; // Slack channel - where to post the messages, can be name like "backend-alerts" // Bot Name - Name of the "user" that will post these messages, it should be based on which server it is running on. // Bot Icon - We can use any slack icon (even custom ones uploaded by us) as the "user" profile picture @@ -19,6 +19,11 @@ exports.html = `
Slack Channel
+
+
+
API Key:
+
+
Bot Name
@@ -69,17 +74,14 @@ exports.install = function(instance) { }`; let headers = { 'Content-type': `application/json`, - 'Authorization': `Bearer xoxb-7060441089557-7144902656932-7IU6yMlvscrNtm5KrZxbm7Tf` + 'Authorization': `Bearer ${instance.options.api_key}` }; if (F.is4) { let opt = { 'method': 'post', 'url': 'https://slack.com/api/chat.postMessage', - 'headers': { - 'Content-type': `application/json`, - 'Authorization': `Bearer xoxb-7060441089557-7144902656932-7IU6yMlvscrNtm5KrZxbm7Tf` - }, + 'headers': headers, 'cookies': null, 'body': JSON.stringify(message), 'type': 'json', From 6d468acd6f308bd9485b39c5ebaaff905b4109c8 Mon Sep 17 00:00:00 2001 From: Jakub Klena Date: Fri, 24 May 2024 08:42:21 +0200 Subject: [PATCH 5/9] proper last version --- flow/slack_connector.js | 114 ++++++++++++++++++++++------------------ 1 file changed, 64 insertions(+), 50 deletions(-) diff --git a/flow/slack_connector.js b/flow/slack_connector.js index ba8638a..6561217 100644 --- a/flow/slack_connector.js +++ b/flow/slack_connector.js @@ -58,57 +58,71 @@ const logger = log4js.getLogger(); const monitor = log4js.getLogger("monitorLogs"); exports.install = function(instance) { - process.on('uncaughtException', function (err) { - errLogger.error('uncaughtException:', err.message); - errLogger.error(err.stack); - instance.error(err); - }); + var can = false; - instance.on('data', function(data) { - let str = String(data); // Ensuring data get converted to string - let message = `{ - channel: ${instance.options.slack_channel}, - username: ${instance.options.bot_name}, - icon_emoji: ${instance.options.bot_icon}, - text: ${str} - }`; - let headers = { - 'Content-type': `application/json`, - 'Authorization': `Bearer ${instance.options.api_key}` + process.on('uncaughtException', function (err) { + errLogger.error('uncaughtException:', err.message); + errLogger.error(err.stack); + instance.error(err); + }); + + instance.on('data', function(data) { + if (!can) return; + + let str = String(data.data); // Ensuring data get converted to string + let message = { + 'channel': instance.options.slack_channel, + 'username': instance.options.bot_name, + 'icon_emoji': instance.options.bot_icon, + 'text': str + }; + let headers = { + 'Content-type': `application/json`, + 'Authorization': `Bearer ${instance.options.api_key}` + }; + + if (F.is4) { + instance.send2("is F4"); + let opt = { + 'method': 'post', + 'url': 'https://slack.com/api/chat.postMessage', + 'headers': headers, + 'body': JSON.stringify(message), + 'type': 'json', + 'callback': function(err, response) { + if (response && !err) { + var msg = { data: response.body, status: response.status, headers: response.headers, host: response.host, cookies: response.cookies }; + instance.send2(msg); + } else if (err) { + errLogger.error('Slack post failed - err:', err, '\n - response was:', response); + instance.error(err, response); + } + } + }; + instance.send2(opt); + REQUEST(opt); + + } else { + instance.send2("is NOT F4"); + + U.request('https://slack.com/api/chat.postMessage', ['json', 'post'], message, function(err, data, status, headers, host) { + if (response && !err) { + response.data = { data: data, status: status, headers: headers, host: host }; + instance.send2(response); + } else if (err) { + errLogger.error('Slack post failed - err:', err, '\n - response was:', response); + instance.error(err, response); + } + }, null, headers); + } + }); + + instance.reconfigure = function() { + var options = instance.options; + can = options.slack_channel && options.bot_name && options.bot_icon && options.api_key ? true : false; + instance.status(can ? '' : 'Not configured', can ? undefined : 'red'); }; - if (F.is4) { - let opt = { - 'method': 'post', - 'url': 'https://slack.com/api/chat.postMessage', - 'headers': headers, - 'cookies': null, - 'body': JSON.stringify(message), - 'type': 'json', - 'callback': function(err, response) { - if (response && !err) { - var msg = { data: response.body, status: response.status, headers: response.headers, host: response.host, cookies: response.cookies }; - instance.send2(msg); - } else if (err) - errLogger.error('Slack post failed - err:', err, '\n - response was:', response); - instance.error(err, response); - } - }; - REQUEST(opt); - - } else { - - U.request('https://slack.com/api/chat.postMessage', ['json', 'post'], JSON.stringify(message), function(err, data, status, headers, host) { - console.log("err: ", err); - console.log("resp: ", response); - if (response && !err) { - response.data = { data: data, status: status, headers: headers, host: host }; - instance.send2(response); - } else if (err) { - errLogger.error('Slack post failed - err:', err, '\n - response was:', response); - instance.error(err, response); - } - }, null, headers); - } - }); + instance.on('options', instance.reconfigure); + instance.reconfigure(); } From 1b7aae45905c624a68280c1e6695bc236fc07815 Mon Sep 17 00:00:00 2001 From: Jakub Klena Date: Fri, 24 May 2024 08:44:15 +0200 Subject: [PATCH 6/9] removing some debug msgs --- flow/slack_connector.js | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/flow/slack_connector.js b/flow/slack_connector.js index 6561217..8c073a6 100644 --- a/flow/slack_connector.js +++ b/flow/slack_connector.js @@ -82,7 +82,6 @@ exports.install = function(instance) { }; if (F.is4) { - instance.send2("is F4"); let opt = { 'method': 'post', 'url': 'https://slack.com/api/chat.postMessage', @@ -99,13 +98,10 @@ exports.install = function(instance) { } } }; - instance.send2(opt); REQUEST(opt); } else { - instance.send2("is NOT F4"); - - U.request('https://slack.com/api/chat.postMessage', ['json', 'post'], message, function(err, data, status, headers, host) { + U.request('https://slack.com/api/chat.postMessage', ['json', 'post'], JSON.stringify(message), function(err, data, status, headers, host) { if (response && !err) { response.data = { data: data, status: status, headers: headers, host: host }; instance.send2(response); From f4ffef94b986f2e49e6523acec5b95fc5f485dad Mon Sep 17 00:00:00 2001 From: rasta5man Date: Thu, 20 Jun 2024 17:56:49 +0200 Subject: [PATCH 7/9] kovalov part delete --- flow/cmd_manager.js | 204 ++------------------------------------------ 1 file changed, 5 insertions(+), 199 deletions(-) diff --git a/flow/cmd_manager.js b/flow/cmd_manager.js index 9216b4c..3a03acc 100644 --- a/flow/cmd_manager.js +++ b/flow/cmd_manager.js @@ -58,8 +58,8 @@ const process = require('process'); //TODO - to remove? // runTasks intervals -const SHORT_INTERVAL = 50; -const LONG_INTERVAL = 500; +const SHORT_INTERVAL = 30; +const LONG_INTERVAL = 300; //send data to following instances: const SEND_TO = { @@ -1052,183 +1052,6 @@ exports.install = function(instance) { let line = parseInt(keys[i]); //line is turned off by default let profilestr = relaysData[line].profile; - //Reset linii - let resetLine = false; - if(FLOW.OMS_rvo_name == "Kovalov RVO 2" && line != 0 && init == true) resetLine = true; - - if(resetLine) - { - /* - - Takže v Koválove sú nastavené offesty pre dusk a dawn nasledovne: - - DUSK: offset +20 minút – teda napr. namiesto 17:00 bude 17:20 a reštart by sa robil v čase 17:19, teda o minútu skôr. Tak aby keď budeš robiť zapnutie o 17:20 tak na RVO1 sa svietidlá zapnú v rovnakom čase. - Teda: vypnutie v čase DUSK_TIME + 19 minút, zapnutie v čase DUSK_TIME + 20 minút - DAWN: offset -30 minút – teda napr. namiesto 7:00 bude 6:30 a reštart by sa robil v čase 6:30, tak aby sa svietidlá zhasli rovnako s RVO1. Zapnutie by bolo 6:31. - Teda: vypnutie v čase DAWN_TIME -30 minút, zapnutie v čase DAWN_TIME -29 minút - - Vždy po reštarte asi 30 sekúnd po zapnutí treba poslať aktuálny čas na nody. - */ - - //function calculateDuskDawn(date, line, duskOffset = 0, dawnOffset = 0) - let duskOffset = 20; - let dawnOffset = -30; - let sunCalcResult = calculateDuskDawn(new Date(), undefined, duskOffset, dawnOffset); - - console.log(sunCalcResult); - monitor.info("--> dusk - dawn", sunCalcResult); - - //if(isDusk) time_points[t].value = 1;//sumrak - zapneme svetlo - //if(isDawn) time_points[t].value = 0;//vychod - vypneme svetlo - - //DUSK - sumrak - { - - //vypneme liniu a o minitu zapneme - { - let value = 0;//vypneme liniu - - let dusk_time = sunCalcResult.dusk_time; - if(dusk_time < now.getTime()) dusk_time = dusk_time + 24*60*60*1000;//1den - - let params = getParams(PRIORITY_TYPES.relay_profile); - params.type = "relay"; - params.line = line; - params.value = value; - params.tbname = relaysData[line].tbname; - params.timestamp = dusk_time; - params.duskOffset = duskOffset; - params.useProfile = false; - - //once a day - params.addMinutesToTimestamp = 24*60; - - //this will be recalculated - params.timePointName = "dusk" - - if(params.value == 0) params.info = "reset - KOVALOV - force turn off line: " + line; - else if(params.value == 1) params.info = "reset - KOVALOV - force turn on line: " + line; - - params.debug = true; - - //turn on/off line - tasks.push(params); - - console.log(params); - } - - //a o minutu zapneme - { - let value = 1;//zapneme liniu - - let dusk_time = sunCalcResult.dusk_time + 60*1000;//o minutu neskor po vypnuti zapneme - if(dusk_time < now.getTime()) dusk_time = dusk_time + 24*60*60*1000;//1den - - let params = getParams(PRIORITY_TYPES.relay_profile); - params.type = "relay"; - params.line = line; - params.value = value; - params.tbname = relaysData[line].tbname; - params.timestamp = dusk_time; - params.duskOffset = duskOffset + 1; - params.useProfile = false; - - //once a day - params.addMinutesToTimestamp = 24*60; - - //this will be recalculated - params.timePointName = "dusk" - - if(params.value == 0) params.info = "reset - KOVALOV - force turn off line: " + line; - else if(params.value == 1) params.info = "reset - KOVALOV - force turn on line: " + line; - - params.debug = true; - - //turn on/off line - tasks.push(params); - - console.log(params); - } - - - } - - //DAWN - vychod - { - //vypneme liniu a o minitu zapneme - { - let value = 0;//vypneme liniu - - let dawn_time = sunCalcResult.dawn_time; - if(dawn_time < now.getTime()) dawn_time = dawn_time + 24*60*60*1000;//1den - - let params = getParams(PRIORITY_TYPES.relay_profile); - params.type = "relay"; - params.line = line; - params.value = value; - params.tbname = relaysData[line].tbname; - params.timestamp = dawn_time; - - params.dawnOffset = dawnOffset; - params.useProfile = false; - - //once a day - params.addMinutesToTimestamp = 24*60; - - //this will be recalculated - params.timePointName = "dawn"; - - if(params.value == 0) params.info = "reset - KOVALOV - force turn off line: " + line; - else if(params.value == 1) params.info = "reset - KOVALOV - force turn on line: " + line; - - params.debug = true; - - //turn on/off line - tasks.push(params); - - console.log(params); - } - - //a o minitu zapneme - { - let value = 1;//vypneme liniu - - let dawn_time = sunCalcResult.dawn_time + 1000*60;//o minutu neskor po vypnuti zapneme - if(dawn_time < now.getTime()) dawn_time = dawn_time + 24*60*60*1000;//1den - - let params = getParams(PRIORITY_TYPES.relay_profile); - params.type = "relay"; - params.line = line; - params.value = value; - params.tbname = relaysData[line].tbname; - params.timestamp = dawn_time; - - params.dawnOffset = dawnOffset + 1; - params.useProfile = false; - - //once a day - params.addMinutesToTimestamp = 24*60; - - //this will be recalculated - params.timePointName = "dawn"; - - if(params.value == 0) params.info = "reset - KOVALOV - force turn off line: " + line; - else if(params.value == 1) params.info = "reset - KOVALOV - force turn on line: " + line; - - params.debug = true; - - //turn on/off line - tasks.push(params); - - console.log(params); - } - - - } - - //console.log("-------------------------Kovalov RVO 2----"); - } - if(processLine != undefined) { if(processLine != line) continue; @@ -1236,7 +1059,6 @@ exports.install = function(instance) { try { - /** * we process line profiles: timepoints, astro clock, lux_sensor, offsets ... */ @@ -2060,22 +1882,11 @@ exports.install = function(instance) { const timePointName = params.timePointName; const value = params.value; - // used just in Kovalov RVO 2 - const useProfile = params.useProfile; - let date = new Date(); date.setDate(date.getDate() + 1);//next day let sunCalcResult; - if(!useProfile) - { - sunCalcResult = calculateDuskDawn(date, params.line); - } - else - { - //do not use profile, line is there for undefined - sunCalcResult = calculateDuskDawn(date, undefined, params.duskOffset, params.dawnOffset); - } + sunCalcResult = calculateDuskDawn(date, params.line); if(timePointName == "dawn") { @@ -2098,12 +1909,7 @@ exports.install = function(instance) { tasks[0].timestamp = currentTimestamp + tasks[0].addMinutesToTimestamp * 60000; } - //monitor.info("new relay timepoint sunCalcResult ,,,,,,,,,,", sunCalcResult); - - let info; - if(!useProfile) info = "aplikovaný bod profilu"; - else info = params.info; //kovalov rvo params.info - + let info = "aplikovaný bod profilu"; let message = ""; if(value == 1) { @@ -2117,7 +1923,7 @@ exports.install = function(instance) { } //sendNotification("CMD Manager: process cmd", relaysData[0].tbname, ERRWEIGHT.INFO, "aplikovaný bod profilu línie " + params.line + " - stav: " + message, "", SEND_TO.tb, instance, null ); - if(!useProfile) sendNotification("CMD Manager: process cmd", FLOW.OMS_edgeName, "switching_profile_point_applied_to_line", {line: params.line, value: message}, "", SEND_TO.tb, instance ); + sendNotification("CMD Manager: process cmd", FLOW.OMS_edgeName, "switching_profile_point_applied_to_line", {line: params.line, value: message}, "", SEND_TO.tb, instance ); interval = setInterval(runTasks, SHORT_INTERVAL); return; From 8929cc3a534f793eabf184b3ab67b1b438b09542 Mon Sep 17 00:00:00 2001 From: rasta5man Date: Mon, 9 Sep 2024 12:32:34 +0200 Subject: [PATCH 8/9] actual working Senica Rvo code 09/2024 --- databases/modbus_config.js | 3 +- databases/notifications.table | 5 +- flow/cmd_manager.js | 120 ++---- flow/designer.json | 678 +++++++++++++++++++++++----------- flow/dido_controller.js | 174 ++++----- flow/modbus_reader.js | 72 ++-- flow/slack_filter.js | 187 ++++++++++ 7 files changed, 810 insertions(+), 429 deletions(-) create mode 100644 flow/slack_filter.js diff --git a/databases/modbus_config.js b/databases/modbus_config.js index 574de9f..b73116a 100644 --- a/databases/modbus_config.js +++ b/databases/modbus_config.js @@ -1,4 +1,5 @@ const timeoutInterval = 150000; + const deviceConfig = [ { device: "em340", @@ -110,4 +111,4 @@ const deviceConfig = [ } ]; -module.exports = { timeoutInterval, deviceConfig }; +module.exports = { timeoutInterval, deviceConfig }; \ No newline at end of file diff --git a/databases/notifications.table b/databases/notifications.table index b207fe7..a0590d3 100644 --- a/databases/notifications.table +++ b/databases/notifications.table @@ -31,4 +31,7 @@ key:string|weight:string|sk:string|en:string +|voltage_on_phase_restored|NOTICE|Napätie na fáze č. ${phase} bolo obnovené|Voltage on phase no. ${phase} has been restored|............... +|flow_start|NOTICE|FLOW bol spustený|FLOW has been started |............... +|twilight_sensor_nok|ERROR|Sensor súmraku neodpovedá|Twilight sensor is not responding|............... -+|twilight_sensor_ok|NOTICE|Sensor súmraku znovu odpovedá|Twilight sensor is responding again|............... \ No newline at end of file ++|twilight_sensor_ok|NOTICE|Sensor súmraku znovu odpovedá|Twilight sensor is responding again|............... ++|lamps_have_turned_on|NOTICE|Lampy sa zapli|Lamps have turned on|............... ++|lamps_have_turned_off|NOTICE|Lampy sa vypli|Lamps have turned off|............... ++|flow_restart|NOTICE|Restart flowu|Flow has been restarted|............... diff --git a/flow/cmd_manager.js b/flow/cmd_manager.js index 3a03acc..48b4987 100644 --- a/flow/cmd_manager.js +++ b/flow/cmd_manager.js @@ -280,30 +280,20 @@ function processNodeProfile(node) try{ nodeProfile = JSON.parse( profile ); if(Object.keys(nodeProfile).length === 0) throw ("profile is not defined"); - } catch (error) {} - - //test reset profilu - //nodeProfile = undefined; + } catch (error) { + logger.debug("Error parsing node profile", error); + } logger.debug("processNodeProfile", node, line, nodeObj, nodeProfile); - //return; - - //let timestamp = PRIORITY_TYPES.node_cmd; - - //let now = new Date(); - //now.setSeconds(now.getSeconds() + 10); - //let timestamp = now.getTime(); let timestamp = PRIORITY_TYPES.node_cmd; - //nodeProfile = undefined; removeTask({type: "set_node_profile", address: node}); cmdNOKNodeCounter[node] = 0; //co ked sa prave spracovava? //if(cmdNOKNodeCounter[params.address] < 5) saveToTb = false; - if(nodeProfile === undefined) { //vypneme profil nodu, posleme cmd @@ -318,7 +308,7 @@ function processNodeProfile(node) params.byte1 = 0; params.byte2 = 0; params.byte3 = 0; - params.byte4 = 32; + params.byte4 = 96; params.recipient = 1; params.register = 8; params.rw = 1;//write @@ -347,7 +337,7 @@ function processNodeProfile(node) params.byte1 = 0; params.byte2 = 0; params.byte3 = 0; - params.byte4 = 32; + params.byte4 = 96; params.recipient = 1; params.register = 8; params.rw = 1;//write @@ -615,7 +605,7 @@ function processNodeProfile(node) else bits.push(0); //Bit 1 - riadenie úsvitu podľa lux senzoru (1 – zapnuté). Úsvit sa môže posúvať v rámci času v registri 97 podľa intenzity osvetlenia - if(profile.dawn_lux_sensor == true)//usvit + if(nodeProfile.dawn_lux_sensor == true)//usvit { bits.push(1); } @@ -765,7 +755,7 @@ exports.install = function(instance) { if(key == "0") continue; if(line != undefined) { - //ak sa jedna o update profilu linie - pozor di_co_controller posiela command pre loadRelaysData + //ak sa jedna o update profilu linie - pozor dido_controller posiela command pre loadRelaysData if(line != value.line ) continue; } @@ -1254,28 +1244,20 @@ exports.install = function(instance) { { //run broadcast Time of dusk - // addMinutesToTimestamp = 60*5; addMinutesToTimestamp = 60 * 3; //kazde 3 hodiny zisti novy dusk let params = getParams(PRIORITY_TYPES.node_broadcast); - let recipient = 2;//2 broadcast, address = 0 - let address = 0;//0 - if(recipient === 2) - { - address = 0xffffffff;//Broadcast - } - let sunCalcResult = calculateDuskDawn(); let dusk_hours = sunCalcResult["dusk_hours"]; let dusk_minutes = sunCalcResult["dusk_minutes"]; - params.address = address;//broadcast + params.address = 0xffffffff;//broadcast params.byte1 = dusk_hours;//h params.byte2 = dusk_minutes;//m params.byte3 = 0;//s params.byte4 = 0; - params.recipient = recipient; + params.recipient = 2;//2 broadcast, params.register = 6;//Time of dusk - Reg 6 params.rw = 1;//write @@ -1300,23 +1282,16 @@ exports.install = function(instance) { let params = getParams(PRIORITY_TYPES.node_broadcast); - let recipient = 2;//2 broadcast, address = 0 - let address = 0;//0 - if(recipient === 2) - { - address = 0xffffffff;//Broadcast - } - let sunCalcResult = calculateDuskDawn(); let dawn_hours = sunCalcResult["dawn_hours"]; let dawn_minutes = sunCalcResult["dawn_minutes"]; - params.address = address;//broadcast + params.address = 0xffffffff;//broadcast params.byte1 = dawn_hours;//h params.byte2 = dawn_minutes;//m params.byte3 = 0;//s params.byte4 = 0; - params.recipient = recipient; + params.recipient = 2; //2 broadcast params.register = 7;//Time of dawn - Reg 6 params.rw = 1;//write @@ -1332,31 +1307,23 @@ exports.install = function(instance) { tasks.push(params); } - { //run broadcast //Actual time addMinutesToTimestamp = 5; let params = getParams(PRIORITY_TYPES.node_broadcast); - let recipient = 2;//2 broadcast, address = 0 - let address = 0;//0 - if(recipient === 2) - { - address = 0xffffffff;//Broadcast - } - var d = new Date(); let hours = d.getHours(); let minutes = d.getMinutes(); let seconds = d.getSeconds(); - params.address = address;//broadcast + params.address = 0xffffffff;//broadcast params.byte1 = hours;//h params.byte2 = minutes;//m params.byte3 = seconds;//s params.byte4 = 0; - params.recipient = recipient; + params.recipient = 2; //2 broadcast params.register = 87;//Actual time params.rw = 1;//write @@ -1370,37 +1337,8 @@ exports.install = function(instance) { params.info = "run broadcast: Actual time"; tasks.push(params); - } - { - //run broadcast Actual Lux level from cabinet - - //Do tohto registra posiela riadiaca jednotka hodnotu intenzity osvetlenia ktorú meria jej senzor pre potreby riadenia časov súmraku resp. úsvitu podľa intenzity osvetlenia. - //Byty 0 (LSB) a 1 obsahujú 16 bitový integer s luxami. - - let params = getParams(PRIORITY_TYPES.node_broadcast); - - addMinutesToTimestamp = 15; - - let recipient = 2;//2 broadcast, address = 0 - let address = 0;//0 - if(recipient === 2) - { - address = 0xffffffff;//Broadcast - } - - //TODO - //16 bitový integer s luxami - params.byte3 = lux_sensor; - params.byte4 = lux_sensor; - params.timestamp = PRIORITY_TYPES.node_broadcast; - params.addMinutesToTimestamp = addMinutesToTimestamp; - params.info = "run broadcast: Actual Lux level from cabinet"; - params.register = 95;//Actual Lux level from cabinet - params.rw = 1;//write - - } } //process nodes & tasks @@ -1909,7 +1847,7 @@ exports.install = function(instance) { tasks[0].timestamp = currentTimestamp + tasks[0].addMinutesToTimestamp * 60000; } - let info = "aplikovaný bod profilu"; + let info = "aplikovany bod profilu"; let message = ""; if(value == 1) { @@ -2099,8 +2037,9 @@ exports.install = function(instance) { let resp = com_generic(params.address, params.recipient, params.rw, params.register, params.name, params.byte1, params.byte2, params.byte3, params.byte4); let readBytes = 11; + let timeout = 5000; - await writeData(rsPort, resp, readBytes).then(function (data) { + await writeData(rsPort, resp, readBytes, timeout).then(function (data) { endTime = new Date(); var timeDiff = endTime - startTime; @@ -2690,8 +2629,31 @@ exports.install = function(instance) { { lux_sensor = parseInt(flowdata.data.value); - //process profiles - turnOnOffLinesAccordingToLuxSensor(lux_sensor); + // POSSIBLE SOURCE OF PROBLEMS, IF USER SETS LUX TRESHOLD LEVEL GREATER THAN 100 - WE SHOULD BE CHECKING "DUSK/DAWN_LUX_SENSOR_VALUE" IN PROFILE MAYBE ?? + if(lux_sensor < 100) + { + + // we send lux_sensor value to all nodes: + let params = getParams(PRIORITY_TYPES.node_broadcast); + + params.recipient = 2;//2 broadcast, address = 0 + params.address = 0xffffffff;//Broadcast + + let ba = longToByteArray(lux_sensor); + + params.byte3 = ba[1];//msb + params.byte4 = ba[0]; + params.timestamp = PRIORITY_TYPES.node_broadcast; + params.info = "run broadcast: Actual Lux level from cabinet"; + params.register = 95;//Actual Lux level from cabinet + params.rw = 1;//write + + tasks.push(params); + + + //process profiles + turnOnOffLinesAccordingToLuxSensor(lux_sensor); + } } else if(cmd == "state_of_breaker") { diff --git a/flow/designer.json b/flow/designer.json index 7cb3ebb..7d57d69 100644 --- a/flow/designer.json +++ b/flow/designer.json @@ -25,8 +25,8 @@ "component": "debug", "tab": "1611921777196", "name": "ERROR", - "x": 404, - "y": 36, + "x": 401, + "y": 31, "connections": {}, "disabledio": { "input": [], @@ -36,13 +36,13 @@ "text": "Enabled", "color": "gray" }, - "color": "#DA4453", - "notes": "", "options": { "type": "data", "repository": false, "enabled": true - } + }, + "color": "#DA4453", + "notes": "" }, { "id": "1612776786008", @@ -87,14 +87,14 @@ "text": "Connected", "color": "green" }, - "color": "#888600", - "notes": "", "options": { "username": "", "clientid": "", "port": "1883", "host": "" - } + }, + "color": "#888600", + "notes": "" }, { "id": "1612778461252", @@ -123,11 +123,11 @@ "text": "tb-push", "color": "gray" }, - "color": "#303E4D", - "notes": "", "options": { "wirename": "tb-push" - } + }, + "color": "#303E4D", + "notes": "" }, { "id": "1612783322136", @@ -147,13 +147,13 @@ "text": "Enabled", "color": "gray" }, - "color": "#967ADC", - "notes": "", "options": { "type": "data", "repository": false, "enabled": true - } + }, + "color": "#967ADC", + "notes": "" }, { "id": "1615551060773", @@ -173,13 +173,13 @@ "text": "Enabled", "color": "gray" }, - "color": "#DA4453", - "notes": "", "options": { "type": "data", "repository": false, "enabled": true - } + }, + "color": "#DA4453", + "notes": "" }, { "id": "1615563373927", @@ -199,13 +199,13 @@ "text": "Enabled", "color": "gray" }, - "color": "#DA4453", - "notes": "", "options": { "type": "data", "repository": false, "enabled": true - } + }, + "color": "#DA4453", + "notes": "" }, { "id": "1615566865233", @@ -223,11 +223,11 @@ "text": "tb-push", "color": "gray" }, - "color": "#303E4D", - "notes": "", "options": { "wirename": "tb-push" - } + }, + "color": "#303E4D", + "notes": "" }, { "id": "1615798582262", @@ -247,21 +247,21 @@ "text": "Enabled", "color": "gray" }, - "color": "#967ADC", - "notes": "", "options": { "type": "data", "repository": false, "enabled": true - } + }, + "color": "#967ADC", + "notes": "" }, { "id": "1615802995322", "component": "debug", "tab": "1611921777196", "name": "Debug", - "x": 400.8833312988281, - "y": 484.3500061035156, + "x": 398.8833312988281, + "y": 528.3500061035156, "connections": {}, "disabledio": { "input": [ @@ -270,24 +270,24 @@ "output": [] }, "state": { - "text": "Enabled", + "text": "Disabled", "color": "gray" }, - "color": "#967ADC", - "notes": "", "options": { "type": "data", "repository": false, - "enabled": true - } + "enabled": false + }, + "color": "#967ADC", + "notes": "" }, { "id": "1615809128443", "component": "debug", "tab": "1611921777196", "name": "Debug", - "x": 405.8833312988281, - "y": 566.3500061035156, + "x": 401.8833312988281, + "y": 625.3500061035156, "connections": {}, "disabledio": { "input": [ @@ -299,21 +299,21 @@ "text": "Enabled", "color": "gray" }, - "color": "#967ADC", - "notes": "", "options": { "type": "data", "repository": false, "enabled": true - } + }, + "color": "#967ADC", + "notes": "" }, { "id": "1615809595184", "component": "virtualwireout", "tab": "1611921777196", "name": "tb-push", - "x": 401.8833312988281, - "y": 306.25, + "x": 400.8833312988281, + "y": 328.25, "connections": {}, "disabledio": { "input": [], @@ -323,11 +323,11 @@ "text": "tb-push", "color": "gray" }, - "color": "#303E4D", - "notes": "", "options": { "wirename": "tb-push" - } + }, + "color": "#303E4D", + "notes": "" }, { "id": "1616165795916", @@ -356,9 +356,6 @@ "text": "Listening", "color": "green" }, - "color": "#5D9CEC", - "notes": "### Configuration\n\n- __POST /terminal__\n- flags: \n- maximum request data length: __5 kB__\n- empty response: __false__\n- cache policy: __no cache__\n- cache expire: __5 minutes__", - "cloning": false, "options": { "timeout": 10, "cachepolicy": 0, @@ -373,7 +370,10 @@ 10000 ], "emptyresponse": false - } + }, + "color": "#5D9CEC", + "notes": "### Configuration\n\n- __POST /terminal__\n- flags: \n- maximum request data length: __5 kB__\n- empty response: __false__\n- cache policy: __no cache__\n- cache expire: __5 minutes__", + "cloning": false }, { "id": "1616165824813", @@ -391,11 +391,11 @@ "text": "", "color": "gray" }, - "color": "#5D9CEC", - "notes": "", "options": { "datatype": "json" - } + }, + "color": "#5D9CEC", + "notes": "" }, { "id": "1617104731852", @@ -415,13 +415,13 @@ "text": "Enabled", "color": "gray" }, - "color": "#967ADC", - "notes": "", "options": { "type": "data", "repository": false, "enabled": true - } + }, + "color": "#967ADC", + "notes": "" }, { "id": "1617114651703", @@ -446,19 +446,19 @@ "text": "", "color": "gray" }, - "color": "#F6BB42", - "notes": "", "options": { "data": "{line: 3, command: \"turnOff\", force: true}", "datatype": "object" - } + }, + "color": "#F6BB42", + "notes": "" }, { "id": "1617115013095", "component": "virtualwireout", "tab": "1615551125555", "name": "tb-push", - "x": 747, + "x": 741, "y": 736, "connections": {}, "disabledio": { @@ -469,11 +469,11 @@ "text": "tb-push", "color": "gray" }, - "color": "#303E4D", - "notes": "", "options": { "wirename": "tb-push" - } + }, + "color": "#303E4D", + "notes": "" }, { "id": "1617178324650", @@ -491,13 +491,13 @@ "text": "Enabled", "color": "gray" }, - "color": "#967ADC", - "notes": "", "options": { "type": "data", "repository": false, "enabled": true - } + }, + "color": "#967ADC", + "notes": "" }, { "id": "1617179044099", @@ -522,12 +522,12 @@ "text": "", "color": "gray" }, - "color": "#F6BB42", - "notes": "", "options": { "datatype": "object", "data": "{table: \"konsberg_production_line_operations_error\", startFrom: 1, delimiter: \";\", uniqueColumn: \"\", path: \"flow/operations_error.csv\", mapImport: {0: \"production_line\",\t1: \"operation\", 2: \"error_type\", 3: \"error_code\", 4: \"error_text\", 5: \"error_text_user_defined\"}}" - } + }, + "color": "#F6BB42", + "notes": "" }, { "id": "1617180390661", @@ -552,11 +552,11 @@ "text": "", "color": "gray" }, - "color": "#2134B0", - "notes": "", "options": { "edge": "undefined" - } + }, + "color": "#2134B0", + "notes": "" }, { "id": "1617197763128", @@ -574,9 +574,9 @@ "text": "", "color": "gray" }, + "options": {}, "color": "#704cff", - "notes": "", - "options": {} + "notes": "" }, { "id": "1617284749681", @@ -601,12 +601,12 @@ "text": "", "color": "gray" }, - "color": "#F6BB42", - "notes": "", "options": { "datatype": "string", "data": "profile_nodes" - } + }, + "color": "#F6BB42", + "notes": "" }, { "id": "1618235171399", @@ -631,11 +631,11 @@ "text": "", "color": "gray" }, - "color": "#F6BB42", - "notes": "", "options": { "data": "run" - } + }, + "color": "#F6BB42", + "notes": "" }, { "id": "1618300858252", @@ -653,13 +653,13 @@ "text": "Enabled", "color": "gray" }, - "color": "#967ADC", - "notes": "", "options": { "type": "data", "repository": false, "enabled": true - } + }, + "color": "#967ADC", + "notes": "" }, { "id": "1618300863816", @@ -679,13 +679,13 @@ "text": "Enabled", "color": "gray" }, - "color": "#967ADC", - "notes": "", "options": { "type": "data", "repository": false, "enabled": true - } + }, + "color": "#967ADC", + "notes": "" }, { "id": "1618393583970", @@ -703,11 +703,11 @@ "text": "from-dido-controller", "color": "gray" }, - "color": "#303E4D", - "notes": "", "options": { "wirename": "from-dido-controller" - } + }, + "color": "#303E4D", + "notes": "" }, { "id": "1618393674428", @@ -732,11 +732,11 @@ "text": "platform-rpc-call", "color": "gray" }, - "color": "#303E4D", - "notes": "", "options": { "wirename": "platform-rpc-call" - } + }, + "color": "#303E4D", + "notes": "" }, { "id": "1618393759854", @@ -765,11 +765,11 @@ "text": "cmd_to_dido", "color": "gray" }, - "color": "#303E4D", - "notes": "", "options": { "wirename": "cmd_to_dido" - } + }, + "color": "#303E4D", + "notes": "" }, { "id": "1618393827655", @@ -787,11 +787,11 @@ "text": "cmd_to_dido", "color": "gray" }, - "color": "#303E4D", - "notes": "", "options": { "wirename": "cmd_to_dido" - } + }, + "color": "#303E4D", + "notes": "" }, { "id": "1618558465485", @@ -809,11 +809,11 @@ "text": "platform-rpc-call", "color": "gray" }, - "color": "#303E4D", - "notes": "", "options": { "wirename": "platform-rpc-call" - } + }, + "color": "#303E4D", + "notes": "" }, { "id": "1618572059773", @@ -838,12 +838,12 @@ "text": "", "color": "gray" }, - "color": "#F6BB42", - "notes": "", "options": { "datatype": "object", "data": "{line: 1, command: \"turnOn\", force: true}" - } + }, + "color": "#F6BB42", + "notes": "" }, { "id": "1619515097737", @@ -896,9 +896,9 @@ "text": "", "color": "gray" }, + "options": {}, "color": "#5D9CEC", - "notes": "", - "options": {} + "notes": "" }, { "id": "1619605019281", @@ -927,9 +927,6 @@ "text": "Listening", "color": "green" }, - "color": "#5D9CEC", - "notes": "### Configuration\n\n- __GET /db__\n- flags: undefined\n- maximum request data length: __5 kB__\n- empty response: __undefined__\n- cache policy: __no cache__\n- cache expire: __5 minutes__", - "cloning": false, "options": { "timeout": 5, "cachepolicy": 0, @@ -943,7 +940,10 @@ "get", 5000 ] - } + }, + "color": "#5D9CEC", + "notes": "### Configuration\n\n- __GET /db__\n- flags: undefined\n- maximum request data length: __5 kB__\n- empty response: __undefined__\n- cache policy: __no cache__\n- cache expire: __5 minutes__", + "cloning": false }, { "id": "1619784672383", @@ -968,12 +968,12 @@ "text": "", "color": "gray" }, - "color": "#F6BB42", - "notes": "", "options": { "data": "{command: \"turnOnAlarm\"}", "datatype": "object" - } + }, + "color": "#F6BB42", + "notes": "" }, { "id": "1619784812964", @@ -998,20 +998,20 @@ "text": "", "color": "gray" }, - "color": "#F6BB42", - "notes": "", "options": { "data": "{command: \"turnOffAlarm\"}", "datatype": "object" - } + }, + "color": "#F6BB42", + "notes": "" }, { "id": "1621340721628", "component": "virtualwireout", "tab": "1611921777196", "name": "modbus_to_dido", - "x": 403, - "y": 394, + "x": 399, + "y": 433, "connections": {}, "disabledio": { "input": [], @@ -1021,11 +1021,11 @@ "text": "modbus_to_dido", "color": "gray" }, - "color": "#303E4D", - "notes": "", "options": { "wirename": "modbus_to_dido" - } + }, + "color": "#303E4D", + "notes": "" }, { "id": "1622640022885", @@ -1050,9 +1050,6 @@ "text": "Listening", "color": "green" }, - "color": "#5D9CEC", - "notes": "### Configuration\n\n- __POST /db_connector__\n- flags: \n- maximum request data length: __5 kB__\n- empty response: __undefined__\n- cache policy: __no cache__\n- cache expire: __5 minutes__", - "cloning": false, "options": { "timeout": 5, "cachepolicy": 0, @@ -1065,7 +1062,10 @@ "post", 5000 ] - } + }, + "color": "#5D9CEC", + "notes": "### Configuration\n\n- __POST /db_connector__\n- flags: \n- maximum request data length: __5 kB__\n- empty response: __undefined__\n- cache policy: __no cache__\n- cache expire: __5 minutes__", + "cloning": false }, { "id": "1622640073521", @@ -1090,11 +1090,11 @@ "text": "", "color": "gray" }, - "color": "#2134B0", - "notes": "", "options": { "edge": "undefined" - } + }, + "color": "#2134B0", + "notes": "" }, { "id": "1622641420685", @@ -1112,9 +1112,9 @@ "text": "", "color": "gray" }, + "options": {}, "color": "#5D9CEC", - "notes": "", - "options": {} + "notes": "" }, { "id": "1634303504177", @@ -1136,15 +1136,15 @@ "output": [] }, "state": { - "text": "801.23 MB / 987.80 MB", + "text": "834.19 MB / 985.68 MB", "color": "gray" }, - "color": "#F6BB42", - "notes": "", "options": { "enabled": true, "interval": 30000 - } + }, + "color": "#F6BB42", + "notes": "" }, { "id": "1634303533779", @@ -1166,16 +1166,16 @@ "output": [] }, "state": { - "text": "5.90 GB / 7.26 GB", + "text": "5.84 GB / 7.26 GB", "color": "gray" }, - "color": "#F6BB42", - "notes": "", "options": { "enabled": true, "path": "/", "interval": 30000 - } + }, + "color": "#F6BB42", + "notes": "" }, { "id": "1634303595494", @@ -1204,11 +1204,11 @@ "text": "send-to-services", "color": "gray" }, - "color": "#303E4D", - "notes": "", "options": { "wirename": "send-to-services" - } + }, + "color": "#303E4D", + "notes": "" }, { "id": "1634303602169", @@ -1226,11 +1226,11 @@ "text": "send-to-services", "color": "gray" }, - "color": "#303E4D", - "notes": "", "options": { "wirename": "send-to-services" - } + }, + "color": "#303E4D", + "notes": "" }, { "id": "1634303685503", @@ -1248,11 +1248,11 @@ "text": "send-to-services", "color": "gray" }, - "color": "#303E4D", - "notes": "", "options": { "wirename": "send-to-services" - } + }, + "color": "#303E4D", + "notes": "" }, { "id": "1634303743260", @@ -1278,13 +1278,13 @@ "text": "", "color": "gray" }, - "color": "#5D9CEC", - "notes": "", "options": { "stringify": "json", "method": "POST", "url": "http://192.168.252.2:8004/sentmessage" - } + }, + "color": "#5D9CEC", + "notes": "" }, { "id": "1634463186563", @@ -1304,13 +1304,13 @@ "text": "Enabled", "color": "gray" }, - "color": "#967ADC", - "notes": "", "options": { "type": "data", "repository": false, "enabled": true - } + }, + "color": "#967ADC", + "notes": "" }, { "id": "1634464580289", @@ -1339,13 +1339,13 @@ "text": "", "color": "gray" }, - "color": "#656D78", - "notes": "", "options": { "keepmessage": true, "code": "let response = {};\nresponse.cpu = value.cpu;\nresponse.uptime = value.uptime;\n\nsend(0, response);", "outputs": 1 - } + }, + "color": "#656D78", + "notes": "" }, { "id": "1634465243324", @@ -1365,13 +1365,13 @@ "text": "Enabled", "color": "gray" }, - "color": "#967ADC", - "notes": "", "options": { "type": "data", "repository": false, "enabled": true - } + }, + "color": "#967ADC", + "notes": "" }, { "id": "1634465281992", @@ -1400,13 +1400,13 @@ "text": "", "color": "gray" }, - "color": "#656D78", - "notes": "", "options": { "keepmessage": true, "code": "value.sender = \"ram\";\n//let total = value.total/1024/1024;\n//let free = value.free/1024/1024;\n//let used = value.used/1024/1024;\nlet response = {};\n//value.memory_total = (total).toFixed(0) + ' MB';\n//value.memory_free = (free).toFixed(0) + ' MB';\n//value.memory_used = (used).toFixed(0) + ' MB';\n\nresponse.memory_total = value.total;\nresponse.memory_free = value.free;\nresponse.memory_used = value.used;\n\nsend(0, response);", "outputs": 1 - } + }, + "color": "#656D78", + "notes": "" }, { "id": "1634465338103", @@ -1426,13 +1426,13 @@ "text": "Enabled", "color": "gray" }, - "color": "#967ADC", - "notes": "", "options": { "type": "data", "repository": false, "enabled": true - } + }, + "color": "#967ADC", + "notes": "" }, { "id": "1634465821120", @@ -1461,13 +1461,13 @@ "text": "", "color": "gray" }, - "color": "#656D78", - "notes": "", "options": { "keepmessage": true, "code": "value.sender = \"hdd\";\n//let total = value.total/1024/1024;\n//let free = value.free/1024/1024;\n//let used = value.used/1024/1024;\nlet response = {};\n//value.hdd_total = (total).toFixed(0) + ' MB';\n//value.hdd_free = (free).toFixed(0) + ' MB';\n//value.used = (used).toFixed(0) + ' MB';\n\nresponse.hdd_total = value.total;\nresponse.hdd_free = value.free;\nresponse.hdd_used = value.used;\n\nsend(0, response);", "outputs": 1 - } + }, + "color": "#656D78", + "notes": "" }, { "id": "1634465892500", @@ -1487,13 +1487,13 @@ "text": "Enabled", "color": "gray" }, - "color": "#967ADC", - "notes": "", "options": { "type": "data", "repository": false, "enabled": true - } + }, + "color": "#967ADC", + "notes": "" }, { "id": "1634484067516", @@ -1513,13 +1513,13 @@ "text": "Enabled", "color": "gray" }, - "color": "#967ADC", - "notes": "", "options": { "type": "data", "repository": false, "enabled": true - } + }, + "color": "#967ADC", + "notes": "" }, { "id": "1634488120710", @@ -1548,11 +1548,11 @@ "text": "", "color": "gray" }, - "color": "#2134B0", - "notes": "", "options": { "edge": "undefined" - } + }, + "color": "#2134B0", + "notes": "" }, { "id": "1635327431236", @@ -1572,13 +1572,13 @@ "text": "Enabled", "color": "gray" }, - "color": "#967ADC", - "notes": "", "options": { "type": "data", "repository": false, "enabled": true - } + }, + "color": "#967ADC", + "notes": "" }, { "id": "1635936391935", @@ -1596,11 +1596,11 @@ "text": "send-to-services", "color": "gray" }, - "color": "#303E4D", - "notes": "", "options": { "wirename": "send-to-services" - } + }, + "color": "#303E4D", + "notes": "" }, { "id": "1637069803394", @@ -1622,11 +1622,9 @@ "output": [] }, "state": { - "text": "11.7% / 69.98 MB", + "text": "1.9% / 86.94 MB", "color": "gray" }, - "color": "#967ADC", - "notes": "", "options": { "monitorfiles": true, "monitorconnections": true, @@ -1634,7 +1632,9 @@ "monitorconsumption": true, "enabled": true, "interval": 30000 - } + }, + "color": "#967ADC", + "notes": "" }, { "id": "1683664161036", @@ -1654,13 +1654,13 @@ "text": "Enabled", "color": "gray" }, - "color": "#967ADC", - "notes": "", "options": { "type": "data", "repository": false, "enabled": true - } + }, + "color": "#967ADC", + "notes": "" }, { "id": "1683981346282", @@ -1689,11 +1689,11 @@ "text": "from-dido-controller", "color": "gray" }, - "color": "#303E4D", - "notes": "", "options": { "wirename": "from-dido-controller" - } + }, + "color": "#303E4D", + "notes": "" }, { "id": "1684055037116", @@ -1713,13 +1713,13 @@ "text": "Enabled", "color": "gray" }, - "color": "#967ADC", - "notes": "", "options": { "type": "data", "repository": false, "enabled": true - } + }, + "color": "#967ADC", + "notes": "" }, { "id": "1684060205000", @@ -1739,13 +1739,13 @@ "text": "Enabled", "color": "gray" }, - "color": "#967ADC", - "notes": "", "options": { "type": "data", "repository": false, "enabled": true - } + }, + "color": "#967ADC", + "notes": "" }, { "id": "1684179110403", @@ -1753,7 +1753,7 @@ "tab": "1611921777196", "name": "MDBToDido", "x": 401, - "y": 125, + "y": 118, "connections": {}, "disabledio": { "input": [], @@ -1763,13 +1763,13 @@ "text": "Enabled", "color": "gray" }, - "color": "#967ADC", - "notes": "", "options": { "type": "data", "repository": false, "enabled": true - } + }, + "color": "#967ADC", + "notes": "" }, { "id": "1699963668903", @@ -1810,11 +1810,11 @@ "text": "", "color": "gray" }, - "color": "#2134B0", - "notes": "", "options": { "edge": "undefined" - } + }, + "color": "#2134B0", + "notes": "" }, { "id": "1699964678894", @@ -1843,11 +1843,11 @@ "text": "modbus_to_dido", "color": "gray" }, - "color": "#303E4D", - "notes": "", "options": { "wirename": "modbus_to_dido" - } + }, + "color": "#303E4D", + "notes": "" }, { "id": "1699964793925", @@ -1867,13 +1867,13 @@ "text": "Enabled", "color": "gray" }, - "color": "#967ADC", - "notes": "", "options": { "type": "data", "repository": false, "enabled": true - } + }, + "color": "#967ADC", + "notes": "" }, { "id": "1699965957410", @@ -1897,6 +1897,10 @@ { "index": "0", "id": "1684179110403" + }, + { + "index": "0", + "id": "1717441414646" } ], "2": [ @@ -1918,17 +1922,17 @@ "text": "", "color": "gray" }, + "options": {}, "color": "#2134B0", - "notes": "", - "options": {} + "notes": "" }, { "id": "1700411878636", "component": "thermometer", "tab": "1611921777196", "name": "Thermometer", - "x": 103.75, - "y": 408, + "x": 107.75, + "y": 449, "connections": { "0": [ { @@ -1961,9 +1965,9 @@ "text": "", "color": "gray" }, + "options": {}, "color": "#5CB36D", - "notes": "", - "options": {} + "notes": "" }, { "id": "1714752862828", @@ -1971,7 +1975,7 @@ "tab": "1611921777196", "name": "MDBToTb", "x": 402, - "y": 215, + "y": 228, "connections": {}, "disabledio": { "input": [], @@ -1981,14 +1985,248 @@ "text": "Enabled", "color": "gray" }, - "color": "#967ADC", - "notes": "", "options": { "type": "data", "repository": false, "enabled": true - } + }, + "color": "#967ADC", + "notes": "" + }, + { + "id": "1717441414646", + "component": "code", + "tab": "1611921777196", + "name": "device-status", + "x": 588.0833282470703, + "y": 177, + "connections": { + "0": [ + { + "index": "0", + "id": "1717442627834" + }, + { + "index": "0", + "id": "1717442631338" + } + ] + }, + "disabledio": { + "input": [], + "output": [] + }, + "state": { + "text": "", + "color": "gray" + }, + "options": { + "keepmessage": true, + "code": "if(value.hasOwnProperty(\"status\"))\n{\n\tif(value.status.includes(\"-em\"))\n\t{\n\t\tsend(0, {\"em_status\": \"NOK\"});\n\t}\n\telse if(value.status.includes(\"twilight\"))\n\t{\n\t\tsend(0, {\"lux_sensor\": \"NOK\"});\n\t}\n}\n\nif(value.hasOwnProperty(\"values\"))\n{\n\tif(value.values.hasOwnProperty(\"twilight_sensor\"))\n\t{\n\t\tsend(0, {\"lux_sensor\": \"OK\"});\n\t}\n\telse if(value.values.hasOwnProperty(\"Phase_1_power\") ||\n\t\t\tvalue.values.hasOwnProperty(\"Phase_1_voltage\") ||\n\t\t\tvalue.values.hasOwnProperty(\"Total_power\") ||\n\t\t\tvalue.values.hasOwnProperty(\"Phase_1_current\"))\n\t{\n\t\tsend(0, {\"em_status\": \"OK\"});\n\t}\n}", + "outputs": 1 + }, + "color": "#656D78", + "notes": "" + }, + { + "id": "1717442627834", + "component": "debug", + "tab": "1611921777196", + "name": "modbus service", + "x": 802.0833282470703, + "y": 139, + "connections": {}, + "disabledio": { + "input": [ + 0 + ], + "output": [] + }, + "state": { + "text": "Enabled", + "color": "gray" + }, + "options": { + "type": "data", + "repository": false, + "enabled": true + }, + "color": "#967ADC", + "notes": "" + }, + { + "id": "1717442631338", + "component": "virtualwireout", + "tab": "1611921777196", + "name": "send-to-services", + "x": 801.0833282470703, + "y": 236, + "connections": {}, + "disabledio": { + "input": [], + "output": [] + }, + "state": { + "text": "send-to-services", + "color": "gray" + }, + "options": { + "wirename": "send-to-services" + }, + "color": "#303E4D", + "notes": "" + }, + { + "id": "1718016045116", + "component": "virtualwirein", + "tab": "1612772287426", + "name": "tb-push", + "x": 84.75, + "y": 1300, + "connections": { + "0": [ + { + "index": "0", + "id": "1718016052341" + } + ] + }, + "disabledio": { + "input": [], + "output": [] + }, + "state": { + "text": "tb-push", + "color": "gray" + }, + "options": { + "wirename": "tb-push" + }, + "color": "#303E4D", + "notes": "" + }, + { + "id": "1718016052341", + "component": "slack_filter", + "tab": "1612772287426", + "name": "Slack Filter", + "x": 278, + "y": 1297, + "connections": { + "0": [ + { + "index": "0", + "id": "1718016086212" + }, + { + "index": "0", + "id": "1718016073501" + } + ] + }, + "disabledio": { + "input": [], + "output": [] + }, + "state": { + "text": "Running", + "color": "gray" + }, + "options": { + "slack_channel": "C071KN2Q8SK", + "tag_on_include": "[{\"user_id\":\"U072JE5JUQG\", \"includes\":[\"Electrometer\", \"Twilight sensor\"]}]", + "message_includes": "[\"is responding again\", \"Lamps have turned\", \"Flow has been restarted\"]", + "types": "[\"emergency\", \"critical\", \"error\", \"alert\"]", + "name": "RVO16 Senica - 10.0.0.131" + }, + "color": "#30E193", + "notes": "" + }, + { + "id": "1718016073501", + "component": "httprequest", + "tab": "1612772287426", + "name": "http://192.168.252.2:8004/slack", + "x": 471, + "y": 1354, + "connections": { + "0": [ + { + "index": "0", + "id": "1718016086212" + } + ] + }, + "disabledio": { + "input": [], + "output": [] + }, + "state": { + "text": "", + "color": "gray" + }, + "options": { + "stringify": "json", + "method": "POST", + "url": "http://192.168.252.2:8004/slack" + }, + "color": "#5D9CEC", + "notes": "" + }, + { + "id": "1718016086212", + "component": "debug", + "tab": "1612772287426", + "name": "Debug", + "x": 808, + "y": 1302, + "connections": {}, + "disabledio": { + "input": [], + "output": [] + }, + "state": { + "text": "Enabled", + "color": "gray" + }, + "options": { + "type": "data", + "repository": false, + "enabled": true + }, + "color": "#967ADC", + "notes": "" + }, + { + "id": "1718016094070", + "component": "trigger", + "tab": "1612772287426", + "name": "Trigger", + "x": 73, + "y": 1388, + "connections": { + "0": [ + { + "index": "0", + "id": "1718016052341" + } + ] + }, + "disabledio": { + "input": [], + "output": [] + }, + "state": { + "text": "", + "color": "gray" + }, + "options": { + "datatype": "object", + "data": "{ \"g9OxBZ5KRwNznlY6pAppqEAWXvjdEL4eGQobMDy2\": [ { \"ts\": 1716289039281, \"values\": { \"_event\": { \"type\": \"alert\", \"status\": \"new\", \"source\": { \"func\": \"CMD Manager: process cmd\", \"component\": \"1619515097737\", \"component_name\": \"CMD Manager\", \"edge\": \"g9OxBZ5KRwNznlY6pAppqEAWXvjdEL4eGQobMDy2\" }, \"message\": \"NOW CONNECTED TO SLACK !\", \"message_data\": \"\" } } } ] }" + }, + "color": "#F6BB42", + "notes": "" } ], - "version": 618 + "version": 615 } \ No newline at end of file diff --git a/flow/dido_controller.js b/flow/dido_controller.js index 0952350..b429b14 100644 --- a/flow/dido_controller.js +++ b/flow/dido_controller.js @@ -11,11 +11,11 @@ exports.icon = 'bolt'; exports.options = { edge: "undefined" }; exports.html = `
-
-
-
Edge TB Name
-
-
+
+
+
Edge TB Name
+
+
`; exports.readme = `# Sets RS232 port and all digital pins on device. Then it starts to receive data from sensors. @@ -60,7 +60,7 @@ state_of_contactor - podľa indexu stykača sa reportuje jeho stav, teda //globals //FIRMWARE version -FLOW.OMS_edge_fw_version = "2024-05-10";//rok-mesiac-den +FLOW.OMS_edge_fw_version = "2024-07-08";//rok-mesiac-den FLOW.OMS_edgeName = ""; FLOW.OMS_maintenance_mode = false; @@ -78,7 +78,7 @@ FLOW.OMS_temperature_adress = "";//cmd_manager let alarmStatus = "OFF"; -const instanceSendTo = { +const SEND_TO = { debug: 0, tb: 1, cmd_manager: 2 @@ -152,7 +152,7 @@ exports.install = function(instance) { /* let conversionTable = { "1": {tbname: "", type: "state_of_main_switch", "line": 0}, //state_of_main_switch pin1 - "2": {tbname: "", type: "rotary_switch_state", "line": 0}, //rotary_switch_state - poloha manual = pin2 + "2": {tbname: "", type: "rotary_switch_state", "line": 0}, //rotary_switch_state - poloha manual = pin2 "3": {tbname: "", type: "rotary_switch_state", "line": 0}, //rotary_switch_state - poloha auto = pin3 "4": {tbname: "", type: "power_supply", "line": 0}, "5": {tbname: "", type: "battery", "line": 0}, @@ -192,7 +192,7 @@ exports.install = function(instance) { /* dbRelays.on('change', function(doc, old) { console.log("'DI_DO_Controller - dbRelays.on('change'"); - instance.send(instanceSendTo.cmd_manager, "reload_relays"); + instance.send(SEND_TO.cmd_manager, "reload_relays"); }); */ @@ -264,14 +264,13 @@ exports.install = function(instance) { { errLogger.error("CRITICAL!!! undefined relay", relaysData[line], line); - //sendNotification("set port ", edgeName, ERRWEIGHT.CRITICAL, "local database is corrupted", "", instanceSendTo.tb, instance, null ); - sendNotification("set port ", edgeName, "local_database_is_corrupted", {}, "", instanceSendTo.tb, instance ); + //sendNotification("set port ", edgeName, ERRWEIGHT.CRITICAL, "local database is corrupted", "", SEND_TO.tb, instance, null ); + sendNotification("set port ", edgeName, "local_database_is_corrupted", {}, "", SEND_TO.tb, instance ); } } if(pinsData[key].type == "state_of_contactor") { - let pin = key - 1; if(controller_type === "unipi") pin = key; @@ -298,37 +297,19 @@ exports.install = function(instance) { } ] } - - instance.send(instanceSendTo.tb, dataToTb); + + instance.send(SEND_TO.tb, dataToTb); let time = 3*1000; setTimeout(function(){ - instance.send(instanceSendTo.cmd_manager, {sender: "dido_controller", cmd: "buildTasks"}); + instance.send(SEND_TO.cmd_manager, {sender: "dido_controller", cmd: "buildTasks"}); - sendNotification("rsPort.open()", edgeName, "flow_start", {}, "", instanceSendTo.tb, instance ); + sendNotification("rsPort.open()", edgeName, "flow_start", {}, "", SEND_TO.tb, instance ); monitor.info("-->FLOW bol spustený", edgeName, FLOW.OMS_edge_fw_version); }, time); } - - // TODO: FIND BETTER SOLUTION, THAN REBUILDING TASKS - // we ensure, all tasks will be rebuild twice a week on tuesday or saturday at 11. To set correct switch off and on times - let sendRebuildTasksAt11 = null; - const checkIf11Oclock = () => - { - const d = new Date(); - const h = d.getHours(); - const day = d.getDay(); - - if((day === 2 || day === 6) && h === 11) - { - instance.send(instanceSendTo.cmd_manager, {sender:"dido_controller", cmd:"buildTasks"}); - monitor.info("Task rebuilt at 11 o'clock, tuesday, saturday"); - } - } - sendRebuildTasksAt11 = setInterval(checkIf11Oclock, 3600000); - function handleRsPort() { @@ -339,14 +320,14 @@ exports.install = function(instance) { rsPort.on('error', function(err) { logger.debug("rsPort opened error - failed", err.message); - instance.send(instanceSendTo.debug, err.message); + instance.send(SEND_TO.debug, err.message); errorHandler.sendMessageToService( exports.title + " rsPort opened error - failed: " + err.message); }) rsPort.on('open', async function() { - await runSyncExec("stty -F /dev/ttymxc0 115200 min 1 time 5 ignbrk -brkint -icrnl -imaxbel -opost -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke").then(function (status) { + await runSyncExec("stty -F /dev/ttymxc0 115200 min 1 time 5 ignbrk -brkint -icrnl -imaxbel -opost -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke").then(function (status) { //set port rsPort.write(Buffer.from(setRSPortData), function(err) { @@ -361,7 +342,7 @@ exports.install = function(instance) { }) }).catch(function (reason) { - //instance.send(instanceSendTo.debug, exports.title + " runSyncExec - promise rejected:" + reason); + //instance.send(SEND_TO.debug, exports.title + " runSyncExec - promise rejected:" + reason); errLogger.error( exports.title + " runSyncExec - promise rejected:" + reason); errorHandler.sendMessageToService( exports.title + " runSyncExec - promise rejected:" + reason); @@ -490,7 +471,7 @@ exports.install = function(instance) { deviceStatuses["temperature"] = "OK"; previousValues["temperature"] = value; - instance.send(instanceSendTo.tb, dataToTb); + instance.send(SEND_TO.tb, dataToTb); } return; } @@ -508,7 +489,7 @@ exports.install = function(instance) { ws.on('error', (err) => { monitor.info('websocket error, reconnect') - instance.send(instanceSendTo.debug, err.message); + instance.send(SEND_TO.debug, err.message); clearInterval(startRequests); ws = null; setTimeout(handleWebSocket, 1000); @@ -657,14 +638,14 @@ exports.install = function(instance) { //console.log(values); - instance.send(instanceSendTo.tb, dataToTb); + instance.send(SEND_TO.tb, dataToTb); } function turnOnLine(line, pin, force, info) { - instance.send(instanceSendTo.debug, "turn on line " + line ); + instance.send(SEND_TO.debug, "turn on line " + line ); if(force == undefined) force = false; if(line == 0) @@ -698,7 +679,7 @@ exports.install = function(instance) { { if(relaysData[line].contactor == 1) { - instance.send(instanceSendTo.debug, "line is already on " + line ); + instance.send(SEND_TO.debug, "line is already on " + line ); logger.debug("turnOnLine: line is already on: ", line); return; @@ -775,7 +756,7 @@ exports.install = function(instance) { { if(relaysData[line].contactor == 0) { - instance.send(instanceSendTo.debug, "line is already off " + line ); + instance.send(SEND_TO.debug, "line is already off " + line ); logger.debug("turnOffLine: line already off:", line); return; @@ -828,7 +809,7 @@ exports.install = function(instance) { if(!flowdata.data instanceof Object) return; // console.log('***********************', flowdata.data) - instance.send(instanceSendTo.debug, flowdata.data); + instance.send(SEND_TO.debug, flowdata.data); // we handle nok status from modbus_reader component and thermometer if(flowdata.data?.status) @@ -846,33 +827,34 @@ exports.install = function(instance) { { deviceStatuses["temperature"] = "NOK"; } - return; } + else if(flowdata.data?.values) + { + const values = flowdata.data.values; + if(values.hasOwnProperty("twilight_sensor")) + { + instance.send(SEND_TO.cmd_manager, {sender: "dido_controller", cmd: "lux_sensor", value: values["twilight_sensor"]}); + deviceStatuses["twilight_sensor"] = "OK" + } + else if(values.hasOwnProperty("temperature")) + { + deviceStatuses["temperature"] = "OK"; + } + // EM + else if(values.hasOwnProperty("total_power") || values.hasOwnProperty("total_energy") || values.hasOwnProperty("power_factor") || values.hasOwnProperty("Phase_1_voltage") || values.hasOwnProperty("Phase_1_current")) + { + deviceStatuses["em"] = "OK"; + } + else + { + return; + } - const values = flowdata.data.values; - if(values.hasOwnProperty("twilight_sensor")) - { - instance.send(instanceSendTo.cmd_manager, {sender: "dido_controller", cmd: "lux_sensor", value: values["twilight_sensor"]}); - deviceStatuses["twilight_sensor"] = "OK" + const updateStatus = checkFinalRVOStatus(); + if(updateStatus) values.status = "OK"; + + sendTelemetry(values, FLOW.OMS_rvo_tbname); } - else if(values.hasOwnProperty("temperature")) - { - deviceStatuses["temperature"] = "OK"; - } - // EM - else if(values.hasOwnProperty("total_power") || values.hasOwnProperty("total_energy") || values.hasOwnProperty("power_factor") || values.hasOwnProperty("Phase_1_voltage") || values.hasOwnProperty("Phase_1_current")) - { - deviceStatuses["em"] = "OK"; - } - else - { - return; - } - - const updateStatus = checkFinalRVOStatus(); - if(updateStatus) values.status = "OK"; - - sendTelemetry(values, FLOW.OMS_rvo_tbname); }) @@ -902,7 +884,7 @@ exports.install = function(instance) { rsPort.write(Buffer.from(obj), function(err) { switchLogic(obj); - instance.send(instanceSendTo.debug, {"WRITE":obj} ); + instance.send(SEND_TO.debug, {"WRITE":obj} ); }); } }) @@ -1195,14 +1177,14 @@ exports.install = function(instance) { { if (newPinValue === 0 && newPinValue !== previousValues[pinIndex]) { - sendNotification("switchLogic", edgeName, "main_switch_has_been_turned_off", {}, "", instanceSendTo.tb, instance , "state_of_main_switch"); + sendNotification("switchLogic", edgeName, "main_switch_has_been_turned_off", {}, "", SEND_TO.tb, instance , "state_of_main_switch"); values["status"] = "NOK"; deviceStatuses["state_of_main_switch"] = "Off"; } else if (newPinValue === 1 && newPinValue !== previousValues[pinIndex]) { - sendNotification("switchLogic", edgeName, "main_switch_has_been_turned_on", {}, "", instanceSendTo.tb, instance , "state_of_main_switch"); + sendNotification("switchLogic", edgeName, "main_switch_has_been_turned_on", {}, "", SEND_TO.tb, instance , "state_of_main_switch"); deviceStatuses["state_of_main_switch"] = "On"; } @@ -1247,7 +1229,7 @@ exports.install = function(instance) { //ak je spracovany, a automatic - tak ho zapnem //ak nie je spracovany, iba profil zapisem - instance.send(instanceSendTo.cmd_manager, {sender: "dido_controller", cmd: "rotary_switch_state", value: value}); + instance.send(SEND_TO.cmd_manager, {sender: "dido_controller", cmd: "rotary_switch_state", value: value}); //console.log("rotary_switch_state pin", pin2, pin3, value); } @@ -1256,16 +1238,16 @@ exports.install = function(instance) { { if (newPinValue === 0 && newPinValue !== previousValues[pinIndex]) { - //sendNotification("switchLogic", edgeName, ERRWEIGHT.ALERT, "Power supply is not OK", "", instanceSendTo.tb, instance); - sendNotification("switchLogic", edgeName, "power_supply_has_disconnected_input", {}, "", instanceSendTo.tb, instance, "power_supply"); + //sendNotification("switchLogic", edgeName, ERRWEIGHT.ALERT, "Power supply is not OK", "", SEND_TO.tb, instance); + sendNotification("switchLogic", edgeName, "power_supply_has_disconnected_input", {}, "", SEND_TO.tb, instance, "power_supply"); values["status"] = "NOK"; deviceStatuses["power_supply"] = "NOK"; } else if (newPinValue === 1 && newPinValue !== previousValues[pinIndex]) { - //sendNotification("switchLogic", edgeName, ERRWEIGHT.NOTICE, "Power supply is is OK", "", instanceSendTo.tb, instance); - sendNotification("switchLogic", edgeName, "power_supply_works_correctly", {}, "", instanceSendTo.tb, instance, "power_supply"); + //sendNotification("switchLogic", edgeName, ERRWEIGHT.NOTICE, "Power supply is is OK", "", SEND_TO.tb, instance); + sendNotification("switchLogic", edgeName, "power_supply_works_correctly", {}, "", SEND_TO.tb, instance, "power_supply"); deviceStatuses["power_supply"] = "OK"; } @@ -1275,16 +1257,16 @@ exports.install = function(instance) { { if (newPinValue === 1 && newPinValue !== previousValues[pinIndex]) { - //sendNotification("switchLogic", edgeName, ERRWEIGHT.ERROR, "Battery is not OK", "", instanceSendTo.tb, instance); - sendNotification("switchLogic", edgeName, "battery_level_is_low", {}, "", instanceSendTo.tb, instance, "battery_level"); + //sendNotification("switchLogic", edgeName, ERRWEIGHT.ERROR, "Battery is not OK", "", SEND_TO.tb, instance); + sendNotification("switchLogic", edgeName, "battery_level_is_low", {}, "", SEND_TO.tb, instance, "battery_level"); values["status"] = "NOK"; deviceStatuses["battery"] = "NOK"; } else if (newPinValue === 0 && newPinValue !== previousValues[pinIndex]) { - //sendNotification("switchLogic", edgeName, ERRWEIGHT.NOTICE, "Battery is OK", "", instanceSendTo.tb, instance); - sendNotification("switchLogic", edgeName, "battery_level_is_ok", {}, "", instanceSendTo.tb, instance, "battery_level"); + //sendNotification("switchLogic", edgeName, ERRWEIGHT.NOTICE, "Battery is OK", "", SEND_TO.tb, instance); + sendNotification("switchLogic", edgeName, "battery_level_is_ok", {}, "", SEND_TO.tb, instance, "battery_level"); deviceStatuses["battery"] = "OK"; } @@ -1298,19 +1280,19 @@ exports.install = function(instance) { if (newPinValue != previousValues[pinIndex]) { - //sendNotification("switchLogic", edgeName, ERRWEIGHT.NOTICE, `RVO door ${value}`, "", instanceSendTo.tb, instance, "rvo_door"); - //TODO ? sendNotification("switchLogic", edgeName, "door_value", {value: value}, "", instanceSendTo.tb, instance, "rvo_door"); + //sendNotification("switchLogic", edgeName, ERRWEIGHT.NOTICE, `RVO door ${value}`, "", SEND_TO.tb, instance, "rvo_door"); + //TODO ? sendNotification("switchLogic", edgeName, "door_value", {value: value}, "", SEND_TO.tb, instance, "rvo_door"); } if (value === "open" && FLOW.OMS_maintenance_mode) { - sendNotification("switchLogic", edgeName, "door_has_been_open", {}, "", instanceSendTo.tb, instance, "rvo_door"); + sendNotification("switchLogic", edgeName, "door_has_been_open", {}, "", SEND_TO.tb, instance, "rvo_door"); } if (value === "open" && !FLOW.OMS_maintenance_mode) { - //sendNotification("switchLogic", edgeName, ERRWEIGHT.WARNING, "RVO open door out of maintenance mode", "", instanceSendTo.tb, instance); - sendNotification("switchLogic", edgeName, "door_has_been_open_without_permision_alarm_is_on", {}, "", instanceSendTo.tb, instance, "rvo_door"); + //sendNotification("switchLogic", edgeName, ERRWEIGHT.WARNING, "RVO open door out of maintenance mode", "", SEND_TO.tb, instance); + sendNotification("switchLogic", edgeName, "door_has_been_open_without_permision_alarm_is_on", {}, "", SEND_TO.tb, instance, "rvo_door"); values["status"] = "NOK"; //console.log(door_has_been_open_without_permision_alarm_is_on); @@ -1325,7 +1307,7 @@ exports.install = function(instance) { if(alarmStatus == "ON") turnOffAlarm(); //turnOffAlarm(); - sendNotification("switchLogic", edgeName, "door_has_been_closed", {}, "", instanceSendTo.tb, instance, "rvo_door"); + sendNotification("switchLogic", edgeName, "door_has_been_closed", {}, "", SEND_TO.tb, instance, "rvo_door"); } deviceStatuses["door_condition"] = value; @@ -1364,12 +1346,12 @@ exports.install = function(instance) { twilightError = true; values["status"] = "NOK"; let value = twilight_sensor_array.shift(); - //sendNotification("switchLogic", edgeName, ERRWEIGHT.ERROR, "Lux sensor error", {"Repeating value": value}, instanceSendTo.tb, instance ); + //sendNotification("switchLogic", edgeName, ERRWEIGHT.ERROR, "Lux sensor error", {"Repeating value": value}, SEND_TO.tb, instance ); newPinValue = 0; } else if (set.size !== 1 && twilightError) { - //sendNotification("switchLogic", edgeName, ERRWEIGHT.NOTICE, "Lux sensor is working again", "", instanceSendTo.tb, instance ); + //sendNotification("switchLogic", edgeName, ERRWEIGHT.NOTICE, "Lux sensor is working again", "", SEND_TO.tb, instance ); twilightError = false; twilight_sensor_array.shift(); newPinValue = value; @@ -1387,7 +1369,7 @@ exports.install = function(instance) { if(diff >= twilight_sensor_interval * 60 * 1000) { const average = twilight_sensor.reduce((acc, c) => acc + c.value, 0) / twilight_sensor.length; - instance.send(instanceSendTo.cmd_manager, {sender: "dido_controller", cmd: "lux_sensor", value: average}); + instance.send(SEND_TO.cmd_manager, {sender: "dido_controller", cmd: "lux_sensor", value: average}); twilight_sensor = []; @@ -1398,11 +1380,11 @@ exports.install = function(instance) { } else if(type == "state_of_contactor") { - //sendNotification("switchLogic", edgeName, ERRWEIGHT.INFO, `State of contactor ${line} is now ${value}`, "", instanceSendTo.tb, instance ); + //sendNotification("switchLogic", edgeName, ERRWEIGHT.INFO, `State of contactor ${line} is now ${value}`, "", SEND_TO.tb, instance ); if(!(deviceStatuses["state_of_contactor"][line] == value)) { - sendNotification("switchLogic", edgeName, "state_of_contactor_for_line", {line: line, value: value}, "", instanceSendTo.tb, instance ); + sendNotification("switchLogic", edgeName, "state_of_contactor_for_line", {line: line, value: value}, "", SEND_TO.tb, instance ); } else { @@ -1444,7 +1426,7 @@ exports.install = function(instance) { //a budu sa odosielat commandy, tie vsak mozu zlyhat, a preto potrebujeme ich spusti trochu neskor setTimeout(function(){ - instance.send(instanceSendTo.cmd_manager, {sender: "dido_controller", cmd: "reload_relays", line: line, time: time, value: value, dataChanged: dataChanged}); + instance.send(SEND_TO.cmd_manager, {sender: "dido_controller", cmd: "reload_relays", line: line, time: time, value: value, dataChanged: dataChanged}); }, time); reportLineStatus(line); @@ -1469,7 +1451,7 @@ exports.install = function(instance) { if(valueChanged) { - instance.send(instanceSendTo.cmd_manager, {sender: "dido_controller", cmd: "state_of_breaker", value: value, line: line}); + instance.send(SEND_TO.cmd_manager, {sender: "dido_controller", cmd: "state_of_breaker", value: value, line: line}); //mame iba 3 istice. vyreportujeme a ohandlujeme liniu na tom istom istici ako paralelna linia (napr linia 1, paralelna s nou je linia 4, key je string "4") // ak je 7 linii, na 1 istici je linia 1,4,7 @@ -1483,7 +1465,7 @@ exports.install = function(instance) { { if(!relaysData.hasOwnProperty(lineOnSameBraker[i])) continue; - instance.send(instanceSendTo.cmd_manager, {sender: "dido_controller", cmd: "state_of_breaker", value: value, line: lineOnSameBraker[i]}); + instance.send(SEND_TO.cmd_manager, {sender: "dido_controller", cmd: "state_of_breaker", value: value, line: lineOnSameBraker[i]}); deviceStatuses["state_of_breaker"][lineOnSameBraker[i]] = value; reportLineStatus(lineOnSameBraker[i]); @@ -1502,7 +1484,7 @@ exports.install = function(instance) { if(relaysData.hasOwnProperty(lineOnSameBraker)) { - instance.send(instanceSendTo.cmd_manager, {sender: "dido_controller", cmd: "state_of_breaker", value: value, line: line + 3}); + instance.send(SEND_TO.cmd_manager, {sender: "dido_controller", cmd: "state_of_breaker", value: value, line: line + 3}); deviceStatuses["state_of_breaker"][line + 3] = value; reportLineStatus(line + 3); @@ -1598,7 +1580,7 @@ exports.install = function(instance) { ] } - instance.send(instanceSendTo.tb, dataToTb); + instance.send(SEND_TO.tb, dataToTb); } } diff --git a/flow/modbus_reader.js b/flow/modbus_reader.js index 898816e..f34ec9a 100644 --- a/flow/modbus_reader.js +++ b/flow/modbus_reader.js @@ -14,8 +14,8 @@ exports.readme = ` This device needs to be configured in dido_controller!!! Double check if it is. In dido_controller we calculate final status and all values with status are pushed to tb. `; -const modbus = require('jsmodbus') -const SerialPort = require('serialport') +const modbus = require('jsmodbus'); +const SerialPort = require('serialport'); const { timeoutInterval, deviceConfig } = require("../databases/modbus_config"); const { sendNotification } = require('./helper/notification_reporter'); @@ -30,6 +30,8 @@ const SEND_TO = { //to handle NOK and OK sendNotifications s const numberOfNotResponding = {}; let tbName = null; +let mainSocket; + exports.install = function(instance) { @@ -50,6 +52,10 @@ exports.install = function(instance) { this.lengthOfActualDeviceStream = null; this.device = null; + // lampSwitchNotification helper variables + this.onNotificationSent = false; + this.offNotificationSent = false; + this.startSocket(); } @@ -215,6 +221,7 @@ exports.install = function(instance) { }; this.checkNullVoltage(values); + this.lampSwitchNotification(values); instance.send(SEND_TO.dido_controller, {values: values}); @@ -243,32 +250,6 @@ exports.install = function(instance) { } } - - // sendFinalObjects = (values) => - // { - - // const date = Date.now(); - // // values["status"] = "OK"; - - // const dataToTB = { - // [tbName]: [ - // { - // "ts": date, - // "values": values - // } - // ] - // }; - - // instance.send(SEND_TO.tb, dataToTB); - - // const dataToDiDo = { - // values: values - // } - - // instance.send(SEND_TO.dido_controller, dataToDiDo); - // } - - calculateValue = (response, multiplier) => { let value = 0; @@ -296,7 +277,6 @@ exports.install = function(instance) { return Math.round(value * multiplier * 10) / 10; } - checkNullVoltage = (values) => { if(!(values.hasOwnProperty("Phase_1_voltage") || values.hasOwnProperty("Phase_2_voltage") || values.hasOwnProperty("Phase_3_voltage"))) return; @@ -313,19 +293,41 @@ exports.install = function(instance) { if(values[singleValue] == 0) { FLOW.OMS_no_voltage.add(phase); - sendNotification("modbus_citys: checkNullVoltage", tbName, "no_voltage_on_phase", {phase: phase}, "", SEND_TO.tb, instance, "voltage" + phase ); + sendNotification("modbus_reader: checkNullVoltage", tbName, "no_voltage_on_phase", {phase: phase}, "", SEND_TO.tb, instance, "voltage" + phase ); // console.log('no voltage') } else { FLOW.OMS_no_voltage.delete(phase); // console.log('voltage detected') - sendNotification("modbus_citys: checkNullVoltage", tbName, "voltage_on_phase_restored", {phase: phase}, "", SEND_TO.tb, instance, "voltage" + phase); + sendNotification("modbus_reader: checkNullVoltage", tbName, "voltage_on_phase_restored", {phase: phase}, "", SEND_TO.tb, instance, "voltage" + phase); } } }) } + /** + * function sends notification to slack and to tb, if EM total_power value changes more than 500. This should show, that RVO lamps has been switched on or off + */ + lampSwitchNotification = (values) => { + + if(!values.hasOwnProperty("total_power")) return; + + const actualTotalPower = values.total_power; + if(actualTotalPower > 600 && this.onNotificationSent == false) + { + sendNotification("modbus_reader: lampSwitchNotification", tbName, "lamps_have_turned_on", {}, "", SEND_TO.tb, instance); + this.onNotificationSent = true; + this.offNotificationSent = false; + } + else if(actualTotalPower <= 600 && this.offNotificationSent == false) + { + sendNotification("modbus_reader: lampSwitchNotification", tbName, "lamps_have_turned_off", {}, "", SEND_TO.tb, instance); + this.onNotificationSent = false; + this.offNotificationSent = true; + } + } + } const isObjectEmpty = (objectName) => { @@ -333,8 +335,14 @@ exports.install = function(instance) { } setTimeout(() => { - const newSocket = new SocketWithClients(); + + mainSocket = new SocketWithClients(); tbName = FLOW.OMS_rvo_tbname; + + // this notification is to show, that flow (unipi) has been restarted + sendNotification("modbus_reader", tbName, "flow_restart", {}, "", SEND_TO.slack, instance); + }, 25000); + } diff --git a/flow/slack_filter.js b/flow/slack_filter.js new file mode 100644 index 0000000..a27c9e1 --- /dev/null +++ b/flow/slack_filter.js @@ -0,0 +1,187 @@ +exports.id = 'slack_filter'; +exports.title = 'Slack Filter'; +exports.group = 'Citysys'; +exports.color = '#30E193'; +exports.input = 1; +exports.output = 1; +exports.author = 'Jakub Klena'; +exports.icon = 'plug'; +exports.version = '1.0.8'; +exports.options = { 'name':'', 'types': '["emergency", "critical", "error", "alert"]', 'message_includes':'["is responding again"]', 'tag_on_include':'[{"user_id":"U072JE5JUQG", "includes":["Electrometer", "Twilight sensor"]}]', 'slack_channel':'' }; + +exports.html = `
+
+
+
@(Name of this server)
+
+
+
@(Slack channel to receive the alerts)
+
+
+
@(Watch these types, comma separated names)
+
+
+
@(Watch messages that include any of the following strings)
+
+
+
@(Tag people if message includes something)
+
+
+
`; + +exports.readme = `# Slack Filter`; + +exports.install = function(instance) { + var running = false; + instance["savedSlackMessages"] = []; + var timer = null; + + instance.on('data', function(response) { + if (!running) return; + let value = response.data; + if (typeof value !== 'object') return; + + let can = false + var k = Object.keys(value); + var interested = JSON.parse(instance.options.types); + var msg_incl = JSON.parse(instance.options.message_includes); + var tags = JSON.parse(instance.options.tag_on_include); + + if (k.length <= 0) return; + if (value[k[0]].length <= 0) return; + if (!Object.prototype.hasOwnProperty.call(value[k[0]][0], 'values')) return; + if (!Object.prototype.hasOwnProperty.call(value[k[0]][0]['values'], '_event')) return; + if (!Object.prototype.hasOwnProperty.call(value[k[0]][0]['values']['_event'], 'type')) return; + if (!Object.prototype.hasOwnProperty.call(value[k[0]][0]['values']['_event'], 'source')) return; + if (!Object.prototype.hasOwnProperty.call(value[k[0]][0]['values']['_event']['source'], 'func')) return; + if (!Object.prototype.hasOwnProperty.call(value[k[0]][0]['values']['_event'], 'message')) return; + if (!Object.prototype.hasOwnProperty.call(value[k[0]][0]['values']['_event'], 'message_data')) return; + + let icon = ':totaljs:'; + let type = value[k[0]][0]['values']['_event']['type']; + let source = value[k[0]][0]['values']['_event']['source']['func']; + let message = value[k[0]][0]['values']['_event']['message']; + let message_data = value[k[0]][0]['values']['_event']['message_data']; + let tag = ''; + + switch(type){ + case 'debug': + icon = ':beetle:'; + break; + case 'info': + icon = ':speech_balloon:'; + break; + case 'notice': + icon = ':speech_balloon:'; + break; + case 'warning': + icon = ':exclamation:'; + break; + case 'alert': + icon = ':warning:'; + break; + case 'error': + icon = ':no_entry:'; + break; + case 'emergency': + icon = ':fire:'; + break; + case 'critical': + icon = ':fire:'; + break; + } + + // Check if this message includes one of the strings we are watching for + for (const msg of msg_incl){ + if (message.includes(msg)){ + if (msg == 'is responding again') icon = ':large_green_circle:'; + can = true; + break; + } + } + // Check if message is one of the types we are watching for + if (interested.includes(type)){ + can = true; + } + + if (!can) return; + + + // Check for each person tags based on what the message includes + for (const person of tags){ + for (const msg of person.includes){ + if (message.includes(msg)){ + tag += '<@'+person.user_id+'> '; + break; // Break out from this person checks as they are already tagged now + } + } + } + // Now that all people are tagged add new line symbol + if (tag != '') tag += '\n'; + + let send_data = tag+instance.options.name+' '+type.toUpperCase()+'\n*Source*: '+source+'\n*Message*: '+message; + if (message_data) { + send_data += '\nData: '+message_data; + } + + let ignore_msg = false + if (message.includes('Configuration of dimming profile to node no')){ + for (let i = 0; i < FLOW["savedSlackMessages"].length; i++){ + if (FLOW["savedSlackMessages"][i].message == message){ + ignore_msg = true; + break; + } + } + if (!ignore_msg){ + FLOW["savedSlackMessages"].push({message, 'dateandtime': Date.now()}); + if (timer === null){ + timer = setTimeout(checkSavedMessages, 60*60000); + } + } + } + + if (!ignore_msg){ + instance.send2({'msg':send_data,'bot_name':instance.options.name+' '+type.toUpperCase(),'bot_icon':icon,'channel':instance.options.slack_channel}); + } + }); + + function checkSavedMessages(){ + var d = Date.now(); + d = d - 86400000; // older then 24hr + var a = []; + //Remove msgs older then 24hr + for (let i = 0; i < FLOW["savedSlackMessages"].length; i++){ + if (FLOW["savedSlackMessages"][i].dateandtime > d){ + a.push(FLOW["savedSlackMessages"][i]); + } + } + FLOW["savedSlackMessages"] = a; + + if (FLOW["savedSlackMessages"].length > 0) { + timer = setTimeout(checkSavedMessages, 60*60000); + } else { + timer = null; + } + } + + instance.reconfigure = function() { + try { + if (!FLOW["savedSlackMessages"]){ + FLOW["savedSlackMessages"] = []; + } + + if (instance.options.name) { + instance.status('Running'); + running = true; + } else { + instance.status('Please enter name', 'red'); + running = false; + } + } catch (e) { + instance.error('Citysys connector: ' + e.message); + } + }; + + instance.on('options', instance.reconfigure); + instance.reconfigure(); +}; \ No newline at end of file From 7e20c7d3f0210647ccd9e53627aba1c2d0044b51 Mon Sep 17 00:00:00 2001 From: Jakub Klena Date: Mon, 9 Sep 2024 13:44:39 +0200 Subject: [PATCH 9/9] Removing duplicate --- flow/gettemperature.js | 218 ----------------------------------------- 1 file changed, 218 deletions(-) delete mode 100644 flow/gettemperature.js diff --git a/flow/gettemperature.js b/flow/gettemperature.js deleted file mode 100644 index 720592a..0000000 --- a/flow/gettemperature.js +++ /dev/null @@ -1,218 +0,0 @@ -exports.id = 'thermometer'; -exports.title = 'Thermometer'; -exports.group = 'Worksys'; -exports.color = '#5CB36D'; -exports.version = '1.0.3'; -exports.output = ["red", "white", "blue"]; -exports.author = 'Rastislav Kovac'; -exports.icon = 'thermometer-three-quarters'; - -exports.readme = `# Getting temperature values for RVO. In case of LM, you need device address. In case of unipi, evok sends values, in case thermometer is installed`; - -const instanceSendTo = { - debug: 0, - tb: 1, - dido_controller: 2 -} - -//read temperature - frequency -let timeoutMin = 5;//minutes - -var path = require('path'); -var log4js = require("log4js"); - -log4js.configure({ - appenders: { - errLogs: { type: 'file', filename: path.join(__dirname + "/../", 'err.txt') }, - monitorLogs: { type: 'file', compress:true, daysToKeep: 2, maxLogSize: 1048576, backups: 1, keepFileExt: true, filename: path.join(__dirname + "/../", 'monitor.txt') }, - console: { type: 'console' } - }, - categories: { - errLogs: { appenders: ['console', 'errLogs'], level: 'error' }, - monitorLogs: { appenders: ['console', 'monitorLogs'], level: 'trace' }, - //another: { appenders: ['console'], level: 'trace' }, - default: { appenders: ['console'], level: 'trace' } - } -}); - -const errLogger = log4js.getLogger("errLogs"); -const logger = log4js.getLogger(); -const monitor = log4js.getLogger("monitorLogs"); - -//logger.debug("text") -//monitor.info('info'); -//errLogger.error("some error"); - -const { promisifyBuilder } = require('./helper/db_helper'); -const dbSettings = TABLE("settings"); -let temperatureAddress = ""; - -async function loadSettings() -{ - //todo global FLOW.OMS_edgeName is making problem, so we load it here as well, it should not be - let responseSettings = await promisifyBuilder(dbSettings.find()); - temperatureAddress = responseSettings[0]["temperature_adress"]; -} - -loadSettings(); - - -exports.install = function(instance) { - - const { exec } = require('child_process'); - const { sendNotification, ERRWEIGHT } = require('./helper/notification_reporter'); - - let startRead; - let dataToTb; - let counter = 0; - - let edgeName = ""; - - - logger.debug(exports.title, "installed"); - - instance.on("close", function(){ - clearInterval(startRead); - }) - - - const start = function() { - - try { - - if(FLOW.OMS_controller_type === "unipi") - { - clearInterval(startRead); - return; - } - - if(temperatureAddress === "") throw "gettemperature: temperatureAddress is not defined"; - - logger.debug("FLOW.OMS_temperature_adress", FLOW.OMS_temperature_adress); - - exec(`owread -C ${temperatureAddress}/temperature`, (error, stdout, stderr) => { - - edgeName = FLOW.OMS_edgeName; - - if(edgeName !== "") - { - if(error) - { - - if(FLOW.OMS_brokerready == undefined) - { - logger.debug("gettemparature - FLOW.OMS_brokerready is undefined"); - - setTimeout(function(){ - start(); - }, 3000); - - return; - } - - if(FLOW.OMS_brokerready) - { - //sendNotification("start", edgeName, ERRWEIGHT.WARNING, "Thermometer is not responding", {"Error": error}, instanceSendTo.tb, instance, "thermometer"); - sendNotification("start", edgeName, "thermometer_is_not_responding", {}, {"Error": error}, instanceSendTo.tb, instance, "thermometer"); - } - - let status = "NOK"; - dataToTb = { - [edgeName]: [ - { - "ts": Date.now(), - "values": { - "status": status - } - } - ] - } - - monitor.info("Thermometer is not responding", error, FLOW.OMS_brokerready); - - // instance.send(instanceSendTo.tb, dataToTb); // poslat stav nok do tb, ak to handluje dido_controller ?? - instance.send(instanceSendTo.dido_controller, {status: "NOK-thermometer"}); - } - else parseData(stdout); - } - else - { - monitor.info("gettemperature: edgeName is not defined", FLOW.OMS_edgeName); - - setTimeout(function(){ - start(); - }, 3000); - - return; - } - - - //instance.send({"Temp":stdout,"stderr":stderr,"err":error}); - }); - - } - catch(err) { - errLogger.error(exports.title, err); - } - } - - const parseData = function(data) { - - data = parseFloat(data); - - logger.debug("gettemperature", data); - - if(!isNaN(data)) { - - if(counter > 290) - { - instance.send(instanceSendTo.debug, "[Get temperature component] - temperature data are comming again from RVO after more than 1 day break"); - - //sendNotification("parseData", edgeName, ERRWEIGHT.NOTICE, "Thermometer is working again", "", instanceSendTo.tb, instance, "thermometer"); - if(FLOW.OMS_brokerready) sendNotification("parseData", edgeName, "thermometer_is_responding_again", {}, "", instanceSendTo.tb, instance, "thermometer"); - } - - logger.debug("gettemperature", data); - const values = { - "temperature": Number(data.toFixed(2)), - "status": "OK" - } - - dataToTb = { - [edgeName]: [ - { - "ts": Date.now(), - "values":values - } - ] - } - - instance.send(instanceSendTo.tb, dataToTb); - instance.send(instanceSendTo.dido_controller, values); - - counter = 0; - - } else { - - counter++; - monitor.info("gettemperature err", counter, data); - - //ked je problem 1 den - let day = 24 * 60 / timeoutMin; - if ( counter > day && counter < day + 2 ) { - //sendNotification("parseData", edgeName, ERRWEIGHT.WARNING, "Thermometer receives invalid data", "", instanceSendTo.tb, instance, "thermometer"); - sendNotification("parseData", edgeName, "thermometer_sends_invalid_data", {}, "", instanceSendTo.tb, instance, "thermometer"); - - instance.send(instanceSendTo.debug, "[Get temperature component] - no temperature data from RVO for more than 1 day"); - instance.send(instanceSendTo.dido_controller, {status: "NOK-thermometer"}); - } - } - - } - - setTimeout(function(){ - start(); - }, 3000); - - startRead = setInterval(start, timeoutMin * 1000 * 60); -}; \ No newline at end of file