我有一台与串行设备通信的服务器。如果我直接在代码中内联配置串口,它会按预期工作。但是,如果我通过函数传入配置以创建新的串行端口对象,则解析器将不起作用。
有效的代码:
// serial port initialization:
var serialport = require('serialport'), // include the serialport library
SerialPort = serialport.SerialPort, // make a local instance of serial
portName = process.argv[2], // get the port name from the command line
portConfig = {
baudrate : 9600,
databits : 8,
parity : 'none',
stopBits : 1,
buffersize : 4096,
parser : serialport.parsers.readline('\n')
};
console.log(portConfig);
// open the serial port:
var myPort = new SerialPort(portName, portConfig);
console.log(myPort);
不起作用的代码:
function SetSerialPortConfig(data) {
var portBundle = JSON.parse(data);
var serialport = require('serialport'), // include the serialport library
SerialPort = serialport.SerialPort,
portName = portBundle[1].portName,
portConfig = {
baudrate : portBundle[0].baudrate,
databits : portBundle[0].databits,
parity : portBundle[0].parity,
stopBits : portBundle[0].stopBits,
buffersize : portBundle[0].buffersize,
parser : serialport.parsers.readline('\n')
};
return new SerialPort(portName, portConfig);
}
并且传递给函数的数据对象(现在使用我们知道的参数进行硬编码):
function configureSerialPort(){
var portBundle = [{
baudrate: 9600,
databits: 8,
parity: 'none',
stopBits: 1,
buffersize: 4096,
},
{
portName: 'com21'
}];
socket.send(JSON.stringify(portBundle));
}
该端口myPort
是使用来自网站上的按钮的输入配置的,该按钮通过套接字读取:
// this function runs if there's input from the client:
socket.on('message', function (data) {
console.log("Client request received.");
console.log("SerialSend: " + data);
//check to see if the port is configured, if not, run configuration
if (typeof myPort === 'undefined') {
myPort = SetSerialPortConfig(data);
//prevents a write to the port with configuration data.
return false;
}
myPort.write(data); // send the data to the serial device
});
我们需要网页能够传入任何一组配置变量,所以我需要让函数方法起作用。如果我console.log(myPort);
在任何一种情况下都这样做,端口似乎是相同的,所以我看不出解析器为什么不工作。我可以直观地看到数据正在通过 RS-485 转换器上的 LED Tx 和 Rx 灯传输,所以我知道设备上的端口正在发送和接收数据,但解析器没有看到 EOL 字符(我认为),所以它只是在等待。