HarmonyOS 如何获取蓝牙广播包中service uuid

如何获取蓝牙广播包中的service uuid,并确认UUID的类型(16位、32位、128位)?

HarmonyOS
2024-09-09 09:25:13
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
FengTianYa

获取service UUID——描述广播包中服务数据内容:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-bluetooth-ble-V5#servicedata

UUID类型:低功耗蓝牙(BLE)采用UUID(通用唯一标识符)来标识不同的基于GATT(Generic Attribute Profile)的蓝牙服务,蓝牙服务UUID的长度为16位(16-bit)。

根据截图,这些Service UUID是特征值。

GATT Service 0x1826 Fitness Machine  
GATT Service 0x1818 Cycling Power  
GATT Service 0x180A Device Information  
GATT Service 0x1816 Cycling Speed and Cadence 

为您提供蓝牙Service UUID文档(注:3.4.2 Services by UUID):https://www.bluetooth.com/wp-content/uploads/Files/Specification/HTML/Assigned_Numbers/out/en/Assigned_Numbers.pdf?v=1714466664289

想要获取ServiceData,主要使用:

import ble from '@ohos.bluetooth.ble'; 
let serviceDataUnit: ble.ServiceData = { 
  serviceUuid: ADV_SERVICE_UUID, 
  serviceValue: serviceValueBuffer 
};

提供蓝牙demo作为参考。

Index.ets:

import promptAction from '@ohos.promptAction'; 
import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl'; 
import common from '@ohos.app.ability.common'; 
import { Device } from '../models/device'; 
import { BleManager } from '../models/bleManager'; 
import { BrManager } from '../models/brManager'; 
import { Result } from '../utils/Utils'; 
const PERMISSIONS: Array<Permissions> = ['ohos.permission.ACCESS_BLUETOOTH']; 
@Entry 
@Component 
struct Index { 
  @State foundDevices: Array<Device> = new Array<Device>(); 
  @State connectedDevices: Array<Device> = new Array<Device>(); 
  @State connectedColors: Array<string> = new Array<string>(); 
  @State receivedLength: Array<string> = new Array<string>(); 
  @State averageLength: Array<string> = new Array<string>(); 
  private bleManager: BleManager = new BleManager(this.foundDevices, this.connectedDevices, this.receivedLength); 
  private brManager: BrManager = new BrManager(this.foundDevices, 
  this.connectedDevices, this.connectedColors, this.receivedLength, this.averageLength); 
  private dataSize: number = 1024; 
  private sendTime: number = 1; 
  private type: number = 0; 
  aboutToAppear() { 
    let context = getContext(this) as common.UIAbilityContext; 
    let accessManager = abilityAccessCtrl.createAtManager(); 
    accessManager.requestPermissionsFromUser(context, PERMISSIONS); 
  } 
  @Builder 
  SelectType() { 
    Row({ space: 200 }) { 
      Column() { 
        Radio({ value: 'Radio1', group: 'radioGroup' }).checked(true).onChange((isChecked: boolean) => { 
          if (isChecked) { 
            this.type = 0; 
          } 
        }); 
        Text('BR') 
      } 
      Column() { 
        Radio({ value: 'Radio2', group: 'radioGroup' }).onChange((isChecked: boolean) => { 
          if (isChecked) { 
            this.type = 1; 
          } 
        }); 
        Text('BLE') 
      } 
    }.justifyContent(FlexAlign.Center) 
  } 
  @Builder 
  SendBroadCast() { 
    Button('开启广播').fontSize(30).onClick(() => { 
      if (this.type == 1) { 
        let result: Result = this.bleManager.CreateGattServer(); 
        result = this.bleManager.AddService(); 
        this.bleManager.SetServerConnectedCallback(); 
        this.bleManager.SetServerReceivedCallback(); 
        result = this.bleManager.StartAdvertising(); 
        promptAction.showToast({ message: 'BLE send broadCast success' }); 
        return; 
      } 
      let result: Result = this.brManager.SendBroadCast(); 
      if (result.isSuccess) { 
        console.log('success') 
      } 
    }) 
  } 
  @Builder 
  StartDiscovery() { 
    Button('开启扫描').fontSize(30).onClick(() => { 
      if (this.type == 1) { 
        let result: Result = this.bleManager.StartDiscovery(); 
        if (result.isSuccess) { 
          promptAction.showToast({ message: 'BLE start Discovery success' }); 
        } 
        return; 
      } 
      let result: Result = this.brManager.StartDiscovery(); 
      if (result.isSuccess) { 
        promptAction.showToast({ message: 'BR start Discovery success' }); 
      } 
    }) 
  } 
  @Builder 
  PresentFoundDevices() { 
    Text('左右滑动可以查看更多设备') 
    Grid() { 
      ForEach(this.foundDevices, (device: Device) => { 
        GridItem() { 
          Text(device.toString()) 
            .onClick(() => { 
              if (this.type == 1) { 
                let result: Result = this.bleManager.CreateGattClient(device.id); 
                this.bleManager.SetClientConnectedCallback(); 
                result = this.bleManager.Connect(); 
                promptAction.showToast({ message: 'BLE start connect to ' + device.toString() }); 
                return; 
              } 
              ; 
              let result: Result = this.brManager.PairDevice(device.id); 
              if (result.isSuccess) { 
                promptAction.showToast({ message: 'BR start connect to ' + device.id }) 
              } 
              return; 
            }) 
        }.width('50%') 
      }) 
    }.rowsTemplate('1fr 1fr 1fr').height('100') 
  } 
  @Builder 
  PresentConnectedDevices() { 
    Text('显示配对成功的设备') 
    Row() { 
      Button('已配对设备').fontSize(30).onClick(() => { 
        this.brManager.CreateSppServerSocket(); 
        let pairedDevices: Array<Device> = this.brManager.GetPairedDevices(); 
        for (let device of pairedDevices) { 
          if (this.connectedDevices.find((cDevice) => cDevice.id == device.id) == undefined) { 
            device.number = this.connectedDevices.length; 
            this.connectedDevices.push(device); 
            this.connectedColors.push('#ffee1818'); 
          } 
        } 
      }) 
      List({ space: 10 }) { 
        ForEach(this.connectedDevices, (device: Device) => { 
          ListItem() { 
            Text(device.toString()).backgroundColor(this.connectedColors[device.number]).onClick(() => { 
              if (this.type == 1) { 
                this.bleManager.GetServices(device); 
                return; 
              } 
              this.brManager.SppClientConnect(device); 
            }) 
          } 
        }) 
      }.height('50') 
    } 
  } 
  @Builder 
  SendData() { 
    Row({ space: 20 }) { 
      TextInput({ placeholder: '发送大小/KB' }).onChange((value: string) => { 
        this.dataSize = Number(value) * 1024; 
      }).width('35%') 
      TextInput({ placeholder: '发送次数' }).onChange((value: string) => { 
        this.sendTime = Number(value); 
      }).width('25%') 
      Button('发送').fontSize(30).onClick(() => { 
        if (this.type == 1) { 
          this.bleManager.SendData(this.dataSize); 
          return; 
        } 
        this.brManager.SendData(this.dataSize, this.sendTime); 
      }).width('30%') 
    } 
  } 
  @Builder 
  PresentReceivedData() { 
    Row() { 
      Column() { 
        Text("历史速率(kb/s):") 
        Grid() { 
          ForEach(this.receivedLength, (len: string) => { 
            GridItem() { 
              Text(len).fontSize(12) 
            } 
          }) 
        }.columnsTemplate('1fr 1fr 1fr').height('20%').width('50%') 
      } 
      Column() { 
        Text("平均速率(kb/s):") 
        Grid() { 
          ForEach(this.averageLength, (len: string) => { 
            GridItem() { 
              Text(len) 
            } 
          }) 
        }.columnsTemplate('1fr 1fr 1fr') 
        .height('20%').width('50%') 
      } 
    } 
  } 
  build() { 
    Column({ space: 10 }) { 
      this.SelectType(); 
      Row({ space: 20 }) { 
        this.SendBroadCast(); 
        this.StartDiscovery(); 
      } 
      this.PresentFoundDevices(); 
      this.PresentConnectedDevices(); 
      this.SendData(); 
      this.PresentReceivedData(); 
    }.width('100%') 
  } 
}

brManager.ets:

import { BusinessError } from '@ohos.base';import promptAction from '@ohos.promptAction'; 
import socket from '@ohos.bluetooth.socket';import connection from '@ohos.bluetooth.connection'; 
import { Result } from '../utils/Utils';import { Device } from '../models/device' 
const SPP_OPTION: socket.SppOptions = { 
  uuid: "xxxx", 
  secure: false, 
  type: 0 
}; 
const connectedColor: string = '#AEEEEE' 
const historyRateInterval: number = 10; 
const averageRateInterval: number = 1000; 
const historyMaxZeroTime: number = 500; 
const averageMaxZeroTime: number = 5; 
const SendInterval: number = 1000; 
export class BrManager { 
  public foundDevices: Array<Device> = new Array<Device>(); 
  public connectedDevices: Array<Device> = new Array<Device>(); 
  public connectedColors: Array<string> = new Array<string>(); 
  public receivedLength: Array<string> = new Array<string>(); 
  public averageLength: Array<string> = new Array<string>(); 
  private currentReceivedLength: number = 0; 
  private averageReceivedLength: number = 0; 
  private serverNumber: number = -1; 
  private remoteClientNumber: number = -1; 
  private timer: number = 0; 
  constructor(foundDevices: Array<Device>, connectedDevices: Array<Device>, connectedColors: Array<string>, 
    receivedLength: Array<string>, averageLength: Array<string>) { 
    this.foundDevices = foundDevices; 
    this.connectedDevices = connectedDevices; 
    this.connectedColors = connectedColors; 
    this.receivedLength = receivedLength; 
    this.averageLength = averageLength; 
  } 
  GetPairedDevices() { 
    let devices : Array<Device> = new Array<Device>(); 
    let deviceIds : Array<string> = connection.getPairedDevices(); 
    for (let deviceId of deviceIds) { 
      let deviceName = connection.getRemoteDeviceName(deviceId); 
      devices.push(new Device(deviceId, deviceName)); 
    } 
    return devices; 
  } 
  CalculateAverageRate(interval: number, maxZeroTime: number, currentZeroTime: number, preTime: nu
分享
微博
QQ
微信
回复
2024-09-09 17:18:00
相关问题
HarmonyOS蓝牙广播问题
527浏览 • 1回复 待解决
HarmonyOS 如何获取手机UUID
40浏览 • 1回复 待解决
HarmonyOS 获取设备的UUID
52浏览 • 1回复 待解决
HarmonyOS 如何生成UUID?
315浏览 • 1回复 待解决
Weather Service Kit获取天气数据
598浏览 • 1回复 待解决
HarmonyOS 如何发送通知或广播
79浏览 • 1回复 待解决
三方应用如何获取蓝牙mac地址
2268浏览 • 1回复 待解决
HarmonyOS uuid的问题
501浏览 • 1回复 待解决
HarmonyOS蓝牙连接后获取GATT服务失败
774浏览 • 1回复 待解决
HarmonyOS UDP广播有无Demo
40浏览 • 1回复 待解决
HarmonyOS无法获取蓝牙设备的真实MAC
764浏览 • 1回复 待解决
如何使用小型系统的service
4865浏览 • 1回复 待解决
如何生成UUID的字符串
2236浏览 • 1回复 待解决
ArkTS 如何生成如下的 uuid呢?
1028浏览 • 1回复 待解决