在 node.js 中使用串行端口进行异步/等待 [英] async/await using serialport in node.js

查看:63
本文介绍了在 node.js 中使用串行端口进行异步/等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Node.js 处理 PC 和基于 Arduino 的硬件之间的通信.最后一个设备是用 G 代码实现的,所以如果我发送G0",我将收到两行;一个是确认收到指令,第二个是数据.

Working on the communication between PC and an Arduino-based Hardware with Node.js. This last device is implemented with G-Code, so if i send ‘G0’ I will receive two lines; one to confirm that the instruction has been received and a second one with data.

我想使用 async/await 但出现问题...代码如下:

I would like to use async/await but something is wrong... here goes the code:

'use strict'
const SerialPort = require('serialport')
const Readline = SerialPort.parsers.Readline

const cardPort = new SerialPort('COM6', {
    baudRate: 115200,
    parity: 'none',
    stopBits: 1,
    dataBits: 8,
    flowControl: false,
    usePromises: true,
}, function(err) {
    if (err){
        console.log('error: ', err.message)
        port.close()
    } else {

    }
})

const cardParser = new Readline({ delimiter: '\r\n' })

cardPort.pipe(cardParser)

function checkCard(port, parser){
    port.write('G0\n', function () {
        console.log('message written')
        parser.on('data', (data) => { 
            console.log(data)
            return (data)
        })
    })
}

async function run () {
    const id = await checkCard(cardPort,cardParser)
    console.log(`ID response is: ${id}`)
}

run()

这是我得到的回复:

ID response is: undefined
message written
Received: G0
ENCR1PT3R!

为什么 ID 响应不等到 checkCard 执行?

why ID response is not waiting until checkCard is executed?

提前致谢

推荐答案

checkCard 应该返回 Promise 工作,但看起来像 port.write 基于回调.将其包含在 new Promise 中以使其正常工作.

checkCard should return Promise to work, but looks like port.write is callback based. Enclose it in new Promise for it work.

function checkCard(port, parser){
    return new Promise(function(resolve, reject) { 
      port.write('G0\n', function () {
        console.log('message written')
        parser.on('data', (data) => { 
            console.log(data)
            resolve(data)
        })
      })
    });      
}

这篇关于在 node.js 中使用串行端口进行异步/等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆