我已经成功地按照说明创建了一个网页来与串口对话,在这里找到。这里是他的项目的GitHub存储库。我稍微修改了一下,使用Windows COM端口并伪造Arduino数据。现在我正试图进一步修改它,以便与我公司的一个测试委员会进行交流。我已经建立了双向通信,所以我知道我可以通过串行端口在两个方向上交谈。
将id?CRLF
通过串行发送到电路板将得到类似id=91
的响应。我可以在PuTTY中输入id?
&按Enter键,或者在DockLight中创建一个发送序列id?rn
,这两种方法都按预期工作,我得到了id=91
响应。
然而,在client.js JavaScript中,试图在控制台中发送:socket.send("id?rn");
不起作用,但我看到它在服务器响应中显示了额外的一行。所以我看到了这样的内容:
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?u000du000a');
与上面收到的第一条消息相同的结果。
我看到发送的命令到达服务器(我对它进行了一些修改,以便在收到来自客户端的消息时执行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页:
我如何插入新的行/回车回车到一个元素。textcontent ?
JavaScript字符串换行字符?
好吧,事实证明,问题并不完全是像我想的CRLF,它是如何处理字符串结束符。我们所有的设备都使用"S"提示符(s>
)来表示命令已被处理。当它完成时,板做的最后一件事是返回一个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>')
};