我正在使用 serialport2用于从 arduino 接收串行数据的 node.js 库。这就像一个魅力,但有时 pc 运行 Node ,由于 EMI 决定停用 USB 端口。 .尽管端口会立即再次激活,但 Serialport 会断开连接。 Node.js 保持运行但永远不会恢复到 arduino 的串行连接。
使用串行端口的“关闭”事件,我希望 Node 在短暂延迟后重新连接到串行端口。到目前为止,这工作正常:
var SerialPort = require('serialport2').SerialPort;
var arduinoPort = '/dev/arduino';
// setting up the serial connection
var arduinoSerial = new SerialPort();
var connectArd = function() {
arduinoSerial.open(arduinoPort, {
baudRate: 9600,
dataBits: 8,
parity: 'none',
stopBits: 1,
flowControl: false
});
}
connectArd();
// do something with incoming data
arduinoSerial.on('data', function (data) {
.
.
.
});
// check for connection errors or drops and reconnect
var reconnectArd = function () {
console.log('INITIATING RECONNECT');
setTimeout(function(){
console.log('RECONNECTING TO ARDUINO');
connectArd();
}, 2000);
};
arduinoSerial.on('close', function(){
console.log('ARDUINO PORT CLOSED');
reconnectArd();
});
arduinoSerial.on('error', function (err) {
console.error("error", err);
reconnectArd();
});
一旦出现 EMI 或 USB 电缆断开连接,“arduinoSerial”的“关闭”监听器就会启动,等待大约 2 秒并重新连接到 arduino。连接恢复, Node 再次从 arduino 接收数据。
但是...这只有效一次!?当第二次断开连接时, Node 停止接收数据,但由于某种原因,这次“关闭”事件没有被触发。我必须重新启动 Node 应用程序才能再次重新连接到 arduino。
我是 javascript 的新手,所以这很可能是菜鸟犯的错误。我究竟做错了什么?有人可以指出我正确的方向吗?
(我知道我应该开始寻找干扰源,但出于设备的可用性/处理原因,这种自动重新连接功能也会派上用场。)
谢谢
最佳答案
这些旧帖子出现在我的 Google 搜索中对我来说仍然很疯狂,但我想我最好在这里为其他时间旅行者发布一个答案。
已接受答案的问题是您可能会超过 Node 设置的最大事件监听器,因为您每次都在重新定义它们。您可以简单地使用最新版本的 Node SerialPort 7.x.x 调用 open() 方法。这是我已经测试和确认的一些示例代码。我怀疑 this.connected 是否必要,因为 SerialPort 上可能有访问方法,但我只是用它来进行故障排除。我也将此类用作父类(super class),因此其中还有一些其他逻辑用于处理不同类型的解析器,因此您也可以忽略它。
connect() {
return new Promise((resolve) => {
this.serialPort = new SerialPort(this.port, { baudRate: this.baudRate, autoOpen: false });
this.parser = this.serialPort.pipe(this.parser);
this.serialPort.on('open', () => {
this.connected = true;
});
this.serialPort.on('close', () => {
this.connected = false;
setTimeout(this.reconnect.bind(this), 5000);
});
this.serialPort.on('error', () => {
setTimeout(this.reconnect.bind(this), 5000);
});
this.serialPort.open();
resolve(this.parser);
});
}
reconnect() {
if (!this.connected) { this.serialPort.open(); }
}
关于javascript - node.js 串口事件在重新连接到端口后停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18551293/