我正在尝试编写使用以下方法的 Node.js 脚本serialport https://serialport.io/用于读取和写入数据的 npm 包COM5
串行端口,使用 RS-232 电缆连接到设备。该设备会自动传输其拥有的数据。
要检索设备内部存储的数据,我需要首先发送一个字节 0x80 (uInt8
) 到设备并期望从设备接收 81 作为十六进制数字。其次,我需要发送另一个字节 0x81 (uInt8
),然后期望以行形式接收所有存储的数据(大约 130000 字节)。
无法仅通过两个字节一个接一个地检索整个存储的数据。与设备的通信只能通过字节来完成。
我尝试了以下代码:
import SerialPort from 'serialport';
const sp = new SerialPort.SerialPort({path: "COM5", baudRate: 115200});
const buff = Buffer.allocUnsafe(1);
buff.writeUInt8(0x80, 0);
sp.write(buff, function (err){
if (err){
return console.log("Error on write: ", err.message);
}
console.log("Port.write: ", buff);
});
sp.on('readable', function () {
var arr = new Uint8Array(sp._pool);
console.log('Data:', arr);
});
运行我的脚本时(使用node myScript.mjs
),我看到以下内容:
PortWrite: <Buffer 80>
Data: Uint8Array(65536) [
0, 30, 167, 106, 127, 2, 0, 0, 32, 31, 170, 106,
127, 2, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0,
16, 84, 18, 76, 196, 0, 0, 0, 100, 84, 18, 76,
196, 0, 0, 0, 184, 84, 18, 76, 196, 0, 0, 0,
160, 84, 18, 76, 196, 0, 0, 0, 244, 84, 18, 76,
196, 0, 0, 0, 72, 85, 18, 76, 196, 0, 0, 0,
240, 120, 18, 76, 196, 0, 0, 0, 68, 121, 18, 76,
196, 0, 0, 0, 152, 121, 18, 76, 196, 0, 0, 0,
240, 120, 18, 76,
... 65436 more items
]
程序不会退出,直到我点击Ctrl+c
。我不知道什么ps._pool
确实如此,但输出似乎不正确,但看起来像是随机给出的东西。
我是 Node.js 新手。我也不确定如何添加参数TimeOut
的 10 秒内sp
object.
我尝试使用Matlab进行测试,并且可以成功检索数据。
我也尝试过Python,但对我不起作用 -PySerial 包在写入之前读取串行数据? https://stackoverflow.com/q/73054548/10543310.