uni.getBLEDeviceServices({
deviceId,
success(res) {
// 检查页面状态
if (!that.isPageActive) {
console.log('页面已离开,忽略服务获取结果');
return;
}
console.log("设备的服务:", res.services);
console.log('服务数量:', res.services ? res.services.length : 0);
if (res.services && res.services.length > 0) {
that.servicesList = res.services;
that.addLog(`成功获取到 ${res.services.length} 个服务`, 'success');
that.isConnected = true; // 成功获取服务后设置连接状态
// 获取每个服务的特征值
res.services.forEach((service) => {
that.getDeviceCharacteristics(deviceId, service.uuid);
});
// 启动连接保持机制
that.startConnectionKeepAlive();
} else {
console.warn('未获取到任何服务,继续尝试...');
that.addLog('未获取到任何服务,继续尝试...', 'info');
// 延时后继续尝试
that.scheduleRetry(() => that.getDeviceServices(deviceId));
}
},
fail(err) {
// 检查页面状态
if (!that.isPageActive) {
console.log('页面已离开,忽略服务获取错误');
return;
}
console.log("获取服务失败:", err);
that.addLog(`获取服务失败: ${err.errMsg} (错误码: ${err.errCode})`, 'error');
// 如果是连接错误,标记为未连接
if (err.errCode === 10004) {
that.isConnected = false;
that.addLog('检测到连接已断开', 'error');
return; // 连接断开时不再重试
}
// 延时后继续尝试
that.addLog('延时后继续尝试获取服务...', 'info');
that.scheduleRetry(() => that.getDeviceServices(deviceId));
}
});
}, 1000); // 修改为1秒延时
1 个回复
落英甘棠
连接成功后延迟1秒再去获取服务