HarmonyOS 鸿蒙Next 蓝牙发送广播问题

发布于 1周前 作者 ionicwang 来自 鸿蒙OS

HarmonyOS 鸿蒙Next 蓝牙发送广播问题

使用 ble.startAdvertising 发送蓝牙广播时, 如果设置的数据里 serviceUuids, serviceData 都为空, 如下:

let advData: ble.AdvertiseData = {
manufactureData: [manufactureDataUnit],
serviceUuids: [],
serviceData: [],
includeDeviceName: fals
};

manufactureDataUnit 内容为:
manuID: 0xfff0
manuBuff: “6db64368931ddd04327b6378db5ae28d0e322d24175e72e0” , hex 字符串转 buffer

是否会影响广播的发送?
PS: 我的蓝牙权限和位置权限均已开启, 状态回调函数 ‘advertisingStateChange’ 返回内容:
{“advertisingId”:0,“state”:1}

但是我在屏蔽房里无法抓取到相应的广播包
 


更多关于HarmonyOS 鸿蒙Next 蓝牙发送广播问题的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

代码中没有去调用addService方法创建服务,然后就发送了广播,这样的话,对端确实是无法获取到相应广播包。serviceUuids和serviceData这两个参数,尤其是serviceUuids最好还是设置一下。服务端开发,可以参考以下代码。

import { ble } from '@kit.ConnectivityKit';

import { BusinessError } from '@kit.BasicServicesKit';

import { promptAction } from '@kit.ArkUI';

import { ADVERTISING_STATE } from '../common/Constants';

import Utils from '../utils/Util';

@Entry

@Component

struct Server {

  private gattServer: ble.GattServer | undefined = undefined;

  @State instanceSwitch: boolean = false;

  @State advSwitch: boolean = false;

  @State advStateChangeSwitch: boolean = false;

  @State addServiceSwitch: boolean = false;

  @State charReadSwitch: boolean = false;

  @State dValueReadSwitch: boolean = false;

  @State descriptorWriteSwitch: boolean = false;

  @State charWriteSwitch: boolean = false;

  private serviceUuid = '00001810-0000-1000-8000-00805F9B34FB';

  private advHandle: number = 0xFF;

  @State advertisingState: ble.AdvertisingStateChangeInfo | undefined = undefined;

  @State connectedBLEDevices: Array<string> = [];

  @State charReadRsp: string = '';

  @State desReadRsp: string = '';

  @State dwRecording: Array<string> = [];

  @State cwRecording: Array<string> = [];

  @State charValue: string = 'BLEServer';

  @State descriptorValue: string = 'BLEServerDescriptor';

  aboutToAppear(): void {

    this.dwRecording.push('原始描述符: ' + this.descriptorValue)

    this.cwRecording.push('原始特征值: ' + this.charValue)

  }

  build() {

    Scroll() {

      Column({ space: 15 }) {

        Row() {

          Text('GattServer实例')

          Blank()

          Toggle({ type: ToggleType.Switch, isOn: this.instanceSwitch })

            .onChange((isOn: boolean) => {

              if (isOn) {

                this.CreateGattServer()

              } else {

                this.CloseGattServer()

              }

              console.info('ble server instanceSwitch status:' + isOn)

            })

        }

        .itemStyle()

        Row() {

          Text('server端添加服务')

          Blank()

          Toggle({ type: ToggleType.Switch, isOn: this.addServiceSwitch })

            .onChange((isOn: boolean) => {

              if (isOn) {

                this.addService()

              } else {

                this.offAdvertisingStateChange()

              }

              console.info('ble server addService status:' + isOn)

            })

            .enabled(this.instanceSwitch)

        }

        .itemStyle()

        Row() {

          Text('发送BLE广播')

          Blank()

          Toggle({ type: ToggleType.Switch, isOn: this.advSwitch })

            .onChange((isOn: boolean) => {

              if (isOn) {

                this.startAdvertising()

              } else {

                this.stopAdvertising()

              }

              console.info('ble server advSwitch status:' + isOn)

            })

            .enabled(this.instanceSwitch)

        }

        .itemStyle()

        Column() {

          Row() {

            Text('订阅BLE广播状态')

            Blank()

            Toggle({ type: ToggleType.Switch, isOn: this.advStateChangeSwitch })

              .onChange((isOn: boolean) => {

                if (isOn) {

                  this.onAdvertisingStateChange()

                } else {

                  this.offAdvertisingStateChange()

                }

                console.info('ble server advStateChangeSwitch status:' + isOn)

              })

          }

          .itemStyle()

          .borderRadius({ topLeft: 10, topRight: 10 })

          Divider()

          Scroll() {

            if (this.advertisingState) {

              Flex() {

                Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Start }) {

                  Row() {

                    Text('广播ID:').width(80)

                    Text(this.advertisingState.advertisingId.toString())

                  }.width('100%')

                  Row() {

                    Text('广播状态:').width(80)

                    Text(ADVERTISING_STATE.get(this.advertisingState.state))

                  }.width('100%')

                }

                .width('100%')

              }

            } else {

              Text('暂无信息')

            }

          }

          .itemStyle()

          .height(60)

          .borderRadius({ bottomLeft: 10, bottomRight: 10 })

          .scrollBar(BarState.Off)

        }

        Column() {

          Row() {

            Text('订阅特征值读请求事件')

            Blank()

            Toggle({ type: ToggleType.Switch, isOn: this.charReadSwitch })

              .onChange((isOn: boolean) => {

                if (isOn) {

                  this.onCharacteristicRead()

                } else {

                  this.offCharacteristicRead()

                }

                console.info('ble server onCharacteristicRead status:' + isOn)

              })

              .enabled(this.instanceSwitch)

          }

          .itemStyle()

          .borderRadius({ topLeft: 10, topRight: 10 })

          Divider()

          Scroll() {

            if (this.charReadRsp) {

              Text(JSON.stringify(JSON.parse(this.charReadRsp)))

            } else {

              Text('暂无信息')

            }

          }

          .itemStyle()

          .height(100)

          .borderRadius({ bottomLeft: 10, bottomRight: 10 })

          .scrollBar(BarState.Off)

        }

        Column() {

          Row() {

            Text('订阅描述符读请求事件')

            Blank()

            Toggle({ type: ToggleType.Switch, isOn: this.dValueReadSwitch })

              .onChange((isOn: boolean) => {

                if (isOn) {

                  this.onDescriptorRead()

                } else {

                  this.offDescriptorRead()

                }

                console.info('ble server onDescriptorRead status:' + isOn)

              })

              .enabled(this.instanceSwitch)

          }

          .itemStyle()

          .borderRadius({ topLeft: 10, topRight: 10 })

          Divider()

          Scroll() {

            if (this.desReadRsp) {

              Text(JSON.stringify(JSON.parse(this.desReadRsp)))

            } else {

              Text('暂无信息')

            }

          }

          .itemStyle()

          .height(100)

          .borderRadius({ bottomLeft: 10, bottomRight: 10 })

          .scrollBar(BarState.Off)

        }

        Column({ space: 10 }) {

          Button('当前设备作为Server端时连接BLE设备地址集合').onClick((event: ClickEvent) => {

            this.getConnectedBLEDevices()

          })

          Scroll() {

            if (this.connectedBLEDevices.length > 0) {

              List() {

                ForEach(this.connectedBLEDevices, (item: string) => {

                  ListItem() {

                    Text(item)

                  }

                })

              }

            } else {

              Text('暂无连接设备')

            }

          }

          .height(50)

          .scrollBar(BarState.Off)

        }

        .itemStyle()

        Column() {

          Row() {

            Text('订阅描述符写请求事件')

            Blank()

            Toggle({ type: ToggleType.Switch, isOn: this.descriptorWriteSwitch })

              .onChange((isOn: boolean) => {

                if (isOn) {

                  this.onDescriptorWrite()

                } else {

                  this.offDescriptorWrite()

                }

                console.info('ble server descriptorWriteSwitch status:' + isOn)

              })

              .enabled(this.instanceSwitch)

          }

          .itemStyle()

          .borderRadius({ topLeft: 10, topRight: 10 })

          Divider()

          Scroll() {

            if (this.dwRecording.length > 0) {

              List() {

                ForEach(this.dwRecording, (item: string) => {

                  ListItem() {

                    Text(item)

                  }

                })

              }

            } else {

              Text('暂无信息')

            }

          }

          .itemStyle()

          .height(80)

          .borderRadius({ bottomLeft: 10, bottomRight: 10 })

          .scrollBar(BarState.Off)

        }

        Column() {

          Row() {

            Text('订阅特征值写请求事件')

            Blank()

            Toggle({ type: ToggleType.Switch, isOn: this.charWriteSwitch })

              .onChange((isOn: boolean) => {

                if (isOn) {

                  this.onCharacteristicWrite()

                } else {

                  this.offCharacteristicWrite()

                }

                console.info('ble server descriptorWriteSwitch status:' + isOn)

              })

              .enabled(this.instanceSwitch)

          }

          .itemStyle()

          .borderRadius({ topLeft: 10, topRight: 10 })

          Divider()

          Scroll() {

            if (this.cwRecording.length > 0) {

              List() {

                ForEach(this.cwRecording, (item: string) => {

                  ListItem() {

                    Text(item)

                  }

                })

              }

            } else {

              Text('暂无信息')

            }

          }

          .itemStyle()

          .height(80)

          .borderRadius({ bottomLeft: 10, bottomRight: 10 })

          .scrollBar(BarState.Off)

        }

      }

      .width('100%')

      .padding({

        left: 15,

        right: 15,

        top: 20,

        bottom: 20

      })

      .backgroundColor($r('app.color.light_gray'))

    }

    .scrollBar(BarState.Off)

  }

  /**

   * 创建GattServer实例

   */

  CreateGattServer() {

    try {

      this.gattServer = ble.createGattServer();

      this.instanceSwitch = true;

    } catch (err) {

      console.error('ble server CreateGattServer errCode: ' + (err as BusinessError).code + ', errMessage: ' +

      (err as BusinessError).message);

    }

  }

  /**

   * 关闭服务端功能

   */

  CloseGattServer() {

    if (!this.gattServer) {

      promptAction.showToast({

        message: 'GattServer实例不存在',

        duration: 2000

      })

      console.warn('ble server CloseGattServer GattServer instance not exist')

      return;

    }

    try {

      this.gattServer.close();

      this.instanceSwitch = false;

      console.info('ble server GattServer closed')

    } catch (err) {

      console.error('ble server CloseGattServer errCode: ' + (err as BusinessError).code + ', errMessage: ' +

      (err as BusinessError).message);

    }

  }

  /**

   * server端添加服务

   */

  addService() {

    if (!this.gattServer) {

      promptAction.showToast({

        message: 'GattServer实例不存在',

        duration: 2000

      })

      console.warn('ble server addService GattServer instance not exist')

      return;

    }

    let characteristicUuid = '00001820-0000-1000-8000-00805F9B34FB';

    // 创建descriptors

    let descriptors: Array<ble.BLEDescriptor> = [];

    let descriptor: ble.BLEDescriptor = {

      serviceUuid: this.serviceUuid,

      characteristicUuid: characteristicUuid,

      descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB',

      descriptorValue: Utils.string2ArrayBuffer(this.descriptorValue)

    };

    descriptors[0] = descriptor;

    let descriptor1: ble.BLEDescriptor = {

      serviceUuid: this.serviceUuid,

      characteristicUuid: characteristicUuid,

      descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB',

      descriptorValue: Utils.string2ArrayBuffer(this.descriptorValue)

    };

    descriptors[1] = descriptor1;

    let properties: ble.GattProperties = {

      write: true,

      writeNoResponse: false,

      read: true,

      notify: true,

      indicate: true

    }

    // 创建characteristics

    let characteristics: Array<ble.BLECharacteristic> = [];

    let characteristic: ble.BLECharacteristic = {

      serviceUuid: this.serviceUuid,

      characteristicUuid: characteristicUuid,

      characteristicValue: Utils.string2ArrayBuffer(this.charValue),

      descriptors: descriptors,

      properties: properties

    };

    characteristics[0] = characteristic;

    // 创建gattService

    let gattService: ble.GattService = {

      serviceUuid: this.serviceUuid,

      isPrimary: true,

      characteristics: characteristics,

      includeServices: []

    };

    try {

      this.gattServer.addService(gattService);

      this.addServiceSwitch = true;

    } catch (err) {

      console.error('ble server addService errCode: ' + (err as BusinessError).code + ', errMessage: ' +

      (err as BusinessError).message);

    }

  }

  /**

   * 删除已添加的服务

   */

  removeService() {

    if (!this.gattServer) {

      promptAction.showToast({

        message: 'GattServer实例不存在',

        duration: 2000

      })

      console.warn('ble server addService GattServer instance not exist')

      return;

    }

    try {

      // 调用removeService接口前需要完成server端和client端的配对及连接。

      this.gattServer.removeService(this.serviceUuid);

      this.addServiceSwitch = false;

    } catch (err) {

      console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);

    }

  }

  /**

   * 开始发送BLE广播

   */

  startAdvertising() {

    let manufactureValueBuffer = new Uint8Array(4);

    manufactureValueBuffer[0] = 1;

    manufactureValueBuffer[1] = 2;

    manufactureValueBuffer[2] = 3;

    manufactureValueBuffer[3] = 4;

    let serviceValueBuffer = new Uint8Array(4);

    serviceValueBuffer[0] = 4;

    serviceValueBuffer[1] = 6;

    serviceValueBuffer[2] = 7;

    serviceValueBuffer[3] = 8;

    console.info('ble server manufactureValueBuffer = ' + JSON.stringify(manufactureValueBuffer));

    console.info('ble server serviceValueBuffer = ' + JSON.stringify(serviceValueBuffer));

    try {

      let setting: ble.AdvertiseSetting = {

        interval: 1600,

        txPower: 0,

        connectable: true,

      };

      let manufactureDataUnit: ble.ManufactureData = {

        manufactureId: 4567,

        manufactureValue: manufactureValueBuffer.buffer

      };

      let serviceDataUnit: ble.ServiceData = {

        serviceUuid: this.serviceUuid,

        serviceValue: serviceValueBuffer.buffer

      };

      let advData: ble.AdvertiseData = {

        serviceUuids: [this.serviceUuid],

        manufactureData: [manufactureDataUnit],

        serviceData: [serviceDataUnit],

        includeDeviceName: true

      };

      let advResponse: ble.AdvertiseData = {

        serviceUuids: [this.serviceUuid],

        manufactureData: [manufactureDataUnit],

        serviceData: [serviceDataUnit],

      };

      let advertisingParams: ble.AdvertisingParams = {

        advertisingSettings: setting,

        advertisingData: advData,

        advertisingResponse: advResponse,

        duration: 0,

      }

      ble.startAdvertising(advertisingParams, (err, outAdvHandle) => {

        if (err) {

          return;

        } else {

          this.advHandle = outAdvHandle;

          console.log("ble server advHandle: " + this.advHandle);

          this.advSwitch = true;

        }

      });

    } catch (err) {

      console.error('ble server startAdvertising errCode: ' + (err as BusinessError).code + ', errMessage: ' +

      (err as BusinessError).message);

    }

  }

  /**

   * 停止发送BLE广播

   */

  stopAdvertising() {

    try {

      ble.stopAdvertising(this.advHandle)

        .then(() => {

          console.info("ble server stopAdvertising success");

          this.advSwitch = false;

        });

    } catch (err) {

      console.error('ble server stopAdvertising errCode: ' + (err as BusinessError).code + ', errMessage: ' +

      (err as BusinessError).message);

    }

  }

  /**

   * 订阅BLE广播状态

   */

  onAdvertisingStateChange() {

    try {

      ble.on('advertisingStateChange', (data: ble.AdvertisingStateChangeInfo) => {

        console.info('ble server advertising state = ' + JSON.stringify(data));

        this.advertisingState = data;

      });

      this.advStateChangeSwitch = true;

    } catch (err) {

      console.error('ble server onAdvertisingStateChange errCode: ' + (err as BusinessError).code + ', errMessage: ' +

      (err as BusinessError).message);

    }

  }

  /**

   * 取消订阅BLE广播状态

   */

  offAdvertisingStateChange() {

    try {

      ble.on('advertisingStateChange', (data: ble.AdvertisingStateChangeInfo) => {

        console.info('bluetooth device offAdvertisingStateChange = ' + JSON.stringify(data));

        this.advertisingState = undefined;

      });

      this.advStateChangeSwitch = false;

    } catch (err) {

      console.error('ble server offAdvertisingStateChange errCode: ' + (err as BusinessError).code + ', errMessage: ' +

      (err as BusinessError).message);

    }

  }

  /**

   * 打开订阅特征值读请求事件

   */

  onCharacteristicRead() {

    if (!this.gattServer) {

      promptAction.showToast({

        message: 'GattServer实例不存在',

        duration: 2000

      })

      console.warn('ble server addService GattServer instance not exist')

      return;

    }

    let gattServer: ble.GattServer = this.gattServer;

    this.charReadSwitch = true;

    this.charReadRsp = '';

    gattServer.on('characteristicRead', (characteristicReadRequest: ble.CharacteristicReadRequest) => {

      let deviceId: string = characteristicReadRequest.deviceId;

      let transId: number = characteristicReadRequest.transId;

      let offset: number = characteristicReadRequest.offset;

      let characteristicUuid: string = characteristicReadRequest.characteristicUuid;

      let serverResponse: ble.ServerResponse = {

        deviceId: deviceId,

        transId: transId,

        status: 0,

        offset: offset,

        value: Utils.string2ArrayBuffer(this.charValue)

      };

      try {

        gattServer.sendResponse(serverResponse);

        this.charReadRsp = JSON.stringify(serverResponse);

        console.info('ble server onCharacteristicRead sendResponse success')

      } catch (err) {

        console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);

      }

    });

  }

  /**

   * 取消订阅特征值读请求事件

   */

  offCharacteristicRead() {

    if (!this.gattServer) {

      promptAction.showToast({

        message: 'GattServer实例不存在',

        duration: 2000

      })

      console.warn('ble server offCharacteristicRead GattServer instance not exist')

      return;

    }

    this.gattServer.off('characteristicRead');

    this.charReadRsp = '';

    console.info('ble server offCharacteristicRead success')

    this.charReadSwitch = false;

  }

  getConnectedBLEDevices() {

    try {

      this.connectedBLEDevices = ble.getConnectedBLEDevices();

    } catch (err) {

      console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);

    }

  }

  /**

   * server端订阅描述符写请求事件

   */

  onDescriptorWrite() {

    try {

      if (!this.gattServer) {

        promptAction.showToast({

          message: 'GattServer实例不存在',

          duration: 2000

        })

        console.warn('ble server offCharacteristicRead GattServer instance not exist')

        return;

      }

      let gattServer: ble.GattServer = this.gattServer;

      this.descriptorWriteSwitch = true;

      this.gattServer.on('descriptorWrite', (descriptorWriteRequest: ble.DescriptorWriteRequest) => {

        this.descriptorValue = Utils.ArrayBuffer2String(descriptorWriteRequest.value);

        console.log('on descriptorWrite start, descriptorValue = ' + this.descriptorValue)

        this.dwRecording.push('写入描述符: ' + this.descriptorValue)

        let deviceId: string = descriptorWriteRequest.deviceId;

        let transId: number = descriptorWriteRequest.transId;

        let offset: number = descriptorWriteRequest.offset;

        let serverResponse: ble.ServerResponse = {

          deviceId: deviceId,

          transId: transId,

          status: 0,

          offset: offset,

          value: Utils.string2ArrayBuffer(this.descriptorValue)

        };

        try {

          gattServer.sendResponse(serverResponse);

        } catch (err) {

          console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);

        }

      });

    } catch (err) {

      console.error("errCode:" + (err as BusinessError).code + ",errMessage:" + (err as BusinessError).message);

    }

  }

/**

   * server端取消订阅描述符写请求事件

   */

  offDescriptorWrite() {

    try {

      if (!this.gattServer) {

        promptAction.showToast({

          message: 'GattServer实例不存在',

          duration: 2000

        })

        console.warn('ble server offCharacteristicRead GattServer instance not exist')

        return;

      }

      this.gattServer.off('descriptorWrite');

      this.descriptorWriteSwitch = false;

    } catch (err) {

      console.error("errCode:" + (err as BusinessError).code + ",errMessage:" + (err as BusinessError).message);

    }

  }

  /**

   * server端订阅特征值写请求事件

   */

  onCharacteristicWrite() {

    try {

      if (!this.gattServer) {

        promptAction.showToast({

          message: 'GattServer实例不存在',

          duration: 2000

        })

        console.warn('ble server offCharacteristicRead GattServer instance not exist')

        return;

      }

      let gattServer: ble.GattServer = this.gattServer;

      this.charWriteSwitch = true;

      gattServer.on('characteristicWrite', (characteristicWriteRequest: ble.CharacteristicWriteRequest) => {

        console.log('on onCharacteristicWrite start')

        let deviceId: string = characteristicWriteRequest.deviceId;

        let transId: number = characteristicWriteRequest.transId;

        let offset: number = characteristicWriteRequest.offset;

        let isPrepared: boolean = characteristicWriteRequest.isPrepared;

        let needRsp: boolean = characteristicWriteRequest.needRsp;

        let value: Uint8Array = new Uint8Array(characteristicWriteRequest.value);

        this.charValue = Utils.ArrayBuffer2String(characteristicWriteRequest.value);

        let characteristicUuid: string = characteristicWriteRequest.characteristicUuid;

        let serverResponse: ble.ServerResponse = {

          deviceId: deviceId,

          transId: transId,

          status: 0,

          offset: offset,

          value: Utils.string2ArrayBuffer(this.charValue)

        };

        let notifyCharacter: ble.NotifyCharacteristic = {

          serviceUuid: characteristicWriteRequest.serviceUuid,

          characteristicUuid: characteristicUuid,

          characteristicValue: Utils.string2ArrayBuffer(this.charValue),

          confirm: true,

        };

        try {

          gattServer.sendResponse(serverResponse);

          gattServer.notifyCharacteristicChanged(deviceId, notifyCharacter).then(() => {

            console.info('notifyCharacteristicChanged promise successfull');

            this.cwRecording.push('写入值: ' + this.charValue)

          });

          console.info('onCharacteristicWrite send success, value = ' + JSON.stringify(serverResponse))

        } catch (err) {

          console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);

        }

      });

    } catch (err) {

      console.error("errCode:" + (err as BusinessError).code + ",errMessage:" + (err as BusinessError).message);

    }

  }

  /**

   * server端取消订阅特征值写请求事件

   */

  offCharacteristicWrite() {

    try {

      if (!this.gattServer) {

        promptAction.showToast({

          message: 'GattServer实例不存在',

          duration: 2000

        })

        console.warn('ble server offCharacteristicRead GattServer instance not exist')

        return;

      }

      this.gattServer.off('characteristicWrite');

      this.charWriteSwitch = false;

    } catch (err) {

      console.error("errCode:" + (err as BusinessError).code + ",errMessage:" + (err as BusinessError).message);

    }

  }

  /**

   * server端订阅描述符读请求事件

   */

  onDescriptorRead() {

    if (!this.gattServer) {

      promptAction.showToast({

        message: 'GattServer实例不存在',

        duration: 2000

      })

      console.warn('ble server offCharacteristicRead GattServer instance not exist')

      return;

    }

    let gattServer: ble.GattServer = this.gattServer;

    this.desReadRsp = '';

    gattServer.on('descriptorRead', (descriptorReadRequest: ble.DescriptorReadRequest) => {

      let deviceId: string = descriptorReadRequest.deviceId;

      let transId: number = descriptorReadRequest.transId;

      let offset: number = descriptorReadRequest.offset;

      let descriptorUuid: string = descriptorReadRequest.descriptorUuid;

      let serverResponse: ble.ServerResponse = {

        deviceId: deviceId,

        transId: transId,

        status: 0,

        offset: offset,

        value: Utils.string2ArrayBuffer(this.descriptorValue)

      };

      try {

        gattServer.sendResponse(serverResponse);

        this.desReadRsp = JSON.stringify(serverResponse);

        console.log('ble server descriptorRead sendResponse success ' + this.desReadRsp)

      } catch (err) {

        console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);

      }

    });

  }

  /**

   * server端取消订阅描述符读请求事件

   */

  offDescriptorRead() {

    try {

      if (!this.gattServer) {

        promptAction.showToast({

          message: 'GattServer实例不存在',

          duration: 2000

        })

        console.warn('ble server offCharacteristicRead GattServer instance not exist')

        return;

      }

      this.gattServer.off('descriptorWrite');

    } catch (err) {

      console.error("errCode:" + (err as BusinessError).code + ",errMessage:" + (err as BusinessError).message);

    }

  }

}

@Styles

function itemStyle() {

  .width('100%')

  .padding({

    left: 15,

    right: 15,

    top: 8,

    bottom: 8

  })

  .backgroundColor($r('app.color.white'))

  .borderRadius(10)

}

更多关于HarmonyOS 鸿蒙Next 蓝牙发送广播问题的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


针对HarmonyOS 鸿蒙Next 蓝牙发送广播问题,以下是一些可能的解决方案:

  1. 检查广播参数

    • 确保广播间隔、发送功率等参数设置正确。
    • 广播间隔不宜过长,否则可能不易被扫描到。
    • 发送功率可根据需求调整,但需注意功耗和覆盖范围。
  2. 构造广播数据

    • 确保广播数据格式正确,包括制造商信息、服务UUID等。
    • 制造商信息中的manufactureValue应为ArrayBuffer类型,而非Uint8Array。
    • 服务数据和服务UUID需正确匹配。
  3. 调用API

    • 使用正确的API调用顺序和参数。
    • 在调用ble.startAdvertising之前,确保已正确设置广播参数和数据。
  4. 权限和状态

    • 确保应用已获取蓝牙权限。
    • 检查蓝牙是否已开启,以及设备是否支持BLE广播。
  5. 调试和日志

    • 使用日志记录功能,查看广播状态和相关错误信息。
    • 根据日志信息调整代码和参数。

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

回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!