2014-05-15 163 views
4

有没有人有任何示例代码以阻塞/同步方式使用node.js serialport模块?Node.js Serialport同步写入读取

我想要做的是发送一个命令给微控制器,并在发送下一个命令之前等待响应。

我已经发送/接收工作,但数据只是听者

serial.on("data", function(data) { 
     console.log(data); 
    }); 

进来有没有办法做一个

serial.write("Send Command"); 

我应该后等待返回的数据设置一个全球标志或什么?

我还是新的Node.js的异步编程风格

感谢

回答

3

有没有这样的选择,它实际上是没有必要的。这样做的一种方法是维护一个命令队列。像这样:

function Device (serial) { 
    this._serial = serial; 
    this._queue = queue; 
    this._busy = false; 
    this._current = null; 
    var device = this; 
    serial.on('data', function (data) { 
     if (!device._current) return; 
     device._current[1](null, data); 
     device.processQueue(); 
    }); 
} 

Device.prototype.send = function (data, callback) { 
    this._queue.push([data, callback]); 
    if (this._busy) return; 
    this._busy = true; 
    this.processQueue(); 
}; 

Device.prototype.processQueue = function() { 
    var next = this._queue.shift(); 

    if (!next) { 
     this._busy = false; 
     return; 
    } 

    this._current = next; 
    this._serial.write(next[0]); 
};