Nodejs映射串口写入接收数据 [英] Nodejs map serial port write to receive data
问题描述
我目前正在使用 node-serialport
模块进行串口通信.我将发送一个命令 ATEC
,它会以 ECHO
响应.
I am currently using node-serialport
module for serial port communication. I will send a command ATEC
and it will respond with ECHO
.
但是,这个发送和接收数据的过程是异步的(发送数据后,在data
事件中不知道数据什么时候到达),示例代码如下:
However, this process of sending and receiving data is async(after i send the data, i will not know when the data will arrive in the data
event), the example code is below:
//Register the data event from the serial port
port.on('data', (data) => {
console.log(data);
});
//Send data using serialport
port.write('ATEC');
无论如何我可以这样写吗?
Is there anyway I could write it in this way?
//When i send the command, I could receive the data
port.write('ATEC').then((data)=> {
console.log(data);
});
这有可能实现吗?
在使用 request
客户端的 http 通信中,我们可以做一些类似
In http communication using request
client, we could do something like
request.get('http:\\google.com')
.on('response', (res) => {
console.log(res);
});
我想使用 serialport
推荐答案
I wrap a promise in the serial data receive
I wrap a promise in the serial data receive
function sendSync(port, src) {
return new Promise((resolve, reject) => {
port.write(src);
port.once('data', (data) => {
resolve(data.toString());
});
port.once('error', (err) => {
reject(err);
});
});
}
请注意,事件使用 once
而不是 on
来防止事件堆叠(请查看下面的评论以获取更多信息 - 感谢 @DKebler 发现它)
Please take note, the event is using once
instead of on
to prevent event from stacking (please check the comments below for more information - thanks @DKebler for spotting it)
然后,我可以同步编写如下代码
Then, I could write the code in sync as below
sendSync(port, 'AThello\n').then((data) => {
//receive data
});
sendSync(port, 'ATecho\n').then((data) => {
//receive data
});
或者我可以使用生成器,使用 co
包
or I could use a generator, using co
package
co(function* () {
const echo = yield sendSync(port, 'echo\n');
const hello = yield sendSync(port, 'hello 123\n');
return [echo, hello]
}).then((result) => {
console.log(result)
}).catch((err) => {
console.error(err);
})
这篇关于Nodejs映射串口写入接收数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!