node.js - 为什么 Node SerialPort Readline 解析器不工作?

标签 node.js arduino serial-port node-serialport

我有一个 Arduino 发送非常基本的消息:

Serial.print('R');
Serial.println(1);

Serial.print('R');
Serial.println(2);

我尝试使用 node.js 和 SerialPort 模块读取每一行,但得到的结果不一致:

Data: <Buffer 52 31 0d 0a> R1

Data: <Buffer 52 32 0d 0a> R2

Data: <Buffer 52 31 0d 0a> R1

Data: <Buffer 52 32 0d 0a> R2

Data: <Buffer 52 31 0d 0a> R1

Data: <Buffer 52 32 0d 0a> R2

Data: <Buffer 52 31 0d 0a> R1

Data: <Buffer 52 32 0d 0a> R2

Data: <Buffer 52> R
Data: <Buffer 31 0d 0a> 1

Data: <Buffer 52 32 0d 0a> R2

这是我尝试解析的方法:

this.port = new SerialPort(portName, {
            baudRate: baudRate,
            autoOpen:false,
            flowControl: false,
            parser: new Readline("\r\n")
        });

        this.port.open(function (err) {
            if (err) {
                return console.log('Error opening port: ', err.message);
            }

            console.log("port open!");

        });

        this.port.on('error', function(err) {
            console.log('Error: ', err.message);
        })

        this.port.on('open', function() {
            console.log("open event called");
        });

        this.port.on('data', function (data) {
            console.log('Data:', data,data.toString('utf8'));
        });

简而言之:我期待 R1R2 消息一致传入,而不是像这样分开:

Data: <Buffer 52> R
Data: <Buffer 31 0d 0a> 1

我将 ("\r\n"/0x0d 0x0a) 传递给 Readline。我缺少什么? 如何在 Node 中使用 SerialPort 获得一致的新行解析?

最佳答案

我认为解决您的问题需要在 parser 对象上绑定(bind)一个事件,而您当前正在 port 对象上监听该事件。通过端口到达的数据并不总是以 0x0d 0x0a (*) 终止。这两个字节是仅用于 ReadLine 解析器的字符串终止符信号。

因此,也许您应该在代码中编写此监听器:

// I'm not actually sure where parser lives, I'm not
// in the condition of trying by myself...
this.port.parser.on('data', function (data) {
  console.log('Data:', data,data.toString('utf8'));
});

不幸的是,我没有任何建议使语法更加优雅,并且对于我的标准来说,这个解决方案比创建一个为您重定向绑定(bind)的函数更优雅。但这取决于您的应用程序,目前我没有足够的信息来建议可能更好的解决方案。

(*) 在我立即删除的第一个(错误)评论中,我问为什么你将两个字节作为行 0x0d 0x0a (\r\n) 的终止符,而不是简单地 0x0a (\n)Serial.println方法实际上默认写入两个字节。

关于node.js - 为什么 Node SerialPort Readline 解析器不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50104668/

相关文章:

node.js - yarn.lock 和 npm 的 package-lock 有什么区别?

javascript - Node.js 服务请求安全网站

qt - QSerialPortInfo : Finding the USB hardware location of a virtual serial Port

serial-port - 如何通过串口传输二进制文件?

c# - 在 .NET Core 1.1 中使用 System.IO.Ports.SerialPort

node.js - 为什么node.js服务器上的日期函数输出错误?

javascript - 为什么 Jest 会给出 ReferenceError?

c++ - 在 avr g++ 中禁用函数声明错误

java - 通过 USB 从 Java 程序读取时,Arduino 出现 Serial.readbytes() 问题

C:小端