Compare commits

...
Sign in to create a new pull request.

12 commits

Author SHA1 Message Date
Jakub Klena
f7350c117d Merged in senica-rvo-fix-line-control (pull request #4)
Senica rvo fix line control
2024-09-09 11:47:59 +00:00
Jakub Klena
e3c68f3d86 Merged master into senica-rvo-fix-line-control 2024-09-09 11:47:05 +00:00
Jakub Klena
7e20c7d3f0 Removing duplicate 2024-09-09 13:44:39 +02:00
8929cc3a53 actual working Senica Rvo code 09/2024 2024-09-09 12:32:34 +02:00
Jakub Klena
464e74fe26 Merged in feat/Create-slack-connector (pull request #2)
Feat/Create slack connector

Approved-by: Rastislav Kovac
2024-09-06 13:00:04 +00:00
rasta5man
f4ffef94b9 kovalov part delete 2024-06-20 17:56:49 +02:00
Jakub Klena
1b7aae4590 removing some debug msgs 2024-05-24 08:44:15 +02:00
Jakub Klena
6d468acd6f proper last version 2024-05-24 08:42:21 +02:00
Jakub Klena
9e2ab3ccea api key fix 2024-05-24 01:24:08 +02:00
Jakub Klena
2f659a164b Slack connector component 2024-05-24 01:19:34 +02:00
rasta5man
54038a06f8 major updated line switching version 2024-05-10 2024-05-21 15:49:42 +02:00
rasta5man
d289a99d07 new switching line functionality - in progress 2024-05-14 16:29:11 +02:00
9 changed files with 2251 additions and 2108 deletions

View file

@ -1,4 +1,5 @@
const timeoutInterval = 300000;
const timeoutInterval = 150000;
const deviceConfig = [
{
device: "em340",

View file

@ -32,3 +32,6 @@ key:string|weight:string|sk:string|en:string
+|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|...............

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -60,7 +60,7 @@ state_of_contactor - podľa indexu stykača sa reportuje jeho stav, teda
//globals
//FIRMWARE version
FLOW.OMS_edge_fw_version = "2023-10-18";//rok-mesiac-den
FLOW.OMS_edge_fw_version = "2024-07-08";//rok-mesiac-den
FLOW.OMS_edgeName = "";
FLOW.OMS_maintenance_mode = false;
@ -78,7 +78,7 @@ FLOW.OMS_temperature_adress = "";//cmd_manager
let alarmStatus = "OFF";
const instanceSendTo = {
const SEND_TO = {
debug: 0,
tb: 1,
cmd_manager: 2
@ -192,7 +192,7 @@ exports.install = function(instance) {
/*
dbRelays.on('change', function(doc, old) {
console.log("'DI_DO_Controller - dbRelays.on('change'");
instance.send(instanceSendTo.cmd_manager, "reload_relays");
instance.send(SEND_TO.cmd_manager, "reload_relays");
});
*/
@ -264,14 +264,13 @@ exports.install = function(instance) {
{
errLogger.error("CRITICAL!!! undefined relay", relaysData[line], line);
//sendNotification("set port ", edgeName, ERRWEIGHT.CRITICAL, "local database is corrupted", "", instanceSendTo.tb, instance, null );
sendNotification("set port ", edgeName, "local_database_is_corrupted", {}, "", instanceSendTo.tb, instance );
//sendNotification("set port ", edgeName, ERRWEIGHT.CRITICAL, "local database is corrupted", "", SEND_TO.tb, instance, null );
sendNotification("set port ", edgeName, "local_database_is_corrupted", {}, "", SEND_TO.tb, instance );
}
}
if(pinsData[key].type == "state_of_contactor")
{
let pin = key - 1;
if(controller_type === "unipi") pin = key;
@ -299,37 +298,19 @@ exports.install = function(instance) {
]
}
instance.send(instanceSendTo.tb, dataToTb);
instance.send(SEND_TO.tb, dataToTb);
let time = 3*1000;
setTimeout(function(){
instance.send(instanceSendTo.cmd_manager, {sender: "dido_controller", cmd: "buildTasks"});
instance.send(SEND_TO.cmd_manager, {sender: "dido_controller", cmd: "buildTasks"});
sendNotification("rsPort.open()", edgeName, "flow_start", {}, "", instanceSendTo.tb, instance );
sendNotification("rsPort.open()", edgeName, "flow_start", {}, "", SEND_TO.tb, instance );
monitor.info("-->FLOW bol spustený", edgeName, FLOW.OMS_edge_fw_version);
}, time);
}
// TODO: FIND BETTER SOLUTION, THAN REBUILDING TASKS
// we ensure, all tasks will be rebuild twice a week on tuesday or saturday at 11. To set correct switch off and on times
let sendRebuildTasksAt11 = null;
const checkIf11Oclock = () =>
{
const d = new Date();
const h = d.getHours();
const day = d.getDay();
if((day === 2 || day === 6) && h === 11)
{
instance.send(instanceSendTo.cmd_manager, {sender:"dido_controller", cmd:"buildTasks"});
monitor.info("Task rebuilt at 11 o'clock, tuesday, saturday");
}
}
sendRebuildTasksAt11 = setInterval(checkIf11Oclock, 3600000);
function handleRsPort()
{
//TODO build according to pins!!!
@ -339,7 +320,7 @@ exports.install = function(instance) {
rsPort.on('error', function(err) {
logger.debug("rsPort opened error - failed", err.message);
instance.send(instanceSendTo.debug, err.message);
instance.send(SEND_TO.debug, err.message);
errorHandler.sendMessageToService( exports.title + " rsPort opened error - failed: " + err.message);
})
@ -361,7 +342,7 @@ exports.install = function(instance) {
})
}).catch(function (reason) {
//instance.send(instanceSendTo.debug, exports.title + " runSyncExec - promise rejected:" + reason);
//instance.send(SEND_TO.debug, exports.title + " runSyncExec - promise rejected:" + reason);
errLogger.error( exports.title + " runSyncExec - promise rejected:" + reason);
errorHandler.sendMessageToService( exports.title + " runSyncExec - promise rejected:" + reason);
@ -490,7 +471,7 @@ exports.install = function(instance) {
deviceStatuses["temperature"] = "OK";
previousValues["temperature"] = value;
instance.send(instanceSendTo.tb, dataToTb);
instance.send(SEND_TO.tb, dataToTb);
}
return;
}
@ -507,15 +488,18 @@ exports.install = function(instance) {
ws.on('error', (err) => {
instance.send(instanceSendTo.debug, err.message);
monitor.info('websocket error, reconnect')
instance.send(SEND_TO.debug, err.message);
clearInterval(startRequests);
startRequests = null;
ws = null;
setTimeout(handleWebSocket, 1000);
})
ws.onclose = function(){
// connection closed, discard old websocket and create a new one in 5s
// stopRequests();
monitor.info('websocket onclose, reconnect')
clearInterval(startRequests);
ws = null;
console.log("ws is null now, reconnecting...");
@ -654,14 +638,14 @@ exports.install = function(instance) {
//console.log(values);
instance.send(instanceSendTo.tb, dataToTb);
instance.send(SEND_TO.tb, dataToTb);
}
function turnOnLine(line, pin, force, info)
{
instance.send(instanceSendTo.debug, "turn on line " + line );
instance.send(SEND_TO.debug, "turn on line " + line );
if(force == undefined) force = false;
if(line == 0)
@ -695,7 +679,7 @@ exports.install = function(instance) {
{
if(relaysData[line].contactor == 1)
{
instance.send(instanceSendTo.debug, "line is already on " + line );
instance.send(SEND_TO.debug, "line is already on " + line );
logger.debug("turnOnLine: line is already on: ", line);
return;
@ -772,7 +756,7 @@ exports.install = function(instance) {
{
if(relaysData[line].contactor == 0)
{
instance.send(instanceSendTo.debug, "line is already off " + line );
instance.send(SEND_TO.debug, "line is already off " + line );
logger.debug("turnOffLine: line already off:", line);
return;
@ -825,7 +809,7 @@ exports.install = function(instance) {
if(!flowdata.data instanceof Object) return;
// console.log('***********************', flowdata.data)
instance.send(instanceSendTo.debug, flowdata.data);
instance.send(SEND_TO.debug, flowdata.data);
// we handle nok status from modbus_reader component and thermometer
if(flowdata.data?.status)
@ -843,13 +827,13 @@ 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(instanceSendTo.cmd_manager, {sender: "dido_controller", cmd: "lux_sensor", value: values["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"))
@ -861,11 +845,16 @@ exports.install = function(instance) {
{
deviceStatuses["em"] = "OK";
}
else
{
return;
}
const updateStatus = checkFinalRVOStatus();
if(updateStatus) values.status = "OK";
sendTelemetry(values, FLOW.OMS_rvo_tbname);
}
})
@ -895,7 +884,7 @@ exports.install = function(instance) {
rsPort.write(Buffer.from(obj), function(err) {
switchLogic(obj);
instance.send(instanceSendTo.debug, {"WRITE":obj} );
instance.send(SEND_TO.debug, {"WRITE":obj} );
});
}
})
@ -1188,14 +1177,14 @@ exports.install = function(instance) {
{
if (newPinValue === 0 && newPinValue !== previousValues[pinIndex])
{
sendNotification("switchLogic", edgeName, "main_switch_has_been_turned_off", {}, "", instanceSendTo.tb, instance , "state_of_main_switch");
sendNotification("switchLogic", edgeName, "main_switch_has_been_turned_off", {}, "", SEND_TO.tb, instance , "state_of_main_switch");
values["status"] = "NOK";
deviceStatuses["state_of_main_switch"] = "Off";
}
else if (newPinValue === 1 && newPinValue !== previousValues[pinIndex])
{
sendNotification("switchLogic", edgeName, "main_switch_has_been_turned_on", {}, "", instanceSendTo.tb, instance , "state_of_main_switch");
sendNotification("switchLogic", edgeName, "main_switch_has_been_turned_on", {}, "", SEND_TO.tb, instance , "state_of_main_switch");
deviceStatuses["state_of_main_switch"] = "On";
}
@ -1240,7 +1229,7 @@ exports.install = function(instance) {
//ak je spracovany, a automatic - tak ho zapnem
//ak nie je spracovany, iba profil zapisem
instance.send(instanceSendTo.cmd_manager, {sender: "dido_controller", cmd: "rotary_switch_state", value: value});
instance.send(SEND_TO.cmd_manager, {sender: "dido_controller", cmd: "rotary_switch_state", value: value});
//console.log("rotary_switch_state pin", pin2, pin3, value);
}
@ -1249,16 +1238,16 @@ exports.install = function(instance) {
{
if (newPinValue === 0 && newPinValue !== previousValues[pinIndex])
{
//sendNotification("switchLogic", edgeName, ERRWEIGHT.ALERT, "Power supply is not OK", "", instanceSendTo.tb, instance);
sendNotification("switchLogic", edgeName, "power_supply_has_disconnected_input", {}, "", instanceSendTo.tb, instance, "power_supply");
//sendNotification("switchLogic", edgeName, ERRWEIGHT.ALERT, "Power supply is not OK", "", SEND_TO.tb, instance);
sendNotification("switchLogic", edgeName, "power_supply_has_disconnected_input", {}, "", SEND_TO.tb, instance, "power_supply");
values["status"] = "NOK";
deviceStatuses["power_supply"] = "NOK";
}
else if (newPinValue === 1 && newPinValue !== previousValues[pinIndex])
{
//sendNotification("switchLogic", edgeName, ERRWEIGHT.NOTICE, "Power supply is is OK", "", instanceSendTo.tb, instance);
sendNotification("switchLogic", edgeName, "power_supply_works_correctly", {}, "", instanceSendTo.tb, instance, "power_supply");
//sendNotification("switchLogic", edgeName, ERRWEIGHT.NOTICE, "Power supply is is OK", "", SEND_TO.tb, instance);
sendNotification("switchLogic", edgeName, "power_supply_works_correctly", {}, "", SEND_TO.tb, instance, "power_supply");
deviceStatuses["power_supply"] = "OK";
}
@ -1268,16 +1257,16 @@ exports.install = function(instance) {
{
if (newPinValue === 1 && newPinValue !== previousValues[pinIndex])
{
//sendNotification("switchLogic", edgeName, ERRWEIGHT.ERROR, "Battery is not OK", "", instanceSendTo.tb, instance);
sendNotification("switchLogic", edgeName, "battery_level_is_low", {}, "", instanceSendTo.tb, instance, "battery_level");
//sendNotification("switchLogic", edgeName, ERRWEIGHT.ERROR, "Battery is not OK", "", SEND_TO.tb, instance);
sendNotification("switchLogic", edgeName, "battery_level_is_low", {}, "", SEND_TO.tb, instance, "battery_level");
values["status"] = "NOK";
deviceStatuses["battery"] = "NOK";
}
else if (newPinValue === 0 && newPinValue !== previousValues[pinIndex])
{
//sendNotification("switchLogic", edgeName, ERRWEIGHT.NOTICE, "Battery is OK", "", instanceSendTo.tb, instance);
sendNotification("switchLogic", edgeName, "battery_level_is_ok", {}, "", instanceSendTo.tb, instance, "battery_level");
//sendNotification("switchLogic", edgeName, ERRWEIGHT.NOTICE, "Battery is OK", "", SEND_TO.tb, instance);
sendNotification("switchLogic", edgeName, "battery_level_is_ok", {}, "", SEND_TO.tb, instance, "battery_level");
deviceStatuses["battery"] = "OK";
}
@ -1291,19 +1280,19 @@ exports.install = function(instance) {
if (newPinValue != previousValues[pinIndex])
{
//sendNotification("switchLogic", edgeName, ERRWEIGHT.NOTICE, `RVO door ${value}`, "", instanceSendTo.tb, instance, "rvo_door");
//TODO ? sendNotification("switchLogic", edgeName, "door_value", {value: value}, "", instanceSendTo.tb, instance, "rvo_door");
//sendNotification("switchLogic", edgeName, ERRWEIGHT.NOTICE, `RVO door ${value}`, "", SEND_TO.tb, instance, "rvo_door");
//TODO ? sendNotification("switchLogic", edgeName, "door_value", {value: value}, "", SEND_TO.tb, instance, "rvo_door");
}
if (value === "open" && FLOW.OMS_maintenance_mode)
{
sendNotification("switchLogic", edgeName, "door_has_been_open", {}, "", instanceSendTo.tb, instance, "rvo_door");
sendNotification("switchLogic", edgeName, "door_has_been_open", {}, "", SEND_TO.tb, instance, "rvo_door");
}
if (value === "open" && !FLOW.OMS_maintenance_mode)
{
//sendNotification("switchLogic", edgeName, ERRWEIGHT.WARNING, "RVO open door out of maintenance mode", "", instanceSendTo.tb, instance);
sendNotification("switchLogic", edgeName, "door_has_been_open_without_permision_alarm_is_on", {}, "", instanceSendTo.tb, instance, "rvo_door");
//sendNotification("switchLogic", edgeName, ERRWEIGHT.WARNING, "RVO open door out of maintenance mode", "", SEND_TO.tb, instance);
sendNotification("switchLogic", edgeName, "door_has_been_open_without_permision_alarm_is_on", {}, "", SEND_TO.tb, instance, "rvo_door");
values["status"] = "NOK";
//console.log(door_has_been_open_without_permision_alarm_is_on);
@ -1318,7 +1307,7 @@ exports.install = function(instance) {
if(alarmStatus == "ON") turnOffAlarm();
//turnOffAlarm();
sendNotification("switchLogic", edgeName, "door_has_been_closed", {}, "", instanceSendTo.tb, instance, "rvo_door");
sendNotification("switchLogic", edgeName, "door_has_been_closed", {}, "", SEND_TO.tb, instance, "rvo_door");
}
deviceStatuses["door_condition"] = value;
@ -1357,12 +1346,12 @@ exports.install = function(instance) {
twilightError = true;
values["status"] = "NOK";
let value = twilight_sensor_array.shift();
//sendNotification("switchLogic", edgeName, ERRWEIGHT.ERROR, "Lux sensor error", {"Repeating value": value}, instanceSendTo.tb, instance );
//sendNotification("switchLogic", edgeName, ERRWEIGHT.ERROR, "Lux sensor error", {"Repeating value": value}, SEND_TO.tb, instance );
newPinValue = 0;
}
else if (set.size !== 1 && twilightError)
{
//sendNotification("switchLogic", edgeName, ERRWEIGHT.NOTICE, "Lux sensor is working again", "", instanceSendTo.tb, instance );
//sendNotification("switchLogic", edgeName, ERRWEIGHT.NOTICE, "Lux sensor is working again", "", SEND_TO.tb, instance );
twilightError = false;
twilight_sensor_array.shift();
newPinValue = value;
@ -1380,7 +1369,7 @@ exports.install = function(instance) {
if(diff >= twilight_sensor_interval * 60 * 1000)
{
const average = twilight_sensor.reduce((acc, c) => acc + c.value, 0) / twilight_sensor.length;
instance.send(instanceSendTo.cmd_manager, {sender: "dido_controller", cmd: "lux_sensor", value: average});
instance.send(SEND_TO.cmd_manager, {sender: "dido_controller", cmd: "lux_sensor", value: average});
twilight_sensor = [];
@ -1391,11 +1380,11 @@ exports.install = function(instance) {
}
else if(type == "state_of_contactor")
{
//sendNotification("switchLogic", edgeName, ERRWEIGHT.INFO, `State of contactor ${line} is now ${value}`, "", instanceSendTo.tb, instance );
//sendNotification("switchLogic", edgeName, ERRWEIGHT.INFO, `State of contactor ${line} is now ${value}`, "", SEND_TO.tb, instance );
if(!(deviceStatuses["state_of_contactor"][line] == value))
{
sendNotification("switchLogic", edgeName, "state_of_contactor_for_line", {line: line, value: value}, "", instanceSendTo.tb, instance );
sendNotification("switchLogic", edgeName, "state_of_contactor_for_line", {line: line, value: value}, "", SEND_TO.tb, instance );
}
else
{
@ -1437,7 +1426,7 @@ exports.install = function(instance) {
//a budu sa odosielat commandy, tie vsak mozu zlyhat, a preto potrebujeme ich spusti trochu neskor
setTimeout(function(){
instance.send(instanceSendTo.cmd_manager, {sender: "dido_controller", cmd: "reload_relays", line: line, time: time, value: value, dataChanged: dataChanged});
instance.send(SEND_TO.cmd_manager, {sender: "dido_controller", cmd: "reload_relays", line: line, time: time, value: value, dataChanged: dataChanged});
}, time);
reportLineStatus(line);
@ -1462,7 +1451,7 @@ exports.install = function(instance) {
if(valueChanged)
{
instance.send(instanceSendTo.cmd_manager, {sender: "dido_controller", cmd: "state_of_breaker", value: value, line: line});
instance.send(SEND_TO.cmd_manager, {sender: "dido_controller", cmd: "state_of_breaker", value: value, line: line});
//mame iba 3 istice. vyreportujeme a ohandlujeme liniu na tom istom istici ako paralelna linia (napr linia 1, paralelna s nou je linia 4, key je string "4")
// ak je 7 linii, na 1 istici je linia 1,4,7
@ -1476,7 +1465,7 @@ exports.install = function(instance) {
{
if(!relaysData.hasOwnProperty(lineOnSameBraker[i])) continue;
instance.send(instanceSendTo.cmd_manager, {sender: "dido_controller", cmd: "state_of_breaker", value: value, line: lineOnSameBraker[i]});
instance.send(SEND_TO.cmd_manager, {sender: "dido_controller", cmd: "state_of_breaker", value: value, line: lineOnSameBraker[i]});
deviceStatuses["state_of_breaker"][lineOnSameBraker[i]] = value;
reportLineStatus(lineOnSameBraker[i]);
@ -1495,7 +1484,7 @@ exports.install = function(instance) {
if(relaysData.hasOwnProperty(lineOnSameBraker))
{
instance.send(instanceSendTo.cmd_manager, {sender: "dido_controller", cmd: "state_of_breaker", value: value, line: line + 3});
instance.send(SEND_TO.cmd_manager, {sender: "dido_controller", cmd: "state_of_breaker", value: value, line: line + 3});
deviceStatuses["state_of_breaker"][line + 3] = value;
reportLineStatus(line + 3);
@ -1591,7 +1580,7 @@ exports.install = function(instance) {
]
}
instance.send(instanceSendTo.tb, dataToTb);
instance.send(SEND_TO.tb, dataToTb);
}
}

View file

@ -1,218 +0,0 @@
exports.id = 'thermometer';
exports.title = 'Thermometer';
exports.group = 'Worksys';
exports.color = '#5CB36D';
exports.version = '1.0.3';
exports.output = ["red", "white", "blue"];
exports.author = 'Rastislav Kovac';
exports.icon = 'thermometer-three-quarters';
exports.readme = `# Getting temperature values for RVO. In case of LM, you need device address. In case of unipi, evok sends values, in case thermometer is installed`;
const instanceSendTo = {
debug: 0,
tb: 1,
dido_controller: 2
}
//read temperature - frequency
let timeoutMin = 5;//minutes
var path = require('path');
var log4js = require("log4js");
log4js.configure({
appenders: {
errLogs: { type: 'file', filename: path.join(__dirname + "/../", 'err.txt') },
monitorLogs: { type: 'file', compress:true, daysToKeep: 2, maxLogSize: 1048576, backups: 1, keepFileExt: true, filename: path.join(__dirname + "/../", 'monitor.txt') },
console: { type: 'console' }
},
categories: {
errLogs: { appenders: ['console', 'errLogs'], level: 'error' },
monitorLogs: { appenders: ['console', 'monitorLogs'], level: 'trace' },
//another: { appenders: ['console'], level: 'trace' },
default: { appenders: ['console'], level: 'trace' }
}
});
const errLogger = log4js.getLogger("errLogs");
const logger = log4js.getLogger();
const monitor = log4js.getLogger("monitorLogs");
//logger.debug("text")
//monitor.info('info');
//errLogger.error("some error");
const { promisifyBuilder } = require('./helper/db_helper');
const dbSettings = TABLE("settings");
let temperatureAddress = "";
async function loadSettings()
{
//todo global FLOW.OMS_edgeName is making problem, so we load it here as well, it should not be
let responseSettings = await promisifyBuilder(dbSettings.find());
temperatureAddress = responseSettings[0]["temperature_adress"];
}
loadSettings();
exports.install = function(instance) {
const { exec } = require('child_process');
const { sendNotification, ERRWEIGHT } = require('./helper/notification_reporter');
let startRead;
let dataToTb;
let counter = 0;
let edgeName = "";
logger.debug(exports.title, "installed");
instance.on("close", function(){
clearInterval(startRead);
})
const start = function() {
try {
if(FLOW.OMS_controller_type === "unipi")
{
clearInterval(startRead);
return;
}
if(temperatureAddress === "") throw "gettemperature: temperatureAddress is not defined";
logger.debug("FLOW.OMS_temperature_adress", FLOW.OMS_temperature_adress);
exec(`owread -C ${temperatureAddress}/temperature`, (error, stdout, stderr) => {
edgeName = FLOW.OMS_edgeName;
if(edgeName !== "")
{
if(error)
{
if(FLOW.OMS_brokerready == undefined)
{
logger.debug("gettemparature - FLOW.OMS_brokerready is undefined");
setTimeout(function(){
start();
}, 3000);
return;
}
if(FLOW.OMS_brokerready)
{
//sendNotification("start", edgeName, ERRWEIGHT.WARNING, "Thermometer is not responding", {"Error": error}, instanceSendTo.tb, instance, "thermometer");
sendNotification("start", edgeName, "thermometer_is_not_responding", {}, {"Error": error}, instanceSendTo.tb, instance, "thermometer");
}
let status = "NOK";
dataToTb = {
[edgeName]: [
{
"ts": Date.now(),
"values": {
"status": status
}
}
]
}
monitor.info("Thermometer is not responding", error, FLOW.OMS_brokerready);
// instance.send(instanceSendTo.tb, dataToTb); // poslat stav nok do tb, ak to handluje dido_controller ??
instance.send(instanceSendTo.dido_controller, {status: "NOK-thermometer"});
}
else parseData(stdout);
}
else
{
monitor.info("gettemperature: edgeName is not defined", FLOW.OMS_edgeName);
setTimeout(function(){
start();
}, 3000);
return;
}
//instance.send({"Temp":stdout,"stderr":stderr,"err":error});
});
}
catch(err) {
errLogger.error(exports.title, err);
}
}
const parseData = function(data) {
data = parseFloat(data);
logger.debug("gettemperature", data);
if(!isNaN(data)) {
if(counter > 290)
{
instance.send(instanceSendTo.debug, "[Get temperature component] - temperature data are comming again from RVO after more than 1 day break");
//sendNotification("parseData", edgeName, ERRWEIGHT.NOTICE, "Thermometer is working again", "", instanceSendTo.tb, instance, "thermometer");
if(FLOW.OMS_brokerready) sendNotification("parseData", edgeName, "thermometer_is_responding_again", {}, "", instanceSendTo.tb, instance, "thermometer");
}
logger.debug("gettemperature", data);
const values = {
"temperature": Number(data.toFixed(2)),
"status": "OK"
}
dataToTb = {
[edgeName]: [
{
"ts": Date.now(),
"values":values
}
]
}
instance.send(instanceSendTo.tb, dataToTb);
instance.send(instanceSendTo.dido_controller, values);
counter = 0;
} else {
counter++;
monitor.info("gettemperature err", counter, data);
//ked je problem 1 den
let day = 24 * 60 / timeoutMin;
if ( counter > day && counter < day + 2 ) {
//sendNotification("parseData", edgeName, ERRWEIGHT.WARNING, "Thermometer receives invalid data", "", instanceSendTo.tb, instance, "thermometer");
sendNotification("parseData", edgeName, "thermometer_sends_invalid_data", {}, "", instanceSendTo.tb, instance, "thermometer");
instance.send(instanceSendTo.debug, "[Get temperature component] - no temperature data from RVO for more than 1 day");
instance.send(instanceSendTo.dido_controller, {status: "NOK-thermometer"});
}
}
}
setTimeout(function(){
start();
}, 3000);
startRead = setInterval(start, timeoutMin * 1000 * 60);
};

View file

@ -14,19 +14,14 @@ 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 instanceSendTo = {
const SEND_TO = {
debug: 0,
dido_controller: 1,
tb: 2
@ -35,6 +30,8 @@ const instanceSendTo = {
//to handle NOK and OK sendNotifications s
const numberOfNotResponding = {};
let tbName = null;
let mainSocket;
exports.install = function(instance) {
@ -49,12 +46,16 @@ exports.install = function(instance) {
this.index = 0;
this.timeoutInterval = 5000;
// kedze potrebujeme ist stale dookola pre jednotlive zariadenia, potrebujeme ci uz index ako aj adresu zariadenia, a aj pocet registrov na vycitanie
this.deviceAddress = null; // adresa zariadenia (1 ma EM340 a 2 ma twilight_sensor)
this.indexInDeviceConfig = 0; // prvy item v deviceConfig
// we need to go always around for all devices. So we need index value, device address, as well as number of registers for single device
this.deviceAddress = null; // device address (1 - EM340 and 2 for twilight_sensor)
this.indexInDeviceConfig = 0; // first item in deviceConfig
this.lengthOfActualDeviceStream = null;
this.device = null;
// lampSwitchNotification helper variables
this.onNotificationSent = false;
this.offNotificationSent = false;
this.startSocket();
}
@ -69,7 +70,7 @@ exports.install = function(instance) {
// we create a client for every deviceAddress ( = address) in list and push them into dictionary
for( let i = 0; i < deviceConfig.length; i++)
{
this.clients[deviceConfig[i].deviceAddress] = new modbus.client.RTU(this.socket, deviceConfig[i].deviceAddress);
this.clients[deviceConfig[i].deviceAddress] = new modbus.client.RTU(this.socket, deviceConfig[i].deviceAddress, 2000); // 2000 is timeout in register request, default is 5000, which is too long
}
this.socket.on('error', function(e) {
@ -133,24 +134,24 @@ exports.install = function(instance) {
{
message = "twilight_sensor_ok";
}
message && sendNotification("modbus_reader: readRegisters", tbName, message, {}, "", instanceSendTo.tb, instance);
message && sendNotification("modbus_reader: readRegisters", tbName, message, {}, "", SEND_TO.tb, instance);
delete numberOfNotResponding[obj.device];
}
obj.transformResponse(resp, register, obj.deviceAddress);
obj.transformResponse(resp, register);
obj.error = 0;
//obj.errors = 0;
obj.index++;
obj.readAnotherRegister();
}).catch (function () {
console.log("error pri citani modbus registra", register, obj.indexInDeviceConfig, tbName, tbAttribute);
console.log("errors pri citani modbus registra", register, obj.indexInDeviceConfig, tbName, tbAttribute);
obj.error++;
if(obj.error == obj.lengthOfActualDeviceStream)
obj.errors++;
if(obj.errors == obj.lengthOfActualDeviceStream)
{
instance.send(instanceSendTo.dido_controller, {status: "NOK-" + obj.device}); // NOK-em340, NOK-em111, NOK-twilight_sensor, NOK-thermometer
instance.send(SEND_TO.dido_controller, {status: "NOK-" + obj.device}); // NOK-em340, NOK-em111, NOK-twilight_sensor, NOK-thermometer
//todo - neposlalo notification, ked sme vypojili twilight a neposle to do tb, ale do dido ??
if(!numberOfNotResponding.hasOwnProperty(obj.device))
@ -164,11 +165,11 @@ exports.install = function(instance) {
{
message = "electrometer_nok";
}
message && sendNotification("modbus_reader: readingTimeouted", tbName, message, {}, "", instanceSendTo.tb, instance);
message && sendNotification("modbus_reader: readingTimeouted", tbName, message, {}, "", SEND_TO.tb, instance);
numberOfNotResponding[obj.device] = 1;
}
obj.error = 0;
obj.errors = 0;
numberOfNotResponding[obj.device] += 1;
}
@ -176,6 +177,12 @@ exports.install = function(instance) {
depth: null
}))
// if reading out of device's last register returns error, we send accumulated allValues to dido_controller (if allValues are not an empty object)
if(obj.index + 1 >= obj.lengthOfActualDeviceStream)
{
if(!isObjectEmpty(obj.allValues)) instance.send(SEND_TO.dido_controller, {values: obj.allValues});
obj.allValues = {};
}
obj.index++;
obj.readAnotherRegister();
})
@ -187,7 +194,7 @@ exports.install = function(instance) {
else this.setNewStream();
}
transformResponse = (response, register, deviceAddress) => {
transformResponse = (response, register) => {
for (let i = 0; i < this.lengthOfActualDeviceStream; i++) {
@ -198,11 +205,11 @@ exports.install = function(instance) {
let multiplier = a.multiplier;
let value = this.calculateValue(response, multiplier);
// console.log(deviceAddress, register, tbName, tbAttribute, response, a.multiplier, value);
// console.log(register, tbName, tbAttribute, response, a.multiplier, value);
// if(tbName == undefined) return;
if(this.index + 1 + this.errors < this.lengthOfActualDeviceStream)
if(this.index + 1 < this.lengthOfActualDeviceStream)
{
this.allValues[tbAttribute] = value;
return;
@ -214,8 +221,9 @@ exports.install = function(instance) {
};
this.checkNullVoltage(values);
this.lampSwitchNotification(values);
instance.send(instanceSendTo.dido_controller, {values: values});
instance.send(SEND_TO.dido_controller, {values: values});
this.allValues = {};
break;
@ -227,8 +235,6 @@ exports.install = function(instance) {
setNewStream = () =>
{
// console.log('------------',this.lengthOfActualDeviceStream, this.index);
// console.log('------------',this.indexInDeviceConfig, deviceConfig.length);
if(this.lengthOfActualDeviceStream == this.index)
{
if(this.indexInDeviceConfig + 1 == deviceConfig.length)
@ -244,32 +250,6 @@ exports.install = function(instance) {
}
}
// sendFinalObjects = (values) =>
// {
// const date = Date.now();
// // values["status"] = "OK";
// const dataToTB = {
// [tbName]: [
// {
// "ts": date,
// "values": values
// }
// ]
// };
// instance.send(instanceSendTo.tb, dataToTB);
// const dataToDiDo = {
// values: values
// }
// instance.send(instanceSendTo.dido_controller, dataToDiDo);
// }
calculateValue = (response, multiplier) =>
{
let value = 0;
@ -297,7 +277,6 @@ exports.install = function(instance) {
return Math.round(value * multiplier * 10) / 10;
}
checkNullVoltage = (values) => {
if(!(values.hasOwnProperty("Phase_1_voltage") || values.hasOwnProperty("Phase_2_voltage") || values.hasOwnProperty("Phase_3_voltage"))) return;
@ -314,27 +293,56 @@ exports.install = function(instance) {
if(values[singleValue] == 0)
{
FLOW.OMS_no_voltage.add(phase);
sendNotification("modbus_citys: checkNullVoltage", tbName, "no_voltage_on_phase", {phase: phase}, "", instanceSendTo.tb, instance, "voltage" + phase );
sendNotification("modbus_reader: checkNullVoltage", tbName, "no_voltage_on_phase", {phase: phase}, "", SEND_TO.tb, instance, "voltage" + phase );
// console.log('no voltage')
}
else
{
FLOW.OMS_no_voltage.delete(phase);
// console.log('voltage detected')
sendNotification("modbus_citys: checkNullVoltage", tbName, "voltage_on_phase_restored", {phase: phase}, "", instanceSendTo.tb, instance, "voltage" + phase);
sendNotification("modbus_reader: checkNullVoltage", tbName, "voltage_on_phase_restored", {phase: phase}, "", SEND_TO.tb, instance, "voltage" + phase);
}
}
})
}
// we use dataToTbHandler. Therefore we need to check, if objects we send to dido_controller are not empty
isObjectEmpty = (objectName) => {
return Object.keys(objectName).length === 0 && objectName.constructor === Object;
/**
* 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;
}
}
setTimeout(() => {
const newSocket = new SocketWithClients();
tbName = FLOW.OMS_rvo_tbname;
}, 25000);
}
const isObjectEmpty = (objectName) => {
return Object.keys(objectName).length === 0 && objectName.constructor === Object;
}
setTimeout(() => {
mainSocket = new SocketWithClients();
tbName = FLOW.OMS_rvo_tbname;
// this notification is to show, that flow (unipi) has been restarted
sendNotification("modbus_reader", tbName, "flow_restart", {}, "", SEND_TO.slack, instance);
}, 25000);
}

124
flow/slack_connector.js Normal file
View file

@ -0,0 +1,124 @@
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 = `<div class="padding">
<div class="row">
<div class="col-md-6">
<div data-jc="textbox" data-jc-path="slack_channel" data-jc-config="placeholder:name or id;required:true" class="m">Slack Channel</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div data-jc="textbox" data-jc-path="api_key" data-jc-config="placeholder:api key;required:true" class="m">API Key:</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div data-jc="textbox" data-jc-path="bot_name" data-jc-config="placeholder:Flow DEMO;required:false" class="m">Bot Name</div>
</div>
<div class="col-md-6">
<div data-jc="textbox" data-jc-path="bot_icon" data-jc-config="placeholder:\:totaljs\:;required:true" class="m">Bot Icon</div>
</div>
</div>
</div>`;
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();
}

187
flow/slack_filter.js Normal file
View file

@ -0,0 +1,187 @@
exports.id = 'slack_filter';
exports.title = 'Slack Filter';
exports.group = 'Citysys';
exports.color = '#30E193';
exports.input = 1;
exports.output = 1;
exports.author = 'Jakub Klena';
exports.icon = 'plug';
exports.version = '1.0.8';
exports.options = { 'name':'', 'types': '["emergency", "critical", "error", "alert"]', 'message_includes':'["is responding again"]', 'tag_on_include':'[{"user_id":"U072JE5JUQG", "includes":["Electrometer", "Twilight sensor"]}]', 'slack_channel':'' };
exports.html = `<div class="padding">
<div class="row">
<div class="col-md-12">
<div data-jc="textbox" data-jc-path="name" data-jc-config="required:true">@(Name of this server)</div>
</div>
<div class="col-md-12">
<div data-jc="textbox" data-jc-path="slack_channel" data-jc-config="required:false">@(Slack channel to receive the alerts)</div>
</div>
<div class="col-md-12">
<div data-jc="textbox" data-jc-path="types" data-jc-config="required:false">@(Watch these types, comma separated names)</div>
</div>
<div class="col-md-12">
<div data-jc="textbox" data-jc-path="message_includes" data-jc-config="required:false">@(Watch messages that include any of the following strings)</div>
</div>
<div class="col-md-12">
<div data-jc="textbox" data-jc-path="tag_on_include" data-jc-config="required:false">@(Tag people if message includes something)</div>
</div>
</div>
</div>`;
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();
};