微信小程序蓝牙通讯

最近一个师兄要求做一个蓝牙通讯功能的微信小程序,记载如下
参考CSDN范例
微信官方的蓝牙API文档

实现功能:

  • 对方设备向手机暴露蓝牙
  • 微信小程序打开蓝牙搜索设备
  • 当得到设备的相应信息后,主动发起连接
  • 通过小程序设置相应信息,将修改的结果显示数据到设备上

1、测试是否能搜索到蓝牙设备

index.wxml



    
    
      蓝牙初始化:
      {{isbluetoothready?"ok":"尚未初始化"}}
    
    
      
    
  
  
  
    
  

index.wcss

/**index.wxss**/
view {
  display: inline-block;
}

.container {
  padding: 0;
  margin: 0;
  align-items: flex-start;
}

.section {
  display: inline-block;
  width: 100%;
  position: relative;
}

.content {
  margin: auto;
  padding: auto;
  position: absolute;
  top: 5px;
  left: 10px;
}

.switch {
  position: relative;
  float: right;
  right: 0px;
}

button {
  background: red\;
}

.list-item {
  margin-top: 20rpx;
  margin-bottom: 20rpx; 
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  border: 1px dashed #000;
}

.list-item text {
   margin-top: 10rpx;
}


.list-item button {
  margin-right: 10rpx;
}

蓝牙开发注意事项:
微信小程序蓝牙的开发是指基于蓝牙4.0的低功耗蓝牙开发。
通常对蓝牙涉猎不深的人来看将BLE等同于蓝牙4.0,其实不然。蓝牙4.0协议包含BLE,BLE隶属于蓝牙4.0协议的一部分
蓝牙4.0是协议,4.0是协议版本号,蓝牙4.0是2010年6月由SIG(Special Interest Group)发布的蓝牙标准,它有两种模式:

  • 1、BLE(Bluetooth low energy)只能与4.0协议设备通信,适应节能且仅收发少量数据的设备(如手环、智能体温计),称之为低功耗蓝牙;
  • 2、BR/EDR(Basic Rate / Enhanced Data Rate),向下兼容(能与3.0/2.1/2.0通信),适应收发数据较多的设备(如耳机、手机、平板)。这个模式常常也有人称之为“传统蓝牙”或“经典蓝牙”;

编写JS思路

  • 通过wx.openBluetoothAdapter初始化蓝牙设备。
  • 通过wx.onBluetoothAdapterStateChange蓝牙适配器状态变化事件
  • 通过wx.onBluetoothDeviceFound搜索回调事件可以得到搜索到的蓝牙设备,如果是小米手环一代(设备名:MI1A),则进行记录该设备信息。

index.js

var app = getApp()
var temp = []
var serviceId = "00002A00-0000-1000-8000-00805F9B34FB"
var characteristicId = "00002A00-0000-1000-8000-00805F9B34FB"
Page({
  data: {
    isbluetoothready: false,
    defaultSize: 'default',
    primarySize: 'default',
    warnSize: 'default',
    disabled: false,
    plain: false,
    loading: false,
    searchingstatus: false,
    receivedata: '',
    onreceiving: false
  },
  onLoad: function () {
    // var str = "A13";
    // // var code = str.charCodeAt();
    // console.log(str.length)
    // console.log(str.charAt(0))
    // wx.showToast({
    //     title: '连接成功',
    //     icon: 'success',
    //     duration: 2000
    // })
    // let buffer = new ArrayBuffer(16)
    // let dataView = new DataView(buffer)
    // dataView.setUint8(1, 6)
    //console.log(dataView.getUint8(1))
  },
  switchBlueTooth: function () {
    var that = this

    that.setData({
      isbluetoothready: !that.data.isbluetoothready,
    })

    if (that.data.isbluetoothready) {
      wx.openBluetoothAdapter({
        success: function (res) {
          console.log("初始化蓝牙适配器成功")
          wx.onBluetoothAdapterStateChange(function (res) {
            console.log("蓝牙适配器状态变化", res)
            that.setData({
              isbluetoothready: res.available,
              searchingstatus: res.discovering
            })
          })
          wx.onBluetoothDeviceFound(function (devices) {
            console.log(devices)
            temp.push(devices)
            that.setData({
              devices: temp
            })
            console.log('发现新蓝牙设备')
            console.log('设备id' + devices.deviceId)
            console.log('设备name' + devices.name)
          }),
        fail: function (res) {
          console.log("初始化蓝牙适配器失败")
          wx.showModal({
            title: '提示',
            content: '请检查手机蓝牙是否打开',
            success: function (res) {
              that.setData({
                isbluetoothready: false,
                searchingstatus: false
              })
            }
          })
        }
      })
    } else {
      temp = []
      //先关闭设备连接
      wx.closeBLEConnection({
        deviceId: that.data.connectedDeviceId,
        complete: function (res) {
          console.log(res)
          that.setData({
            deviceconnected: false,
            connectedDeviceId: ""
          })
        }
      })
      wx.closeBluetoothAdapter({
        success: function (res) {
          console.log(res)
          that.setData({
            isbluetoothready: false,
            deviceconnected: false,
            devices: [],
            searchingstatus: false,
            receivedata: ''
          })
        },
        fail: function (res) {
          wx.showModal({
            title: '提示',
            content: '请检查手机蓝牙是否打开',
            success: function (res) {
              that.setData({
                isbluetoothready: false
              })
            }
          })
        }
      })
    }
  },
  searchbluetooth: function () {
    temp = []
    var that = this
    if (!that.data.searchingstatus) {
      var that = this
      wx.startBluetoothDevicesDiscovery({
        success: function (res) {
          console.log("开始搜索附近蓝牙设备")
          console.log(res)
          that.setData({
            searchingstatus: !that.data.searchingstatus
          })
        }
      })
    } else {
      wx.stopBluetoothDevicesDiscovery({
        success: function (res) {
          console.log("停止蓝牙搜索")
          console.log(res)
        }
      })
    }
  },
  connectTO: function (e) {
    var that = this

    if (that.data.deviceconnected) {
      wx.notifyBLECharacteristicValueChanged({
        state: false, // 停用notify 功能
        deviceId: that.data.connectedDeviceId,
        serviceId: serviceId,
        characteristicId: characteristicId,
        success: function (res) {
          console.log("停用notify 功能")
        }
      })
      wx.closeBLEConnection({
        deviceId: e.currentTarget.id,
        complete: function (res) {
          console.log("断开设备")
          console.log(res)
          that.setData({
            deviceconnected: false,
            connectedDeviceId: "",
            receivedata: ""
          })
        }
      })
    } else {
      wx.showLoading({
        title: '连接蓝牙设备中...',
      })
      wx.createBLEConnection({
        deviceId: e.currentTarget.id,
        success: function (res) {
          wx.hideLoading()
          wx.showToast({
            title: '连接成功',
            icon: 'success',
            duration: 1000
          })
          console.log("连接设备成功")
          console.log(res)
          that.setData({
            deviceconnected: true,
            connectedDeviceId: e.currentTarget.id
          })

          wx.notifyBLECharacteristicValueChanged({
            state: true, // 启用 notify 功能
            deviceId: that.data.connectedDeviceId,
            serviceId: serviceId,
            characteristicId: characteristicId,
            success: function (res) {
              console.log("启用notify")
            }
          })
        },
        fail: function (res) {
          wx.hideLoading()
          wx.showToast({
            title: '连接设备失败',
            icon: 'success',
            duration: 1000
          })
          console.log("连接设备失败")
          console.log(res)
          that.setData({
            connected: false
          })
        }
      })
      wx.stopBluetoothDevicesDiscovery({
        success: function (res) {
          console.log("停止蓝牙搜索")
          console.log(res)
        }
      })
    }
  },
  formSubmit: function (e) {
    console.log('form发生了submit事件,携带数据为:', e.detail.value.senddata)
    var senddata = e.detail.value.senddata;
    var that = this
    let buffer = new ArrayBuffer(senddata.length)
    let dataView = new DataView(buffer)
    for (var i = 0; i < senddata.length; i++) {
      dataView.setUint8(i, senddata.charAt(i).charCodeAt())
    }
    wx.writeBLECharacteristicValue({
      deviceId: that.data.connectedDeviceId,
      serviceId: serviceId,
      characteristicId: characteristicId,
      value: buffer,
      success: function (res) {
        console.log(res)
        console.log('writeBLECharacteristicValue success', res.errMsg)
      }
    })
  },
  formReset: function () {
    console.log('form发生了reset事件')
  }
})



function getNowFormatDate() {
  var date = new Date();
  var seperator1 = "-";
  var seperator2 = ":";
  var month = date.getMonth() + 1;
  var strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
    + " " + date.getHours() + seperator2 + date.getMinutes()
    + seperator2 + date.getSeconds();
  return currentdate;
}

console output

微信小程序蓝牙通讯_第1张图片
OneTest.png

查询文档回调方法wx.onBluetoothDeviceFound与wx.getBluetoothDevices

尝试使用getBluetoothDevices获取所有已发现的蓝牙设备,包括已经和本机处于连接状态的设备fgdfgdf

你可能感兴趣的:(微信小程序蓝牙通讯)