将 JavaScript 字符串中的 CR LF 发送到 node.js 串口服务器

Send CR LF in JavaScript string to node.js serialport server

我已成功按照说明创建网页以与找到的串口通信 here. And here's the GitHub repository for his project。我稍微修改了它以使用 Windows COM 端口并伪造 Arduino 数据。现在我试图进一步修改它以与我公司的一个测试板交谈。我建立了双向通信,所以我知道我可以通过串口双向通信。

通过串口发送 id?CRLF 到电路板将得到类似于 id=91 的响应。我可以通过在 PuTTY 中输入 id? 并按下 Enter 键来完成此操作,或者在 DockLight 中通过创建发送序列 id?rn 来完成此操作,两者都按预期工作,我得到 id=91回复。

但是,在 client.js JavaScript 中,尝试在控制台中发送:socket.send("id?\r\n"); 不起作用,但我看到它在服务器中显示了一个额外的行回复。所以我看到这样的东西:

Message received
id?
                                                                  <=blank line

所以我尝试通过以下方式发送 ASCII 等价物:

var id = String.fromCharCode(10,13);
socket.send("id?" + id);

尽管服务器中显示了两条额外的行,但这也不起作用。

Message received
id?
                                                                  <=blank line
                                                                  <=another blank line

编辑:我也尝试过:socket.send('id?\u000d\u000a'); 与上面收到的第一条消息的结果相同。

我看到发送的命令到达了服务器(我对其进行了一些修改,以便在收到来自客户端的消息后执行 console.log):

function openSocket(socket){
console.log('new user address: ' + socket.handshake.address);
// send something to the web client with the data:
socket.emit('message', 'Hello, ' + socket.handshake.address);

// this function runs if there's input from the client:
socket.on('message', function(data) {
    console.log("Message received");
    console.log(data);
    //here's where the CRLF should get sent along with the id? command
    myPort.write(data);// send the data to the serial device
});

// this function runs if there's input from the serialport:
myPort.on('data', function(data) {
    //here's where I'm hoping to see the response from the board
    console.log('message', data);  
    socket.emit('message', data);       // send the data to the client
});
}

我不肯定 CRLF 是问题所在,但我很确定它是。可能它被服务器吞没了?

如何将它嵌入要发送到服务器的字符串中,以便正确解释并发送到串行端口?

我读过的其他 SO 页面:

How can I insert new line/carriage returns into an element.textContent?

JavaScript string newline character?

好吧,事实证明问题并不完全像我想的那样是 CRLF,而是字符串终止符的处理方式。当命令被处理时,我们所有的设备都使用我们可以使用的 "S prompt" (s>)。当它完成后,董事会做的最后一件事是 return S 提示,所以我修改了原始服务器解析器代码来寻找它。但是,这是响应终止符,而不是请求终止符。一旦我把它改回 parser: serialport.parsers.readline('\n') 它就开始工作了。

// 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,
    // call myPort.on('data') when a newline is received:
    parser: serialport.parsers.readline('\n')
    //changed from '\n' to 's>' and works.
    //parser: serialport.parsers.readline('s>')
};