1.前言
微信小程序中連接藍牙設備,信息寫入流程
1、檢測當前使用設備(如自己的手機)是否支持藍牙/藍牙開啟狀態
wx:openBluetoothAdapter({})
2、如藍牙已開啟狀態,檢查藍牙適配器的狀態
wx.getBluetoothAdapterState({})
3、添加監聽藍牙適配器狀態變化
wx.onBluetoothAdapterStateChange({})
4、搜索附近藍牙設備
wx.startBluetoothDevicesDiscovery({})
5、監聽搜索的到設備
wx.onBluetoothDeviceFound({})
遍歷設備列表找到和macAddr(看自己家的藍牙裝置的物理地址)匹配的設備的deviceId
6、連接想要連接的切匹配成功的設備
wx.createBLEConnection({})
7、獲取連接成功的設備的設備服務servicesID
wx.getBLEDeviceServices({})
8、獲取設備特征id
wx.getBLEDeviceCharacteristics({})
9、向設備寫入指令
wx.writeBLECharacteristicValue({})
以下是代碼重點,本人親測有效,集官網和百家之所長,匯聚之大成,入我門來,使君不負觀賞
#2. 小程序前端index.wxml
<wxs module="utils">
module.exports.max = function(n1, n2) {return Math.max(n1, n2)
}
module.exports.len = function(arr) {arr = arr || []return arr.length
}
</wxs>
<button bindtap="openBluetoothAdapter" class="primary-btn" >開始掃描</button>
<button bindtap="closeBLEConnection" class="default-btn" >斷開連接</button>
<button bindtap="opendeng" class="sumit-btn" >開燈</button>
<button bindtap="guandeng" class="warn-btn" >關燈</button><view class="devices_summary">已發現 {{devices.length}} 個外圍設備:</view>
<scroll-view class="device_list" scroll-y scroll-with-animation><view wx:for="{{devices}}" wx:key="index"data-device-id="{{item.deviceId}}"data-name="{{item.name || item.localName}}"bindtap="createBLEConnection" class="device_item"hover-class="device_item_hover"><view style="font-size: 16px; color: #333;">{{item.name}}</view><view style="font-size: 10px">信號強度: {{item.RSSI}}dBm ({{utils.max(0, item.RSSI + 100)}}%)</view><view style="font-size: 10px">UUID: {{item.deviceId}}</view><view style="font-size: 10px">Service數量: {{utils.len(item.advertisServiceUUIDs)}}</view></view>
</scroll-view><view class="connected_info" wx:if="{{connected}}"><view><icon class="icon-box-img" type="success" size="33"></icon><view class="icon-box-text"> {{name}}連接成功!!!</view></view> </view>
3.小程序index.wxss
page {color: #333;
}
.icon-box-img{height: 20px;float: left;margin-left: 20%;
}
.icon-box-text{height: 30px;line-height: 30px;margin-left:5px;float: left;
}.primary-btn{margin-top: 30rpx;/* border: rgb(7, 80, 68) 1px solid; */color: rgb(241, 238, 238);background-color: rgb(14, 207, 46);
}
.default-btn{margin-top: 30rpx;/* border: #333 1px solid; */color: rgb(243, 236, 236);background-color: rgb(189, 112, 25);
}.warn-btn{margin-top: 30rpx;/* border: #333 1px solid; */color: rgb(240, 231, 231);background-color: rgb(235, 10, 10);
}
.sumit-btn{margin-top: 30px;width: 60px;color: rgb(240, 231, 231);background-color: rgb(10, 100, 235);
}.devices_summary {margin-top: 30px;padding: 10px;font-size: 16px;
}
.device_list {height: 300px;margin: 50px 5px;margin-top: 0;border: 1px solid #EEE;border-radius: 5px;width: auto;
}
.device_item {border-bottom: 1px solid #EEE;padding: 10px;color: #666;
}
.device_item_hover {background-color: rgba(0, 0, 0, .1);
}
.connected_info {position: fixed;bottom: 10px;width: 80%;margin-left: 6%;background-color: #F0F0F0;padding: 10px;padding-bottom: 20px;margin-bottom: env(safe-area-inset-bottom);font-size: 18px;/* line-height: 20px; */color: #1da54d;text-align: center;/* height: 20px; */box-shadow: 0px 0px 3px 0px;
}
.connected_info .operation {position: absolute;display: inline-block;right: 30px;
}
4.小程序 index.ts
const app = getApp()function inArray(arr, key, val) {for (let i = 0; i < arr.length; i++) {if (arr[i][key] === val) {return i;}}return -1;
}// ArrayBuffer轉16進度字符串示例
function ab2hex(buffer) {var hexArr = Array.prototype.map.call(new Uint8Array(buffer),function (bit) {return ('00' + bit.toString(16)).slice(-2)})return hexArr.join('');
}Page({data: {devices: [],connected: false,chs: [],},getCeshi() {wx.navigateTo({url: '/pages/main/main',})},// 搜尋周邊藍牙openBluetoothAdapter() {//console.log('openBluetoothAdapter success')wx.openBluetoothAdapter({success: (res) => {console.log('openBluetoothAdapter success', res)this.startBluetoothDevicesDiscovery()},fail: (res) => {if (res.errCode === 10001) {wx.onBluetoothAdapterStateChange(function (res) {console.log('onBluetoothAdapterStateChange', res)if (res.available) {this.startBluetoothDevicesDiscovery()}})}}})},// 停止搜尋周邊藍牙getBluetoothAdapterState() {wx.getBluetoothAdapterState({success: (res) => {console.log('getBluetoothAdapterState', res)if (res.discovering) {this.onBluetoothDeviceFound()} else if (res.available) {this.startBluetoothDevicesDiscovery()}}})},// 開始搜尋附近的藍牙外圍設備startBluetoothDevicesDiscovery() {if (this._discoveryStarted) {return}this._discoveryStarted = truewx.startBluetoothDevicesDiscovery({allowDuplicatesKey: true,success: (res) => {console.log('startBluetoothDevicesDiscovery success', res)this.onBluetoothDeviceFound()},})},//停止搜尋附近的藍牙外圍設備。若已經找到需要的藍牙設備并不需要繼續搜索時,建議調用該接口停止藍牙搜索。stopBluetoothDevicesDiscovery() {wx.stopBluetoothDevicesDiscovery()},//監聽搜索到新設備的事件onBluetoothDeviceFound() {wx.onBluetoothDeviceFound((res) => {res.devices.forEach(device => {if (!device.name && !device.localName) {return}const foundDevices = this.data.devicesconst idx = inArray(foundDevices, 'deviceId', device.deviceId)const data = {}if (idx === -1) {data[`devices[${foundDevices.length}]`] = device} else {data[`devices[${idx}]`] = device}this.setData(data)})})},//連接藍牙低功耗設備。createBLEConnection(e) {const ds = e.currentTarget.datasetconst deviceId = ds.deviceIdconst name = ds.namewx.createBLEConnection({deviceId,success: (res) => {this.setData({connected: true,name,deviceId,})this.getBLEDeviceServices(deviceId)}})this.stopBluetoothDevicesDiscovery()},closeBLEConnection() {wx.closeBLEConnection({deviceId: this.data.deviceId})this.setData({connected: false,chs: [],canWrite: false,})},//獲取藍牙低功耗設備所有服務。getBLEDeviceServices(deviceId) {console.log('deviceId ========', deviceId)wx.getBLEDeviceServices({deviceId,success: (res) => {for (let i = 0; i < res.services.length; i++) {//獲取通過設備id多個特性服務serviceid (包含 讀、寫、通知、等特性服務)// console.log('serviceId ========', res.services[2].uuid)// 通過上邊注釋解封,排查到判斷服務id 中第三個服務id 代表寫入服務// isPrimary代表 :判斷服務id是否為主服務// if (res.services[2].isPrimary) {// this.getBLEDeviceCharacteristics(deviceId, res.services[2].uuid)// }//判斷通過(設備id獲取的多個特性服務)中是否有與(藍牙助手獲取的寫入特性服務),相一致的serviceidif (res.services[i].uuid=="0000FFE0-0000-1000-8000-00805F9B34FB") {this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid) }}}})},//獲取藍牙低功耗設備某個服務中所有特征 (characteristic)。getBLEDeviceCharacteristics(deviceId, serviceId) {console.info("藍牙的deviceId====" + deviceId);console.info("藍牙服務的serviceId====" + serviceId);wx.getBLEDeviceCharacteristics({deviceId,serviceId,success: (res) => {console.log('getBLEDeviceCharacteristics success', res.characteristics)for (let i = 0; i < res.characteristics.length; i++) {let item = res.characteristics[i]if (item.properties.read) {wx.readBLECharacteristicValue({deviceId,serviceId,characteristicId: item.uuid,})}if (item.properties.write) {this.setData({canWrite: true})this._deviceId = deviceIdthis._serviceId = serviceIdthis._characteristicId = item.uuidconsole.info("寫入(第一步)的characteristicId====" + item.uuid);//初始化調用 寫入信息的方法 1:代表開燈this.writeBLECharacteristicValue("1")}if (item.properties.notify || item.properties.indicate) {wx.notifyBLECharacteristicValueChange({deviceId,serviceId,characteristicId: item.uuid,state: true,})}}},fail(res) {console.error('getBLEDeviceCharacteristics', res)}})// 操作之前先監聽,保證第一時間獲取數據wx.onBLECharacteristicValueChange((characteristic) => {const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId)const data = {}if (idx === -1) {data[`chs[${this.data.chs.length}]`] = {uuid: characteristic.characteristicId,value: ab2hex(characteristic.value)}} else {data[`chs[${idx}]`] = {uuid: characteristic.characteristicId,value: ab2hex(characteristic.value)}}this.setData(data)})},/*** 寫入的數據 格式轉換* @param str* @returns 字符串 轉 ArrayBuffer*/
hex2buffer(str) {console.info("寫入的數據====" + str);//字符串 轉 十六進制var val = "";for (var i = 0; i < str.length; i++) {if (val == "")val = str.charCodeAt(i).toString(16);elseval += "," + str.charCodeAt(i).toString(16);}//十六進制 轉 ArrayBuffervar buffer = new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {return parseInt(h, 16)})).buffer;return buffer;
},
//開燈
opendeng() {// 調用寫入信息的方法 向藍牙設備發送一個開燈的參數數據 , 1:代表開燈var writeValue ="1";this.writeBLECharacteristicValue(writeValue)},
//關燈
guandeng() {// 調用寫入信息的方法 向藍牙設備發送一個關燈的參數數據 , 0:代表關燈var writeValue ="0";this.writeBLECharacteristicValue(writeValue)},
writeBLECharacteristicValue(writeValue) {// 向藍牙設備發送一個0x00的16進制數據// let buffer = new ArrayBuffer(1)// let dataView = new DataView(buffer)// dataView.setUint8(0, 0)//調用hex2buffer()方法,轉化成ArrayBuffer格式console.log('獲取傳遞參數writeValue的數據為=====',writeValue)var buffer =this.hex2buffer(writeValue);console.log('獲取二進制數據',buffer)//向低功耗藍牙設備特征值中寫入二進制數據。wx.writeBLECharacteristicValue({deviceId: this._deviceId,serviceId: this._serviceId,characteristicId: this._characteristicId,value: buffer,success (res) {console.log('成功寫數據writeBLECharacteristicValue success', res)//如果 uni.writeBLECharacteristicValue 走 success ,證明你已經把數據向外成功發送了,但不代表設備一定就收到了。通常設備收到你發送過去的信息,會返回一條消息給你,而這個回調消息會在 uni.onBLECharacteristicValueChange 觸發},fail(res) {console.error('失敗寫數據getBLEDeviceCharacteristics', res)}})
},
//斷開與藍牙低功耗設備的連接。closeBluetoothAdapter() {wx.closeBluetoothAdapter()this._discoveryStarted = false},
})
5.疑難點
1.如果你不確定寫入的特性服務值可以通過(安卓)藍牙助手獲取特性值 deviceId(mac地址)、serviceId、characteristicId(蘋果手機)藍牙助手獲得特性值deviceId(uuid地址)、serviceId、characteristicId
注意:手機品類不同獲取的deviceId的名稱不同,但serviceId、characteristicId,是相同的
1.安卓手機(藍牙助手獲取的信息)
2.蘋果手機(藍牙助手)獲取的信息
FFF0代表的serviceId全稱:0000FFF0-0000-1000-8000-00805F9B34FB
FFF3代表的characteristicId全稱:0000FFF3-0000-1000-8000-00805F9B34FB
最后:
祝愿你能一次成功
(代碼直接復制粘貼到你的小程序中,替換下你自己設備的寫入特性serviceId值),
就可以測試了
最后如果還滿意,記得點下贊、收藏加關注、我也好回關,相互進步!!!!!!!!!!