上一篇 微信小程序搜索蓝牙设备
选择搜索到的蓝牙设备列表中的设备,点击链接设备按钮进行蓝牙设备的连接。
一、data 里面定义一个参数:isCreateBLEConnection 蓝牙设备连接状态
isCreateBLEConnection:false, //蓝牙设备连接状态
二、onload 中自定义蓝牙低功耗连接状态改变事件的监听 onBLEConnectionStateChangeCallback 代码
//蓝牙低功耗连接状态改变事件的监听
Bluetooth.onBLEConnectionStateChangeCallback = function(res){
//console.log(res);
if(res.deviceId == that.data.deviceId)
{
that.setData({isCreateBLEConnection:res.connected});
}
};
三、连接和断开蓝牙设备
//连接设备 按钮事件
connectDeviceClick()
{
var that=this;
let deviceId = that.data.deviceId;
if(deviceId!='')
{
Bluetooth.CheckSystemInfo().then(res=>{
if(res)
{
wx.showLoading({
title: '连接中',
mask:true
});
//console.log(that.data.isStartBluetoothdeviceDiscovery);
//如果正在进行蓝牙搜索,先停止蓝牙搜索
if(that.data.isStartBluetoothdeviceDiscovery)
{
that.stopBluetoothDevicesDiscovery();
}
that.createBLEConnection().then(
function(res){
wx.hideLoading();
},
function(err){
wx.hideLoading();
}
);
}
});
}
else
{
wx.showModal({
content: '请先选择要连接的设备',
showCancel:false,
success: function (res) {
if (res.confirm) {
console.log('用户点击确定');
}
}
});
}
},
//断开设备
closeBLEConnection()
{
var that=this;
let deviceId = that.data.deviceId;
Bluetooth.closeBLEConnection(deviceId).then(
function(res){
console.log('蓝牙设备连接状态', that.data.isCreateBLEConnection);
that.seeConsole('断开连接设备成功');
//that.setData({ isCreateBLEConnection: false });
//移除蓝牙低功耗连接状态改变事件的监听函数
Bluetooth.offBLEConnectionStateChange();
//移除蓝牙低功耗设备的特征值变化事件的全部监听函数
Bluetooth.onBLECharacteristicValueChange();
},
function(err){
that.seeConsole('断开连接设备失败');
}
);
},
//断开设备 按钮事件
closeDeviceClick()
{
var that=this;
let isCreateBLEConnection = that.data.isCreateBLEConnection;
if(isCreateBLEConnection)
{
Bluetooth.CheckSystemInfo().then(res=>{
if(res)
{
that.closeBLEConnection();
}
});
}
else
{
wx.showModal({
content: '请先连接设备',
showCancel:false,
success: function (res) {
if (res.confirm) {
console.log('用户点击确定');
}
}
});
}
},
四、页面代码
<view class="event-bar" list-item>
<view class="view_left">
<button class="btn_bg" bindtap="connectDeviceClick">连接设备</button>
</view>
<view class="view_right">
<button class="btn_bg" bindtap="closeDeviceClick">断开连接</button>
</view>
</view>
下一篇 将继续介绍 微信小程序获取连接的蓝牙设备的服务及特征值