蓝牙GATT数据在飞行中被破坏

时间:2017-09-03 05:34:40

标签: node.js bluetooth bluetooth-lowenergy gatt

我使用noble来使用我的bleno外围设备。我在onReadRequest()回调中返回的数据缓冲区在到达我的贵宾Characteristic.read()时会以某种方式被破坏。我在onReadRequest()的回调之前转储缓冲区,当我在Characteristic.read()中获取它时立即将其转储:

消费

...
Characteristic.read((err, data) => {
      if (err) {
        reject(err);
      } else {     
        console.log(data);
      }
    });
...

生产者

...
const bleno = require('bleno');

const flags = {
    a: 1 << 0,
    b: 1 << 1,
    c: 1 << 2
  },
  numBytesInReturnData = 18,
  supportedFlags = flags.a | flags.b | flags.c,
  accelPrecision = Math.pow(10, 5),
  bPrecision = Math.pow(10, 3);

module.exports = class DataCharacteristic extends bleno.Characteristic {
  constructor(pin) {
    super({
      uuid: '1234',
      properties: ['read'],
      descriptors: [new bleno.Descriptor({
        uuid: '2901',
        value: 'blah'
      })]
    });
    this._hardware = hardware;
    this._hasData = false;
    this._dataBuffer = new Buffer.allocUnsafe(numBytesInReturnData).fill(0);
  }

  onReadRequest(offset, callback) {
    if (!offset) {
      this._hasData = false;
      this._dataBuffer.fill(0);
      Promise.all([
          this._hardware.getA),
          this._hardware.getB(),
          this._hardware.getC(),
        ]).then((responses) => {
          this._dataBuffer.writeUInt8(supportedFlags, 0);

          this._dataBuffer.writeUInt8(responses[0], 1);
          this._dataBuffer.writeInt32LE(responses[0] * aPrecision, 2, true);
          this._dataBuffer.writeInt32LE(responses[2].x * accelPrecision, 6, true); //accel
          this._dataBuffer.writeInt32LE(responses[2].y * accelPrecision, 10, true);
          this._dataBuffer.writeInt32LE(responses[2].z * accelPrecision, 14, true);

          console.log(this._dataBuffer);

          this._hasData = true;
          callback(this.RESULT_SUCCESS, this._dataBuffer);
        })
        .catch(err => {
          console.error('Error when reading hardware data', err);
          callback(this.RESULT_UNLIKELY_ERROR);
        });
    } else if (this._hasData) { //reading a second time for rest of data
      callback(this.RESULT_SUCCESS, this._dataBuffer.slice(offset));
    } else {
      callback(this.RESULT_ATTR_NOT_LONG);
    }
  }
}
制片人超越

<Buffer 07 00 00 00 00 00 c2 c9 ff ff e4 2c 00 00 1c 47 0f 00>

消费者外包

<Buffer 07 00 00 00 00 00 c2 c9 ff ff 5f 34 00 00 5f 43 0f 00>

正如您所看到的,只有部分缓冲区被破坏。为什么会这样?

1 个答案:

答案 0 :(得分:0)

外围设备通知或指示后,您是否可能立即阅读?如果是这样,可能是传递给您的读回调的数据实际上是来自上次通知或指示的数据。请参阅此问题here