let blueName = "asdsadsa",//想要连接的蓝牙名
initFlag = false,//是否继续查找
connected = false;//是否连接上
Page({
onLoad: function (options) {
initFlag = false;
connected = false;
this.initBlue();//初始化
},
onHide: function () { },
onUnload: function () {
initFlag = true;
},
initBlue: function () {//1、初始化
var _this = this;
wx.openBluetoothAdapter({//初始化蓝牙模块
success: function (res) {
_this.startBluetoothDevicesDiscovery();//开始搜索蓝牙设备
},
fail(res) {
_this.showTip();//提示打开蓝牙
wx.onBluetoothAdapterStateChange(function (res) {//监听蓝牙打开关闭
if (res.available && !res.discovering && !connected) {//可用 且不在搜索中 且没有连接
_this.startBluetoothDevicesDiscovery()
}
})
}
})
},
startBluetoothDevicesDiscovery: function () {//2、开始搜寻附近的蓝牙外围设备
var _this = this;
wx.startBluetoothDevicesDiscovery({
// services:["00000000-0000-0000-0000-000000071920"],//根据uuid过滤蓝牙 搜索速度加快
allowDuplicatesKey: true,//是否允许重复上报同一设备。
success: function (res) {
setTimeout(function () {//28s超时没找到 关闭搜索
if (!initFlag) {
initFlag = true;//不搜索了
_this.stopBluetoothDevicesDiscovery();
wx.closeBluetoothAdapter({
success(res) {
console.log('关闭蓝牙模块');
}
})
}
}, 28000)
setTimeout(function () {
_this.getBluetoothDevices();//获取搜索到的设备 同时进行
}, 300);
_this.onBluetoothDeviceFound();//监听搜索到新设备 同时进行
},
fail: function (err) {
console.log(err);
}
});
},
getBluetoothDevices: function () {//3、获取在蓝牙模块生效期间所有已发现的蓝牙设备。
var _this = this;
wx.getBluetoothDevices({
success: function (res) {
let deviceA = res.devices;
for (let i = 0; i < deviceA.length; i++) {
let name = deviceA[i].name;
if (name == blueName) {//找到后连接并停止搜素
let blueDeviceId = deviceA[i].deviceId;//设置蓝牙设备id
wx.setStorageSync('blueDeviceId', blueDeviceId);//设置蓝牙设备id
initFlag = true;//停止循环
_this.connetBlue(blueDeviceId);//连接蓝牙
_this.stopBluetoothDevicesDiscovery();//停止搜索
break;
}
}
if (!initFlag) {//没找到 递归调用
setTimeout(function () {
_this.getBluetoothDevices();
}, 800)
}
}
})
},
onBluetoothDeviceFound: function () {//3、监听寻找到新设备的事件
var _this = this;
wx.onBluetoothDeviceFound(function (res) {
res.devices.forEach(device => {
if (!device.name) {
return;
}
let name = device.name;
if (name == blueName) {//根据设备名查找需要连接的蓝牙
let blueDeviceId = device.deviceId;
wx.setStorageSync('blueDeviceId', blueDeviceId);//设置蓝牙设备id
initFlag = true;//停止循环
_this.connetBlue(blueDeviceId);
_this.stopBluetoothDevicesDiscovery();
}
})
})
},
connetBlue: function (blueDeviceId) {//4、连接低功耗蓝牙设备
var _this = this;
if (connected) {//已连接
return;
}
wx.createBLEConnection({
deviceId: blueDeviceId,
success: function (res) {
connected = true;//已经连接上
},
fail: function () {//连接失败 定时重连
setTimeout(function () {
_this.connetBlue(blueDeviceId)
}, 200)
}
})
},
showTip: function () {//提示
wx.showToast({
title: '请打开蓝牙',
duration: 2000
})
},
stopBluetoothDevicesDiscovery: function () {//停止搜索
wx.stopBluetoothDevicesDiscovery({
success: function (res) {
console.log('关闭蓝牙搜索');
}
})
}
})
微信小程序蓝牙开发2、查找蓝牙并连接
最新推荐文章于 2024-05-12 16:34:19 发布