微信小程序的便利性,让我们很多时候,希望能通过微信小程序实现对蓝牙设备的控制,下面我们介绍一下如何实现这一功能。
该项目是通过微信小程序来控制雾化器的工作模式及工作时间,希望能对大家提供一点帮助。
先看界面:
1、要访问并控制蓝牙设备首先要搜索并连接上设备,代码如下:
CreatedLink() {
let that = this;
wx.openBluetoothAdapter({
success: function(res) {
if (!that.data.isConnected) {
that.startBluetoothDevicesDiscovery();
wx.showLoading({
title: '搜索中',
})
}
},
fail: function(res) {
wx.showToast({
title: '请先开启蓝牙',
icon: 'none',
duration: 1000
})
}
});
},
startBluetoothDevicesDiscovery: function() {
var that = this;
wx.startBluetoothDevicesDiscovery({
success: function(res) {
console.log("discovery", res);
if (res.errCode == 0) {
that.getConnect();
}
},
});
},
getConnect: function() {
var that = this;
var timer = setInterval(function() {
wx.getBluetoothDevices({
success: function(res) {
console.log("devices", res);
for (var i = 0; i < res.devices.length; i++) {
if (res.devices[i].name == that.data.deviceName) {
wx.hideLoading();
wx.showLoading({
title: '连接中',
})
that.setData({
isFinded: true
});
clearInterval(timer);
that.setData({