NodeJS 和 node-serialport 我在编写时遇到了问题

NodeJS and node-serialport i'm having trouble writing

我无法通过 RS232 串行连接向 RFID-reader 发送命令。我可以连接到 reader 并向其写入消息,但我没有收到任何回复。

在 reader 的 documentation 中,我可以找到这个问题的可能解释(第 16 页):

如果协议帧失败,reader 没有回复。

以下信息可用于协议帧格式:

所以这是 0x02 0x00 0x09 0x00 0xB0 0x01 0x00 0xCA 0x86 十六进制的清单(获取范围内的所有标签)命令。

我 100% 确定 reader 工作正常并且串行设置正确,但我不确定我是否以正确的方式使用缓冲区。

这是我目前的代码:

settings.json

{
  "serialport":"COM3",
  "baudrate":38400
}

app.js

var settings = require('./settings');
var serialport= require('serialport');
var SerialPort = serialport.SerialPort;

var inventorycommand = new Buffer([0x02,0x00,0x09,0x00,0xB0,0x01,0x00,0xCA,0x86],'hex');

var serialconnection = new SerialPort(settings.serialport,{baudRate:settings.baudrate,parity:'even',encoding:'hex'},false);

serialconnection.open(portOpened);

function portOpened(err) {
    if(err)console.log('ERR: '+ err);
    console.log('serial port opened: '+ settings.serialport+' with baudrate '+ settings.baudrate);

    setTimeout(function(){
        serialconnection.write(inventorycommand.toString('hex'));
        console.log(inventorycommand.toString('hex'));
    },1000);


    serialconnection.on('data',dataReceived);
    serialconnection.on('close', portClosed);
    serialconnection.on('error',errorReceived);

    function dataReceived(data) {
        console.log('data received: ' +data);
    }

    function portClosed() {
        console.log('port closed.')
    }

    function errorReceived(err) {
        console.log('error: ' + err);
    }
}

似乎在 write() 函数调用中添加回调函数解决了问题。

serialconnection.write(inventorycommand,function(err,result){
            if(err){
                console.log('ERR: ' + err);
            }
            console.log('result:' + result)
        });