OpenHarmony蓝牙模块提供了ble的功能,本篇提供一个简单的app供测试时使用。代码使用API10,对应4.0Release版本固件。
1.开启BLE
开启BLE前,先在设置界面中打开蓝牙开关。
openBle()函数负责打开ble扫描,并打印扫描结果。主要代码如下:
import ble from "@ohos.bluetooth.ble"
openBle():void {
try {
ble.on("BLEDeviceFind", (data:Array<ble.ScanResult>) => {
// console.info('BLE scan device find result = '+ JSON.stringify(data));
let i = 0
data.forEach(element => {
console.info('BLE scan device[' + i + '] deviceId = '+ element["deviceId"] +
' name = ' + element["deviceName"] +
' rssi = ' + element["rssi"] +
' data['+element["data"].byteLength+'] = ' +
this.dataToString(element["data"]))
if (element.rssi > minRssi && element.deviceName != '' ) {
this.addData(element)
}
i++
});
});
ble.startBLEScan(
null,
{
interval: 500,
dutyMode: ble.ScanDuty.SCAN_MODE_LOW_POWER,
matchMode: ble.MatchMode.MATCH_MODE_AGGRESSIVE,
}
);
} catch (err) {
console.error("ble errCode:" + (err as BusinessError).code + ",errMessage:" + (err as BusinessError).message);
}
}
2.关闭BLE
ble.off('BLEDeviceFind')
ble.stopBLEScan();
3.添加ble设备
扫描到ble设备后,添加到本地列表并显示
addData(data:ble.ScanResult):void {
let bFind = false
this.availableDevices.forEach(element => {
if (!bFind && element.deviceId == data.deviceId) {
console.info('BLE scan update ' + data.deviceId + ' rssi:' + element.rssi +' ==> '+ data.rssi)
element.rssi = data.rssi
bFind = true
}
})
if (!bFind) {
console.info('BLE scan add ' + data.deviceId + ' count:' + this.availableDevices.length)
this.availableDevices.push(data)
this.message='BLE count:' + this.availableDevices.length
}
}
4.ble数据转换
将ble的data为16进制字符串
dataToString(data:ArrayBuffer) :String {
let str = ''
let v = new Uint8Array(data);
v.forEach(element => {
let s = ''
s = element.toString(16)
if (s.length == 1) {
s = '0'+s
}
str+=s+' '
});
return str
}
最终的效果:
完整hap代码,请从链接下载