My scenario is that a node chooses a random number as a counter, then starts to auto-decrement the counter (I did this step). When the counter reaches to zero, then the node processes data for 1 minute only. After 1 minute of processing, the node will choose again a random number and auto-decrement it, then process the data for 1 minute. The node must do that repeatedly.
I have tried this:
var mqtt = require('mqtt')
var Broker_URL = 'mqtt://localhost';
var client = mqtt.connect(Broker_URL);
client.on('connect', function () {
console.log("MQTT connected "+ client.connected);
client.subscribe('DAG1');
})
var MIN_PER_RANK =3;
var MAX_PER_RANK =5;
function animateValue(start, end) {
if (start === end) return;
var current = start;
var increment = end > start? 1 : -1;
var timer = setInterval(function() {
current += increment;
if (current == end) {
clearInterval(timer);
}
console.log (current);
if (current === 0){
console.log("finish counter")
console.log("process data for 1 minute")
client.on('message', function (topic, message) {
processdata(topic, message)
})
}
}, 1000);
}
var randomvalue = Math.floor(Math.random() * (MAX_PER_RANK - MIN_PER_RANK + 1) + MIN_PER_RANK);
animateValue(randomvalue, 0);
var start = true;
setInterval(function(){
if(start){
start = false;
} else {
start = true;
console.log("start counter")
var randomvalue = Math.floor(Math.random() * (MAX_PER_RANK - MIN_PER_RANK + 1) + MIN_PER_RANK);
animateValue(randomvalue, 0);
}
}, 60000); //1 minute
function processdata(top, param) {
if (start){
console.log(param.toString())
}
}
The code is running in this way: The node chooses a random number as a counter, starts to auto-decrement the counter. When node reaches to zero, it processes the data for 1 minute. Then, the node will sleep for another 1 minute. After that, the node will wake up and start the process again. How to make the node starts a counter right away after 1 minute of process instead of getting to sleep? How I could solve it? Thanks in adavance
the output:
MQTT connected true
4
3
2
1
0
finish counter
process data for 1 minute
{"sensorvalue":"91","timestamp":1611236199874,"topicsensor":"sensor1","dataID":"0a9e9f87-51b4-4a37-91d5-773de6869491"}
{"sensorvalue":"99","timestamp":1611236214889,"topicsensor":"sensor1","dataID":"109bbf17-78b8-4357-90ac-ca23f760a4eb"}
start counter
3
2
1
0
finish counter
process data for 1 minute
{"sensorvalue":"80","timestamp":1611236219894,"topicsensor":"sensor1","dataID":"71398516-3757-4a0b-ad61-20e9a17891cc"}
{"sensorvalue":"80","timestamp":1611236219894,"topicsensor":"sensor1","dataID":"71398516-3757-4a0b-ad61-20e9a17891cc"}