藍牙部分知識
-
關於Service:
每個設備包含有多個Service,每個Service對應一個uuid
-
關於Characteristic
每個Service包含多個Characteristic,每個Characteristic對應一個uuid
-
如何得到數據
我們想要的數據是包含在每一個Characteristic
wx.openBluetoothAdapter //初始化藍牙適配器 wx.closeBluetoothAdapter //關閉藍牙模塊 wx.getBluetoothAdapterState //獲取本機藍牙適配器狀態 wx.onBluetoothAdapterStateChange //監聽藍牙適配器狀態變化事件
2.連接前使用的共有4個,分別是
wx.startBluetoothDevicesDiscovery //開始搜尋附近的藍牙外圍設備 wx.stopBluetoothDevicesDiscovery //停止搜尋附近的藍牙外圍設備 wx.getBluetoothDevices //獲取所有已發現的藍牙設備 wx.onBluetoothDeviceFound //監聽尋找到新設備的事件
3.連接和斷開時使用的共有2個,分別是
wx.createBLEConnection //連接低功耗藍牙設備 wx.closeBLEConnection //斷開與低功耗藍牙設備的連接
4.連接成功后使用的共有8個,分別是
wx.getConnectedBluetoothDevices //根據 uuid 獲取處於已連接狀態的設備 wx.getBLEDeviceServices //獲取藍牙設備所有 service(服務) wx.getBLEDeviceCharacteristics //獲取藍牙設備所有 characteristic(特征值) wx.readBLECharacteristicValue //讀取低功耗藍牙設備的特征值的二進制數據值 wx.writeBLECharacteristicValue //向低功耗藍牙設備特征值中寫入二進制數據 wx.notifyBLECharacteristicValueChange //啟用低功耗藍牙設備特征值變化時的 notify 功能 wx.onBLECharacteristicValueChange //監聽低功耗藍牙設備的特征值變化 wx.onBLEConnectionStateChange //監聽低功耗藍牙連接的錯誤事件
基本操作流程
1.初始化藍牙適配器
2.開始搜尋附近的藍牙外圍設備
3.監聽尋找到新設備的事件
4.連接低功耗藍牙設備
5獲取藍牙設備所有 service 和 characteristic
6.讀取或寫入低功耗藍牙設備的特征值的二進制數據值。
示例:
<!--index.wxml--> <view class="container"> <view class="content"> <text class="status">適配器狀態:{{ status }}</text> <text class="sousuo">是否搜索:{{ sousuo }}</text> <text class="msg">消息:{{ msg }} </text> <button type="default" class="button" bindtap="initializeBluetooth">初始化藍牙適配器</button> <button type="default" class="button" bindtap="searchBluetooth">搜索藍牙設備 </button> <button type="default" class="button" bindtap="getServices">獲取連接設備所有service</button> <button type="default" class="button" bindtap="sendMessages">發送消息</button> <button type="default" class="button" bindtap="startBletNotify">啟用設備特征值變化時的notify</button> <button type="default" class="button" bindtap="receiveMessages">接收消息</button> <button type="default" class="button" bindtap="closeBluetooth">斷開藍牙連接</button> <view class="section"> <text class="status">接收到消息:{{ jieshou }}</text> </view> </view> <view class="venues_list" > <block wx:for="{{devices}}" wx:key="{{test}}"> <view class="venues_item"> <text class="status1">設備名稱: {{item.name}} </text> <text class="status">設備ID: {{item.deviceId}} </text> <text class='status'>廣播數據: {{item.advertisData}} </text> <text class='status'>信號強度RSSI: {{item.RSSI}} </text> <text class="status">連接狀態:{{connectedDeviceId == item.deviceId?"已連接":"未連接"}} </text> <view class="section"> </view> <view class="section"> <button type="warn" class="button" id="{{item.deviceId}}" bindtap="connectTO">連接</button> </view> </view> </block> </view> </view>
//index.js //獲取應用實例 //index.js //獲取應用實例 const app = getApp() Page({ data: { status: "", sousuo: "", connectedDeviceId: "", //已連接設備uuid services: [], // 連接設備的服務 serviceId: "", characteristics: "", // 連接設備的狀態值 writeServicweId: "", // 可寫服務uuid writeCharacteristicsId: "",//可寫特征值uuid readServicweId: "", // 可讀服務uuid readCharacteristicsId: "",//可讀特征值uuid notifyServicweId: "", //通知服務UUid notifyCharacteristicsId: "", //通知特征值UUID inputValue: "", characteristics1: "", // 連接設備的狀態值 }, onLoad: function () { }, // 初始化藍牙適配器 initializeBluetooth: function () { var that = this; if (!wx.openBluetoothAdapter) { console.log('藍牙適配器打開失敗,請檢查微信版本或手機是否支持小程序藍牙模塊!') } else { wx.openBluetoothAdapter({ success: function (res) { that.setData({ msg: "初始化藍牙適配器成功!" }) wx.getBluetoothAdapterState({//獲取本機藍牙適配器狀態 success: function (res) { console.log('本機藍牙適配器狀態:') console.log(res) } }) } }) } }, //搜索獲取已發現設備 searchBluetooth: function () { var that = this; wx.startBluetoothDevicesDiscovery({//開始搜尋附近的藍牙外圍設備 success: function (res) { console.log('開始搜索周邊藍牙設備') console.log(res) wx.getBluetoothDevices({//sucess返回uuid 對應的的已連接設備列表,Array類型 success: function (res) { //是否有已連接設備 wx.getConnectedBluetoothDevices({////根據 uuid 獲取處於已連接狀態的設備 success: function (res) { console.log('已連接的藍牙設備:') console.log(JSON.stringify(res.devices)); that.setData({ connectedDeviceId: res.deviceId }) } }) that.setData({ devices: res.devices, }) } }) } }) }, //連接設備 connectTO: function (e) { var that = this; wx.stopBluetoothDevicesDiscovery({ //先停止搜索周邊設備 success: function (res) { console.log('連接設備前,先停止搜索周邊設備:') console.log(res) } }) wx.showLoading({ title: '連接藍牙設備中...', }) wx.createBLEConnection({//若小程序在之前已有搜索過某個藍牙設備,並成功建立鏈接,可直接傳入之前搜索獲取的deviceId直接嘗試連接該設備,無需進行搜索操作。 deviceId: e.currentTarget.id, success: function (res) { console.log('連接成功:') console.log(res) wx.hideLoading() that.setData({ connectedDeviceId: e.currentTarget.id, //currentTarget: 事件綁定的元素 msg: "已連接" + e.currentTarget.id, }) }, fail: function () { console.log("調用失敗"); }, complete: function () { console.log('已連接設備ID:' + that.data.connectedDeviceId); console.log("調用結束"); } }) }, // 獲取連接設備的service服務 getServices: function () { var that = this; wx.getBLEDeviceServices({//獲取在小程序藍牙模塊生效期間所有已發現的藍牙設備,包括已經和本機處於連接狀態的設備 // 這里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中獲取 deviceId: that.data.connectedDeviceId, success: function (res) { //console.log('獲取藍牙設備所有服務成功:', res); that.data.services = res.services console.log('獲取藍牙設備所有服務成功:', that.data.services); that.setData({ serviceId: that.data.services[0].uuid, }) console.log("服務uuid:", that.data.serviceId) wx.getBLEDeviceCharacteristics({ // 這里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中獲取 deviceId: that.data.connectedDeviceId, // 這里的 serviceId 需要在上面的 getBLEDeviceServices 接口中獲取 serviceId: that.data.serviceId, //-----注意是that.data.services[0].uuid success: function (res) { console.log('serviceId: that.data.services[0].uuid: ', that.data.serviceId) console.log(res) for (var i = 0; i < res.characteristics.length; i++) { if (res.characteristics[i].properties.notify) { //注意characteristic(特征值)信息,properties對象 that.setData({ notifyServicweId: that.data.services[0].uuid, notifyCharacteristicsId: res.characteristics[i].uuid, }) console.log("notifyServicweId:", that.data.notifyServicweId,"notifyCharacteristicsId", that.data.notifyCharacteristicsId) } if (res.characteristics[i].properties.write) { that.setData({ writeServicweId: that.data.services[0].uuid, writeCharacteristicsId: res.characteristics[i].uuid, }) console.log("writeServicweId:", that.data.writeServicweId, "writeCharacteristicsId", that.data.writeCharacteristicsId) } else if (res.characteristics[i].properties.read) { that.setData({ readServicweId: that.data.services[0].uuid, readCharacteristicsId: res.characteristics[i].uuid, }) console.log("readServicweId:", that.data.readServicweId, "readCharacteristicsId", that.data.readCharacteristicsId) } } }, fail: function () { console.log("獲取連接設備的所有特征值:", res); }, complete: function () { console.log("complete!"); } }) } }) }, //斷開設備連接 closeBluetooth: function () { var that = this; wx.closeBLEConnection({ deviceId: that.data.connectedDeviceId, success: function (res) { console.log('斷開設備連接: ', devicedId) console.log(res) } }) }, //發送 sendMessages: function () { var that = this; // 這里的回調可以獲取到 write 導致的特征值改變 wx.onBLECharacteristicValueChange(function (characteristic) { console.log('characteristic value changed:1', characteristic) }) var buf = new ArrayBuffer(16) var dataView = new DataView(buf) dataView.setUint8(0, 99) wx.writeBLECharacteristicValue({ deviceId: that.data.connectedDeviceId, serviceId: that.data.writeServicweId, characteristicId: that.data.writeCharacteristicsId, value: buf, success: function (res) { console.log('writeBLECharacteristicValue success', res) } }) }, //啟用低功耗藍牙設備特征值變化時的 notify 功能 startBletNotify: function () { var that = this; wx.notifyBLECharacteristicValueChange({ state: true, // 啟用 notify 功能 deviceId: that.data.connectedDeviceId, serviceId: that.data.notifyServicweId, characteristicId: that.data.notifyCharacteristicsId, success: function (res) { console.log('notifyBLECharacteristicValueChange success', res.errMsg) }, fail: function () { console.log('啟用notify功能失敗!'); console.log(that.data.notifyServicweId); console.log(that.data.notifyCharacteristicsId); }, }) }, //接收消息 receiveMessages: function () { var that = this; // 必須在這里的回調才能獲取 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) }) console.log(that.data.readServicweId); console.log(that.data.readCharacteristicsId); wx.readBLECharacteristicValue({ deviceId: that.data.connectedDeviceId, serviceId: that.data.readServicweId, characteristicId: that.data.readCharacteristicsId, success: function (res) { console.log('readBLECharacteristicValue:', res.errMsg); } }) }, onHide: function () { var that = this this.setData({ devices_list: [] }) if (this.data.searching) { wx.stopBluetoothDevicesDiscovery({//隱藏界面是建議停止 success: function (res) { console.log(res) that.setData({ searching: false }) } }) } } })