在流星中包装异步NPM

时间:2014-07-21 16:00:03

标签: meteor npm

我正在使用meteor-npm在我的Meteor应用程序中使用NPM。我已经成功添加了serialport和xbee-api。我可以使用console.log读取xbee帧,但我无法将帧传递给Meteor方法。下面的代码给出了一个关于NPM函数和使用bindEnvironment的错误。我确信它与Meteor运行同步vs xbee-api运行异步有关。我对Meteor非常熟悉,但不能与NPM一起使用。我相信答案可能在https://github.com/arunoda/meteor-npm。我真的不需要回调,因为我只想将帧数据传递给方法,我将从那里处理它。任何人都可以为我阐明这一点吗?提前谢谢。

// Load serialport and xbee-api
var serialport = Meteor.require('serialport');
var SerialPort = serialport.SerialPort;

var xbee_api = Meteor.require('xbee-api');

// Load constants to help with remembering hex codes for xbees
var C = xbee_api.constants;

// Create xbee
var xbee = new xbee_api.XBeeAPI({
    api_mode: 2
});

// Create serial port
var serialPort = new SerialPort('/dev/tty.usbserial-A901L66E', {
    baudrate: 9600,
    // Provided with xbee-api. Could use com.parsers.raw and feed that to xbee-api
    parser: xbee.rawParser()
});

// Setup action to take when serial port is connected
serialPort.on('open',function() {
  console.log('Port open');
});

// Setup action to take when xbee packet is received
// frame_object is emitted by the xbee.rawParser every time a complete xbee packets is    received
xbee.on('frame_object', function(frame) {
    //Send frame to Meteor method
    Meteor.call('xbeeIncoming', frame);
    //console.log('>>',frame);
});

流星方法定义:

Meteor.methods({
    xbeeIncoming: function xbeeIncoming(frame) {
        console.log('xbeeData');
        //var xbeeSenderAddr = frame.addr
    }
});

1 个答案:

答案 0 :(得分:0)

为什么使用方法执行此操作。如果它们都在服务器端,则可以使用私有方法,即

xbeeIncoming = function(frame) {
    console.log('xbeeData');
}

而不是Meteor.call('xbeeIncoming', frame);您可以使用xbeeIncoming(frame);

您需要在bindEnvironment中包装来自xbee的回调(提供它可以序列化为JSON / EJSON):

var onFrame = function(frame ) {
    Meteor.call('xbeeIncoming', frame);
    //console.log('>>',frame);
}

xbee.on('frame_object', Meteor.bindEnvironment(onFrame));

在此范围内,Meteor.call应按预期工作