node.js node-serialport具有显着的写延迟

时间:2014-03-08 00:08:37

标签: jquery node.js socket.io raspberry-pi node-serialport

我有一个系统,包括一个通过串口连接到树莓派的微处理器。 raspberry pi正在运行带有node-serialport的node.js,以提供基于Web的用户界面。

当我尝试通过Web界面写入串行端口时,在收到微控制器的回复(10秒到几分钟)之前,我经常遇到很长的延迟,这意味着serialport.write会以某种方式延迟。 (我看到没有错误也没有关闭端口..) 在第6次串口写入后,这种情况非常一致。如果我重新加载浏览器,它会再次正常工作,直到第7次请求..

这是在node.js中打开和推送数据到serialport的例程:

var myPort = new SerialPort("/dev/ttyAMA0", { 
  baudrate: 38400,
  parser: serialport.parsers.readline("\n")
});

app.post('/sendtoavr', function(req, res) {
  myPort.write(req.body.cmd);
});

myPort.on('close', function(err) {
  console.log('node-serialport closed!!!');
});

myPort.on('error', function(err) {
  console.log('node-serialport error!!!');
});

这个用于向rpi发送http post请求的jquery例程:

$("#btnSearchTempSensors").click(function() {
  var strCMD = String.fromCharCode(84) + String.fromCharCode(83) + String.fromCharCode(13);
  $.post('/sendtoavr', {cmd: strCMD});
});

在chrome中查看网络控制台时,看起来http post请求会立即发送,当通过ssh通过minicom将命令发送到微控制器时,根本没有问题。

因此我怀疑是node-serialport或node.js,但是如何进一步挖掘?

有人有任何想法吗?

1 个答案:

答案 0 :(得分:0)

找到了一个解决方法..我没有通过http post请求发送命令,而是使用了socket.io/websockets。

的node.js:

socket.on('sendcmd', function(data) {
  myPort.write(data);
});

的index.html:

$("#btnListTempSensors").click(function() {
  var strCMD = String.fromCharCode(84) + String.fromCharCode(76) + String.fromCharCode(13);
  socket.emit('sendcmd', strCMD);
});