1 个回答

造成此问题的可能原因:

1、重复创建createGattClientDevice。

2、没调用获取所有服务getServices()。

3、this指向有问题,建议后续参考demo,改写一下。

示例如下:

writeCharacteristicValue() {
  if (!this.gattServiceInfo) {
    this.characteristicValue = '';
    console.log('BluetoothPage bluetooth gattServiceInfo is undefined ');
    return
  }
  let services: ble.GattService = this.gattServiceInfo;

  let descriptors: Array<ble.BLEDescriptor> = [];
  let descriptor: ble.BLEDescriptor = {
    serviceUuid: services.serviceUuid,
    characteristicUuid: services.characteristics[0].characteristicUuid,
    descriptorUuid: services.characteristics[0].descriptors[0].descriptorUuid,
    descriptorValue: services.characteristics[0].descriptors[0].descriptorValue
  };
  descriptors[0] = descriptor;

  let characteristic: ble.BLECharacteristic = {
    serviceUuid: services.serviceUuid,
    characteristicUuid: services.characteristics[0].characteristicUuid,
    characteristicValue: Utils.string2ArrayBuffer(this.cValue),
    descriptors: descriptors
  };
  try {
    if (this.gattClient) {
      this.gattClient.writeCharacteristicValue(characteristic, ble.GattWriteType.WRITE);
      promptAction.showToast({
        message: '特征值写结束'
      })
      console.log('BluetoothPage writeCharacteristicValue finish');
    }
  } catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
  }
}
logo
HarmonyOS
子站问答
访问
宣传栏