Interval Function in Function flow

I'm having issues with having my node to start interval function , I need to start function when get data from input like my code cmd == "01" and stop function when i get cmd == "06" i try can't run

Here my flow

[{"id":"8a66f209.73b0a","type":"mqtt out","z":"68b22cc5.bf042c","name":"","topic":"SUB/867724030292780","qos":"","retain":"","broker":"1b33bbc4.fa5024","x":1476.3333740234375,"y":901.5333251953125,"wires":[]},{"id":"3c583e87.f57792","type":"function-npm","z":"68b22cc5.bf042c","name":"Check Null Test","func":"var moment = require('moment-timezone');\n\nvar current = moment().tz(\"Asia/Bangkok\").format(\"YYYYMMDDHHmmss\");\nvar x = global.get('YourVariable');\n\n    if (msg.payload === undefined || msg.payload.length === 0){\n        \n        node.send({\n            payload:\"UHM\".concat(\"21\").concat(\"06\").concat(\"867724030292780\").concat(current).concat(\"ff\")\n        });\n    } else{\n    \n        node.send({\n            payload:\"UHM\".concat(\"21\").concat(\"03\").concat(\"867724030292780\").concat(current).concat(\"ff\")\n        });\n    }\n    \n\n\nreturn  null;\n","outputs":1,"noerr":0,"x":1152.36669921875,"y":900,"wires":[["8a66f209.73b0a"]]},{"id":"237e9cde.764f04","type":"mysql","z":"68b22cc5.bf042c","mydb":"3941ded9.ccf0b2","name":"","x":850.75,"y":761.5,"wires":[["3c583e87.f57792","5117888c.a10a2"]]},{"id":"5117888c.a10a2","type":"debug","z":"68b22cc5.bf042c","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","x":1217.36669921875,"y":780.75,"wires":[]},{"id":"dab2b97e.1f7f78","type":"function-npm","z":"68b22cc5.bf042c","name":"Check CMD","func":"var converter = require('hex2dec');\n\nvar x;\n\nfunction start(){\n\n    x = setInterval(function(){\n        \n        msg.topic = \"SELECT `casename`, id , imei ,start_time FROM operation_database WHERE imei = 867724030292780 AND casename = ' ' ORDER by id DESC LIMIT 1\";\n        return msg;\n    \n    }, 1000);\n\n}\n\nfunction stop(){\n\n    clearInterval(x);\n\n}\n\nvar newMsg = msg.payload;\n\nglobal.set('YourVariable', newMsg); \n\n\nvar header = newMsg.substr(0,3);\nvar lengths = newMsg.substr(3,2);\nvar cmd = newMsg.substr(5,2);\n\nif(cmd == \"01\"){\n    \n    \n    var imei = newMsg.substr(7,15);\n    var sim_id = newMsg.substr(22,15);\n    var ip_1 = converter.hexToDec(newMsg.substr(37,2));\n    var ip_2 = converter.hexToDec(newMsg.substr(39,2));\n    var ip_3 = converter.hexToDec(newMsg.substr(41,2));\n    var ip_4 = converter.hexToDec(newMsg.substr(43,2));\n    var ip = ip_1.concat(\".\").concat(ip_2).concat(\".\").concat(ip_3).concat(\".\").concat(ip_4);\n    var port = newMsg.substr(45,5);\n    var device_timestamp = newMsg.substr(50,14);\n    var device_date = newMsg.substr(50,8);\n    var device_time = newMsg.substr(58,6);\n    var battery = converter.hexToDec(newMsg.substr(64,2));\n    var rssi = converter.hexToDec(newMsg.substr(66,2));\n    var rssi_before = converter.hexToDec(newMsg.substr(68,2));\n    var event_setup = newMsg.substr(70,1);\n    var byte_check = newMsg.substr(71,2);\n\n \n    node.send([null, {payload:\"UHM\".concat(\"15\").concat(\"01\").concat(\"867724030292780\").concat(\"N\").concat(\"N\").concat(\"ff\")},null]);\n    \n    if (lengths == \"44\"){\n        msg.topic = \"SELECT `casename`, id , imei ,start_time FROM operation_database WHERE imei = 867724030292780 AND casename = ' ' ORDER by id DESC LIMIT 1\";\n        return[msg,null,null];\n        \n    }\n    \n}\n\nif(cmd == \"06\"){\n    \n    var imei = newMsg.substr(7,15);\n    var check1 = newMsg.substr(22,1);\n    var check2 = newMsg.substr(23,1);\n    var byte_check = newMsg.substr(24,2);\n    \n    msg.topic = \"INSERT INTO `device_ack` (`header`, `length`, `cmd`, `imei`, `check1`, `check2`, `byte_check`) VALUES ('\"+header+\"', '\"+lengths+\"', '\"+cmd+\"', '\"+imei+\"', '\"+check1+\"', '\"+check2+\"', '\"+byte_check+\"')\";\n    return[null,null,msg];\n}\n\n\n\n\n\n","outputs":3,"noerr":0,"x":482.36669921875,"y":849.75,"wires":[["237e9cde.764f04"],["86d8f9a3.34d978"],["748d064f.1020d8"]]},{"id":"79c8542a.0a7db4","type":"mqtt in","z":"68b22cc5.bf042c","name":"","topic":"PUB/867724030292780","qos":"2","broker":"1b33bbc4.fa5024","x":147.36666870117188,"y":930,"wires":[["dab2b97e.1f7f78"]]},{"id":"b91edbb1.b55588","type":"inject","z":"68b22cc5.bf042c","name":"","topic":"","payload":"UHM440186772403029278052004510000143236e3cd7d1210620190220141500645a5aNff","payloadType":"str","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":116.75,"y":775.5,"wires":[["dab2b97e.1f7f78"]]},{"id":"86d8f9a3.34d978","type":"mqtt out","z":"68b22cc5.bf042c","name":"","topic":"SUB/867724030292780","qos":"","retain":"","broker":"1b33bbc4.fa5024","x":840.3333129882812,"y":821.5333251953125,"wires":[]},{"id":"748d064f.1020d8","type":"mysql","z":"68b22cc5.bf042c","mydb":"3941ded9.ccf0b2","name":"","x":852,"y":875,"wires":[[]]},{"id":"1b33bbc4.fa5024","type":"mqtt-broker","z":"","name":"","broker":"m15.cloudmqtt.com","port":"12106","clientid":"","usetls":false,"compatmode":true,"keepalive":"60","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","closeTopic":"","closeQos":"0","closePayload":"","willTopic":"","willQos":"0","willPayload":""},{"id":"3941ded9.ccf0b2","type":"MySQLdatabase","z":"","host":"43.241.57.67","port":"3306","db":"vnsoftt_flushvalve_phuket","tz":""}]

Here my code

var converter = require('hex2dec');

var x;

function start(){

    x = setInterval(function(){
        
        msg.topic = "SELECT `casename`, id , imei ,start_time FROM operation_database WHERE imei = 867724030292780 AND casename = ' ' ORDER by id DESC LIMIT 1";
        return msg;
    
    }, 1000);

}

function stop(){

    clearInterval(x);

}

var newMsg = msg.payload;

global.set('YourVariable', newMsg); 


var header = newMsg.substr(0,3);
var lengths = newMsg.substr(3,2);
var cmd = newMsg.substr(5,2);

if(cmd == "01"){
    
    
    var imei = newMsg.substr(7,15);
    var sim_id = newMsg.substr(22,15);
    var ip_1 = converter.hexToDec(newMsg.substr(37,2));
    var ip_2 = converter.hexToDec(newMsg.substr(39,2));
    var ip_3 = converter.hexToDec(newMsg.substr(41,2));
    var ip_4 = converter.hexToDec(newMsg.substr(43,2));
    var ip = ip_1.concat(".").concat(ip_2).concat(".").concat(ip_3).concat(".").concat(ip_4);
    var port = newMsg.substr(45,5);
    var device_timestamp = newMsg.substr(50,14);
    var device_date = newMsg.substr(50,8);
    var device_time = newMsg.substr(58,6);
    var battery = converter.hexToDec(newMsg.substr(64,2));
    var rssi = converter.hexToDec(newMsg.substr(66,2));
    var rssi_before = converter.hexToDec(newMsg.substr(68,2));
    var event_setup = newMsg.substr(70,1);
    var byte_check = newMsg.substr(71,2);

 
    node.send([null, {payload:"UHM".concat("15").concat("01").concat("867724030292780").concat("N").concat("N").concat("ff")},null]);
    
    if (lengths == "44"){
        msg.topic = "SELECT `casename`, id , imei ,start_time FROM operation_database WHERE imei = 867724030292780 AND casename = ' ' ORDER by id DESC LIMIT 1";
        return[msg,null,null];
        
    }
    
}

if(cmd == "06"){
    
    var imei = newMsg.substr(7,15);
    var check1 = newMsg.substr(22,1);
    var check2 = newMsg.substr(23,1);
    var byte_check = newMsg.substr(24,2);
    
    msg.topic = "INSERT INTO `device_ack` (`header`, `length`, `cmd`, `imei`, `check1`, `check2`, `byte_check`) VALUES ('"+header+"', '"+lengths+"', '"+cmd+"', '"+imei+"', '"+check1+"', '"+check2+"', '"+byte_check+"')";
    return[null,null,msg];
}

You can't use return inside a async function (a setInterval function for example). After starting the timer the code drops through and returns at that point. Inside the interval function you have to use node.send().

Now i can run interval but i don't know how i use a query code inside node.send i got an error
function.error.non-message-returned

var converter = require('hex2dec');

    var x;
    
    x = setInterval(function(){
            
        node.send("SELECT `casename`, id , imei ,start_time FROM operation_database WHERE imei = 867724030292780 AND casename = ' ' ORDER by id DESC LIMIT 1");
        
    }, 1000);

    function stop(){
    
        clearInterval(x);
    
    }
    
    var newMsg = msg.payload;
    
    global.set('YourVariable', newMsg); 
    
    
    var header = newMsg.substr(0,3);
    var lengths = newMsg.substr(3,2);
    var cmd = newMsg.substr(5,2);



if(cmd == "01"){
    
    
    var imei = newMsg.substr(7,15);
    var sim_id = newMsg.substr(22,15);
    var ip_1 = converter.hexToDec(newMsg.substr(37,2));
    var ip_2 = converter.hexToDec(newMsg.substr(39,2));
    var ip_3 = converter.hexToDec(newMsg.substr(41,2));
    var ip_4 = converter.hexToDec(newMsg.substr(43,2));
    var ip = ip_1.concat(".").concat(ip_2).concat(".").concat(ip_3).concat(".").concat(ip_4);
    var port = newMsg.substr(45,5);
    var device_timestamp = newMsg.substr(50,14);
    var device_date = newMsg.substr(50,8);
    var device_time = newMsg.substr(58,6);
    var battery = converter.hexToDec(newMsg.substr(64,2));
    var rssi = converter.hexToDec(newMsg.substr(66,2));
    var rssi_before = converter.hexToDec(newMsg.substr(68,2));
    var event_setup = newMsg.substr(70,1);
    var byte_check = newMsg.substr(71,2);
    
    node.send(x);
    
    node.send([null, {payload:"UHM".concat("15").concat("01").concat("867724030292780").concat("N").concat("N").concat("ff")},null]);
    
    if (lengths == "44"){
        msg.topic = "SELECT `casename`, id , imei ,start_time FROM operation_database WHERE imei = 867724030292780 AND casename = ' ' ORDER by id DESC LIMIT 1";
        return[msg,null,null];
        
    }
    
}

if(cmd == "06"){
    
    var imei = newMsg.substr(7,15);
    var check1 = newMsg.substr(22,1);
    var check2 = newMsg.substr(23,1);
    var byte_check = newMsg.substr(24,2);
    
    msg.topic = "INSERT INTO `device_ack` (`header`, `length`, `cmd`, `imei`, `check1`, `check2`, `byte_check`) VALUES ('"+header+"', '"+lengths+"', '"+cmd+"', '"+imei+"', '"+check1+"', '"+check2+"', '"+byte_check+"')";
    return[null,null,msg];
}






node.send( { payload:"SELECT ...."} )

I got it with this code thank so much

var converter = require('hex2dec');

var newMsg = msg.payload;
    
global.set('YourVariable', newMsg); 
    
var header = newMsg.substr(0,3);
var lengths =  converter.hexToDec(newMsg.substr(3,2));
var cmd = newMsg.substr(5,2);

function start(){
    x = setInterval(function(){
        node.send({"topic" :"SELECT `casename`, id , imei ,start_time FROM operation_database WHERE imei = 867724030292780 AND casename = ' ' ORDER by id DESC LIMIT 1"});
    } , 1000);
}

function stop(){
    clearInterval(x)
}

if(cmd == "01"){
    
    msg.payload = start();

    var imei = newMsg.substr(7,15);
    var sim_id = newMsg.substr(22,15);
    var ip_1 = converter.hexToDec(newMsg.substr(37,2));
    var ip_2 = converter.hexToDec(newMsg.substr(39,2));
    var ip_3 = converter.hexToDec(newMsg.substr(41,2));
    var ip_4 = converter.hexToDec(newMsg.substr(43,2));
    var ip = ip_1.concat(".").concat(ip_2).concat(".").concat(ip_3).concat(".").concat(ip_4);
    var port = newMsg.substr(45,5);
    var device_timestamp = newMsg.substr(50,14);
    var device_date = newMsg.substr(50,8);
    var device_time = newMsg.substr(58,6);
    var battery = converter.hexToDec(newMsg.substr(64,2));
    var rssi = converter.hexToDec(newMsg.substr(66,2));
    var rssi_before = converter.hexToDec(newMsg.substr(68,2));
    var event_setup = newMsg.substr(70,1);
    var byte_check = newMsg.substr(71,2);
    
    node.send([null, {payload:"UHM".concat("15").concat("01").concat("867724030292780").concat("N").concat("N").concat("ff")},null]);
    
    if (lengths == "68"){
        msg.topic = "SELECT `casename`, id , imei ,start_time FROM operation_database WHERE imei = 867724030292780 AND casename = ' ' ORDER by id DESC LIMIT 1";
        return[msg,null,null];
        
    }
}

if(cmd == "06"){
    
    msg.payload = stop();
    
    var imei = newMsg.substr(7,15);
    var check1 = newMsg.substr(22,1);
    var check2 = newMsg.substr(23,1);
    var byte_check = newMsg.substr(24,2);
    
    msg.topic = "INSERT INTO device_ack (`header`, `length`, `cmd`, `imei`, `check1`, `check2`, `byte_check`) VALUES ('"+header+"', '"+lengths+"', '"+cmd+"', '"+imei+"', '"+check1+"', '"+check2+"', '"+byte_check+"')";
    return[null,null,msg];
}

There are a few issues with your function, some serious, some not
If cmd is "01" then you set the variable x to the timer id from the setInterval function, which starts it sending the SELECT message once a second. When another message comes in, if cmd is "06" you call stop() which tries to reset the timer using x. However the variable x will not be remembered from the previous message as you have not saved it in the node context. I cannot see how this will ever stop the setInterval function, unless I am missing something. Does it actually work?

The usual way of doing this would be to have at that start
var x = context.get("x") || 0
then in start()

if (x) stop();        // clear the timer if it is already running
x = setInterval(....);
context.set("x",x);

and in stop()

if (x) {
  clearInterval(x)
  context.set("x",0)
}

In fact I would not call it x, I would call it something like timerId, it makes the code more understandable.

Not serious:
If cmnd is "01" you set msg.payload to the value returned by start, but start() does not return a value. Similarly if it is "06" you are setting payload to stop() which also does not return a value
You have a variable called newMsg but it isn't a message, it is a string. Naming variables in meaningful ways helps to make code understandable and reduces bugs.
You are setting a global context variable called 'YourVariable'. Is that just a line that has been accidentally left in or are you actually using a global context var called that?

1 Like

Oh thank a lot i can use my code but not good enougth i use your code it's perfect i don't think before i will learn a lot of this , and i use global for use to another flow like this code i don't know how use another code for perfectly thank you

Unfortunately most of the nodes in that flow are of types that I have not installed (and don't know what they are) so I can't see how you are using the global. But even if you have a good use of a global variable is it a good idea to call it "YourVariable"?

I call that for test sample and i will change a good word , and i change my flow function to normal flow please see this

[{"id":"da278859.595f38","type":"mysql","z":"de99db21.fe06d","mydb":"3941ded9.ccf0b2","name":"","x":900,"y":620,"wires":[["1d4bdd46.f0ff13","d0e94497.7aea7"]]},{"id":"1d4bdd46.f0ff13","type":"debug","z":"de99db21.fe06d","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","x":1310,"y":640,"wires":[]},{"id":"9f8d343e.6e476","type":"function","z":"de99db21.fe06d","name":"CHECK CMD","func":"//var converter = require('hex2dec');\n\nvar newMsg = msg.payload;\n    \nglobal.set('YourVariable', newMsg); \n    \nvar header = newMsg.substr(0,3);\nvar lengths =  newMsg.substr(3,2);\nvar cmd = newMsg.substr(5,2);\n\nvar timer;\n\nfunction start(){\n    timer = setInterval(function(){\n        node.send({\"topic\" :\"SELECT `casename`, id , imei ,start_time FROM operation_database WHERE imei = 867724030292780 AND casename = ' ' ORDER by id DESC LIMIT 1\"});\n    } , 1000);\n}\n\nfunction stop(){\n    clearInterval(timer)\n}\n\nif(cmd == \"01\"){\n    \n    msg.payload = start();\n\n    var imei = newMsg.substr(7,15);\n    var sim_id = newMsg.substr(22,15);\n    var ip_1 = newMsg.substr(37,2);\n    var ip_2 = newMsg.substr(39,2);\n    var ip_3 = newMsg.substr(41,2);\n    var ip_4 = newMsg.substr(43,2);\n    var ip = ip_1.concat(\".\").concat(ip_2).concat(\".\").concat(ip_3).concat(\".\").concat(ip_4);\n    var port = newMsg.substr(45,5);\n    var device_timestamp = newMsg.substr(50,14);\n    var device_date = newMsg.substr(50,8);\n    var device_time = newMsg.substr(58,6);\n    var battery = newMsg.substr(64,2);\n    var rssi = newMsg.substr(66,2);\n    var rssi_before = newMsg.substr(68,2);\n    var event_setup = newMsg.substr(70,1);\n    var byte_check = newMsg.substr(71,2);\n    \n    node.send([null, {payload:\"UHM\".concat(\"15\").concat(\"01\").concat(\"867724030292780\").concat(\"N\").concat(\"N\").concat(\"ff\")},null]);\n    \n    if (lengths == \"68\"){\n        msg.topic = \"SELECT `casename`, id , imei ,start_time FROM operation_database WHERE imei = 867724030292780 AND casename = ' ' ORDER by id DESC LIMIT 1\";\n        return[msg,null,null];\n        \n    }\n}\n\nif(cmd == \"06\"){\n    \n    msg.payload = stop();\n    \n    var imei = newMsg.substr(7,15);\n    var check1 = newMsg.substr(22,1);\n    var check2 = newMsg.substr(23,1);\n    var byte_check = newMsg.substr(24,2);\n    \n    msg.topic = \"INSERT INTO device_ack (`header`, `length`, `cmd`, `imei`, `check1`, `check2`, `byte_check`) VALUES ('\"+header+\"', '\"+lengths+\"', '\"+cmd+\"', '\"+imei+\"', '\"+check1+\"', '\"+check2+\"', '\"+byte_check+\"')\";\n    return[null,null,msg];\n}","outputs":3,"noerr":0,"x":490,"y":680,"wires":[["da278859.595f38"],["f25fed5f.813148"],["e332a142.2ad9e"]]},{"id":"d0e94497.7aea7","type":"function","z":"de99db21.fe06d","name":"","func":"\nvar x = global.get('YourVariable');\nvar header = x.substr(0,3);\n\n    if (msg.payload === undefined || msg.payload.length === 0){\n        \n        node.send({\n            payload:header.concat(\"21\").concat(\"06\").concat(\"867724030292780\").concat(\"ff\")\n        });\n    } else{\n    \n        node.send({\n            payload:\"UHM\".concat(\"21\").concat(\"03\").concat(\"867724030292780\").concat(\"ff\")\n        });\n    }\n    \n\n\nreturn  null;\n","outputs":1,"noerr":0,"x":1290,"y":700,"wires":[["a7417d66.0648"]]},{"id":"f25fed5f.813148","type":"mqtt out","z":"de99db21.fe06d","name":"","topic":"SUB/867724030292780","qos":"","retain":"","broker":"1b33bbc4.fa5024","x":890,"y":680,"wires":[]},{"id":"e332a142.2ad9e","type":"mysql","z":"de99db21.fe06d","mydb":"3941ded9.ccf0b2","name":"","x":900,"y":740,"wires":[["25bfd0a9.c39fb8"]]},{"id":"6573f146.d933e","type":"inject","z":"de99db21.fe06d","name":"","topic":"","payload":"UHM440186772403029278052004510000143236e3cd7d1210620190220141500645a5aNff","payloadType":"str","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":130,"y":680,"wires":[["9f8d343e.6e476"]]},{"id":"a08612d2.a76d58","type":"mqtt in","z":"de99db21.fe06d","name":"","topic":"PUB/867724030292780","qos":"2","broker":"1b33bbc4.fa5024","x":178.66668701171875,"y":755.4666748046875,"wires":[["9f8d343e.6e476"]]},{"id":"a7417d66.0648","type":"mqtt out","z":"de99db21.fe06d","name":"","topic":"SUB/867724030292780","qos":"","retain":"","broker":"1b33bbc4.fa5024","x":1570,"y":700,"wires":[]},{"id":"25bfd0a9.c39fb8","type":"debug","z":"de99db21.fe06d","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":1130,"y":740,"wires":[]},{"id":"3941ded9.ccf0b2","type":"MySQLdatabase","z":"","host":"43.241.57.67","port":"3306","db":"vnsoftt_flushvalve_phuket","tz":""},{"id":"1b33bbc4.fa5024","type":"mqtt-broker","z":"","name":"","broker":"m15.cloudmqtt.com","port":"12106","clientid":"","usetls":false,"compatmode":true,"keepalive":"60","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","closeTopic":"","closeQos":"0","closePayload":"","willTopic":"","willQos":"0","willPayload":""}]

Since you are using it in the same flow you should also change it to Flow context not Global. However, since you are using further down the same path on output 1 you should be able to save it in the message. If, instead of saving it to the context, in the setInterval function where you currently do

node.send({"topic" :"SELECT ..."});

instead do

node.send({YourVariable: newMsg, topic:"SELECT ..."});

Then in the second function node instead of picking it up from the context use
var x = msg.YourVariable;
This relies on the nodes between passing on attributes of the message that they are not interested in, such as msg.YourVariable, which they should do.