1

I'm using MQTT client for Node.js and I want to publish mqtt data only when data values change.

The actual result I can sent data every second.

const client = mqtt.connect(connectUrl, options);
client.on('connect', () => {
   setInterval(() => {
     const deviceState = getDeviceState(0, 1);
     client.publish('state', deviceState);
   }, 1000);
});
// ...
function getDeviceState(min, max) {
    const randomInt = Math.floor(Math.random() * (max - min + 1) + min);
    if(randomInt === 0) {
        return 'off';
    }
    return 'on';
}
hardillb
  • 54,545
  • 11
  • 67
  • 105
Dev M
  • 1,519
  • 3
  • 29
  • 50
  • [Update](https://stackoverflow.com/posts/75352470/edit) the question with what you've tried to limit the sending to only when the data has changed. – hardillb Feb 05 '23 at 14:10
  • The MQTT client doesn't have any facilities to help you with that, you'll need to implement the on-change logic yourself. I actually wrote a package for exactly this. I haven't yet gotten around to documenting it, but feel free to take a look. You might be able to figure out how to use it from the test cases and the code-documentation: https://github.com/transitiverobotics/transitive-utils/blob/main/common/MqttSync.js – Christian Fritz Feb 05 '23 at 16:49

0 Answers0