Node / Javascript仅发送更改的值

时间:2015-08-05 13:16:57

标签: javascript node.js

我正在编写一个简单的应用程序,我将值发送到由mqtt broker(可变电阻)给出的pot-meter。我想要完成的是我只发送更改的值以节省带宽。我正在尝试Object.observe,但这没有做任何事情。有人能帮助我吗?

我的代码:

var analogValue = 0;

every((0.5).second(), function() {
    analogValue = my.sensor.analogRead();
    var values = {values:[{key:'resistance', value: analogValue}]}

    //another experiment here
    var arr = ['resitance', analogValue];
    Array.observe(arr, function(changes) {
      console.log(changes);
    });
    arr[1] = analogValue

    console.log('sent ',values,'to ',thingTopic)
    client.publish(thingTopic,  JSON.stringify(values));
});

var o = [analogValue];
Object.observe(o, function (changes) {
  console.log(changes);
  //eventually publish only changes to broker here
})
o.name = [analogValue]

1 个答案:

答案 0 :(得分:1)

您无需使用Object.observe。您可以保存最后一个测量并检查新测量。像这样:

// I'm assuming that any actual measurement will be different than 0
var lastMeasurement = 0;

every((0.5).second(), function() {
    var analogValue = my.sensor.analogRead();
    if (lastMeasurement !== analogValue) {
        // the new value is different
        var values = {values:[{key:'resistance', value: analogValue}]};
        client.publish(thingTopic,  JSON.stringify(values));

        // update the last measurement value
        lastMeasurement = analogValue;
    }
});