微信小程序蓝牙模块通信

微信小程序与蓝牙之间的通信

因为项目要求,本次实现与蓝牙的通信是直接根据蓝牙设备的deviceId直接进行连接,后续会继续改进。实现的功能有连接蓝牙,获取蓝牙的服务,特征值,关闭蓝牙搜索,开启notify通知,监听蓝牙,接受蓝牙模块信息,向蓝牙模块发送信息。

一、硬件

4.2BLE低功耗蓝牙模块

二、微信小程序代码

1.初始化蓝牙模块
wx.openBluetoothAdapter(){
	success:function (res) {
		console.log("初始化蓝牙适配器成功")
	}
	fail:function() {
		console.log("初始化蓝牙适配器失败")
	}
}
2.根据获取的deviceId建立与蓝牙的连接
 wx.createBLEConnection({
            deviceId: "deviceId",
            success(res) {
              that.setData({
                connectedDeviceId: "deviceId",
                msg: "已连接" + "deviceId",
              })
              console.log("已连接" + "deviceId")
                },
            fail: function(res) {
              setTimeout(function() {
                that.onLoad()
              }, 10000) //延迟时间 这里是10秒
              console.log("当蓝牙没有连接上,继续连接")
            }
        })
3.根据获取的deviceId获取蓝牙设备服务信息
wx.getBLEDeviceServices({
    // 这里的 deviceId 根据 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
    deviceId: that.data.connectedDeviceId,
    success: function(res) {
        console.log('device services:', JSON.stringify(res.services));
        that.setData({
           services: res.services,
           msg: JSON.stringify(res.services),
         })
    }
})
4.根据获取的deviceId获取蓝牙设备特征值
wx.getBLEDeviceCharacteristics({
                // 这里的 deviceId 根据  getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
                // deviceId: that.data.connectedDeviceId,
                deviceId: "deviceId",
                // 这里的 serviceId 根据  getBLEDeviceServices 接口中获取
                serviceId: "serviceId ",
                success: function(res) {
                  for (var i = 0; i < res.characteristics.length; i++) {
                    if (res.characteristics[i].properties.notify) {
                      console.log("第" + i)
                      console.log(that.data.services[0].uuid);
                      console.log( res.characteristics[0].uuid);
                      that.setData({
                        notifyServicweId: that.data.services[0].uuid,
                        notifyCharacteristicsId: res.characteristics[0].uuid,
                      })
                    }
                  }
                  console.log('device getBLEDeviceCharacteristics:', res.characteristics);
                  
                  that.setData({
                    msg: JSON.stringify(res.characteristics),
                  })
                },
                fail: function(res) {
                  console.log("fail" + res);
                },
                complete: function() {
                }
              })
4.根据获取的deviceId,serviceId,characteristicId开启notify通知,监听蓝牙信息
        wx.notifyBLECharacteristicValueChange({
                state: true, // 启用 notify 功能
                // 这里的 deviceId 根据  getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
                deviceId: that.data.connectedDeviceId,
                // 这里的 serviceId 根据  getBLEDeviceServices 接口中获取
                serviceId: that.data.notifyServicweId,
                // 这里的 characteristicId 根据  getBLEDeviceCharacteristics 接口中获取
                characteristicId: that.data.notifyCharacteristicsId,
                success: function(res) {
                  console.log('notifyBLECharacteristicValueChange success', res.errMsg)
                  //开启接收蓝牙端数据服务
                  wx.notifyBLECharacteristicValueChange({
                    state: true, // 启用 notify 功能
                    // 这里的 deviceId 根据  getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
                	deviceId: that.data.connectedDeviceId,
                	// 这里的 serviceId 根据  getBLEDeviceServices 接口中获取
                	serviceId: that.data.notifyServicweId,
                	// 这里的 characteristicId 根据  getBLEDeviceCharacteristics 接口中获取
                	characteristicId: that.data.notifyCharacteristicsId,
                    success: function(res) {
                      console.log('notifyBLECharacteristicValueChange success', res)
                    }
                  })
                },
                fail: function() {
                  console.log('失败');
                  console.log(that.data.connectedDeviceId);
                  console.log(that.data.notifyServicweId);
                  console.log(that.data.notifyCharacteristicsId);
                },
              })
5.接收蓝牙信息
wx.onBLECharacteristicValueChange(function (characteristic) {
     let hex = Array.prototype.map.call(new Uint8Array(characteristic.value), x => ('00' + x.toString(16)).slice(-2)).join('');
     console.log(hex)
     //接收到的信息
     var res = hex;
     that.setData({
       	 resiviced: res,
     })

})
6.发送信息给蓝牙
  sendMessagesToBlue: function(arr) {
    var that = this;
    var buf = new ArrayBuffer(3)
    var dataView = new DataView(buf)
    console.log(arr.length);
    for (var i = 0; i < arr.length; i++) {
      dataView.setInt8(i, arr[i]);
    }

    wx.writeBLECharacteristicValue({
      // 这里的 deviceId 根据  getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
      deviceId: "deviceId",
      // 这里的 serviceId 根据  getBLEDeviceServices 接口中获取
      serviceId: "serviceId",
      // 这里的 characteristicId 根据 getBLEDeviceCharacteristics 接口中获取
      characteristicId: "characteristicId",
      // 这里的value是ArrayBuffer类型
      value: buf,
      success: function(res) {
        //读取低功耗蓝牙设备的特征值的二进制数据值。注意:必须设备的特征值支持 read 才可以成功调用。
        console.log('writeBLECharacteristicValue success', res)
      },
      fail: function(res) {
        console.log('writeBLECharacteristicValue fail', res)
      }
    })
  }

三、结束

因为项目原因,采用硬核连接的方式来实现,没有把完整的蓝牙从搜索到连接的全部过程细化出来,后续有时间会慢慢优化。测试时需要开启调试模式才会正常启用功能。仅作为个人学习参考。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值