0

我正在使用 node-serialport 与一块硬件进行通信。它只是写一个命令并接收一个响应。

https://serialport.io/docs/en/api-parsers-overview

以下代码有效:

const port = new SerialPort(path);
const parser = port.pipe(new Readline({ delimiter: '\r', encoding: 'ascii' }));

const requestArray = [];

parser.on('data', (data) => {
  // get first item in array
  const request = requestArray[0];

  // remove first item
  requestArray.shift();

  // resolve promise
  request.promise.resolve(data);
});

export const getFirmwareVersion = async () => {
  let resolvePromise;
  let rejectPromise;

  const promise = new Promise((resolve, reject) => {
    resolvePromise = resolve;
    rejectPromise = reject;
  });

  const title = 'getFirmwareVersion';
  const cmd = 'V\r';

  requestArray.push({
    title,
    cmd,
    promise: {
      resolve: resolvePromise,
      reject: rejectPromise
    }
  });

  await v2Port.write(cmd);

  return promise;
};

然后从我的应用程序(用电子/反应编写)我可以调用该函数:

<Button onClick={() => {
  let data = await _api.getFirmwareVersion();
  console.log('done waiting...');
  console.log(data);
}>
  Click Me
</Button>

无论如何我可以重构这段代码以使其更简洁吗?

有没有办法从async函数中获取 Promise,而不必做出新的 Promise?

有没有办法利用已经存在的转换流并以某种方式将 Promise 传递到那里?

我也是 async/await 的新手,想避免使用回调,尤其是在 React/Redux 方面。

I aim to have a lot of these endpoints for the api (i.e. getFirmwareVersion, getTemperature, etc...). So I want to make the code as concise as possible. I don't want the UI to have any underlying knowledge of how the API is getting the data. It just needs to request it like any other API and wait for a response.

4

2 回答 2

2

Oh, I think I get it. The parser is receiving data constantly. So when a request comes, you wait for the next data and send it when it arrives. I suggest you to write an intermediate class.

Like this:

const SerialPort = require('serialport')
const Readline = require('@serialport/parser-readline')
const { EventEmitter } = require('events');

class SerialPortListener extends EventEmitter {
  constructor(path) {
    super();
    this.serialPortPath = path;
  }

  init() {
    this.serialPort = new SerialPort(this.serialPortPath);
    const parser = this.serialPort.pipe(new Readline({ delimiter: '\r', encoding: 'ascii' }));

    parser.on('data', data => this.emit('data', data));
  }
}

Then you could modify the getFirmwareVersion like this:

const serialPortListener = new SerialPortListener(path);

serialPortListener.init();

export const getFirmwareVersion = () => {
  return new Promise((resolve, reject) => {
    serialPortListener.once('data', async (data) => {
      try {
        const cmd = 'V\r';
        await v2Port.write(cmd);
        resolve(data);
      } catch (ex) {
        reject(ex);
      }
    });
  });
};
于 2018-11-12T21:21:17.723 回答
0

Based on help from Mehmet, here is what I ended up with:

const _port = new SerialPort(path);
const _parser = _port.pipe(new Readline({ delimiter: '\r', encoding: 'ascii' }));

const waitForData = async () => {
  return new Promise((resolve, reject) => {
    const timeoutId = setTimeout(() => reject('Write Timeout'), 500);

    _parser.once('data', (data) => {
      clearTimeout(timeoutId);
      resolve(data);
    });
  });
};

const createAPIFunction = (cmdTemplate, validationString) => {
  return async (config) => {
    try {
      // replace {key} in template with config[key] props
      const cmd = cmdTemplate.replace(/{(\w+)}/g, (_, key) => {
        return config[key];
      });

      _port.write(cmd + '\r');

      const data = await waitForData();

      // validate data
      if (data.startsWith(validationString)) {
        // is valid
        return data;
      } else {
        // invalid data
        throw new Error('Invalid Data Returned');
      }
    } catch (err) {
      throw err;
    }
  };
};

export const getFirmwareVersion = createAPIFunction('V', 'V1');
export const enableSampling = createAPIFunction('G1{scope}', 'G11');
于 2018-11-22T16:25:07.913 回答