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

时间:2016-06-29 21:44:30

标签: javascript node.js node-serialport

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

id?CRLF串行发送到电路板会得到类似id=91的响应。我只需输入id?&amp ;,就可以在PuTTY中执行此操作点击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?

1 个答案:

答案 0 :(得分:0)

嗯,事实证明问题并不像我想的那样完全是CRLF,而是字符串终止符的处理方式。我们所有的设备都使用我们可以提供的&#34; S提示&#34; (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>')
};