微信小程序實現藍牙打印
最近剛好完成了一個打印標簽的項目,其中就涉及到了小程序的藍牙功能。所以寫下這篇粗略的文章記錄一下,同時也是給即將做相關項目的親們提供一個參考,也希望有什么描述不恰當或者技術上不正確的地方大家可以指出,一起進步。
藍牙打印只要按這九個步驟(前六個步驟連接藍牙,后三個步驟打印數據)就可以搞定啦!步驟如下:
第一步:初始化藍牙模塊 wx.openBluetoothAdapter
wx.openBluetoothAdapter({ success (res) { console.log(res)//res:{errMsg: "openBluetoothAdapter:ok"} } })
第二步:開始搜尋附近的藍牙外圍設備 wx.startBluetoothDevicesDiscovery
wx.startBluetoothDevicesDiscovery({ //services: ['FEE7'],只搜索主服務 UUID 為 FEE7 的設備,如果明確知道主服務UUID可以用此項做篩選 success (res) { console.log(res)//res:{errCode: 0, errMsg: "startBluetoothDevicesDiscovery:ok", isDiscovering: true} } })
第三步:獲取已搜素到的藍牙設備列表 wx.getBluetoothDevices
wx.getBluetoothDevices({ success: function (res) { console.log(res)//res:{errMsg: "getBluetoothDevices:ok", devices: Array(3)} } })
第四步:監(jiān)聽尋找到新設備的事件 wx.onBluetoothDeviceFound(有時候會第三步會搜不到所以需要使用監(jiān)聽器去隨時監(jiān)聽搜索到的藍牙設備并返回給你)
wx.onBluetoothDeviceFound(function(res) { console.log(res)//res:{devices: Array(1)} })
第五步:連接藍牙設備 wx.createBLEConnection
wx.createBLEConnection({ deviceId,//上面選擇藍牙設備的deviceId,例:連接第一個設備devices[0].deviceId success (res) { console.log(res)//{errCode: 0, errMsg: "createBLEConnection:ok"} } })
第六步:停止搜尋附近的藍牙外圍設備 wx.stopBluetoothDevicesDiscovery(可以寫在第五步成功回調之后,或者是
onUnload()函數里) wx.stopBluetoothDevicesDiscovery({ success (res) { console.log(res) } })
第七步:獲取藍牙設備所有服務 wx.getBLEDeviceServices
wx.getBLEDeviceServices({ deviceId,//已連接的藍牙設備ID success (res) { console.log(res)//{errMsg: "getBLEDeviceServices:ok", services: Array(5), errCode: 0} } }) //這邊獲取到了5個服務
第八步:獲取藍牙設備中某一個服務的所有特征值 wx.getBLEDeviceCharacteristics
var characteristics=""; wx.getBLEDeviceCharacteristics({ deviceId, serviceId,//第七步的服務ID, success (res) { //res:{errMsg: "getBLEDeviceCharacteristics:ok", characteristics: Array(4), errCode: 0} //characteristics[0].properties: {read: true, write: false, notify: false, indicate: false} //特征值有好幾種類型,我們這邊打印需要的是item.properties.write為true的特征值 for (var i = 0; i < res.characteristics.length; i++) { var item = res.characteristics[i]; if (item.properties.write) { characteristics = item.uuid; } } //保存特征值 } })
第九步:向藍牙設備特征值中寫入數據 wx.writeBLECharacteristicValue
wx.writeBLECharacteristicValue({ deviceId, serviceId, characteristicId,//上面保存的特征值 value: buffer, // 這里的value是ArrayBuffer類型,中間層傳過來的打印數據前端自己做轉換,轉換過程我這邊就不描述了; success (res) { console.log('writeBLECharacteristicValue success', res.errMsg) } }) //特別提醒建議每次寫入的buffer不超過20字節(jié),超過會有寫入錯誤的風險,所以一個打印的內容可能要拆成N個20字節(jié)的buffer去循環(huán)writeBLECharacteristicValue,這樣就能打印成功啦。
附:
另注:無論是原生、WePY、mpvue或uniapp、調用步驟都是一樣的,不過調用API的前綴需要改成對應的就OK了
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
JS for循環(huán)中i++ 和 ++i的區(qū)別介紹
這篇文章主要介紹了JS for循環(huán)中i++ 和 ++i的區(qū)別介紹的相關資料,需要的朋友可以參考下2016-07-07