「这是我参与2022首次更文挑战的第15天,活动详情查看:2022首次更文挑战」
大家好,我是 摸鱼小公举,真正的强者,不会怨天尤人,如果想不被别人看轻,你就只有付出比别人多十倍百倍的努力,才能站的比别人更高。上一篇文章是 js 中 Map 和 Set 的用法以及区别 ;今天我们来学习一下微信小程序api蓝牙的使用。
蓝牙调用流程
1,初始化蓝牙
wx.openBluetoothAdapter();
starble(){
wx.openBluetoothAdapter({
success: res => {
console.log("初始化成功", res);
//根据后台接口返回mac 赋值为 this.data.mac ,上报发现外围的设备时需要用来匹配。
// 调用开始搜索外围设备的方法
this.starsherchble()
},
fail: res => {
console.log("初始化失败", res);
}
})
}
2,开始搜索外围蓝牙设备
wx.startBluetoothDevicesDiscovery();
starsherchble() {
wx.startBluetoothDevicesDiscovery({
services: [],
success: res => {
// console.log('开启搜索成功', res);
this.sheachBLE();
},
fail: res => {
// console.log('开启搜索失败', res);
},
})
},
3,上报发现外围的设备
wx.onBluetoothDeviceFound();
sheachBLE() {
wx.onBluetoothDeviceFound(devs => {
console.log('上报发现的外围设备', devs.devices);
for (let i = 0; i < devs.devices.length; i++) {
if (devs.devices[i].name && devs.devices[i].name.indexOf(this.data.mac) != -1) {
//停止搜索蓝牙
wx.stopBluetoothDevicesDiscovery({
complete: res => {
console.log('停止搜索蓝牙', res);
//搜索到蓝牙设备后调用连接蓝牙的方法
this.linkblue(devs.devices[i].deviceId);
}
});
console.log('找到蓝牙设备了,就不往下找了');
break;
}
}
})
},
4,连接蓝牙设备
wx.createBLEConnection();
linkblue(device) {
wx.createBLEConnection({
deviceId: device, //蓝牙设备 id
success: res => {
this.data.devices_id = device;
setTimeout(() => {
//蓝牙连接成功获取链接设备的服务uuid
this.getSevice();
}, 1000);
},
fail: res => {
console.log('连接失败', res);
}
})
},
5,获取连接设备的服务uuid
wx.getBLEDeviceServices();
getSevice() {
wx.getBLEDeviceServices({
deviceId: this.data.devices_id, //蓝牙设备 id
success: res => {
console.log('获取设备的服务uuid', res);
for (let i = 0; i < res.services.length; i++) {
let _uuid = res.services[i].uuid.replace(/-/g, "");
// 此对应的uuid是客户给的蓝牙设备相关文档里的
if (_uuid === '6E400001B5A3F393E0A9E50E24DCCA9E') {
this.data.services_id = res.services[i].uuid;
setTimeout(() => {
//获取uuid成功后,获取已链接设备的所有特征值
this.getCharact();
}, 1000);
break;
}
};
},
fail: res => {
console.log('未获取到设备的服务uuid', res);
}
})
},
6, 获取已链接设备的所有特征值
wx.getBLEDeviceCharacteristics();
getCharact() {
wx.getBLEDeviceCharacteristics({
deviceId: this.data.devices_id, //蓝牙设备 id
serviceId: this.data.services_id, //蓝牙服务 uuid
success: res => {
console.log('获取设备所有特征值', res);
for (let i = 0; i < res.characteristics.length; i++) {
// 6E400002 write 的特征值 6E400003 notify的特征值
if (res.characteristics[i].uuid.toUpperCase().indexOf('6E400002') != -1) {
this.data.write_id = res.characteristics[i].uuid;
};
if (res.characteristics[i].uuid.toUpperCase().indexOf('6E400003') != -1) {
this.data.notify_id = res.characteristics[i].uuid;
};
};
setTimeout(() => {
// 获取所需特征值成功之后开启notify功能
this.openNotify();
}, 1500);
},
fail: res => {
console.log('未获取到已链接设备的所有特征值', res)
}
})
},
7, 开启notify功能
必须先启用 wx.notifyBLECharacteristicValueChange();才能监听到设备 characteristicValueChange 事件
openNotify() {
wx.notifyBLECharacteristicValueChange({
state: true,
deviceId: this.data.devices_id, //蓝牙设备 id
serviceId: this.data.services_id, //蓝牙服务 uuid
characteristicId: this.data.notify_id, //蓝牙特征的 uuid
success: res => {
console.log('notify成功', res);
//开启notify成功后调用监听特征值变化的方法
this.characteristicChange();
},
fail: res => {
console.log('notify失败', res)
}
})
},
8,监听特征值变化
wx.onBLECharacteristicValueChange();//发送蓝牙指令成功后会返回
characteristicChange() {
wx.onBLECharacteristicValueChange(characteristic => {
console.log('监听特征值发生改变了', characteristic);
//characteristic.value ArrayBuffer数据类型 ,这里要转成16进制的值
let _token = Util.ab2hex(characteristic.value).join('');
// 我这里是监听到了开锁的蓝牙指令
if (_token.indexOf('7b5b019200') != -1) {
// 匹配到客户给蓝牙文档里的开锁指令后,
this.readLoad();
};
})
},
// arraybuffer转16进制字符串的方法如下
const ab2hex = buffer => {
var hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function (bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr;
}
9, 开始发送蓝牙指令
wx.writeBLECharacteristicValue();向蓝牙低功耗设备特征值中写入二进制数据。注意:必须设备的特征支持 write 才可以成功调用。
这里发送指令后,监听特征值变化的方法会返回对应的状态来显示是否真的发送指令成功
openWrite() {
let _dataArr = ['7B', '5B', '01', '61', '00', '61'];
console.log('开锁指令', '7B5B01610061')
let buffer = Util.hex2ab(_dataArr);
wx.writeBLECharacteristicValue({
deviceId: this.data.devices_id, //蓝牙设备 id
serviceId: this.data.services_id, //蓝牙服务 uuid
characteristicId: this.data.write_id, //蓝牙特征的 uuid
value: buffer,
success: res => {
console.log('开锁成功success', res);
},
fail: res => {
console.log('开锁失败success', res);
}
})
},
// 16进制字符串转arraybuffer
const hex2ab =(str) => {
if (!str) {
return new ArrayBuffer(0);
}
var buffer = new ArrayBuffer(str.length);
var dataView = new DataView(buffer)
for (var i = 0, len = str.length; i < len; i++) {
var code = parseInt(str[i], 16)
dataView.setUint8(i, code)
}
return buffer;
}
10,完成需要的操作功能后释放蓝牙
wx.closeBLEConnection();
wx.closeBluetoothAdapter();
//既然我这里时开锁指令,那么就应该发送关锁指令成功之后关闭蓝牙连接;关锁指令发送跟开锁指令是一样的操作;就要看监听特征值返回的状态是开锁还是关锁才能进行判断。
wx.closeBluetoothAdapter({
deviceId: this.data.devices_id,
success(res) {
console.log('关闭蓝牙成功!!', res);
wx.closeBluetoothAdapter({
success(res) {
console.log('释放蓝牙成功', res);
},
fail(res) {
console.log('释放蓝牙失败', res);
}
});
},
fail(res) {
console.log('关闭蓝牙失败', res);
}
});
错误返回处理:以上api调用返回错误码详情请参考微信官方文档小程序。
结语:
关于微信小程序蓝牙api的调用过程中会遇到各种各样的问题,不过还是希望大家能耐心的解决它。好了文章到此就结束了,欢迎大家( 点赞+评论+关注 ) 有问题可以来互相交流一下。希望这篇文章对大家有帮助,也希望大家多多支持我,今天是我参与2022首次更文挑战的第15天,加油!