Why & How微信小程序

微信小程序蓝牙通讯

2017-06-29  本文已影响9497人  语落心生

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

实现功能:

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

index.wxml

<!--index.wxml-->
<view class="container">
    <view class="section">
    <view class="content">
      <text>蓝牙初始化:</text>
      <text>{{isbluetoothready?"ok":"尚未初始化"}}</text>
    </view>
    <view class="switch">
      <switch checked="{{isbluetoothready}}" bindchange="switchBlueTooth" />
    </view>
  </view>
  <view class="section" hidden="{{!isbluetoothready}}">
    <button type="default" size="{{primarySize}}" loading="{{searchingstatus}}" plain="{{plain}}" disabled="{{disabled}}" bindtap="searchbluetooth"> {{searchingstatus?"搜索中":"搜索蓝牙"}} </button>
  </view>
  <block>
    <view class="section" hidden="{{!isbluetoothready}}">
      <view class="list-item {{deviceconnected?'deviceconnected':''}}">
        <text>设备名称:{{item.deviceId}}</text>
        <text>设备名称:{{item.deviceId}}</text>
        <button id="{{item.deviceId}}" type="default" size="mini" bindtap="connectTO">{{deviceconnected?"已连接":"链接"}}</button>
      </view>
    </view>
  </block>
</view>

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;
}

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

编写JS思路

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

OneTest.png

查询文档回调方法wx.onBluetoothDeviceFoundwx.getBluetoothDevices

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

上一篇 下一篇

猜你喜欢

热点阅读