首页 > 解决方案 > 如何使用 NodeJS 从串行设备流式传输不完整的数据 csv 数据?

问题描述

我有一个简单的 Arduino 草图,看起来像这样(请暂时忽略阻塞延迟)......

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
}

void loop() {
    Serial.println("Hello world from Ardunio!\n");
    delay(5000);
}

这很好用,所以我创建了一个节点库来与串口通信......

import SerialPort from 'serialport';
import parse from 'csv-parse';

const output=[];
const parser = parse({
  to_line: 10
});

const port = new SerialPort('/dev/ttyACM0', {
  baudRate: 115200
});

port.on('readable', function () {
  let record
  while (record = port.read()) {
    output.push(record.toString());
    console.log(`The collection is \n ${JSON.stringify(output)}`);
  }
})
port.on('error', function(err) {
  console.log('Error: ', err.message);
});
port.on('close', function(){
  console.log('The port is closed');
});
port.on('open', err =>{
  console.log("The port is opened");
});

我的期望是这将读取 10 行并停止。但是,当它运行时,我会看到这样的记录...

The collection is 
 ["d from Ardunio!\n\r\n"]
The collection is 
 ["d from Ardunio!\n\r\n","Hello world from Ardu"]
The collection is 
 ["d from Ardunio!\n\r\n","Hello world from Ardu","nio!\n\r\n"]

这当然是不对的,因为缓冲区一次只读取每条记录的片段。处理这些记录并将字符串组合到新行(如果多列则为逗号)的最佳方法是什么(库或滚动我自己的)?

标签: node.jsarduinoraspberry-piserial-portstreaming

解决方案


推荐阅读