功能介绍
结合微信小程序,实现扫描周围BLE4.0设备,并显示在微信小程序上。并可读取设备的服务值、特征值。
小程序体验
代码实现
- index:点击顶部搜索按钮,展示周围蓝牙设备(UUID、RSSI、广播)。展示完毕后,可以点击"连接设备",并连接设备
//点击搜索按钮方法
scanBtnClick:function(){
this.reloadBLEData();
},
reloadBLEData(){
var that = this;
wx.openBluetoothAdapter({
success:function(res){
wx.getBluetoothAdapterState({
success:function(res){
var available = res.available;
var discovering = res.discovering;
if (!available){
wx.showToast({
title:"蓝牙不可用"
});
wx.hideLoading({
complete: (res) => {},
});
return;
}
if(!discovering){
var deviceArr = [];
// 开始搜索周围蓝牙设备
wx.startBluetoothDevicesDiscovery({
// allowDuplicatesKey: true,
success:function(res){
wx.hideLoading({
complete: (res) => {},
});
//发现周围蓝牙设备
wx.onBluetoothDeviceFound((result) => {
var device = result.devices[0];
console.log(result.devices[0]);
var deviceName = device.localName;
var deviceId = device.deviceId;
var rssi = device.rssi;
var adid = device.advertisServiceUUIDs;
if(deviceArr.length == 0){
deviceArr.push(device);
} else{
//对数组中重复的数据去重
deviceArr.forEach(function(item, index, arr) {
if(arr.length > 0 && item.localName == deviceName){
arr.splice(index,1);
console.log('删除');
}
});
deviceArr.push(device);
console.log('添加');
}
that.setData({
//存放蓝牙设备数组
deviceArr:deviceArr,
})
})
},
})
}
},
})
},
fail:function(res){
wx.hideLoading({
complete: (res) => {},
});
wx.showToast({
title: '请先开启蓝牙',
image:'../../images/fail.png'
});
}
})
},
//点击链接
connectTap(res){
var deviceName = res.currentTarget.dataset.devicename;
var deviceId = res.currentTarget.dataset.deviceid;
wx.stopBluetoothDevicesDiscovery({
});
wx.navigateTo({
url: '../device/device?deviceName='+deviceName+'&deviceId='+deviceId,
})
},
- device:展示已经连接设备的的服务值、特征值(read、write、notify)
//处理连接后设备的服务、特征值
wx.getBLEDeviceServices({
deviceId: deviceId,
success:function(res){
var serviceIdArr = [];
for (var i = 0; i <= res.services.length - 1; i++) {
var serviceId = res.services[i].uuid;
serviceIdArr.push(serviceId);
that.setData({
serviceIdArr: serviceIdArr
})
console.log('-----------'+serviceIdArr);
}
var bleDataArr = [];
that.data.serviceIdArr.forEach(element => {
var bleDataDict = {};
wx.getBLEDeviceCharacteristics({
deviceId: deviceId,
serviceId: element,
success:function(res){
bleDataDict.deviceId = element;
bleDataDict.characteristics = res.characteristics;
bleDataArr.push(bleDataDict);
wx.hideLoading({
complete: (res) => {},
});
that.setData({
bleDataArr:bleDataArr
})
}
})
});
console.log(bleDataArr);
}
})
- write:对获取了可写特征值的设备进行写操作
writeBLEValue:function(deviceId,serviceId,charaId,value){
console.log('------'+deviceId+'------'+serviceId+'-------'+charaId);
wx.writeBLECharacteristicValue({
characteristicId: charaId,
deviceId: deviceId,
serviceId: serviceId,
value: value,
success:function(res){
console.log('成功'+JSON.stringify(res));
wx.showToast({
title: '写入成功',
})
},
fail:function(res){
console.log('失败'+JSON.stringify(res));
var errorMsg = '';
if(res.errCode == '10000'){
errorMsg = '未初始化蓝牙适配器';
}else if(res.errCode == '10001'){
errorMsg = '当前蓝牙适配器不可用';
}else if(res.errCode == '10002'){
errorMsg = '没有找到指定设备';
}else if(res.errCode == '10003'){
errorMsg = '连接失败';
}else if(res.errCode == '10004'){
errorMsg = '没有找到指定服务';
}else if(res.errCode == '10005'){
errorMsg = '没有找到指定特征值';
}else if(res.errCode == '10006'){
errorMsg = '当前连接已断开';
}else if(res.errCode == '10007'){
errorMsg = '当前特征值不支持此操作';
}else if(res.errCode == '10008'){
errorMsg = '其余所有系统上报的异常';
}else if(res.errCode == '10009'){
errorMsg = '系统版本低于 4.3 不支持 BLE';
}else if(res.errCode == '10012'){
errorMsg = '连接超时';
}else if(res.errCode == '10013'){
errorMsg = '连接 deviceId 为空或者是格式不正确';
}
wx.showToast({
title: errorMsg,
image:'../../images/fail.png'
})
}
});
},
//16进制数据处理
string2buffer: function (str) {
// 首先将字符串转为16进制
let val = ""
for (let i = 0; i < str.length; i++) {
if (val === '') {
val = str.charCodeAt(i).toString(16)
} else {
val += ',' + str.charCodeAt(i).toString(16)
}
}
// 将16进制转化为ArrayBuffer
return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {
return parseInt(h, 16)
})).buffer
},