簡體   English   中英

Node.js Serialport 同步讀寫

[英]Node.js Serialport synchronous write-read

有沒有人有任何示例代碼以阻塞/同步方式使用 node.js 串行端口模塊?

我想要做的是將命令發送到微控制器並在發送下一個命令之前等待響應。

我有發送/接收的工作,但數據只是隨着監聽器進來

serial.on( "data", function( data) {
        console.log(data);
    }); 

有沒有辦法在做一個之后等待返回的數據

serial.write("Send Command");

我應該設置一個全局標志還是什么?

我對 node.js 的異步編程風格仍然很陌生

謝謝

沒有這樣的選擇,實際上沒有必要。 這樣做的一種方法是維護命令隊列。 像這樣的東西:

function Device (serial) {
    this._serial = serial;
    this._queue = queue;
    this._busy = false;
    this._current = null;
    var device = this;
    serial.on('data', function (data) {
        if (!device._current) return;
        device._current[1](null, data);
        device.processQueue();
    });
}

Device.prototype.send = function (data, callback) {
    this._queue.push([data, callback]);
    if (this._busy) return;
    this._busy = true;
    this.processQueue();
};

Device.prototype.processQueue = function () {
    var next = this._queue.shift();

    if (!next) {
        this._busy = false;
        return;
    }

    this._current = next;
    this._serial.write(next[0]);
};

現在可以使用 npm 中的串行端口同步庫來完成。

考慮以下串行端口流:

1. << READY
2. >> getTemp
3. << Received: getTemp
4. << Temp: 23.11

我們可以通過以下代碼獲取溫度值:

import { SerialPortController } from 'serialport-synchronous'

const TEMP_REGEX = /^Temp: (\d+\.\d+)$/
const ERROR_REGEX = /^ERROR$/
const READY_REGEX = /^READY$/

const controller = new SerialPortController({
  path: '/dev/ttyUSB0',
  baudRate: 19200,
  handlers: [{
    pattern: READY_REGEX,
    callback: main // call the main() function when READY_REGEX has matched.
  }]
})

// push the log events from the library to the console
controller.on('log', (log) => console[log.level.toLowerCase()](`${log.datetime.toISOString()} [${log.level.toUpperCase()}] ${log.message}`))

// open the serial port connection
controller.open()

async function main () {
  try {
    // send the getTemp text to the serialport
    const result = await controller.execute({
      description: 'Querying current temperature', // optional, used for logging purposes
      text: 'getTemp',                             // mandatory, the text to send
      successRegex: TEMP_REGEX,                    // mandatory, the regex required to resolve the promise
      bufferRegex: TEMP_REGEX,                     // optional, the regex match required to buffer the response
      errorRegex: ERROR_REGEX,                     // optional, the regex match required to reject the promise
      timeoutMs: 1000                              // mandatory, the maximum time to wait before rejecting the promise
    })
    
    // parse the response to extract the temp value
    const temp = result.match(TEMP_REGEX)[1]
    console.log(`\nThe temperature reading was ${temp}c`)
  } catch (error) {
    console.error('Error occured querying temperature')
    console.error(error)
  }
}

輸出看起來像這樣:

2022-07-20T01:33:56.855Z [INFO] Connection to serial port '/dev/ttyUSB0' has been opened
2022-07-20T01:33:58.391Z [INFO] << READY
2022-07-20T01:33:58.392Z [INFO] Inbound message matched unsolicited handler pattern: /^READY$/. Calling custom handler function
2022-07-20T01:33:58.396Z [INFO] Querying current temperature
2022-07-20T01:33:58.397Z [INFO] >> [TEXT] getTemp
2022-07-20T01:33:58.415Z [INFO] << Received: getTemp
2022-07-20T01:33:58.423Z [INFO] << Temp: 23.11
2022-07-20T01:33:58.423Z [DEBUG] Received expected response, calling resolve handler

The temperature reading was 23.11c

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM