蓝牙扫描报错:
[napi_bluetooth_access.cpp(EnableBluetooth:67)]bluetoothManager napi assert failed.
import { access, ble } from '@kit.ConnectivityKit';
import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
import { abilityAccessCtrl } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
export class LST_BLESDK {
private static instance: LST_BLESDK;
static sharedBLESDK(): LST_BLESDK {
if (!LST_BLESDK.instance) {
LST_BLESDK.instance = new LST_BLESDK();
}
return LST_BLESDK.instance;
}
onReceiveEvent(data: Array<ble.ScanResult>) {
console.info('BLE scan device find result = ' + JSON.stringify(data));
}
requestPermission = async () => {
let permissionRequestResult = await abilityAccessCtrl.createAtManager().requestPermissionsFromUser(getContext(this),
[
'ohos.permission.USE_BLUETOOTH'
]);
// 如果权限列表中有-1,说明用户拒绝了授权
if (permissionRequestResult.authResults[0] === 0) {
hilog.info(0x0000, 'testTag', '%{public}s', 'request permission success');
}
}
async connectDevice() {
await this.requestPermission()
this.enableBluetooth()
try {
ble.on("BLEDeviceFind", this.onReceiveEvent);
let scanOptions: ble.ScanOptions = {
interval: 500,
dutyMode: ble.ScanDuty.SCAN_MODE_LOW_POWER,
matchMode: ble.MatchMode.MATCH_MODE_AGGRESSIVE
}
ble.startBLEScan(null, scanOptions);
} catch (err) {
console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}
}
enableBluetooth() {
access.enableBluetooth();
access.on('stateChange', (data) => {
let btStateMessage = '';
switch (data) {
case 0:
btStateMessage += 'STATE_OFF';
break;
case 1:
btStateMessage += 'STATE_TURNING_ON';
break;
case 2:
btStateMessage += 'STATE_ON';
break;
case 3:
btStateMessage += 'STATE_TURNING_OFF';
break;
case 4:
btStateMessage += 'STATE_BLE_TURNING_ON';
break;
case 5:
btStateMessage += 'STATE_BLE_ON';
break;
case 6:
btStateMessage += 'STATE_BLE_TURNING_OFF';
break;
default:
btStateMessage += 'unknown status';
break;
}
if (btStateMessage == 'STATE_ON') {
access.off('stateChange');
}
console.info('bluetooth statues: ' + btStateMessage);
})
}
}
请参考:
获取server的services信息,测试没问题。可以参考: