HarmonyOS 鸿蒙Next 蓝牙连接成功后获取服务列表报错
HarmonyOS 鸿蒙Next 蓝牙连接成功后获取服务列表报错
蓝牙连接成功后,获取服务报错
tailgBle.connectBle(data2[0].deviceId)
//连接蓝牙
connectBle(mac:string){
this.bleMac = mac
console.log('----connectBle mac:' + mac);
let device: ble.GattClientDevice = this.getBleGattClientDevice(mac);
//ble连接状态监听
device.on('BLEConnectionStateChange', ConnectStateChanged);
//发起连接
device.connect();
//服务发现监听
//this.getBleGattClientDevice(mac).getServices(getServices);
}
//ble连接状态
function ConnectStateChanged(state: ble.BLEConnectionChangeState) {
console.log('bluetooth connect state changed tailgBle.bleMac:' + tailgBle.bleMac);
let device: ble.GattClientDevice = tailgBle.getBleGattClientDevice(tailgBle.bleMac);
let connectState: ble.ProfileConnectionState = state.state;
//0-已断连 1-正在连接 2-已连接 3-正在断连
console.log('ConnectStateChanged state:' + connectState);
console.log('ConnectStateChanged deviceId:' + state.deviceId);
if(connectState == 2){
device.getServices(getServices);
}
emitter.emit({
eventId: BaseEmitterId.ble_connection_state,
priority: emitter.EventPriority.IMMEDIATE//优先级 立即投递
}, {
data: {
"data":connectState//0-已断连 1-正在连接 2-已连接 3-正在断连
}
});
}
//ble服务发现监听
function getServices(code: BusinessError, gattServices: Array<ble.GattService>) {
console.log('getServices code:' + JSON.stringify(code));
if (code.code == 0) {
let services: Array<ble.GattService> = gattServices;
console.log('getServices code is ' + code.code);
console.log('bluetooth services size is ', services.length);
for (let i = 0; i < services.length; i++) {
console.log('bluetooth serviceUuid is ' + services[i].serviceUuid);
}
}
更多关于HarmonyOS 鸿蒙Next 蓝牙连接成功后获取服务列表报错的实战教程也可以访问 https://www.itying.com/category-93-b0.html
2 回复
1、getBleGattClientDevice(mac)传入的这个mac地址参数是写死的吗
2、状态监听要监听客户端的状态不是服务端
let gattClientDevice = ble.createGattClientDevice()
gattClientDevice.on
可以尝试:
@State gattClient: ble.GattClientDevice | undefined = undefined;
if (!this.gattClient) {
this.gattClient = ble.createGattClientDevice(this.device?.deviceId);
}
或者用arr 的方式,每一次取最新创建的
private gattClients : Array<ble.GattClientDevice> = new Array<ble.GattClientDevice>();
let gattClient: ble.GattClientDevice = ble.createGattClientDevice(remoteDeviceId);
this.gattClients.push(gattClient);
其它方法里面调用:
let gattClient: ble.GattClientDevice = this.gattClients[0];
更多关于HarmonyOS 鸿蒙Next 蓝牙连接成功后获取服务列表报错的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html