diff --git a/databases/modbus_config.js b/databases/modbus_config.js
index b73116a..d63430f 100644
--- a/databases/modbus_config.js
+++ b/databases/modbus_config.js
@@ -1,5 +1,4 @@
-const timeoutInterval = 150000;
-
+const timeoutInterval = 300000;
const deviceConfig = [
{
device: "em340",
@@ -111,4 +110,4 @@ const deviceConfig = [
}
];
-module.exports = { timeoutInterval, deviceConfig };
\ No newline at end of file
+module.exports = { timeoutInterval, deviceConfig };
diff --git a/databases/notifications.table b/databases/notifications.table
index a0590d3..b207fe7 100644
--- a/databases/notifications.table
+++ b/databases/notifications.table
@@ -31,7 +31,4 @@ 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|...............
-+|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|...............
++|twilight_sensor_ok|NOTICE|Sensor súmraku znovu odpovedá|Twilight sensor is responding again|...............
\ No newline at end of file
diff --git a/flow/cmd_manager.js b/flow/cmd_manager.js
index 48b4987..3c18f1d 100644
--- a/flow/cmd_manager.js
+++ b/flow/cmd_manager.js
@@ -19,15 +19,15 @@ exports.html = `
RPC - run RPC calls
- @(User)
-
+ @(User)
+
`;
@@ -43,49 +43,38 @@ const bitwise = require('bitwise');
var SunCalc = require('./helper/suncalc.js');
const DataToTbHandler = require('./helper/DataToTbHandler.js');
const ErrorToServiceHandler = require('./helper/ErrorToServiceHandler.js');
-const { promisifyBuilder, makeMapFromDbResult} = require('./helper/db_helper.js');
+const { promisifyBuilder } = 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');
-//TODO - to remove?
-// runTasks intervals
-const SHORT_INTERVAL = 30;
-const LONG_INTERVAL = 300;
+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' }
+ }
+});
-//send data to following instances:
-const SEND_TO = {
- debug: 0,
- tb: 1,
- http_response: 2,
- dido_controller: 3,
- infoSender: 4
-}
+const errLogger = log4js.getLogger("errLogs");
+const logger = log4js.getLogger();
+const monitor = log4js.getLogger("monitorLogs");
-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 = {};
+//USAGE
+//logger.debug("text")
+//monitor.info('info');
+//errLogger.error("some error");
//load from settings
let latitude = 48.70826502;//48.682255758;
@@ -122,9 +111,15 @@ priorities["8"] = minutes;
priorities["3"] = minutes;
priorities["89"] = minutes;
-//prikazy kt sa budu spustat na dany node - see config.js in terminal-oms.app. (1 - dimming)
+//prikazy kt sa budu spustat na dany node - see config.js in terminal-oms.app
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";
@@ -138,35 +133,6 @@ 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))
@@ -175,12 +141,13 @@ function cmdCounterResolve(address)
let result = cmdCounter[address];
if(result == 0) delete cmdCounter[address];
+
return result;
}
+
return -1;
}
-
function getParams(priority)
{
let params = {};
@@ -196,25 +163,25 @@ function getParams(priority)
params.rw = 0;//0: read, 1: write
//other values
- //params.type = "cmd"; "relay" "cmd-terminal" "set_node_profile" "process_profiles" "edge_date_time" "number_of_luminaires"
+ //params.type = "cmd"; "relay" "cmd-terminal"
//params.tbname = tbname;
- 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
+ params.priority = priorityTypes.node_cmd;//default priority
+ params.timestamp = 0;//execution time
if(priority != undefined )
{
params.timestamp = priority;
params.priority = priority;
}
- params.addMinutesToTimestamp = 0;//repeat task if value is > 0,
+ params.addMinutesToTimestamp = 0;//repeat if > 0,
- //params.timePointName = "luxOff" // "luxOn", "dusk", "dawn", "profileTimepoint"
+ //params.isDusk = false;
+ //params.isDawn = false;
//params.info = "";
return params;
}
-
async function loadSettings()
{
let responseSettings = await promisifyBuilder(dbSettings.find());
@@ -233,21 +200,12 @@ async function loadSettings()
//logger.debug('settings', responseSettings[0]);
+ //FLOW.OMS_tem
+ //rvo_name:string|lang:string|temperature_adress:string|latitude:number|longitude:number
+
initNotifications();
}
-loadSettings();
-
-
-async function loadNodes()
-{
- const responseNodes = await promisifyBuilder(dbNodes.find());
- nodesData = makeMapFromDbResult(responseNodes, "node");
-}
-
-loadNodes();
-
-
//nastav profil nodu
function processNodeProfile(node)
{
@@ -280,20 +238,30 @@ function processNodeProfile(node)
try{
nodeProfile = JSON.parse( profile );
if(Object.keys(nodeProfile).length === 0) throw ("profile is not defined");
- } catch (error) {
- logger.debug("Error parsing node profile", error);
- }
+ } catch (error) {}
+
+ //test reset profilu
+ //nodeProfile = undefined;
logger.debug("processNodeProfile", node, line, nodeObj, nodeProfile);
+ //return;
- let timestamp = PRIORITY_TYPES.node_cmd;
+ //let timestamp = priorityTypes.node_cmd;
+ //let now = new Date();
+ //now.setSeconds(now.getSeconds() + 10);
+ //let timestamp = now.getTime();
+
+ let timestamp = priorityTypes.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
@@ -302,13 +270,13 @@ function processNodeProfile(node)
logger.debug("turn off profile");
- let params = getParams(PRIORITY_TYPES.node_cmd);
+ let params = getParams(priorityTypes.node_cmd);
params.type = "set_node_profile";
params.address = node;
params.byte1 = 0;
params.byte2 = 0;
params.byte3 = 0;
- params.byte4 = 96;
+ params.byte4 = 32;
params.recipient = 1;
params.register = 8;
params.rw = 1;//write
@@ -320,7 +288,7 @@ function processNodeProfile(node)
tasks.push(params);
- //sendNotification("CMD Manager: process cmd", relaysData[0].tbname, ERRWEIGHT.NOTICE, "Master node is working again", "", SEND_TO.tb, instance );
+ //sendNotification("CMD Manager: process cmd", relaysData[0].tbname, ERRWEIGHT.NOTICE, "Master node is working again", "", instanceSendTo.tb, instance );
}
else
{
@@ -328,16 +296,16 @@ function processNodeProfile(node)
//cmdCounter[node] = tasksProfile.length;
//tasks.push(tasksProfile);
- //let timestamp = PRIORITY_TYPES.node_cmd;
+ //let timestamp = priorityTypes.node_cmd;
- //vypneme profil - Zapísať hodnotu 32 do registra Time Schedule Settings – reset profilu
- let params = getParams(PRIORITY_TYPES.node_cmd);
+ //vypneme profil - Zapísať hodnotu 32 do registra Time Schedule Settings – reset profilu
+ let params = getParams(priorityTypes.node_cmd);
params.type = "set_node_profile";
params.address = node;
params.byte1 = 0;
params.byte2 = 0;
params.byte3 = 0;
- params.byte4 = 96;
+ params.byte4 = 32;
params.recipient = 1;
params.register = 8;
params.rw = 1;//write
@@ -367,7 +335,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).
*/
@@ -385,7 +353,7 @@ function processNodeProfile(node)
logger.debug("processNodeProfile: TS1 Time point ", (i + 1), node);
- params = getParams(PRIORITY_TYPES.node_cmd);
+ params = getParams(priorityTypes.node_cmd);
params.type = "set_node_profile";
params.address = node;
params.byte1 = parseInt(t[0]);//hh
@@ -404,7 +372,7 @@ function processNodeProfile(node)
register++;
timestamp++;
- params = getParams(PRIORITY_TYPES.node_cmd);
+ params = getParams(priorityTypes.node_cmd);
params.type = "set_node_profile";
params.address = node;
params.byte1 = 0;
@@ -439,7 +407,7 @@ function processNodeProfile(node)
logger.debug("processNodeProfile: Threshold lux level for DUSK/DAWN", node);
- let params = getParams(PRIORITY_TYPES.node_cmd);
+ let params = getParams(priorityTypes.node_cmd);
params.type = "set_node_profile";
params.address = node;
params.register = 96;
@@ -477,7 +445,7 @@ function processNodeProfile(node)
logger.debug("processNodeProfile: DUSK/DAWN max. adjust period", node);
- let params = getParams(PRIORITY_TYPES.node_cmd);
+ let params = getParams(priorityTypes.node_cmd);
params.type = "set_node_profile";
params.address = node;
params.register = 97;
@@ -514,12 +482,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(PRIORITY_TYPES.node_cmd);
+ let params = getParams(priorityTypes.node_cmd);
params.type = "set_node_profile";
params.address = node;
params.register = 98;
@@ -559,7 +527,7 @@ function processNodeProfile(node)
logger.debug("Time schedule settings - turn on", node);
- params = getParams(PRIORITY_TYPES.node_cmd);
+ params = getParams(priorityTypes.node_cmd);
params.type = "set_node_profile";
params.address = node;
params.register = 8;
@@ -588,7 +556,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);
@@ -605,7 +573,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(nodeProfile.dawn_lux_sensor == true)//usvit
+ if(profile.dawn_lux_sensor == true)//usvit
{
bits.push(1);
}
@@ -639,29 +607,53 @@ function processNodeProfile(node)
}
+const instanceSendTo = {
+ debug: 0,
+ tb: 1,
+ http_response: 2,
+ dido_controller: 3,
+ infoSender: 4
+}
-function cleanUpRefFlowdataObj()
-{
- 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];
-
- if((timestamp - timestampKey) > 60*1000 )
- {
- console.log("cleanUpRefFlowdataObj delete", timestampKey);
- delete refFlowdataObj[ timestampKey ];
- }
- }
+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();
+
+ //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 ];
+ }
+ }
+}
+
+let tasks = [];//list of command calls to process
+
function removeTask(obj)
{
+
let keys = Object.keys(obj);
tasks = tasks.filter((task) => {
@@ -673,40 +665,25 @@ 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
@@ -720,170 +697,253 @@ exports.install = function(instance) {
//te();//force error
+ const tbHandler = new DataToTbHandler(instanceSendTo.tb);
+ tbHandler.setSender(exports.title);
- function processAllNodeProfilesOnLine(line)
+ //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)
{
-
- 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`);
- }
- }
- }
+ 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);
+
+ })
}
-
- 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 dido_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 3 sek neskor - status, brightness
+ //broadcast cas, o 1-2 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)
{
- address = 0xffffffff;//Broadcast
- }
+ //run broadcast //Actual time
+ addMinutesToTimestamp = 0;
- var d = new Date();
- let hours = d.getHours();
- let minutes = d.getMinutes();
- let seconds = d.getSeconds();
+ let params = {};
- 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 recipient = 2;//2 broadcast, address = 0
+ let address = 0;//0
+ if(recipient === 2)
+ {
+ address = 0xffffffff;//Broadcast
+ }
- let timestampStart = PRIORITY_TYPES.node_broadcast;
+ var d = new Date();
+ let hours = d.getHours();
+ let minutes = d.getMinutes();
+ let seconds = d.getSeconds();
- //other values
- params.type = "cmd";
- //params.tbname = tbname;
- params.timestamp = timestampStart;
- params.addMinutesToTimestamp = addMinutesToTimestamp;
- params.info = "run broadcast: Actual time";
+ 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
- tasks.push(params);
+ let timestampStart = priorityTypes.node_broadcast;
- let sec = 3;
- setTimeout(function(){
- //Po zapnutí línie - spraviť hromadný refresh stavu práve zapnutých svietidiel
+ //other values
+ params.type = "cmd";
+ //params.tbname = tbname;
+ params.timestamp = timestampStart;
+ params.addMinutesToTimestamp = addMinutesToTimestamp;
+ params.info = "run broadcast: Actual time";
- 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;
+ tasks.push(params);
- //prud, vykon - current, input power pre liniu pre vsetky nody
-
- //a pridame aj vyreportovanie dimmingu
+ 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 params = getParams(PRIORITY_TYPES.high_priority);
+ let tbname = nodesData[k].tbname;
+ let node = nodesData[k].node;
- 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;
+ //prud, vykon - current, input power pre liniu pre vsetky nody
+
+ //a pridame aj vyreportovanie dimmingu
+ {
+ let params = getParams(priorityTypes.high_priority);
- tasks.push(params);
- }
+ 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;
- //Prúd
- {
- let params = getParams(PRIORITY_TYPES.high_priority);
+ tasks.push(params);
+ }
- 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;
+ //Prúd
+ {
+ let params = getParams(priorityTypes.high_priority);
- tasks.push(params);
- }
+ 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;
- //výkon
- {
- let params = getParams(PRIORITY_TYPES.high_priority);
+ tasks.push(params);
+ }
- 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;
+ //výkon
+ {
+ let params = getParams(priorityTypes.high_priority);
- tasks.push(params);
+ 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);
- }
+ },sec*1000);
+
+ }
+
+ }
function reportOfflineNodeStatus(line)
{
+
logger.debug("--->reportOfflineNodeStatus for line", line);
values = {};
@@ -910,7 +970,7 @@ exports.install = function(instance) {
]
}
- //instance.send(SEND_TO.tb, dataToTb);
+ //instance.send(instanceSendTo.tb, dataToTb);
tbHandler.sendToTb(dataToTb, instance);
}
}
@@ -922,35 +982,40 @@ 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(SEND_TO.dido_controller, obj);
+
+ instance.send(instanceSendTo.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(SEND_TO.dido_controller, obj);
+ logger.debug("linia", line, obj);
+
+ instance.send(instanceSendTo.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";
@@ -968,7 +1033,7 @@ exports.install = function(instance) {
//CRC_ERROR
message = "NOK";
error = "CRC_ERROR c1";
- instance.send(SEND_TO.debug, "CRC_ERROR c1");
+ instance.send(instanceSendTo.debug, "CRC_ERROR c1");
}
if(c2 != bytes[10])
@@ -976,16 +1041,16 @@ exports.install = function(instance) {
//CRC_ERROR
message = "NOK";
error = "CRC_ERROR c2";
- instance.send(SEND_TO.debug, "CRC_ERROR c2");
+ instance.send(instanceSendTo.debug, "CRC_ERROR c2");
}
//crc error
if(type != "RESPONSE")
{
- instance.send(SEND_TO.debug, bytes);
- instance.send(SEND_TO.debug, "RESPONSE " + type + " - " + bytes[4]);
+ instance.send(instanceSendTo.debug, bytes);
+ instance.send(instanceSendTo.debug, "RESPONSE " + type + " - " + bytes[4]);
- //logger.debug(SEND_TO.debug, "RESPONSE " + type + " - " + bytes[4], bytes);
+ //logger.debug(instanceSendTo.debug, "RESPONSE " + type + " - " + bytes[4], bytes);
error = "type is: " + type;
@@ -995,18 +1060,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
- //return;
-
monitor.info("buildTasks - params", params);
let processLine; //defined line
+
let init = false;
let processLineProfiles = true;
let processBroadcast = true;
@@ -1016,6 +1079,7 @@ exports.install = function(instance) {
{
init = true;
tasks = [];
+
logger.debug("-->buildTasks clear tasks");
}
else
@@ -1039,22 +1103,208 @@ exports.install = function(instance) {
let keys = Object.keys(relaysData);
for(let i = 0; i < keys.length; i++)
{
- let line = parseInt(keys[i]); //line is turned off by default
+ let line = 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 calculateDuskDown(date, line, duskOffset = 0, dawnOffset = 0)
+ let duskOffset = 20;
+ let dawnOffset = -30;
+ let sunCalcResult = calculateDuskDown(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 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);
+ 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.isDusk = isDusk;
+ params.isDawn = isDawn;
+
+ 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 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);
+ 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.isDusk = isDusk;
+ params.isDawn = isDawn;
+
+ 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 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);
+ 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.isDusk = isDusk;
+ params.isDawn = isDawn;
+
+ 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 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);
+ 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.isDusk = isDusk;
+ params.isDawn = isDawn;
+
+ 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;
}
- try {
+ try{
- /**
- * we process line profiles: timepoints, astro clock, lux_sensor, offsets ...
- */
- 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 empty");
+ if(Object.keys(profile).length === 0) throw ("profile is not defined");
monitor.info("buildTasks: profile for line", line);
monitor.info("profile:", profile);
@@ -1062,62 +1312,52 @@ 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;
-
- /**
- * 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
- */
+ //create task for tun on + turn off, calculate dusk/down
if(profile.astro_clock == true)
{
+ //let now = new Date().toLocaleString("en-US", {timeZone: "Europe/Bratislava"});
+ let sunCalcResult = calculateDuskDown(new Date(), line);
- // if astro clock true, we remove all regular profile points
- time_points = [];
+ // monitor.info("dusk and dawn sunCalcResult", line, sunCalcResult);
- let sunCalcResult = calculateDuskDawn(new Date(), line);
+ //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} );
- // 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
+ //aby nam to neostalo svietit
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, "name": "luxOff"});
+ time_points.push( {"value": 0, "start_time": strDate} );
}
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.dusk_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": 1, "start_time": strDate, "name": "luxOn"});
- //time_points.push({"value": 1, "start_time": "15:19", "name": "luxOn"}); //testing
+ time_points.push( {"value": 1, "start_time": strDate} );
}
}
@@ -1140,57 +1380,76 @@ 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(':');
- start_time.setHours( parseInt(hours) );
- start_time.setMinutes( parseInt(minutes) );
- start_time.setSeconds(0);
+ 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);
+ }
//task is the past
if(now.getTime() > start_time.getTime())
{
currentValue = time_points[t].value;
- //timepoint is in past, we add 24 hours
+ //je v minulosti, pridame 24h
start_time.setDate(start_time.getDate() + 1);
}
- let params = getParams(PRIORITY_TYPES.relay_profile);
+ let params = getParams(priorityTypes.relay_profile);
params.type = "relay";
- params.line = parseInt(line);
+ params.line = line;
params.value = time_points[t].value;
params.tbname = relaysData[line].tbname;
params.timestamp = start_time.getTime();
params.addMinutesToTimestamp = 0;
- // 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;
+ //once a day
+ if(!isDusk && !isDawn) params.addMinutesToTimestamp = 24*60;
- //astro timepoints will be recalculated dynamically:
- params.timePointName = time_points[t].name;
+ //inak sa cas vypocita dynamicky
- // if astro timepoint, we save time window:
- if(['luxOn', 'luxOff', 'dusk','dawn'].includes(params.timePointName))
+ //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)
{
- params.dawn_lux_sensor_time_window = profile.dawn_lux_sensor_time_window;
- params.dusk_lux_sensor_time_window = profile.dusk_lux_sensor_time_window;
+ 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;
}
-
- 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);
}
@@ -1198,13 +1457,15 @@ exports.install = function(instance) {
monitor.info("-->time_points final", line, time_points);
//ensure to turn on/off according to calculated value
- let params = getParams(PRIORITY_TYPES.terminal);
+ let params = getParams(priorityTypes.terminal);
params.type = "relay";
params.line = parseInt(line);
params.tbname = relaysData[line].tbname;
params.value = currentValue;
+ params.isDusk = false;
+ params.isDawn = false;
- params.timestamp = PRIORITY_TYPES.terminal;
+ params.timestamp = priorityTypes.terminal;
params.addMinutesToTimestamp = 0;
params.debug = true;
@@ -1217,6 +1478,7 @@ exports.install = function(instance) {
tasks.push(params);
+
} catch (error) {
if(profilestr !=="" )
{
@@ -1244,24 +1506,32 @@ 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 params = getParams(priorityTypes.node_broadcast);
- let sunCalcResult = calculateDuskDawn();
+ let recipient = 2;//2 broadcast, address = 0
+ let address = 0;//0
+ if(recipient === 2)
+ {
+ address = 0xffffffff;//Broadcast
+ }
+
+ let sunCalcResult = calculateDuskDown();
let dusk_hours = sunCalcResult["dusk_hours"];
let dusk_minutes = sunCalcResult["dusk_minutes"];
- params.address = 0xffffffff;//broadcast
+ params.address = address;//broadcast
params.byte1 = dusk_hours;//h
params.byte2 = dusk_minutes;//m
params.byte3 = 0;//s
params.byte4 = 0;
- params.recipient = 2;//2 broadcast,
+ params.recipient = recipient;
params.register = 6;//Time of dusk - Reg 6
params.rw = 1;//write
- let timestampStart = PRIORITY_TYPES.node_broadcast;
+ let timestampStart = priorityTypes.node_broadcast;
//other values
params.type = "cmd";
@@ -1280,22 +1550,29 @@ exports.install = function(instance) {
// addMinutesToTimestamp = 60*5;
addMinutesToTimestamp = 60 * 3; //kazde 3 hodiny zisti novy dawn
- let params = getParams(PRIORITY_TYPES.node_broadcast);
+ let params = getParams(priorityTypes.node_broadcast);
- let sunCalcResult = calculateDuskDawn();
+ let recipient = 2;//2 broadcast, address = 0
+ let address = 0;//0
+ if(recipient === 2)
+ {
+ address = 0xffffffff;//Broadcast
+ }
+
+ let sunCalcResult = calculateDuskDown();
let dawn_hours = sunCalcResult["dawn_hours"];
let dawn_minutes = sunCalcResult["dawn_minutes"];
- params.address = 0xffffffff;//broadcast
+ params.address = address;//broadcast
params.byte1 = dawn_hours;//h
params.byte2 = dawn_minutes;//m
params.byte3 = 0;//s
params.byte4 = 0;
- params.recipient = 2; //2 broadcast
+ params.recipient = recipient;
params.register = 7;//Time of dawn - Reg 6
params.rw = 1;//write
- let timestampStart = PRIORITY_TYPES.node_broadcast;
+ let timestampStart = priorityTypes.node_broadcast;
//other values
params.type = "cmd";
@@ -1307,27 +1584,35 @@ exports.install = function(instance) {
tasks.push(params);
}
+
{
//run broadcast //Actual time
addMinutesToTimestamp = 5;
- let params = getParams(PRIORITY_TYPES.node_broadcast);
+ let params = getParams(priorityTypes.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 = 0xffffffff;//broadcast
+ params.address = address;//broadcast
params.byte1 = hours;//h
params.byte2 = minutes;//m
params.byte3 = seconds;//s
params.byte4 = 0;
- params.recipient = 2; //2 broadcast
+ params.recipient = recipient;
params.register = 87;//Actual time
params.rw = 1;//write
- let timestampStart = PRIORITY_TYPES.node_broadcast;
+ let timestampStart = priorityTypes.node_broadcast;
//other values
params.type = "cmd";
@@ -1337,8 +1622,37 @@ 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(priorityTypes.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 = priorityTypes.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
@@ -1357,7 +1671,7 @@ exports.install = function(instance) {
{
register = listOfCommands[i];
- let params = getParams(PRIORITY_TYPES.node_cmd);
+ let params = getParams(priorityTypes.node_cmd);
//core rpc values
params.address = address;
@@ -1371,7 +1685,7 @@ exports.install = function(instance) {
let addMinutesToTimestamp = priorities[register];
- let timestampStart = PRIORITY_TYPES.node_cmd; //run imediatelly in function runTasks
+ let timestampStart = priorityTypes.node_cmd; //run imediatelly in function runTasks
if(addMinutesToTimestamp > 1)
{
timestampStart = timestampStart + addMinutesToTimestamp * 60000;
@@ -1410,12 +1724,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(PRIORITY_TYPES.fw_detection);
+ let params = getParams(priorityTypes.fw_detection);
params.type = "cmd";
params.register = 4;
params.address = 0;
- let timestampStart = PRIORITY_TYPES.fw_detection;
+ let timestampStart = priorityTypes.fw_detection;
params.timestamp = timestampStart;
params.addMinutesToTimestamp = 5;
params.tbname = FLOW.OMS_edgeName;
@@ -1429,10 +1743,10 @@ exports.install = function(instance) {
//kazdu hodinu skontrolovat nastavenie profilov
{
- let params = getParams(PRIORITY_TYPES.fw_detection);
+ let params = getParams(priorityTypes.fw_detection);
params.type = "process_profiles";
- let timestampStart = PRIORITY_TYPES.relay_profile;
+ let timestampStart = priorityTypes.relay_profile;
params.timestamp = timestampStart;
params.addMinutesToTimestamp = 60;//60 = every hour
params.info = "detekcia nespracovaných profilov linie a nodov";
@@ -1444,10 +1758,10 @@ exports.install = function(instance) {
{
//edge_date_time
- let params = getParams(PRIORITY_TYPES.node_cmd);
+ let params = getParams(priorityTypes.node_cmd);
params.type = "edge_date_time";
- let timestampStart = PRIORITY_TYPES.node_cmd;
+ let timestampStart = priorityTypes.node_cmd;
params.timestamp = timestampStart;
params.addMinutesToTimestamp = 1;
params.tbname = FLOW.OMS_edgeName;
@@ -1459,10 +1773,10 @@ exports.install = function(instance) {
{
//edge_date_time
- let params = getParams(PRIORITY_TYPES.node_cmd);
+ let params = getParams(priorityTypes.node_cmd);
params.type = "number_of_luminaires";
- let timestampStart = PRIORITY_TYPES.node_cmd + 1;
+ let timestampStart = priorityTypes.node_cmd + 1;
params.timestamp = timestampStart;
params.addMinutesToTimestamp = 1;
params.tbname = FLOW.OMS_edgeName;
@@ -1474,91 +1788,131 @@ exports.install = function(instance) {
monitor.info("tasks created:", tasks.length);
}
-
- /**
- * 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);
+ 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 = keys[i];//line is turned off by default
let profilestr = relaysData[line].profile;
- const contactor = relaysData[line].contactor;
+ let contactor = relaysData[line].contactor; // 0 or 1 - vypnuta/zapnuta
- try {
+ try{
let profile = JSON.parse(profilestr);
- if(Object.keys(profile).length === 0) throw ("turnOnOffLinesAccordingToLuxSensor - profile is not defined");
+ if(Object.keys(profile).length === 0) throw ("profile is not defined");
if(profile.astro_clock == true)
{
- let sunCalcResult = calculateDuskDawn(now, line);
+ let sunCalcResult = calculateDuskDown(now, line);
- //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: usvit/vychod - lux je nad hranicou - vypnem
+ //dusk: zapad pod hranicou - zapnem
- if(currentTimestamp >= lux_sensor_time_window1 && currentTimestamp <= lux_sensor_time_window2)
+ //"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(lux_sensor_value > profile.dawn_lux_sensor_value)
- {
- if(contactor) turnOffLine(line, "Profile: dawn - turnOff line according to lux sensor");
- }
+ 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
+ }
}
- }
- //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)
+ //zapad
+ if(profile.dusk_lux_sensor == true)
{
- if(lux_sensor_value < profile.dusk_lux_sensor_value)
- {
- if(!contactor) turnOnLine(line, "Profile: dusk - turnOn line according to lux sensor");
- }
+ 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");
+ // }
+
+ }
}
- }
+
}
} catch (error) {
- if(profilestr !== "" ) monitor.info('Error parsing profile in turnOnOffLinesAccordingToLuxSensor', error);
+ //if(profilestr !=="" ) logger.debug(profilestr, error);
}
-
}
-
}
+ 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)
{
@@ -1583,7 +1937,7 @@ exports.install = function(instance) {
});
}
}
-
+
async function runTasks() {
@@ -1600,7 +1954,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"]}, "", SEND_TO.tb, instance);
+ sendNotification("CMD Manager: calculated Time of dusk", FLOW.OMS_edgeName, "dusk_has_occured", {value: sunCalcResult["dusk"]}, "", instanceSendTo.tb, instance);
reportDuskDawn.dusk_time_reported = sunCalcResult.dusk_time;
}
}
@@ -1608,7 +1962,7 @@ exports.install = function(instance) {
var nextDay = new Date();
nextDay.setDate(nextDay.getDate() + 1);
- sunCalcResult = calculateDuskDawn(nextDay);
+ sunCalcResult = calculateDuskDown(nextDay);
reportDuskDawn.dusk_time = sunCalcResult.dusk_time;
}
@@ -1620,7 +1974,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"]}, "", SEND_TO.tb, instance);
+ sendNotification("CMD Manager: calculated Time of dawn", FLOW.OMS_edgeName, "dawn_has_occured", {value: sunCalcResult["dawn"]}, "", instanceSendTo.tb, instance);
reportDuskDawn.dawn_time_reported = sunCalcResult.dawn_time;
}
}
@@ -1628,32 +1982,39 @@ exports.install = function(instance) {
var nextDay = new Date();
nextDay.setDate(nextDay.getDate() + 1);
- sunCalcResult = calculateDuskDawn(nextDay);
+ sunCalcResult = calculateDuskDown(nextDay);
reportDuskDawn.dawn_time = sunCalcResult.dawn_time;
}
//--------------------------------------------------------
- //sort tasks based on timestamp
+ //sort tasks
+ //tasks.sort((a,b) => a.timestamp - b.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(SEND_TO.debug, "no tasks created");
- interval = setInterval(runTasks, LONG_INTERVAL);
+ instance.send(instanceSendTo.debug, "no tasks created");
+ interval = setInterval(runTasks, longInterval);
+
return;
}
if(!rsPort.isOpen)
{
- instance.send(SEND_TO.debug, "!rsPort.isOpen");
+ instance.send(instanceSendTo.debug, "!rsPort.isOpen");
//await rsPort.open();
+
+ //continue
}
let currentTask = tasks[0];
@@ -1667,36 +2028,47 @@ exports.install = function(instance) {
{
let params = {...tasks[0]};
- //allow terminal commands
- if(FLOW.OMS_maintenance_mode && params.type !== "cmd-terminal")
+ if(FLOW.OMS_maintenance_mode)
{
- interval = setInterval(runTasks, LONG_INTERVAL);
- return;
+
+ //allow terminal commands
+ if(params.type == "cmd-terminal");
+ else
+ {
+ interval = setInterval(runTasks, longInterval);
+ return;
+ }
}
let type = params.type;
let tbname = params.tbname;
let nodeKey = params.address;
- let line = null;
+ 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 || params.timePointName) repeatTask = true;
+ if(params.addMinutesToTimestamp > 0) repeatTask = true;
+ if(params.isDawn || params.isDusk) 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();
}
@@ -1742,16 +2114,17 @@ exports.install = function(instance) {
]
}
- //instance.send(SEND_TO.tb, dataToTb);
+ //instance.send(instanceSendTo.tb, dataToTb);
tbHandler.sendToTb(dataToTb, instance);
- interval = setInterval(runTasks, SHORT_INTERVAL);
+ interval = setInterval(runTasks, shortIterval);
return;
}
}
+
//kontrola nespracovanych profilov nodov
if(type == "process_profiles")
{
@@ -1787,20 +2160,25 @@ exports.install = function(instance) {
//vsetky linie kt. su zapnute, a spracuju sa nespracovane profily nodov
loadRelaysData();
- interval = setInterval(runTasks, SHORT_INTERVAL);
+ interval = setInterval(runTasks, shortIterval);
return;
}
if(type == "edge_date_time")
{
- const ts = Date.now();
- let values = {"edge_date_time": ts};
+ //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 dataToTb = {
[tbname]: [
{
- "ts": ts,
+ "ts": Date.now(),
"values": values
}
]
@@ -1808,8 +2186,11 @@ exports.install = function(instance) {
tasks[0].timestamp = currentTimestamp + tasks[0].addMinutesToTimestamp * 60000;
- instance.send(SEND_TO.tb, dataToTb);
- interval = setInterval(runTasks, SHORT_INTERVAL);
+ //instance.send(instanceSendTo.tb, dataToTb);
+ tbHandler.sendToTb(dataToTb, instance);
+
+ interval = setInterval(runTasks, shortIterval);
+
return;
}
@@ -1817,53 +2198,56 @@ exports.install = function(instance) {
if(type == "relay")
{
- const timePointName = params.timePointName;
- const value = params.value;
+ //ak je dusk, alebo dawn, vypocitame si dynamicky nove values
+ if(params.isDawn || params.isDusk)
+ {
+ let date = new Date();
+ date.setDate(date.getDate() + 1);//next day
- 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);
+ }
- let sunCalcResult;
- sunCalcResult = calculateDuskDawn(date, params.line);
+ if(params.isDawn)
+ {
+ tasks[0].timestamp = sunCalcResult.dawn_time;
+ }
- if(timePointName == "dawn")
- {
- tasks[0].timestamp = sunCalcResult.dawn_time;
+ if(params.isDusk)
+ {
+ tasks[0].timestamp = sunCalcResult.dusk_time;
+ }
}
- else if(timePointName == "dusk")
+ else
{
- 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;
+ if(tasks[0].addMinutesToTimestamp == 0);// tasks.shift();
+ else tasks[0].timestamp = currentTimestamp + tasks[0].addMinutesToTimestamp * 60000;
}
- let info = "aplikovany bod profilu";
+ let info;
+ if(useProfile) info = "aplikovaný bod profilu";
+ else info = params.info;
+
let message = "";
- if(value == 1)
+ if(params.value == 1)
{
turnOnLine(params.line, info);
message = "on";
}
- else if(value == 0)
+ else if(params.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, "", SEND_TO.tb, instance, null );
- 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", 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 );
- interval = setInterval(runTasks, SHORT_INTERVAL);
+ interval = setInterval(runTasks, shortIterval);
return;
}
@@ -1901,11 +2285,11 @@ exports.install = function(instance) {
if(!disconnectedReport[tbname])
{
- //instance.send(SEND_TO.tb, dataToTb);
+ //instance.send(instanceSendTo.tb, dataToTb);
tbHandler.sendToTb(dataToTb, instance);
}
- interval = setInterval(runTasks, SHORT_INTERVAL);
+ interval = setInterval(runTasks, shortIterval);
return;
}
@@ -1926,9 +2310,10 @@ exports.install = function(instance) {
if(stop)
{
- interval = setInterval(runTasks, LONG_INTERVAL);
+ interval = setInterval(runTasks, longInterval);
return;
}
+
}
let relayStatus = 1;
@@ -1956,16 +2341,17 @@ exports.install = function(instance) {
]
}
- //instance.send(SEND_TO.tb, dataToTb);
+ //instance.send(instanceSendTo.tb, dataToTb);
tbHandler.sendToTb(dataToTb, instance);
- interval = setInterval(runTasks, SHORT_INTERVAL);
+ interval = setInterval(runTasks, shortIterval);
+
return;
}
if(!rsPort.isOpen)
{
- interval = setInterval(runTasks, LONG_INTERVAL);
+ interval = setInterval(runTasks, longInterval);
return;
}
@@ -1984,14 +2370,15 @@ exports.install = function(instance) {
params.byte4 = 0;
}
- //SET DUSK/DAWN FOR BROADCAST
+ //set dusk/down for broadcast
+
//Time of dusk
if(params.register == 6 && params.recipient === 2)
{
if(params.type != "cmd-terminal")
{
- let sunCalcResult = calculateDuskDawn();
+ let sunCalcResult = calculateDuskDown();
let dusk_hours = sunCalcResult["dusk_hours"];
let dusk_minutes = sunCalcResult["dusk_minutes"];
@@ -2002,7 +2389,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, "", SEND_TO.tb, instance, null );
+ //sendNotification("CMD Manager: calculated Time of dusk", relaysData[0].tbname, ERRWEIGHT.INFO, dusk, "", instanceSendTo.tb, instance, null );
}
}
@@ -2011,7 +2398,7 @@ exports.install = function(instance) {
{
if(params.type != "cmd-terminal")
{
- let sunCalcResult = calculateDuskDawn();
+ let sunCalcResult = calculateDuskDown();
let dawn_hours = sunCalcResult["dawn_hours"];
let dawn_minutes = sunCalcResult["dawn_minutes"];
@@ -2022,7 +2409,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, "", SEND_TO.tb, instance, null );
+ //sendNotification("CMD Manager: calculated Time of dusk", relaysData[0].tbname, ERRWEIGHT.INFO, dawn, "", instanceSendTo.tb, instance, null );
}
}
@@ -2030,16 +2417,27 @@ exports.install = function(instance) {
let register = params.register;
- instance.send(SEND_TO.debug, "address: " + params.address + " register:" + params.register + "type: " + params.type);
+ instance.send(instanceSendTo.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;
- let timeout = 5000;
- await writeData(rsPort, resp, readBytes, timeout).then(function (data) {
+ 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();
var timeDiff = endTime - startTime;
@@ -2098,7 +2496,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}, "", SEND_TO.tb, instance );
+ sendNotification("CMD Manager: process cmd", FLOW.OMS_edgeName, "dimming_profile_was_successfully_received_by_node", {node: params.address}, "", instanceSendTo.tb, instance );
logger.debug( "--> profil úspešne odoslaný na node č. " + params.address);
nodesData[params.address].processed = true;
@@ -2126,17 +2524,17 @@ exports.install = function(instance) {
if(params.address == 0)
{
- //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" );
+ //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" );
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, SEND_TO.tb, instance, null );
- sendNotification("CMD Manager: process cmd", FLOW.OMS_edgeName, "command_was_sent_from_terminal_interface", {}, params, SEND_TO.tb, instance );
+ //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 );
}
if(params.debug)
@@ -2155,7 +2553,7 @@ exports.install = function(instance) {
]
}
- //instance.send(SEND_TO.tb, dataToTb);
+ //instance.send(instanceSendTo.tb, dataToTb);
tbHandler.sendToTb(dataToTb, instance);
}
@@ -2176,11 +2574,11 @@ exports.install = function(instance) {
responseObj["bytes"] = data;
//params.refFlowdata.data = responseObj;
- //instance.send(SEND_TO.http_response, params.refFlowdata);
+ //instance.send(instanceSendTo.http_response, params.refFlowdata);
let refFlowdata = refFlowdataObj[ params.refFlowdataKey ];
refFlowdata.data = responseObj;
- instance.send(SEND_TO.http_response, refFlowdata);
+ instance.send(instanceSendTo.http_response, refFlowdata);
}
else
@@ -2209,13 +2607,13 @@ exports.install = function(instance) {
responseObj["bytes"] = data;
//params.refFlowdata.data = responseObj;
- //instance.send(SEND_TO.http_response, params.refFlowdata);
+ //instance.send(instanceSendTo.http_response, params.refFlowdata);
let refFlowdata = refFlowdataObj[ params.refFlowdataKey ];
if(refFlowdata !== undefined)
{
refFlowdata.data = responseObj;
- instance.send(SEND_TO.http_response, refFlowdata);
+ instance.send(instanceSendTo.http_response, refFlowdata);
}
@@ -2236,7 +2634,7 @@ exports.install = function(instance) {
responseObj["bytes"] = data;
params.refFlowdata.data = responseObj;
- instance.send(SEND_TO.http_response, params.refFlowdata);
+ instance.send(instanceSendTo.http_response, params.refFlowdata);
}
}
@@ -2244,8 +2642,8 @@ exports.install = function(instance) {
if(params.address == 0)
{
- //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");
+ //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");
logger.debug("master_node_is_not_responding", params);
FLOW.OMS_masterNodeIsResponding = false;
}
@@ -2257,8 +2655,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, "", 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 );
+ //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 );
}
//is it node?
@@ -2284,11 +2682,11 @@ exports.install = function(instance) {
]
}
- //instance.send(SEND_TO.tb, dataToTb);
+ //instance.send(instanceSendTo.tb, dataToTb);
tbHandler.sendToTb(dataToTb, instance);
}
- //instance.send(SEND_TO.debug, result);
+ //instance.send(instanceSendTo.debug, result);
if(params.hasOwnProperty("debug"))
{
@@ -2318,13 +2716,13 @@ exports.install = function(instance) {
responseObj["message"] = "ERROR WRITE FAILED: " + reason;//
//params.refFlowdata.data = responseObj;
- //instance.send(SEND_TO.http_response, params.refFlowdata);
+ //instance.send(instanceSendTo.http_response, params.refFlowdata);
let refFlowdata = refFlowdataObj[ params.refFlowdataKey ];
if(refFlowdata !== undefined)
{
refFlowdata.data = responseObj;
- instance.send(SEND_TO.http_response, refFlowdata);
+ instance.send(instanceSendTo.http_response, refFlowdata);
}
@@ -2344,7 +2742,7 @@ exports.install = function(instance) {
//responseObj["bytes"] = data;
params.refFlowdata.data = responseObj;
- instance.send(SEND_TO.http_response, params.refFlowdata);
+ instance.send(instanceSendTo.http_response, params.refFlowdata);
//refFlowdata = undefined;
}
@@ -2368,8 +2766,8 @@ exports.install = function(instance) {
if(params.address == 0)
{
- //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");
+ //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");
logger.debug("master_node_is_not_responding", params);
FLOW.OMS_masterNodeIsResponding = false;
@@ -2382,8 +2780,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", "", 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 );
+ //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 );
}
//is it node?
@@ -2409,7 +2807,7 @@ exports.install = function(instance) {
]
}
- //instance.send(SEND_TO.tb, dataToTb);
+ //instance.send(instanceSendTo.tb, dataToTb);
tbHandler.sendToTb(dataToTb, instance);
FLOW.OMS_masterNodeIsResponding = false;
@@ -2431,11 +2829,11 @@ exports.install = function(instance) {
]
}
- instance.send(SEND_TO.tb, dataToTb);
+ instance.send(instanceSendTo.tb, dataToTb);
}
*/
- instance.send(SEND_TO.debug, reason);
+ instance.send(instanceSendTo.debug, reason);
});
}
@@ -2447,607 +2845,615 @@ exports.install = function(instance) {
logger.debug("currentTask is not processed - task is in the future", currentTask);
}
- interval = setInterval(runTasks, LONG_INTERVAL);
+ interval = setInterval(runTasks, longInterval);
return;
}
//console.log("----->runTasks - setInterval", new Date());
- interval = setInterval(runTasks, SHORT_INTERVAL);
+ interval = setInterval(runTasks, shortIterval);
}
-
//! 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 == undefined || 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 = "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 });
//(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");
- loadRelaysData();
+ await 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(SEND_TO.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(instanceSendTo.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(SEND_TO.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(instanceSendTo.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);
- });
- });
+ //----
- rsPort.on('error', function(err) {
+ 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) {
//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(SEND_TO.debug, err.message);
+ instance.send(instanceSendTo.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(SEND_TO.debug, "on Data");
- //instance.send(SEND_TO.debug, flowdata);
-
- //logger.debug(flowdata.data);
+ //instance.send(instanceSendTo.debug, "on Data");
+ //instance.send(instanceSendTo.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 = [];
-
- if(tasks.length == 0)
+ //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 = [];
- buildTasks();
+ if(tasks.length == 0)
+ {
- if(rsPort.isOpen)
- {
- interval = setInterval(runTasks, 100);
- }
- else
- {
- instance.send(SEND_TO.debug, "port is not opened!!!");
+ buildTasks();
+
+ if(rsPort.isOpen)
+ {
+ interval = setInterval(runTasks, 100);
+ }
+ else
+ {
+ instance.send(instanceSendTo.debug, "port is not opened!!!");
+ }
}
}
- }
- else
- {
- //terminal data - object
- //logger.debug("flowdata", flowdata.data);
-
- if(typeof flowdata.data === 'object')
+ else
{
- //logger.debug("dido", flowdata.data);
- if(flowdata.data.hasOwnProperty("sender"))
+ //terminal data - object
+ //logger.debug("flowdata", flowdata.data);
+
+ if(typeof flowdata.data === 'object')
{
- //data from dido_controller
- if(flowdata.data.sender == "dido_controller")
+ //logger.debug("dido", flowdata.data);
+ if(flowdata.data.hasOwnProperty("sender"))
{
-
- if(flowdata.data.hasOwnProperty("cmd"))
+ //data from dido_controller
+ if(flowdata.data.sender == "dido_controller")
{
- let cmd = flowdata.data.cmd;
-
- if(cmd == "buildTasks")
+ if(flowdata.data.hasOwnProperty("cmd"))
{
- clearInterval(interval);
+ let cmd = flowdata.data.cmd;
- 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);
- }
- }
- }
- else if(cmd == "rotary_switch_state")
- {
- //state was changed
- if(rotary_switch_state != flowdata.data.value)
+ if(cmd == "buildTasks")
{
- if(rotary_switch_state == "Off")
- {
- //vyreportovat vsetky svietdla
- reportOfflineNodeStatus();
- }
- else reportOnlineNodeStatus();
+ 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);
}
-
- rotary_switch_state = flowdata.data.value;
- }
- else if(cmd == "lux_sensor")
- {
- lux_sensor = parseInt(flowdata.data.value);
-
- // 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)
+ else if(cmd == "reload_relays")
{
+ await loadRelaysData(flowdata.data.line);
- // we send lux_sensor value to all nodes:
- let params = getParams(PRIORITY_TYPES.node_broadcast);
+ if(flowdata.data.dataChanged)
+ {
+ if(!flowdata.data.value)
+ {
+ reportOfflineNodeStatus(flowdata.data.line);
+ }
+ else
+ {
+ reportOnlineNodeStatus(flowdata.data.line);
+ }
+ }
+
+ }
+ else if(cmd == "rotary_switch_state")
+ {
+ //state was changed
+ if(rotary_switch_state != flowdata.data.value)
+ {
+ if(rotary_switch_state == "Off")
+ {
+ //vyreportovat vsetky svietdla
+ reportOfflineNodeStatus();
+ }
+ else reportOnlineNodeStatus();
- 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);
+ }
+ 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")
+ else if(cmd == "state_of_breaker")
{
- weight = ERRWEIGHT.ERROR;
- message = `vypnutý istič línie č. ${line}`;
- status = "NOK";
- }
+ //istic linie
+ let value = flowdata.data.value;
+ let line = parseInt(flowdata.data.line);
- if(dataChanged) {
+ let dataChanged = false;
+ if(state_of_breaker[line] != value) dataChanged = true;
- if(relaysData.hasOwnProperty(line))
+ state_of_breaker[line] = value;
+
+ let status = "OK";
+ let weight = ERRWEIGHT.NOTICE;
+ let message = `zapnutý istič línie č. ${line}`;
+ if(value == "Off")
{
- let tbname = relaysData[line].tbname;
+ weight = ERRWEIGHT.ERROR;
+ message = `vypnutý istič línie č. ${line}`;
+ status = "NOK";
+ }
- 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");
+ if(dataChanged) {
- //report status liniu
- let values = {
- "status": status
- };
-
- let dataToTb = {
- [tbname]: [
- {
- "ts": Date.now(),
- "values": values
- }
- ]
- }
-
- //instance.send(SEND_TO.tb, dataToTb);
- tbHandler.sendToTb(dataToTb, instance);
-
- //current value
- if(value == "Off")
+ if(relaysData.hasOwnProperty(line))
{
- //vyreportovat vsetky svietdla na linii
- reportOfflineNodeStatus(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);
+ }
+ else reportOnlineNodeStatus(line);
}
- else reportOnlineNodeStatus(line);
- }
- }
- }
- else{
- logger.debug("undefined cmd", cmd);
- }
- }
- }
-
- 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")
- {
- if(method == "set_command")
- {
-
- //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(PRIORITY_TYPES.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 = PRIORITY_TYPES.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 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{
+ logger.debug("undefined cmd", cmd);
}
}
- else
- {
- instance.send(SEND_TO.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(SEND_TO.debug, "set_profile" + command);
-
- 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;
- }
- }
-
- //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(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;
}
- else
+
+ //data from worksys
+ if(flowdata.data.hasOwnProperty("topic"))
{
- instance.send(SEND_TO.debug, "UNKNOW entity_type " + entity_type);
- logger.debug("UNKNOW entity_type", entity_type);
+
+ 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")
+ {
+
+ //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 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, instanceSendTo.tb, instance, null );
+ sendNotification("CMD manager", tbname, "dimming_profile_was_processed_for_node", {node: node}, profile, instanceSendTo.tb, instance );
+
+ nodesData[node].processed = false;
+ nodesData[node].profile = profile;
+
+ let line = nodesData[node].line;
+ processNodeProfile(node);
+
+ });
+ });
+ }
+ }
+ }
+ 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);
+ }
+
+ return;
+
+ }
+ else{
+ instance.send(instanceSendTo.debug, "UNKNOW entity_type " + entity_type);
+ logger.debug("UNKNOW entity_type", entity_type);
+ }
+
+ return;
}
- 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 = 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);
+
}
-
- //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
@@ -3180,7 +3586,7 @@ setCorrectPlcTimeOnceADay();
///helper functions
-function calculateDuskDawn(date, line, duskOffset = 0, dawnOffset = 0)
+function calculateDuskDown(date, line, duskOffset = 0, dawnOffset = 0)
{
if(date === undefined) date = new Date();
@@ -3205,7 +3611,7 @@ function calculateDuskDawn(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");
@@ -3265,7 +3671,6 @@ function calculateDuskDawn(date, line, duskOffset = 0, dawnOffset = 0)
return result;
}
-
function processResponse(register, bytes)
{
@@ -3391,56 +3796,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;
@@ -3463,6 +3868,7 @@ function processResponse(register, bytes)
timestamp = d.getTime();
}
+
//aktuálny čas
if(register == 87)
{
@@ -3494,13 +3900,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 = [];
@@ -3515,7 +3921,7 @@ function com_generic(adresa, rec, rw, register, name, byte1, byte2, byte3, byte4
if (rw === 0)
{
- cmd = cmd + 0x8000;
+ cmd = cmd + 0x8000;
}
//master
@@ -3529,24 +3935,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
@@ -3574,220 +3980,3 @@ function com_generic(adresa, rec, rw, register, name, byte1, byte2, byte3, byte4
-
-
-// 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}'
- }
-}
-
-
-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
-}
diff --git a/flow/designer.json b/flow/designer.json
index 7d57d69..7cb3ebb 100644
--- a/flow/designer.json
+++ b/flow/designer.json
@@ -25,8 +25,8 @@
"component": "debug",
"tab": "1611921777196",
"name": "ERROR",
- "x": 401,
- "y": 31,
+ "x": 404,
+ "y": 36,
"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,47 +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": 398.8833312988281,
- "y": 528.3500061035156,
- "connections": {},
- "disabledio": {
- "input": [
- 0
- ],
- "output": []
- },
- "state": {
- "text": "Disabled",
- "color": "gray"
- },
- "options": {
- "type": "data",
- "repository": false,
- "enabled": false
- },
- "color": "#967ADC",
- "notes": ""
- },
- {
- "id": "1615809128443",
- "component": "debug",
- "tab": "1611921777196",
- "name": "Debug",
- "x": 401.8833312988281,
- "y": 625.3500061035156,
+ "x": 400.8833312988281,
+ "y": 484.3500061035156,
"connections": {},
"disabledio": {
"input": [
@@ -299,21 +273,47 @@
"text": "Enabled",
"color": "gray"
},
+ "color": "#967ADC",
+ "notes": "",
"options": {
"type": "data",
"repository": false,
"enabled": true
+ }
+ },
+ {
+ "id": "1615809128443",
+ "component": "debug",
+ "tab": "1611921777196",
+ "name": "Debug",
+ "x": 405.8833312988281,
+ "y": 566.3500061035156,
+ "connections": {},
+ "disabledio": {
+ "input": [
+ 0
+ ],
+ "output": []
+ },
+ "state": {
+ "text": "Enabled",
+ "color": "gray"
},
"color": "#967ADC",
- "notes": ""
+ "notes": "",
+ "options": {
+ "type": "data",
+ "repository": false,
+ "enabled": true
+ }
},
{
"id": "1615809595184",
"component": "virtualwireout",
"tab": "1611921777196",
"name": "tb-push",
- "x": 400.8833312988281,
- "y": 328.25,
+ "x": 401.8833312988281,
+ "y": 306.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,6 +356,9 @@
"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,
@@ -370,10 +373,7 @@
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": 741,
+ "x": 747,
"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": ""
+ "notes": "",
+ "options": {}
},
{
"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": ""
+ "notes": "",
+ "options": {}
},
{
"id": "1619605019281",
@@ -927,6 +927,9 @@
"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,
@@ -940,10 +943,7 @@
"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": 399,
- "y": 433,
+ "x": 403,
+ "y": 394,
"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,6 +1050,9 @@
"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,
@@ -1062,10 +1065,7 @@
"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": ""
+ "notes": "",
+ "options": {}
},
{
"id": "1634303504177",
@@ -1136,15 +1136,15 @@
"output": []
},
"state": {
- "text": "834.19 MB / 985.68 MB",
+ "text": "801.23 MB / 987.80 MB",
"color": "gray"
},
+ "color": "#F6BB42",
+ "notes": "",
"options": {
"enabled": true,
"interval": 30000
- },
- "color": "#F6BB42",
- "notes": ""
+ }
},
{
"id": "1634303533779",
@@ -1166,16 +1166,16 @@
"output": []
},
"state": {
- "text": "5.84 GB / 7.26 GB",
+ "text": "5.90 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,9 +1622,11 @@
"output": []
},
"state": {
- "text": "1.9% / 86.94 MB",
+ "text": "11.7% / 69.98 MB",
"color": "gray"
},
+ "color": "#967ADC",
+ "notes": "",
"options": {
"monitorfiles": true,
"monitorconnections": true,
@@ -1632,9 +1634,7 @@
"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": 118,
+ "y": 125,
"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,10 +1897,6 @@
{
"index": "0",
"id": "1684179110403"
- },
- {
- "index": "0",
- "id": "1717441414646"
}
],
"2": [
@@ -1922,17 +1918,17 @@
"text": "",
"color": "gray"
},
- "options": {},
"color": "#2134B0",
- "notes": ""
+ "notes": "",
+ "options": {}
},
{
"id": "1700411878636",
"component": "thermometer",
"tab": "1611921777196",
"name": "Thermometer",
- "x": 107.75,
- "y": 449,
+ "x": 103.75,
+ "y": 408,
"connections": {
"0": [
{
@@ -1965,9 +1961,9 @@
"text": "",
"color": "gray"
},
- "options": {},
"color": "#5CB36D",
- "notes": ""
+ "notes": "",
+ "options": {}
},
{
"id": "1714752862828",
@@ -1975,7 +1971,7 @@
"tab": "1611921777196",
"name": "MDBToTb",
"x": 402,
- "y": 228,
+ "y": 215,
"connections": {},
"disabledio": {
"input": [],
@@ -1985,248 +1981,14 @@
"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": 615
+ "version": 618
}
\ No newline at end of file
diff --git a/flow/dido_controller.js b/flow/dido_controller.js
index b429b14..60e3976 100644
--- a/flow/dido_controller.js
+++ b/flow/dido_controller.js
@@ -11,11 +11,11 @@ exports.icon = 'bolt';
exports.options = { edge: "undefined" };
exports.html = ``;
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-07-08";//rok-mesiac-den
+FLOW.OMS_edge_fw_version = "2023-10-18";//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 SEND_TO = {
+const instanceSendTo = {
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(SEND_TO.cmd_manager, "reload_relays");
+ instance.send(instanceSendTo.cmd_manager, "reload_relays");
});
*/
@@ -264,13 +264,14 @@ exports.install = function(instance) {
{
errLogger.error("CRITICAL!!! undefined relay", relaysData[line], line);
- //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 );
+ //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 );
}
}
if(pinsData[key].type == "state_of_contactor")
{
+
let pin = key - 1;
if(controller_type === "unipi") pin = key;
@@ -297,19 +298,37 @@ exports.install = function(instance) {
}
]
}
-
- instance.send(SEND_TO.tb, dataToTb);
+
+ instance.send(instanceSendTo.tb, dataToTb);
let time = 3*1000;
setTimeout(function(){
- instance.send(SEND_TO.cmd_manager, {sender: "dido_controller", cmd: "buildTasks"});
+ instance.send(instanceSendTo.cmd_manager, {sender: "dido_controller", cmd: "buildTasks"});
- sendNotification("rsPort.open()", edgeName, "flow_start", {}, "", SEND_TO.tb, instance );
+ sendNotification("rsPort.open()", edgeName, "flow_start", {}, "", instanceSendTo.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()
{
@@ -320,14 +339,14 @@ exports.install = function(instance) {
rsPort.on('error', function(err) {
logger.debug("rsPort opened error - failed", err.message);
- instance.send(SEND_TO.debug, err.message);
+ instance.send(instanceSendTo.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) {
@@ -342,7 +361,7 @@ exports.install = function(instance) {
})
}).catch(function (reason) {
- //instance.send(SEND_TO.debug, exports.title + " runSyncExec - promise rejected:" + reason);
+ //instance.send(instanceSendTo.debug, exports.title + " runSyncExec - promise rejected:" + reason);
errLogger.error( exports.title + " runSyncExec - promise rejected:" + reason);
errorHandler.sendMessageToService( exports.title + " runSyncExec - promise rejected:" + reason);
@@ -471,7 +490,7 @@ exports.install = function(instance) {
deviceStatuses["temperature"] = "OK";
previousValues["temperature"] = value;
- instance.send(SEND_TO.tb, dataToTb);
+ instance.send(instanceSendTo.tb, dataToTb);
}
return;
}
@@ -488,18 +507,15 @@ exports.install = function(instance) {
ws.on('error', (err) => {
- monitor.info('websocket error, reconnect')
- instance.send(SEND_TO.debug, err.message);
+ instance.send(instanceSendTo.debug, err.message);
clearInterval(startRequests);
- ws = null;
- setTimeout(handleWebSocket, 1000);
+ startRequests = null;
})
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...");
@@ -638,14 +654,14 @@ exports.install = function(instance) {
//console.log(values);
- instance.send(SEND_TO.tb, dataToTb);
+ instance.send(instanceSendTo.tb, dataToTb);
}
function turnOnLine(line, pin, force, info)
{
- instance.send(SEND_TO.debug, "turn on line " + line );
+ instance.send(instanceSendTo.debug, "turn on line " + line );
if(force == undefined) force = false;
if(line == 0)
@@ -679,7 +695,7 @@ exports.install = function(instance) {
{
if(relaysData[line].contactor == 1)
{
- instance.send(SEND_TO.debug, "line is already on " + line );
+ instance.send(instanceSendTo.debug, "line is already on " + line );
logger.debug("turnOnLine: line is already on: ", line);
return;
@@ -689,7 +705,7 @@ exports.install = function(instance) {
// if(!rsPort.isOpen && !ws)
if(!rsPort && !ws)
{
- errLogger.error("dido controller - port or websocket is not opened");
+ errLogger.error("di do controller - port or websocket is not opened");
return;
}
@@ -756,7 +772,7 @@ exports.install = function(instance) {
{
if(relaysData[line].contactor == 0)
{
- instance.send(SEND_TO.debug, "line is already off " + line );
+ instance.send(instanceSendTo.debug, "line is already off " + line );
logger.debug("turnOffLine: line already off:", line);
return;
@@ -809,7 +825,7 @@ exports.install = function(instance) {
if(!flowdata.data instanceof Object) return;
// console.log('***********************', flowdata.data)
- instance.send(SEND_TO.debug, flowdata.data);
+ instance.send(instanceSendTo.debug, flowdata.data);
// we handle nok status from modbus_reader component and thermometer
if(flowdata.data?.status)
@@ -827,34 +843,29 @@ 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 updateStatus = checkFinalRVOStatus();
- if(updateStatus) values.status = "OK";
-
- sendTelemetry(values, FLOW.OMS_rvo_tbname);
+ 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"
}
+ 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";
+ }
+
+ const updateStatus = checkFinalRVOStatus();
+ if(updateStatus) values.status = "OK";
+
+ sendTelemetry(values, FLOW.OMS_rvo_tbname);
})
@@ -884,7 +895,7 @@ exports.install = function(instance) {
rsPort.write(Buffer.from(obj), function(err) {
switchLogic(obj);
- instance.send(SEND_TO.debug, {"WRITE":obj} );
+ instance.send(instanceSendTo.debug, {"WRITE":obj} );
});
}
})
@@ -1177,14 +1188,14 @@ exports.install = function(instance) {
{
if (newPinValue === 0 && newPinValue !== previousValues[pinIndex])
{
- sendNotification("switchLogic", edgeName, "main_switch_has_been_turned_off", {}, "", SEND_TO.tb, instance , "state_of_main_switch");
+ sendNotification("switchLogic", edgeName, "main_switch_has_been_turned_off", {}, "", instanceSendTo.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", {}, "", SEND_TO.tb, instance , "state_of_main_switch");
+ sendNotification("switchLogic", edgeName, "main_switch_has_been_turned_on", {}, "", instanceSendTo.tb, instance , "state_of_main_switch");
deviceStatuses["state_of_main_switch"] = "On";
}
@@ -1229,7 +1240,7 @@ exports.install = function(instance) {
//ak je spracovany, a automatic - tak ho zapnem
//ak nie je spracovany, iba profil zapisem
- instance.send(SEND_TO.cmd_manager, {sender: "dido_controller", cmd: "rotary_switch_state", value: value});
+ instance.send(instanceSendTo.cmd_manager, {sender: "dido_controller", cmd: "rotary_switch_state", value: value});
//console.log("rotary_switch_state pin", pin2, pin3, value);
}
@@ -1238,16 +1249,16 @@ exports.install = function(instance) {
{
if (newPinValue === 0 && newPinValue !== previousValues[pinIndex])
{
- //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");
+ //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");
values["status"] = "NOK";
deviceStatuses["power_supply"] = "NOK";
}
else if (newPinValue === 1 && newPinValue !== previousValues[pinIndex])
{
- //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");
+ //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");
deviceStatuses["power_supply"] = "OK";
}
@@ -1257,16 +1268,16 @@ exports.install = function(instance) {
{
if (newPinValue === 1 && newPinValue !== previousValues[pinIndex])
{
- //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");
+ //sendNotification("switchLogic", edgeName, ERRWEIGHT.ERROR, "Battery is not OK", "", instanceSendTo.tb, instance);
+ sendNotification("switchLogic", edgeName, "battery_level_is_low", {}, "", instanceSendTo.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", "", SEND_TO.tb, instance);
- sendNotification("switchLogic", edgeName, "battery_level_is_ok", {}, "", SEND_TO.tb, instance, "battery_level");
+ //sendNotification("switchLogic", edgeName, ERRWEIGHT.NOTICE, "Battery is OK", "", instanceSendTo.tb, instance);
+ sendNotification("switchLogic", edgeName, "battery_level_is_ok", {}, "", instanceSendTo.tb, instance, "battery_level");
deviceStatuses["battery"] = "OK";
}
@@ -1280,19 +1291,19 @@ exports.install = function(instance) {
if (newPinValue != previousValues[pinIndex])
{
- //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");
+ //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");
}
if (value === "open" && FLOW.OMS_maintenance_mode)
{
- sendNotification("switchLogic", edgeName, "door_has_been_open", {}, "", SEND_TO.tb, instance, "rvo_door");
+ sendNotification("switchLogic", edgeName, "door_has_been_open", {}, "", instanceSendTo.tb, instance, "rvo_door");
}
if (value === "open" && !FLOW.OMS_maintenance_mode)
{
- //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");
+ //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");
values["status"] = "NOK";
//console.log(door_has_been_open_without_permision_alarm_is_on);
@@ -1307,7 +1318,7 @@ exports.install = function(instance) {
if(alarmStatus == "ON") turnOffAlarm();
//turnOffAlarm();
- sendNotification("switchLogic", edgeName, "door_has_been_closed", {}, "", SEND_TO.tb, instance, "rvo_door");
+ sendNotification("switchLogic", edgeName, "door_has_been_closed", {}, "", instanceSendTo.tb, instance, "rvo_door");
}
deviceStatuses["door_condition"] = value;
@@ -1346,12 +1357,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}, SEND_TO.tb, instance );
+ //sendNotification("switchLogic", edgeName, ERRWEIGHT.ERROR, "Lux sensor error", {"Repeating value": value}, instanceSendTo.tb, instance );
newPinValue = 0;
}
else if (set.size !== 1 && twilightError)
{
- //sendNotification("switchLogic", edgeName, ERRWEIGHT.NOTICE, "Lux sensor is working again", "", SEND_TO.tb, instance );
+ //sendNotification("switchLogic", edgeName, ERRWEIGHT.NOTICE, "Lux sensor is working again", "", instanceSendTo.tb, instance );
twilightError = false;
twilight_sensor_array.shift();
newPinValue = value;
@@ -1369,7 +1380,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(SEND_TO.cmd_manager, {sender: "dido_controller", cmd: "lux_sensor", value: average});
+ instance.send(instanceSendTo.cmd_manager, {sender: "dido_controller", cmd: "lux_sensor", value: average});
twilight_sensor = [];
@@ -1380,11 +1391,11 @@ exports.install = function(instance) {
}
else if(type == "state_of_contactor")
{
- //sendNotification("switchLogic", edgeName, ERRWEIGHT.INFO, `State of contactor ${line} is now ${value}`, "", SEND_TO.tb, instance );
+ //sendNotification("switchLogic", edgeName, ERRWEIGHT.INFO, `State of contactor ${line} is now ${value}`, "", instanceSendTo.tb, instance );
if(!(deviceStatuses["state_of_contactor"][line] == value))
{
- sendNotification("switchLogic", edgeName, "state_of_contactor_for_line", {line: line, value: value}, "", SEND_TO.tb, instance );
+ sendNotification("switchLogic", edgeName, "state_of_contactor_for_line", {line: line, value: value}, "", instanceSendTo.tb, instance );
}
else
{
@@ -1426,7 +1437,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(SEND_TO.cmd_manager, {sender: "dido_controller", cmd: "reload_relays", line: line, time: time, value: value, dataChanged: dataChanged});
+ instance.send(instanceSendTo.cmd_manager, {sender: "dido_controller", cmd: "reload_relays", line: line, time: time, value: value, dataChanged: dataChanged});
}, time);
reportLineStatus(line);
@@ -1451,7 +1462,7 @@ exports.install = function(instance) {
if(valueChanged)
{
- instance.send(SEND_TO.cmd_manager, {sender: "dido_controller", cmd: "state_of_breaker", value: value, line: line});
+ instance.send(instanceSendTo.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
@@ -1465,7 +1476,7 @@ exports.install = function(instance) {
{
if(!relaysData.hasOwnProperty(lineOnSameBraker[i])) continue;
- instance.send(SEND_TO.cmd_manager, {sender: "dido_controller", cmd: "state_of_breaker", value: value, line: lineOnSameBraker[i]});
+ instance.send(instanceSendTo.cmd_manager, {sender: "dido_controller", cmd: "state_of_breaker", value: value, line: lineOnSameBraker[i]});
deviceStatuses["state_of_breaker"][lineOnSameBraker[i]] = value;
reportLineStatus(lineOnSameBraker[i]);
@@ -1484,7 +1495,7 @@ exports.install = function(instance) {
if(relaysData.hasOwnProperty(lineOnSameBraker))
{
- instance.send(SEND_TO.cmd_manager, {sender: "dido_controller", cmd: "state_of_breaker", value: value, line: line + 3});
+ instance.send(instanceSendTo.cmd_manager, {sender: "dido_controller", cmd: "state_of_breaker", value: value, line: line + 3});
deviceStatuses["state_of_breaker"][line + 3] = value;
reportLineStatus(line + 3);
@@ -1580,7 +1591,7 @@ exports.install = function(instance) {
]
}
- instance.send(SEND_TO.tb, dataToTb);
+ instance.send(instanceSendTo.tb, dataToTb);
}
}
diff --git a/flow/gettemperature.js b/flow/gettemperature.js
new file mode 100644
index 0000000..720592a
--- /dev/null
+++ b/flow/gettemperature.js
@@ -0,0 +1,218 @@
+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
diff --git a/flow/modbus_reader.js b/flow/modbus_reader.js
index f34ec9a..fd1ac62 100644
--- a/flow/modbus_reader.js
+++ b/flow/modbus_reader.js
@@ -14,14 +14,19 @@ 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 ErrorToServiceHandler = require('./helper/ErrorToServiceHandler');
+const errorHandler = new ErrorToServiceHandler();
+
const { sendNotification } = require('./helper/notification_reporter');
const DELAY_BETWEEN_DEVICES = 10000;
-const SEND_TO = {
+const instanceSendTo = {
debug: 0,
dido_controller: 1,
tb: 2
@@ -30,8 +35,6 @@ const SEND_TO = {
//to handle NOK and OK sendNotifications s
const numberOfNotResponding = {};
let tbName = null;
-let mainSocket;
-
exports.install = function(instance) {
@@ -46,16 +49,12 @@ exports.install = function(instance) {
this.index = 0;
this.timeoutInterval = 5000;
- // 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
+ // 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
this.lengthOfActualDeviceStream = null;
this.device = null;
- // lampSwitchNotification helper variables
- this.onNotificationSent = false;
- this.offNotificationSent = false;
-
this.startSocket();
}
@@ -70,7 +69,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, 2000); // 2000 is timeout in register request, default is 5000, which is too long
+ this.clients[deviceConfig[i].deviceAddress] = new modbus.client.RTU(this.socket, deviceConfig[i].deviceAddress);
}
this.socket.on('error', function(e) {
@@ -134,24 +133,24 @@ exports.install = function(instance) {
{
message = "twilight_sensor_ok";
}
- message && sendNotification("modbus_reader: readRegisters", tbName, message, {}, "", SEND_TO.tb, instance);
+ message && sendNotification("modbus_reader: readRegisters", tbName, message, {}, "", instanceSendTo.tb, instance);
delete numberOfNotResponding[obj.device];
}
- obj.transformResponse(resp, register);
+ obj.transformResponse(resp, register, obj.deviceAddress);
- //obj.errors = 0;
+ obj.error = 0;
obj.index++;
obj.readAnotherRegister();
}).catch (function () {
- console.log("errors pri citani modbus registra", register, obj.indexInDeviceConfig, tbName, tbAttribute);
+ console.log("error pri citani modbus registra", register, obj.indexInDeviceConfig, tbName, tbAttribute);
- obj.errors++;
- if(obj.errors == obj.lengthOfActualDeviceStream)
+ obj.error++;
+ if(obj.error == obj.lengthOfActualDeviceStream)
{
- instance.send(SEND_TO.dido_controller, {status: "NOK-" + obj.device}); // NOK-em340, NOK-em111, NOK-twilight_sensor, NOK-thermometer
+ instance.send(instanceSendTo.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))
@@ -165,11 +164,11 @@ exports.install = function(instance) {
{
message = "electrometer_nok";
}
- message && sendNotification("modbus_reader: readingTimeouted", tbName, message, {}, "", SEND_TO.tb, instance);
+ message && sendNotification("modbus_reader: readingTimeouted", tbName, message, {}, "", instanceSendTo.tb, instance);
numberOfNotResponding[obj.device] = 1;
}
- obj.errors = 0;
+ obj.error = 0;
numberOfNotResponding[obj.device] += 1;
}
@@ -177,12 +176,6 @@ 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();
})
@@ -194,7 +187,7 @@ exports.install = function(instance) {
else this.setNewStream();
}
- transformResponse = (response, register) => {
+ transformResponse = (response, register, deviceAddress) => {
for (let i = 0; i < this.lengthOfActualDeviceStream; i++) {
@@ -205,11 +198,11 @@ exports.install = function(instance) {
let multiplier = a.multiplier;
let value = this.calculateValue(response, multiplier);
- // console.log(register, tbName, tbAttribute, response, a.multiplier, value);
+ // console.log(deviceAddress, register, tbName, tbAttribute, response, a.multiplier, value);
// if(tbName == undefined) return;
- if(this.index + 1 < this.lengthOfActualDeviceStream)
+ if(this.index + 1 + this.errors < this.lengthOfActualDeviceStream)
{
this.allValues[tbAttribute] = value;
return;
@@ -221,9 +214,8 @@ exports.install = function(instance) {
};
this.checkNullVoltage(values);
- this.lampSwitchNotification(values);
- instance.send(SEND_TO.dido_controller, {values: values});
+ instance.send(instanceSendTo.dido_controller, {values: values});
this.allValues = {};
break;
@@ -235,6 +227,8 @@ 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)
@@ -250,6 +244,32 @@ exports.install = function(instance) {
}
}
+
+ // sendFinalObjects = (values) =>
+ // {
+
+ // const date = Date.now();
+ // // values["status"] = "OK";
+
+ // const dataToTB = {
+ // [tbName]: [
+ // {
+ // "ts": date,
+ // "values": values
+ // }
+ // ]
+ // };
+
+ // instance.send(instanceSendTo.tb, dataToTB);
+
+ // const dataToDiDo = {
+ // values: values
+ // }
+
+ // instance.send(instanceSendTo.dido_controller, dataToDiDo);
+ // }
+
+
calculateValue = (response, multiplier) =>
{
let value = 0;
@@ -277,6 +297,7 @@ 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;
@@ -293,56 +314,27 @@ exports.install = function(instance) {
if(values[singleValue] == 0)
{
FLOW.OMS_no_voltage.add(phase);
- sendNotification("modbus_reader: checkNullVoltage", tbName, "no_voltage_on_phase", {phase: phase}, "", SEND_TO.tb, instance, "voltage" + phase );
+ sendNotification("modbus_citys: checkNullVoltage", tbName, "no_voltage_on_phase", {phase: phase}, "", instanceSendTo.tb, instance, "voltage" + phase );
// console.log('no voltage')
}
else
{
FLOW.OMS_no_voltage.delete(phase);
// console.log('voltage detected')
- sendNotification("modbus_reader: checkNullVoltage", tbName, "voltage_on_phase_restored", {phase: phase}, "", SEND_TO.tb, instance, "voltage" + phase);
+ sendNotification("modbus_citys: checkNullVoltage", tbName, "voltage_on_phase_restored", {phase: phase}, "", instanceSendTo.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;
- }
+ // 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(() => {
-
- mainSocket = new SocketWithClients();
+ const newSocket = 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_connector.js b/flow/slack_connector.js
deleted file mode 100644
index 8c073a6..0000000
--- a/flow/slack_connector.js
+++ /dev/null
@@ -1,124 +0,0 @@
-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", 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
-
-exports.html = ``;
-
-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) {
- var can = false;
-
- 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) {
- 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);
- }
- }
- };
- REQUEST(opt);
-
- } else {
- 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);
- } 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');
- };
-
- instance.on('options', instance.reconfigure);
- instance.reconfigure();
-}
diff --git a/flow/slack_filter.js b/flow/slack_filter.js
deleted file mode 100644
index a27c9e1..0000000
--- a/flow/slack_filter.js
+++ /dev/null
@@ -1,187 +0,0 @@
-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