createBLEConnection() {
//设备deviceId
let deviceId = this.deviceId;
let self = this;
try{
return new Promise((resolve, reject) => {
uni.showLoading({
mask: true,
title: '设备连接中,请稍候...'
})
uni.getConnectedBluetoothDevices({
success: function(res) {
var devices = res.devices;
var isDeviceConnected = false;
for (var i = 0; i < devices.length; i++) {
if (devices[i].deviceId === deviceId) {
isDeviceConnected = true;
break;
}
}
if (isDeviceConnected) {
uni.hideLoading();
// 设备已连接,可以直接执行操作
self.showToast(`蓝牙设备已连接,请勿重复操作`)
} else {
uni.getBluetoothAdapterState({
success: function (res) {
console.log('getBluetoothAdapterState success', res)
if (res.discovering) {//停止搜索后,再连接
uni.stopBluetoothDevicesDiscovery({
success: function(res) {
uni.createBLEConnection({
deviceId,
timeout:10000,
success: (res) => {
uni.hideLoading();
self.showToast(`连接蓝牙设备成功`)
},
fail: (err) => {
uni.hideLoading();
self.showToast(`连接蓝牙设备失败` + JSON.stringify(err));
}
})
console.log('stopBluetoothDevicesDiscovery success')
},
fail: function(res) {
self.showToast(`连接蓝牙设备失败` + JSON.stringify(res));
console.log('stopBluetoothDevicesDiscovery fail')
}
})
} else {
console.log('未在搜索蓝牙设备')
// 未在搜索蓝牙设备的逻辑处理
uni.createBLEConnection({
deviceId,
timeout:10000,
success: (res) => {
uni.hideLoading();
self.showToast(`连接蓝牙设备成功`)
},
fail: (err) => {
uni.hideLoading();
self.showToast(`连接蓝牙设备失败` + JSON.stringify(err));
}
})
}
},
fail: function (res) {
uni.hideLoading();
self.showToast(`获取蓝牙状态失败` + JSON.stringify(res));
console.log('getBluetoothAdapterState fail', res)
}
})
}
}
})
});
}catch(e){
uni.hideLoading()
self.showToast(`连接蓝牙异常,请断开蓝牙连接后重试`);
}
}

- 发布:2023-06-21 14:24
- 更新:2023-06-21 14:47
- 阅读:579
产品分类: uniapp/App
PC开发环境操作系统: Windows
PC开发环境操作系统版本号: win10
HBuilderX类型: 正式
HBuilderX版本号: 3.8.4
手机系统: Android
手机系统版本号: Android 11
手机厂商: 小米
手机机型: iphone11
页面类型: vue
vue版本: vue2
打包方式: 云端
项目创建方式: HBuilderX
示例代码:
操作步骤:
第一台连接成功后,第二台连接时会提示{"errMsg":"createBLEConnection:fail operate time out","errCode":10012,"code":10012} ,使用closeBLEConnection断开第一台设备连接后,第二台设备才可成功连接
第一台连接成功后,第二台连接时会提示{"errMsg":"createBLEConnection:fail operate time out","errCode":10012,"code":10012} ,使用closeBLEConnection断开第一台设备连接后,第二台设备才可成功连接
预期结果:
可直接多台设备连接同一蓝牙设备
可直接多台设备连接同一蓝牙设备
实际结果:
多台设备不可连接同一蓝牙设备
多台设备不可连接同一蓝牙设备
bug描述:
多台设备不能连接同一台蓝牙打印机,但蓝牙打印机是支持多台终端连接
第一台连接成功后,第二台连接时会提示{"errMsg":"createBLEConnection:fail operate time out","errCode":10012,"code":10012} ,使用closeBLEConnection断开第一台设备连接后,第二台设备才可成功连接
1***@qq.com (作者)
蓝牙打印机是中心设备,手机是外设,目前的情况是多个手机不能连接同一个蓝牙打印机。
2023-06-21 14:49
昭昭L
回复 1***@qq.com: 打印机吗?那确实手机是作为外设。实在不行可以用uts搞个ble插件
2023-06-21 15:05
1***@qq.com (作者)
回复 昭昭L: 是的,需要连接打印机,现在就只能连一台手机
2023-06-21 16:23