//1、打开蓝牙适配器
openBluetoothAdapter() {
uni.openBluetoothAdapter({
success: res => {
console.log('openBluetoothAdapter success', res);
this.startBluetoothDevicesDiscovery();
},
fail: res => {
if (res.errCode === 10001) {
uni.showToast({
title: '请打开蓝牙',
icon: 'none'
});
uni.onBluetoothAdapterStateChange(res => {
console.log('onBluetoothAdapterStateChange', res);
if (res.available) {
//这里是调用开启蓝牙搜索
this.startBluetoothDevicesDiscovery();
}
});
}
}
});
},
//2、开启蓝牙搜索
startBluetoothDevicesDiscovery() {
if (this.discoveryStarted) {
return;
}
this.discoveryStarted = true;
uni.startBluetoothDevicesDiscovery({
allowDuplicatesKey: true,
success: res => {
console.log('startBluetoothDevicesDiscovery success', res);
//这里调用开始监听蓝牙设备列表
this.onBluetoothDeviceFound();
}
});
},
//3、监听蓝牙设备列表
onBluetoothDeviceFound() {
uni.onBluetoothDeviceFound(res => {
this.bluthlist.push(res)
}
this.stopBluetoothDevicesDiscovery()
//此方法是去重 去掉重复的蓝牙设备
this.bluthlist = [...new Set(this.bluthlist)]
//调用筛选所需的蓝牙
this.getlist()
},
//此方法筛选自己所需要的蓝牙蓝牙设备
getlist() {
this.bluthlist.forEach(val => {
val.devices.forEach(item => {
if (item.name.slice(0, 5) == 'CTJHQ') {
item.name = '丁丁浇花器'
let arrlists = []
arrlists.push(item)
console.log(item, '100')
// 去重
this.devicesList = [...new Set(arrlists)]
}
})
})
if(this.devicesList.length == 0){
console.log(this.devicesList.length,'1010111')
this.tishiflag = true
}
},
//4、建立连接 给个点击蓝牙事件调用这个回调函数即可
createBLEConnection(device) {
console.log(11)
const deviceId = device.deviceId;
uni.createBLEConnection({
deviceId,
success: res => {
console.log(res.errMsg, '连接')
uni.showLoading({
title: '连接蓝牙设备中...'
});
if (res.errMsg == 'createBLEConnection:ok') {
uni.showLoading({
title: '连接成功'
});
setTimeout(() => {
uni.navigateTo({
url: '/pages/device/wifilist/index'
})
}, 1000)
} else {
uni.showLoading({
title: '连接失败'
});
}
}
});
//连接成功后停止蓝牙搜索
this.stopBluetoothDevicesDiscovery();
},
//停止蓝牙搜搜
stopBluetoothDevicesDiscovery() {
uni.stopBluetoothDevicesDiscovery();
this.discoveryStarted = false;
},