ismsm
ismsm

Reputation: 173

How to generate a random values periodically and publish it using MQTT protocol?

I want to repletely generate different random values for every 1 second and publish it to MQTT protocol. The code is working but it is keep sending the last value how to make it that it will send a different value every 1 second?

var mqtt = require('mqtt')

var Broker_URL = 'mqtt://localhost';
var client  = mqtt.connect(Broker_URL);

var MIN_PER_RANK =75
var MAX_PER_RANK =100

client.on('connect', function () {
    console.log("MQTT connected  "+ client.connected);
})

class virtualsensor {
    
    sendStateUpdate (newdata) {
        client.publish("testtopic", newdata)
    }
}

let vs = new virtualsensor()

let newdata = '';

for (var i=0; i<5; i++){
    newdata= String(Math.floor(Math.random() * (MAX_PER_RANK - MIN_PER_RANK  + 1) + MIN_PER_RANK));
    vs.sendStateUpdate(newdata)
}

var interval = setInterval(function(){vs.sendStateUpdate(newdata)},1000);

the output:

testtopic 81
testtopic 76
testtopic 89
testtopic 100
testtopic 96
testtopic 96
testtopic 96
testtopic 96
testtopic 96
testtopic 96
testtopic 96
testtopic 96
testtopic 96

Thanks in advance.

Upvotes: 0

Views: 739

Answers (1)

hardillb
hardillb

Reputation: 59628

The for loop only generates 5 values, then the setInterval() just reuses the last value from that loop again.

The for loop isn't really doing anything useful here, it will publish the 5 "random" values in under a second (Which is not what you asked for) then the setInterval() just repeats the sending the last value over and over.

Remove the for loop and move the random value generator to the function passed to setInterval()

var interval = setInterval(function(){
  newdata= String(Math.floor(Math.random() * (MAX_PER_RANK - MIN_PER_RANK  + 1) + MIN_PER_RANK));
  vs.sendStateUpdate(newdata)
},1000);

Upvotes: 1

Related Questions