nodejs async.series post object

时间:2017-04-26 16:44:02

标签: javascript json node.js

我有一个sensortag和一个覆盆子pi.Raspberry pi从sensortag收集数据并尝试将数据发送到google cloud.I使用nodejs脚本进行收集。这是代码:

var util = require('util');

var async = require('async');
var request = require('request');

var SensorTag = require('./index');
var http = require('http');
var CC2650SensorTag = require('./index').CC2650;

var USE_READ = true;
var date = new Date().getTime();
var json_sensor_value_obj = [];
var json_final_obj;

function Sensor_value(type, value) {
    this.value = value;
    this.type = type;
}
function Sensor_object(sensor_value, date) {
    this.sensor_value = sensor_value;
    this.date = date;
}
function send_data(data) {
    console.log("send func. called");
    request({
        url: "http://fasensor.tk/post_data", method: "POST", headers: { "content-type": "application/json" }, json: true, body: JSON.stringify(data)
    },
    function (error, response, body) {
        console.log("connection");
        console.log(error);
        console.log(response);
    });
}
    
CC2650SensorTag.discover(function (sensorTag) {
  console.log('discovered: ' + sensorTag);

  sensorTag.on('disconnect', function() {
      console.log('disconnected!');
      send_data(json_final_obj);
    process.exit(0);
  });

  async.series([
      function(callback) {
        console.log('connectAndSetUp');
        sensorTag.connectAndSetUp(callback);
      },
      function(callback) {
        console.log('readDeviceName');
        sensorTag.readDeviceName(function(error, deviceName) {
          console.log('\tdevice name = ' + deviceName);
          callback();
        });
      },
      function(callback) {
        console.log('readSystemId');
        sensorTag.readSystemId(function(error, systemId) {
          console.log('\tsystem id = ' + systemId);
          callback();
        });
      },
      function(callback) {
        console.log('readSerialNumber');
        sensorTag.readSerialNumber(function(error, serialNumber) {
          console.log('\tserial number = ' + serialNumber);
          callback();
        });
      },
      function(callback) {
        console.log('readFirmwareRevision');
        sensorTag.readFirmwareRevision(function(error, firmwareRevision) {
          console.log('\tfirmware revision = ' + firmwareRevision);
          callback();
        });
      },
      function(callback) {
        console.log('readHardwareRevision');
        sensorTag.readHardwareRevision(function(error, hardwareRevision) {
          console.log('\thardware revision = ' + hardwareRevision);
          callback();
        });
      },
      function(callback) {
        console.log('readSoftwareRevision');
        sensorTag.readHardwareRevision(function(error, softwareRevision) {
          console.log('\tsoftware revision = ' + softwareRevision);
          callback();
        });
      },
      function(callback) {
        console.log('readManufacturerName');
        sensorTag.readManufacturerName(function(error, manufacturerName) {
          console.log('\tmanufacturer name = ' + manufacturerName);
          callback();
        });
      },
      function(callback) {
        console.log('enableIrTemperature');
        sensorTag.enableIrTemperature(callback);
      },
      function(callback) {
        setTimeout(callback, 2000);
      },
      function(callback) {
        if (USE_READ) {
          console.log('readIrTemperature');
          sensorTag.readIrTemperature(function(error, objectTemperature, ambientTemperature) {
            console.log('\tobject temperature = %d °C', objectTemperature.toFixed(1));
            console.log('\tambient temperature = %d °C', ambientTemperature.toFixed(1));
            var temp_obj = new Sensor_value('Temperature', ambientTemperature.toFixed(1));
            json_sensor_value_obj.push(temp_obj);

            callback();
          });
        } else {
          sensorTag.on('irTemperatureChange', function(objectTemperature, ambientTemperature) {
            console.log('\tobject temperature = %d °C', objectTemperature.toFixed(1));
            console.log('\tambient temperature = %d °C', ambientTemperature.toFixed(1))
          });

          console.log('setIrTemperaturePeriod');
          sensorTag.setIrTemperaturePeriod(500, function(error) {
            console.log('notifyIrTemperature');
            sensorTag.notifyIrTemperature(function(error) {
              setTimeout(function() {
                console.log('unnotifyIrTemperature');
                sensorTag.unnotifyIrTemperature(callback);
              }, 5000);
            });
          });
        }
      },
      function(callback) {
        console.log('disableIrTemperature');
        sensorTag.disableIrTemperature(callback);
      },
      function(callback) {
        console.log('enableHumidity');
        sensorTag.enableHumidity(callback);
      },
      function(callback) {
        setTimeout(callback, 2000);
      },
      function(callback) {
        if (USE_READ) {
          console.log('readHumidity');
          sensorTag.readHumidity(function(error, temperature, humidity) {
            console.log('\ttemperature = %d °C', temperature.toFixed(1));
            console.log('\thumidity = %d %', humidity.toFixed(1));
            var hum_obj = new Sensor_value('Humidity', humidity.toFixed(1));
            json_sensor_value_obj.push(hum_obj);
            callback();
          });
        } else {
          sensorTag.on('humidityChange', function(temperature, humidity) {
            console.log('\ttemperature = %d °C', temperature.toFixed(1));
            console.log('\thumidity = %d %', humidity.toFixed(1));
          });

          console.log('setHumidityPeriod');
          sensorTag.setHumidityPeriod(500, function(error) {
            console.log('notifyHumidity');
            sensorTag.notifyHumidity(function(error) {
              setTimeout(function() {
                console.log('unnotifyHumidity');
                sensorTag.unnotifyHumidity(callback);
              }, 5000);
            });
          });
        }
      },
      function(callback) {
        console.log('disableHumidity');
        sensorTag.disableHumidity(callback);
      },
      function(callback) {
        console.log('enableBarometricPressure');
        sensorTag.enableBarometricPressure(callback);
      },
      function(callback) {
        setTimeout(callback, 2000);
      },
      function(callback) {
        if (USE_READ) {
          console.log('readBarometricPressure');
          sensorTag.readBarometricPressure(function(error, pressure) {
            console.log('\tpressure = %d mBar', pressure.toFixed(1));
            var air_press_obj = new Sensor_value('Air Pressure', pressure.toFixed(1));
            json_sensor_value_obj.push(air_press_obj);
            callback();
          });
        } else {
          sensorTag.on('barometricPressureChange', function(pressure) {
            console.log('\tpressure = %d mBar', pressure.toFixed(1));
          });

          console.log('setBarometricPressurePeriod');
          sensorTag.setBarometricPressurePeriod(500, function(error) {
            console.log('notifyBarometricPressure');
            sensorTag.notifyBarometricPressure(function(error) {
              setTimeout(function() {
                console.log('unnotifyBarometricPressure');
                sensorTag.unnotifyBarometricPressure(callback);
              }, 5000);
            });
          });
        }
      },
      function(callback) {
        console.log('disableBarometricPressure');
        sensorTag.disableBarometricPressure(callback);
      },
      function(callback) {
          if (sensorTag.type === 'cc2650') {
          async.series([
            function(callback) {
              console.log('readIoData');
              sensorTag.readIoData(function(error, value) {
                console.log('\tdata = ' + value);

                 console.log('writeIoData');
                sensorTag.writeIoData(value, callback);
              });
            },
            function(callback) {
              console.log('readIoConfig');
              sensorTag.readIoConfig(function(error, value) {
                console.log('\tconfig = ' + value);

                 console.log('writeIoConfig');
                sensorTag.writeIoConfig(value, callback);
              });
            },
            function(callback) {
              console.log('enableLuxometer');
              sensorTag.enableLuxometer(callback);
            },
            function(callback) {
              setTimeout(callback, 2000);
            },
            function(callback) {
              if (USE_READ) {
                console.log('readLuxometer');
                sensorTag.readLuxometer(function(error, lux) {
                  console.log('\tlux = %d', lux.toFixed(1));

                  callback();
                });
              } else {
                sensorTag.on('luxometerChange', function(lux) {
                  console.log('\tlux = %d', lux.toFixed(1));
                });

                console.log('setLuxometer');
                sensorTag.setLuxometerPeriod(500, function(error) {
                  console.log('notifyLuxometer');
                  sensorTag.notifyLuxometer(function(error) {
                    setTimeout(function() {
                      console.log('unnotifyLuxometer');
                      sensorTag.unnotifyLuxometer(callback);
                    }, 5000);
                  });
                });
              }
            },
            function(callback) {
              console.log('disableLuxometer');
              sensorTag.disableLuxometer(callback);
            },
            function() {
              callback();
            }
          ]);
        } else {
          callback();
        }
      },
      function (callback) {
          console.log('Values are converting to json object...');
          var sensor_obj = new Sensor_object(json_sensor_value_obj, date);
          json_final_obj = JSON.stringify(sensor_obj);
          console.log(json_final_obj);
          console.log('Coverting has finihed.');
        console.log('disconnect');
        sensorTag.disconnect(callback);
      }
    ]
  );
});

重要的部分是异步系列的结束。我已成功收集数据并使其成为json格式然后调用disconnect函数。但是,在disconnect函数中,请求未正确执行,因为没有状态代码输出(仅“发送func。称为”被打印出来)。 我怀疑这个问题来自谷歌云,但我可以在执行时在另一个nodejs脚本中发布一个json对象。我不知道为什么请求在这个实例中无法正常工作。

1 个答案:

答案 0 :(得分:0)

我怀疑它在下面:

sensorTag.on('disconnect', function() {
    console.log('disconnected!');
    send_data(json_final_obj);
    process.exit(0);
});

send_data()调用请求,这是异步的,因此在收到回复之前会调用process.exit(0)。添加回调到send_data()并在我们收到回复后放入process.exit()。以下更改可能会解决此问题:

sensorTag.on('disconnect', function() {
  console.log('disconnected!');
  send_data(json_final_obj, () => process.exit(0));
});

function send_data(data, callback) {
    console.log("send func. called");
    request({
        url: "http://fasensor.tk/post_data", method: "POST", headers: { "content-type": "application/json" }, json: true, body: JSON.stringify(data)
    },
    function (error, response, body) {
        console.log("connection");
        console.log(error);
        console.log(response);
        callback()
    });
}