小程序操作蓝牙进行读写
本文讲述小程序使用蓝牙进行数据的读写。
这篇将是全代码,但关键地方都会有注释。
一、打开适配器
initBLE:function(back) {
wx.openBluetoothAdapter({
success(res){
// ===== 打开成功 =====
this.searchBLE(); // 开始搜索蓝牙外设
// 在蓝牙打开的情况下突然关闭
wx.onBluetoothAdapterStateChange(function (res) {
if (!res.available) {
//蓝牙适配器是否可用
this.setData({
tipsBox: "tipsBox",
tipsTitle: "温馨提示",
tipsContent: "蓝牙未打开,请重新打开蓝牙"
})
}
})
},fail(err) {
wx.showToast({
title: '请检查手机蓝牙是否打开',
icon: 'none',
})
}
})
},
二、搜索蓝牙外设
// 开始搜索
searchBLE() {
let that =this;
BLEMag.bluetoothMag.startMonitorBluetoothSearch({
success(res) {
that.monitorSearchDevice(); // 监听蓝牙搜索回调
that.searchDevice(); // 开始蓝牙搜索
}
});
},
// 监听蓝牙搜索回调
monitorSearchDevice() {
var that = this;
wx.startBluetoothDevicesDiscovery({
allowDuplicatesKey: true,
interval: 0,
// ===== 搜索打开成功 =====
success: function () {
that.setData({
showProgress: false
})
},
// ===== 搜索打开失败 =====
fail: function (res) {
that.failCallback('蓝牙设备服务发现失败')
that.printLog("蓝牙设备服务发现失败: " + res.errMsg);
}
})
},
// 搜索蓝牙
searchDevice:function(back) {
var that = this;
var deviceArr = [];
wx.onBluetoothDeviceFound(function (res) {
res.devices.forEach(device => {
// TODO
// 做搜索到设备的处理
wx