HarmonyOS 鸿蒙Next 蓝牙读写各种报错

HarmonyOS 鸿蒙Next 蓝牙读写各种报错

蓝牙读写各种报错,且发送信息后 未收到蓝牙设备回复信息, 代码如下

import ble from '@ohos.bluetooth.ble';
import { BusinessError } from '@ohos.base';
import constants from '../constants/LST_BLEConstants'
import { JSON } from '@kit.ArkTS';
import { LST_Hex } from '../utils/LST_Hex';
import { packWechatInit1, packWechatInit2 } from './LST_WechatProtocol'
import { LST_BLESDK } from './LST_BLESDK';

export class LST_BLEClient {
  public connectState: string = 'STATE_DISCONNECTING'
  public serverDeviceId: string
  private mGattClientDevice: ble.GattClientDevice
  private buffer: string = ''
  private dataLength: number = 0
  private headerReceived = false
  private readData: string = new Uint8Array();

  constructor(serverDeviceId: string, stateChangeCallback: Function) {
    this.serverDeviceId = serverDeviceId;
    this.mGattClientDevice = ble.createGattClientDevice(serverDeviceId);
    this.connect(stateChangeCallback)
  }

  connect(stateChangeCallback: Function) { // 订阅连接状态改变事件 
    this.mGattClientDevice.on('BLEConnectionStateChange', (bleConnectionState) => {
      switch (bleConnectionState.state) {
        case 0:
          this.connectState = 'DISCONNECTED';
          break;
        case 1:
          this.connectState = 'CONNECTING';
          break;
        case 2:
          this.connectState = 'STATE_CONNECTED';
          this.findServer();
          break;
        case 3:
          this.connectState = 'STATE_DISCONNECTING';
          break;
        default:
          this.connectState = 'undefined'; break;
      }
      stateChangeCallback(this.connectState)
      console.info('GattClient BLEConnectionStateChange: ' + this.connectState);
    }) // 连接GattServer服务
    this.mGattClientDevice.connect()
  }

  findServer() { // 获取server的services信息
    this.mGattClientDevice.getServices()
      .then((result: Array<ble.GattService>) => { // 设置最大传输单元,示例为256
        this.mGattClientDevice.setBLEMtuSize(256)
        for (let i = 0; i < result.length; i++) {
          if (result[i].isPrimary && result[i].serviceUuid === constants.weChatServiceUuid) {
            for (let j = 0; j < result[i].characteristics.length; j++) {
              let mBLECharacteristic: ble.BLECharacteristic = result[i].characteristics[j]
              console.log('mBLECharacteristic.characteristicUuid=', mBLECharacteristic.characteristicUuid)
              if (mBLECharacteristic.characteristicUuid === constants.weChatResponseCharacteristicUuid) {
                this.mGattClientDevice.setCharacteristicChangeNotification(mBLECharacteristic, true).then(() => {
                  console.log('onEvent')
                  this.onEvent();
                })
              }
            }
          }
        }
      })
  }

  onEvent() {
    this.mGattClientDevice.on('BLECharacteristicChange', (characteristicChangeReq: ble.BLECharacteristic) => {
      let hex = LST_Hex.arrayBufferToHex(characteristicChangeReq.characteristicValue)
      console.info('GattClient BLECharacteristicChange value: ' + hex)
      if (!hex || hex.length ==
        0) { // 没有数据或数据长度为0,可以选择忽略或处理
        return;
      } // 将新数据追加到缓冲区
      this.buffer += hex; // 检查是否收到包头
      if (!this.headerReceived && this.buffer.length >= 4) {
        let data =
          LST_Hex.hexStringToUint8Array(this.buffer) // 假设长度是2个字节,存储在数据的第3和第4个字节
        this.dataLength = (data[3] | (data[2] << 8))
        this.readData = ''
        this.headerReceived = true;
      }
      console.log('this.buffer.length' + this.buffer.length / 2 + 'this.dataLength' +
      this.dataLength) // 检查是否收到了完整的数据帧
      if (this.headerReceived && this.buffer.length / 2 >= this.dataLength) {
        this.readData = this.buffer
        this.buffer = '' // 你可以在这里处理frame,或者将其传递给其他方法 // 重置缓冲区和数据长度
        this.dataLength = 0;
        this.headerReceived = false;
        this.readEnd()
      }
      console.info('strList: ' + hexList.toString())
    })
  }

  readEnd() {
    let flag_wechat = this.readData.substring(8, 12);
    console.log('this.readData=' + this.readData + 'flag_wechat=', flag_wechat)
    if (flag_wechat ===
      '2711') //微信协议初始化1
    {
      this.write(packWechatInit1(this.readData))
    } else if (flag_wechat ===
      '2713') //微信协议初始化2
    {
      this.write(packWechatInit2())
    }
  }

  async write(hexStringArr: Array<string>) {
    for (let i = 0; i < hexStringArr.length; i++) {
      let hexString: string = hexStringArr[i];
      console.log('write now' + hexString)
      let buffer = LST_Hex.hexStringToArrayBuffer(hexString)
      let wBLECharacteristic: ble.BLECharacteristic = {
        serviceUuid: constants.weChatServiceUuid,
        characteristicUuid: constants.weChatResponseCharacteristicUuid,
        characteristicValue: buffer,
        descriptors: []
      }
      this.mGattClientDevice.writeCharacteristicValue(wBLECharacteristic, ble.GattWriteType.WRITE).then(() => {
        console.log('write success')
      })
      await this.mGattClientDevice.writeDescriptorValue(wBLECharacteristic[0].descriptors)
    }
  } //取消订阅蓝牙低功耗设备的特征值变化事件。

  offEvent() {
    this.mGattClientDevice.off('BLECharacteristicChange');
  }

  disconnect() { // 断开连接
    this.mGattClientDevice.disconnect();
    console.info('GattClient disconnect success')
  }

  close() {
    try {
      this.offEvent();
      this.disconnect(); // 关闭GattClient实例 
      this.mGattClientDevice.close();
      console.info('GattClient close gattClientDevice success');
    } catch (err) {
      console.error(`GattClient close error ${err.code} ${err.message}`);
    }
  }
}

更多关于HarmonyOS 鸿蒙Next 蓝牙读写各种报错的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复
看代码 蓝牙侧写数据成功没有问题,有明显的成功回调

未收到未收到蓝牙设备回复信息:可以从两方面排查:1:排查开通知参数 setCharacteristicChangeNotification()相关入参是否正确 2:确认写过去的数据是否准备是否是是对端想要的数据

你目前是已经写成功了的,根据日志是能看到的。也要确认一下 写过去的数据是否准备是否是是对端想要的数据

更多关于HarmonyOS 鸿蒙Next 蓝牙读写各种报错的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


HarmonyOS 鸿蒙Next在蓝牙读写过程中遇到的各种报错,通常与权限配置、蓝牙状态管理、设备兼容性以及API使用不当等因素有关。

  1. 权限配置:确保你的应用已在config.json中声明了蓝牙相关的权限,如ohos.permission.BLUETOOTHohos.permission.BLUETOOTH_ADMIN。同时,针对需要精确位置信息的蓝牙操作,还需声明ohos.permission.LOCATION

  2. 蓝牙状态管理:在读写蓝牙数据前,检查蓝牙是否已开启,并确保设备已处于可被发现或已连接状态。使用BluetoothAdapter的API来管理蓝牙状态。

  3. 设备兼容性:不同蓝牙设备间的兼容性可能导致读写操作失败。确保目标设备与你的鸿蒙设备兼容,并尝试更新设备的蓝牙驱动或固件。

  4. API使用:正确调用蓝牙读写相关的API,如BluetoothGattBluetoothGattCharacteristic等。注意异步回调的处理,避免在回调中执行耗时操作。

  5. 错误处理:详细检查报错信息,根据错误码进行针对性处理。鸿蒙系统提供了丰富的错误码和日志输出,有助于定位问题。

如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html

回到顶部