因为最近写了小程序蓝牙连接设备、所以想分享出来让大家一起探讨探讨。可以加我微信x79818253
App({
globalData:{
lanya:'',//蓝牙状态提示
lanyaif:false,//蓝牙命令是否可执行
deviceId:'',
deviceIdli:[],
serviceId:'自己的',
characteristics:"自己的",
connectDeviceIndex:0,
lyspqi:true,//蓝牙适配器节流
},
onLaunch: function () {
this.startConnect();
},
/蓝牙链接部分****************/
//开启蓝牙适配 判断蓝牙是否可用
startConnect: function () {
var that = this;
this.globalData.lanya='正在开启蓝牙设配';
wx.openBluetoothAdapter({ //初始化小程序蓝牙模块,生效周期为调用wx.openBluetoothAdapter至调用wx.closeBluetoothAdapter或小程序被销毁为止。 在小程序蓝牙适配器模块生效期间,开发者可以正常调用下面的小程序API,并会收到蓝牙模块相关的on回调。
success: function (res) {
console.log(res)
that.getBluetoothAdapterState(); //获取本机蓝牙适配器状态 判断蓝牙是否打开
},
fail: function (err) {
console.log(err)
that.globalData.lanya='蓝牙初始化失败,请检查蓝牙是否打开';
}
});
wx.onBluetoothAdapterStateChange(function (res) { //监听手机蓝牙状态的改变
console.log('手机蓝牙状态改变',res)
var available = res.available;
if (available) {
if (that.globalData.lyspqi) {//蓝牙适配器节流
that.globalData.lyspqi = false;
that.getBluetoothAdapterState(); //获取本机蓝牙适配器状态 判断蓝牙是否打开
setTimeout(function(){
that.globalData.lyspqi = true;
},5000)
}
}
})
},
//获取本机蓝牙适配器状态 判断蓝牙是否打开
getBluetoothAdapterState: function () { //获取本机蓝牙适配器状态
var that = this;
wx.getBluetoothAdapterState({ //获取本机蓝牙适配器状态
success: function (res) {
// console.log(res)
var available = res.available, //蓝牙适配器是否可用
discovering = res.discovering; // 是否正在搜索设备
console.log(res)
if (!available) { //蓝牙适配器是不可用
that.globalData.lany ='设备无法开启蓝牙连接';
} else {//蓝牙适配器是可用
if (!discovering) { //蓝牙没有在搜索设备
that.startBluetoothDevicesDiscovery(); //开启扫描附近的蓝牙设备
that.getConnectedBluetoothDevices(); //获取在小程序蓝牙模块生效期间所有已发现的蓝牙设备,包括已经和本机处于连接状态的设备。
// console.log(999)
}
}
}
})
},
//开始搜索蓝牙设备提示蓝牙搜索。
startBluetoothDevicesDiscovery: function () {
var that = this;
wx.closeBluetoothAdapter({
success: function (res) {
console.log(res)
}
})
wx.openBluetoothAdapter({
success: function (res) {
console.log(res)
that.getBluetoothAdapterState(); //获取本机蓝牙适配器状态 判断蓝牙是否打开
},
fail: function (err) {
console.log(err)
that.globalData.lanya = '蓝牙初始化失败,请检查蓝牙是否打开';
}
});
that.globalData.lanya = '搜索蓝牙设备中';
wx.startBluetoothDevicesDiscovery({ //开始搜寻附近的蓝牙外围设备。注意,该操作比较耗费系统资源,请在搜索并连接到设备后调用 stop 方法停止搜索。
services: ["FFFF"], //蓝牙设备主 service 的 uuid 列表
allowDuplicatesKey: false, //是否允许重复上报同一设备, 如果允许重复上报,则onDeviceFound 方法会多次上报同一设备,但是 RSSI 值会有不同
success: function (res) {
if (!res.isDiscovering) { //未发现设备
that.globalData.lanya = '未发现可连接设备';
that.getBluetoothAdapterState(); //获取本机蓝牙适配器状态 判断蓝牙是否打开
} else { //发现设备
console.log('新设备列表已经建立')
that.onBluetoothDeviceFound(); //监听寻找到新设备的事件
}
},
fail: function (err) {
console.log(err);
}
});
},
//获取在小程序蓝牙模块生效期间所有已发现的蓝牙设备,包括已经和本机处于连接状态的设备。
getConnectedBluetoothDevices: function () {
console.log('已发现设备')
var that = this;
wx.getConnectedBluetoothDevices({ //根据 uuid 获取处于已连接状态的设备
services: [that.globalData.serviceId],
success: function (res) {
console.log("获取处于连接状态的设备", res);
var devices = res['devices'], flag = false, index = 0, conDevList = [];
devices.forEach(function (value, index, array) {
if (value['name'].indexOf('boke') != -1 ) {
// 如果存在包含FeiZhi字段的设备
flag = true;
index += 1;
conDevList.push(value['deviceId']);
that.globalData.deviceId = value['deviceId'];
return;
}
});
if (flag) {
that.globalData.connectDeviceIndex = 0;
that.loopConnect(conDevList);
} else {
if (that.getConnectedTimer) {
that.getConnectedTimer = setTimeout(function () {
that.getConnectedBluetoothDevices(); //获取在小程序蓝牙模块生效期间所有已发现的蓝牙设备,包括已经和本机处于连接状态的设备。
}, 5000);
}
}
},
fail: function (err) {
if (!that.getConnectedTimer) {
that.getConnectedTimer = setTimeout(function () {
console.log('获取小程序模块')
that.getConnectedBluetoothDevices(); //获取在小程序蓝牙模块生效期间所有已发现的蓝牙设备,包括已经和本机处于连接状态的设备。
}, 5000);
212313213211111111
}
}
});
},
//监听寻找到新设备的事件
onBluetoothDeviceFound: function () {
var that = this;
console.log('在蓝牙设备发现');
wx.onBluetoothDeviceFound(function (res) { //监听寻找到新设备的事件
console.log("1111111111111111111111111111111");
console.log(res);
if (res.devices[0]) {
var name = res.devices[0]['name']; //搜索到的设备名称
console.log(name);
if (name.indexOf('boke') != -1) { //indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。 如果要检索的字符串值没有出现,则该方法返回 -1。
var deviceId = res.devices[0]['deviceId']; //保存
that.globalData.deviceId = deviceId; //保存需要配对的设备id
console.log(that.globalData.deviceId);
that.startConnectDevices(); //发现了某个想配对的设备,则获取到该设备的deviceId,然后开始配对该设备
}
}
})
},
//发现了某个想配对的设备,则获取到该设备的deviceId,然后开始配对该设备
startConnectDevices: function (ltype, array) {
var that = this;
clearTimeout(that.getConnectedTimer);
that.getConnectedTimer = null;
clearTimeout(that.discoveryDevicesTimer);
wx.stopBluetoothDevicesDiscovery(); //停止搜寻附近的蓝牙外围设备。若已经找到需要的蓝牙设备并不需要继续搜索时,建议调用该接口停止蓝牙搜索。
this.isConnectting = true;
that.globalData.lanya = '蓝牙设备链接中...';
that.globalData.lanyaif = false;//false
wx.createBLEConnection({ // 连接低功耗蓝牙设备。
deviceId: that.globalData.deviceId,
success: function (res) {
console.log('蓝牙链接',res)
if (res.errCode == 0) {
that.discoveryDevicesTimer = setTimeout(function () {
that.globalData.lanya = '已连接蓝牙设备';
console.log("已连接蓝牙设备")
that.getService(that.globalData.deviceId); //链接设备 传入需要配对的设备id
}, 2000)
}
},
fail: function (err) {
that.globalData.lanya = '链接失败...';
if (ltype == 'loop') {
if (that.globalData.connectDeviceIndex < array.length){
that.globalData.connectDeviceIndex += 1;
}
that.loopConnect(array);
} else {
console.log('链接失败')
that.startBluetoothDevicesDiscovery(); //开始搜索蓝牙设备提示蓝牙搜索。
that.getConnectedBluetoothDevices(); //获取在小程序蓝牙模块生效期间所有已发现的蓝牙设备,包括已经和本机处于连接状态的设备。
}
},
complete: function () {
console.log('complete connect devices');
this.isConnectting = false;
}
});
},
getService: function (deviceId) {
var that = this;
// 监听蓝牙连接
wx.onBLEConnectionStateChange(function (res) {
console.log(res,12);
if(!res.connected){
that.globalData.lanya = '蓝牙设备断开链接';
console.log('蓝牙设备断开链接')
that.globalData.lanyaif=false;
clearTimeout(that.globalData.yxsj)
that.getBluetoothAdapterState()
}else{
that.globalData.lanya = '蓝牙设备已连接';
console.log('蓝牙设备已连接')
that.globalData.lanyaif = true;
}
});
// 获取蓝牙设备service值
wx.getBLEDeviceServices({
deviceId: deviceId,
success: function (res) {
console.log(res);
that.getCharacter(deviceId, res.services);
console.log(res.services, 0)
}
})
},
getCharacter: function (deviceId, services) { //读取服务的特征值。
var that = this;
console.log(that.globalData.serviceId,1)
services.forEach(function (value, index, array) {
console.log(value.uuid,1111)
if (value.uuid == that.globalData.serviceId) {
console.log('成功')
that.globalData.serviceId = array[index].uuid;
}
});
console.log(that.globalData.serviceId,2)
wx.getBLEDeviceCharacteristics({ //获取特征值
deviceId: deviceId,
serviceId: that.globalData.serviceId, //
success: function (res) {
console.log(res)
let characteristics = res.characteristics;
characteristics.forEach(function (value, index, array) {
if (value.uuid == that.globalData.characteristics) {
console.log('成功')
that.globalData.characteristics = array[index].uuid;
console.log(that.globalData.characteristics )
}
});
},
fail: function (err) {
console.log('获取特征值失败',err);
},
complete: function () {
console.log('complete');
}
})
},
// 如果扫描到的设备中没有想要连接的设备,可以尝试使用系统蓝牙手动配对,然后再小程序中调用getConnectedBluetoothDevices() 获取本机已配对的蓝牙设备,然后过滤设备(可能获取多个已配对的蓝牙设备)。将以获取的蓝牙设备deviceId放入到一个数组中调用自定义方法this.loopConnect(); 思路:通过递归调用获取已配对蓝牙设备的deviceId,如果获取到了就去连接,devicesId[x] 为空说明上传调用getConnectedBluetoothDevices()时获取到的已配对设备全部连接失败了。则开启重新获取已配对蓝牙设备,并开启扫描附近蓝牙设备。
loopConnect: function (devicesId) {
var that = this;
var listLen = devicesId.length;
if (devicesId[this.globalData.connectDeviceIndex]) {
this.deviceId = devicesId[this.globalData.connectDeviceIndex];
this.startConnectDevices('loop', devicesId);
} else {
console.log('已配对的设备小程序蓝牙连接失败');
that.startBluetoothDevicesDiscovery();
that.getConnectedBluetoothDevices();
}
},
shebeiqueren:function(){ //设备确认
var that = this;
wx.notifyBLECharacteristicValueChange({
deviceId: that.globalData.deviceId, //设备mac IOS和安卓系统不一样
serviceId: that.globalData.serviceId, //服务通道,这里主要是notify
characteristicId: that.globalData.characteristics, //notify uuid
state: true,
success: function (res) {
console.log("开启notify 成功")
console.log(res)
//TODO onBLECharacteristicValueChange 监听特征值 设备的数据在这里获取到
wx.onBLECharacteristicValueChange(function (characteristic) {
console.log(characteristic)
console.log('characteristic value comed:')
let buffer = characteristic.value
let dataView = new DataView(buffer)
let dataResult = []
console.log("拿到的数据")
console.log("dataView.byteLength", dataView.byteLength)
for (let i = 0; i < dataView.byteLength; i++) {
console.log("0x" + dataView.getUint8(i).toString(16))
dataResult.push(dataView.getUint8(i).toString(16))
}
console.log('设备确认', dataResult)
})
},
fail: function (res) {
console.log(res)
}
})
var hex = 'AA010506413446442B' //16进制
var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {
return parseInt(h, 16)
}))
var buffer = typedArray.buffer
wx.writeBLECharacteristicValue({
deviceId: that.globalData.deviceId,
serviceId: that.globalData.serviceId,
characteristicId: that.globalData.characteristics,
value: buffer,
success: function (res) {
console.log('writeBLECharacteristicValue success', res.errMsg)
},
fail: function (err) {
console.log(err);
}
})
}
})