微信小程序实现对蓝牙设备的控制

微信小程序的便利性,让我们很多时候,希望能通过微信小程序实现对蓝牙设备的控制,下面我们介绍一下如何实现这一功能。

该项目是通过微信小程序来控制雾化器的工作模式及工作时间,希望能对大家提供一点帮助。

先看界面:

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({
                  deviceId: res.devices[i].deviceId
                });
                console.log('设备号', that.data.deviceId);
                console.log("开始尝试建立连接");
                wx.createBLEConnection({
                  deviceId: that.data.deviceId,
                  timeout: 10000,
                  success: function(res) {
                    console.log(res);
                    if (res.errCode == 0) {
                      console.log('连接成功')
                      that.setData({
                        isConnected: true
                      });
                      wx.stopBluetoothDevicesDiscovery();
                    } else {
                      wx.showModal({
                        title: '提示',
                        content: '不能正常对蓝牙设备进行连接',
                        showCancel: false
                      })
                    }
                  },
                  fail: (res) => {
                    wx.hideLoading();
                    if (res.errCode == 10012) {
                      wx.showModal({
                        title: '提示',
                        content: '连接超时',
                        showCancel: false
                      })
                    }
                    console.warn("fail", res);
                  },
                  complete: () => {
                    wx.hideLoading();
                  }
                })
                break;
              }
            }
          }
        });
      },
      3000);
    setTimeout(function() {
      if (!that.data.isFinded && !that.data.isConnected) {
        clearInterval(timer);
        that.setData({
          isFailed: false
        });
        wx.hideLoading();
        wx.showModal({
          title: '提示',
          content: '搜索蓝牙超时',
          showCancel: false
        })
      }
    }, 12000);
  },

对了,手机蓝牙要打开并确保微信对蓝牙设备的访问权限。

2、连接上蓝牙后,根据自己的需求,是监听蓝牙设备还是发送控制命令给蓝牙设备,代码略有不同,另外,不同的蓝牙设备,characteristicId会有所不同。

监听蓝牙设备代码:

getuuid(){
    let that = this;
    if(that.data.isConnected && that.data.isFailed){
    wx.showLoading({
      title: '获取serviceId',
    })
    console.log("开始获取设备信息");
    wx.getBLEDeviceServices({
      deviceId: that.data.deviceId,
      success(getServicesRes) {
        console.log("getServicesRes", getServicesRes);
        let service = getServicesRes.services[1]
        let serviceId = service.uuid
        wx.showLoading({
          title: '获取characteristicId',
        })
        wx.getBLEDeviceCharacteristics({
          deviceId: that.data.deviceId,
          serviceId: serviceId,
          success(getCharactersRes) {
            console.log("getCharactersRes", getCharactersRes);
            wx.hideLoading();
            let characteristic = getCharactersRes.characteristics[0]
            let characteristicId = characteristic.uuid
            that.setData({
              serviceId: serviceId,
              characteristicId: characteristicId
            })
            console.log('成功获取uuId', that.data.serviceId, that.data.characteristicId);
            wx.notifyBLECharacteristicValueChange({
              state: true,
              deviceId: that.data.deviceId,
              serviceId: serviceId,
              characteristicId: getCharactersRes.characteristics[2].uuid,
              success() {
                console.log('开始监听特征值')
                wx.onBLECharacteristicValueChange(function (onNotityChangeRes) {
                  console.log('监听到特征值更新', onNotityChangeRes);
                  let characteristicValue = that.ab2hex(onNotityChangeRes.value);
                  wx.showModal({
                    title: '监听到特征值更新',
                    content: `更新后的特征值(16进制格式):${characteristicValue}`,
                    showCancel: false
                  })
                })
              },
              fail: (res) => {
                console.warn("监听特征值失败");
              }
            })
          },
          fail: (res) => {
            console.warn("获取特征值信息失败", res);
          },
          complete: (res) => {
            console.log('获取服务信息完成',res);
            wx.hideLoading();
          }
        })
      },
      fail: (res) => {
        console.warn("获取服务信息失败", res);
      },
      complete: () => {
        wx.hideLoading();
      }
    })
    }else{
      wx.showToast({
        title: '请先连接蓝牙',
      })
    }
  },

发送指令代码:

getuuid(){
    let that = this;
    if(that.data.isConnected && that.data.isFailed){
    wx.showLoading({
      title: '获取serviceId',
    })
    console.log("开始获取设备信息");
    wx.getBLEDeviceServices({
      deviceId: that.data.deviceId,
      success(getServicesRes) {
        console.log("getServicesRes", getServicesRes);
        let service = getServicesRes.services[1]
        let serviceId = service.uuid
        wx.showLoading({
          title: '获取characteristicId',
        })
        wx.getBLEDeviceCharacteristics({
          deviceId: that.data.deviceId,
          serviceId: serviceId,
          success(getCharactersRes) {
            console.log("getCharactersRes", getCharactersRes);
            wx.hideLoading();
            let characteristic = getCharactersRes.characteristics[0]
            let characteristicId = characteristic.uuid
            that.setData({
              serviceId: serviceId,
              characteristicId: characteristicId
            })
            console.log('成功获取uuId', that.data.serviceId, that.data.characteristicId);
            wx.writeBLECharacteristicValue({
              deviceId: that.data.deviceId,
              serviceId: that.data.serviceId,
              characteristicId: getCharactersRes.characteristics[0].uuid,
              value: that.fillcmdbuff(),
              success: function(res) {
                console.log("设置成功");
                wx.showToast({
                  title: '设置成功',
                  icon: 'none'
                })
              },
              fail: function(res) {
                console.warn("设置失败", res)
              }
            })            
          },
          fail: (res) => {
            console.warn("获取特征值信息失败", res);
          },
          complete: (res) => {
            console.log('获取服务信息完成',res);
            wx.hideLoading();
          }
        })
      },
      fail: (res) => {
        console.warn("获取服务信息失败", res);
      },
      complete: () => {
        wx.hideLoading();
      }
    })
    }else{
      wx.showToast({
        title: '请先连接蓝牙',
      })
    }
  },

如果既需要监听蓝牙设备又需要发送命令给蓝牙设备的话,代码部分可能需要适当的优化。

3、最后完成工作需要断开蓝牙设备。

 CloseLink(){
    this.setData({
      isConnected:false,
      isFinded:false
    })
    wx.closeBLEConnection({
      deviceId: this.data.deviceId,
      success: function(res) {
        console.log("成功断开连接");
        wx.showToast({
          title: '成功断开连接',
        })
      },
    })
  }

如果需要完整工程代码可以留言。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

永远的元子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值