如何在node.js中使用serialport读取确定数量的行

时间:2018-06-14 14:01:04

标签: node.js serial-port

我有一个与nodejs中的serialport相关的问题。我有一个使用G-CODE协议与PC通信的Arduino,因此每条指令都会收到不同数量的行。

我的问题是,当我收到确定数量的线路时,如何“停止”端口监听?有没有像“port.stop()?”我没有找到任何关于它的信息......

问题是双方已经听到了回应,所以我收到两次回复。这些是我正在使用的方法,首先是类:

class cardDevice {
    constructor (portAddress) {

        //about connection
        this.port = portAddress,
        this.baudRate = 115200,
        this.parity = 'none',
        this.stopBits = 1,
        this.dataBits = 8,
        this.flowControl = false
    }

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

    readSensors(port, parser){
        port.write('G9\n', function () {
            parser.on('data', (data) => {
                console.log(`read got: ${data}`)
                return (data)
            })
        })
    }

    disconnectDevice (port) {
          port.close()
    }
}

这是index.js代码:

'use strict'
const SerialPort = require('serialport')
const COMs = []

// List serial ports
SerialPort.list(function(err, results) {
    if (err) {
        throw err
    }
    for (let index = 0; index < results.length; index++) {
        COMs.push(results[index])

    }
    //console.log(COMs)
})

const Readline = SerialPort.parsers.Readline

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

    }
})

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

cardPort.pipe(cardParser)


function run () {
    const id = card.checkCard(cardPort,cardParser)
    const lecture = card.readSensors(cardPort,cardParser)
}

run()

我在控制台中收到了这个回复:

message written
check got: Received: G0
read got: Received: G0
check got: ENCR1PT3R
read got: ENCR1PT3R
check got: Received: G9
read got: Received: G9
check got: OK
read got: OK

0 个答案:

没有答案