主要流程:
1.初始化藍牙適配器openBluetoothAdapter,如果不成功就onBluetoothAdapterStateChange監聽藍牙適配器狀態變化事件
2.startBluetoothDevicesDiscovery開始搜尋附近的藍牙外圍設備
3.onBluetoothDeviceFound監聽尋找到新設備的事件,在這里你可以用代碼匹配設備
4.createBLEConnection創建藍牙連接,順便在stopBluetoothDevicesDiscovery關閉搜尋附近的藍牙外圍設備
5.getBLEDeviceServices獲取藍牙設備所有服務
6.getBLEDeviceCharacteristics獲取藍牙設備某個服務中所有特征值
7.onBLECharacteristicValueChange監聽藍牙設備發送給你的數據
8.writeBLECharacteristicValue向藍牙設備發送一個0x00的16進制數據
1 // ************************************************************************************************** 2 3 /** 4 * 第一步 在頁面顯示的時候判斷是否已經初始化完成藍牙適配器若成功,則開始查找設備 5 */ 6 OpenBluetoothAdapter() { 7 uni.openBluetoothAdapter({ 8 success:(res) => { 9 console.log('第一步初始化藍牙成功:' + res.errMsg); 10 // 初始化完畢開始搜索 11 this.StartBluetoothDeviceDiscovery() 12 }, 13 fail:(res) => { 14 console.log('初始化藍牙失敗: '+JSON.stringify(res)); 15 if (res.errCode == 10001) { 16 uni.showToast({ 17 title: '藍牙未打開', 18 duration: 2000, 19 }) 20 } else { 21 uni.showToast({ 22 title: res.errMsg, 23 duration: 2000, 24 }) 25 } 26 } 27 }); 28 }, 29 /** 30 * 第二步 在頁面顯示的時候判斷是都已經初始化完成藍牙適配器若成功,則開始查找設備 31 */ 32 StartBluetoothDeviceDiscovery() { 33 uni.startBluetoothDevicesDiscovery({ 34 // services: ['0000FFE0'], 35 success: res => { 36 console.log('第二步 開始搜尋附近的藍牙外圍設備:startBluetoothDevicesDiscovery success', res) 37 this.OnBluetoothDeviceFound(); 38 }, 39 fail: res => { 40 uni.showToast({ 41 icon: "none", 42 title: "查找設備失敗!", 43 duration: 3000 44 }) 45 } 46 }); 47 }, 48 /** 49 * 第三步 發現外圍設備 50 */ 51 OnBluetoothDeviceFound() { 52 console.log("監聽尋找新設備"); 53 uni.onBluetoothDeviceFound(res => { 54 console.log("第三步 監聽尋找到新設備的事件:",JSON.stringify(res)) 55 console.log("第三步 監聽尋找到新設備列表:",res.devices) 56 57 res.devices.forEach(device => {//這一步就是去篩選找到的藍牙中,有沒有你匹配的名稱 58 console.log("這一步就是去篩選找到的藍牙中,有沒有你匹配的名稱:",JSON.stringify(device)) 59 if (device.name == 'XT453_9101L') {//匹配藍牙名稱 60 uni.setStorageSync("DeviceID",device.deviceId)//把已經連接的藍牙設備信息放入緩存 61 this.DeviceID = device.deviceId 62 let DeviceID = device.deviceId//這里是拿到的uuid 63 64 this.StopBluetoothDevicesDiscovery()//當找到匹配的藍牙后就關掉藍牙搜尋,因為藍牙搜尋很耗性能 65 66 console.log("匹配到的藍牙this.DeviceID:",this.DeviceID) 67 this.CreateBLEConnection(DeviceID)//創建藍牙連接,連接低功耗藍牙設備 68 69 } 70 }) 71 }); 72 }, 73 /** 74 * 第四步 停止搜索藍牙設備 75 */ 76 StopBluetoothDevicesDiscovery() { 77 uni.stopBluetoothDevicesDiscovery({ 78 success: res => { 79 console.log("第四步 找到匹配的藍牙后就關掉藍牙搜尋:",JSON.stringify(res)) 80 }, 81 fail: res => { 82 console.log('第四步 停止搜索藍牙設備失敗,錯誤碼:' + res.errCode); 83 } 84 }); 85 }, 86 // 第五步 創建藍牙連接,連接低功耗藍牙設備 87 CreateBLEConnection(DeviceID,index){ 88 let doc = this 89 uni.createBLEConnection({//創建藍牙連接,連接低功耗藍牙設備 90 deviceId: DeviceID,//傳入剛剛獲取的uuid 91 success(res) { 92 console.log("第五步 創建藍牙連接成功:",JSON.stringify(res)) 93 doc.GetBLEDeviceServices(DeviceID) //獲取藍牙設備所有服務(service)。 94 95 }, 96 fail(res) { 97 console.log(res) 98 } 99 }) 100 }, 101 102 //第六步 獲取藍牙設備所有服務(service)。 103 GetBLEDeviceServices(DeviceID,index){ 104 let doc = this 105 setTimeout(function () {//這里為什么要用setTimeout呢,等等下面會解釋 106 uni.getBLEDeviceServices({//獲取藍牙設備所有服務 107 deviceId: DeviceID, 108 success(res) {//為什么要用延時,因為不用延時就拿不到所有的服務,在上一步,連接低功耗藍牙 109 //設備的時候,需要一個600-1000毫秒的時間后,再去獲取設備所有服務,不給延時就會一直返回錯誤碼10004 110 111 console.log("第六步 獲取藍牙設備所有服務:",JSON.stringify(res)) 112 uni.setStorageSync("ServiceUUID",res.services[2].uuid)//把已經連接的藍牙設備信息放入緩存 113 uni.setStorageSync("ServiceUUIDNew",res.services[2].uuid)//把已經連接的藍牙設備信息放入緩存 114 let ServiceUUIDNew = res.services[2].uuid 115 this.ServiceUUID = res.services[2].uuid 116 117 console.log("this.ServiceUUID:",this.ServiceUUID); 118 doc.GetBLEDeviceCharacteristics(DeviceID)//獲取藍牙設備某個服務中所有特征值 119 120 }, 121 fail(res) { 122 console.log(JSON.stringify(res)) 123 } 124 }) 125 }, 1000) 126 127 }, 128 129 // 第七步 獲取藍牙特征值 130 GetBLEDeviceCharacteristics(DeviceID){ 131 console.log("第七步 獲取藍牙特征值DeviceID:",DeviceID,"serviceId:",uni.getStorageSync('ServiceUUIDNew')); 132 setTimeout(()=>{ 133 uni.getBLEDeviceCharacteristics({//獲取藍牙設備某個服務中所有特征值 134 deviceId: DeviceID, 135 serviceId: uni.getStorageSync('ServiceUUIDNew'),//這個serviceId可以在上一步獲取中拿到,也可以在 136 //藍牙文檔中(硬件的藍牙文檔)拿到,我這里是通過文檔直接賦值上去的,一般有兩個,一個是收的uuid,一個是發的uuid,我們這邊是發 137 success(res) { 138 console.log("第七步 獲取藍牙設備某個服務中所有特征值成功:",JSON.stringify(res)) 139 uni.showToast({ 140 title: '開啟藍牙連接', 141 duration: 2000 142 }); 143 uni.setStorageSync("CharacteristicId",res.characteristics[1].uuid)//把某個服務中所有特征值信息放入緩存 144 this.characteristicId = res.characteristics[1].uuid 145 }, 146 fail(res) { 147 console.log("獲取藍牙設備某個服務中所有特征值失敗:",JSON.stringify(res)) 148 } 149 }) 150 },2000) 151 }, 152 // 第八步 發送二進制數據 153 WriteBLECharacteristicValue(){ 154 let doc = this 155 /* 數據格式如下: 156 doc.defaultVal = [ 157 ["0x21", "0x20", "0x30", "0x4E", "0x54", "0x0A"],//第一張出紙數據 158 ["0x21", "0x20", "0x30", "0x4E", "0x54", "0x0A"]//第二張出紙數據 159 。。。。。。。 160 ] */ 161 for (let i = 0; i < doc.defaultVal.length; i++) { 162 163 plus.bluetooth.writeBLECharacteristicValue({ 164 // 這里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中獲取 165 deviceId: uni.getStorageSync('DeviceID'), 166 // 這里的 serviceId 需要在 getBLEDeviceServices 接口中獲取 167 serviceId: uni.getStorageSync('ServiceUUIDNew'), 168 // 這里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中獲取 169 characteristicId: uni.getStorageSync('CharacteristicId'), 170 // 這里的value是ArrayBuffer類型 171 value: doc.defaultVal[i], 172 173 success(res) { 174 console.log('writeBLECharacteristicValue success', res) 175 console.log("開始打印第" + (i + 1) + "張:",doc.defaultVal[i]); 176 if (doc.defaultVal.length != 0) { 177 uni.showToast({ 178 title: "正在打印第" + (i + 1) + "張", 179 // duration: 2000 180 mask: true 181 }); 182 183 }else{ 184 uni.hideLoading() 185 186 } 187 }, 188 fail(res) { 189 console.log(JSON.stringify(res)) 190 doc.errorCodeTip(res.code); 191 192 // console.log(JSON.stringify(buffer)) 193 } 194 }) 195 } 196 }, 197 198 //錯誤碼提示 199 errorCodeTip(code) { 200 let doc = this 201 if (code == 0) { 202 //正常 203 } else if (code == 10000) { 204 uni.showToast({ 205 title: '未初始化藍牙適配器', 206 icon: 'none' 207 }) 208 } else if (code == 10001) { 209 uni.showToast({ 210 title: '當前藍牙適配器不可用', 211 icon: 'none' 212 }) 213 } else if (code == 10002) { 214 uni.showToast({ 215 title: '沒有找到指定設備', 216 icon: 'none' 217 }) 218 } else if (code == 10003) { 219 uni.showToast({ 220 title: '連接失敗', 221 icon: 'none' 222 }) 223 } else if (code == 10004) { 224 uni.showToast({ 225 title: '沒有找到指定服務', 226 icon: 'none' 227 }) 228 } else if (code == 10005) { 229 uni.showToast({ 230 title: '沒有找到指定特征值', 231 icon: 'none' 232 }) 233 } else if (code == 10006) { 234 uni.showToast({ 235 title: '當前連接已斷開', 236 icon: 'none' 237 }) 238 } else if (code == 10007) { 239 uni.showToast({ 240 title: '當前特征值不支持此操作', 241 icon: 'none' 242 }) 243 } else if (code == 10008) { 244 uni.showToast({ 245 title: '其余所有系統上報的異常', 246 icon: 'none' 247 }) 248 } else if (code == 10009) { 249 uni.showToast({ 250 title: 'Android 系統特有,系統版本低於 4.3 不支持 BLE', 251 icon: 'none' 252 }) 253 } 254 if (code != 0) { 255 //正常 256 //在頁面加載時候初始化藍牙適配器 257 doc.OpenBluetoothAdapter() 258 } 259 }, 260 // *********************暫時未用 start 根據情況調用吧************************************************************ 261 /** 262 * 獲取在藍牙模塊生效期間所有已發現的藍牙設備。包括已經和本機處於連接狀態的設備。 263 */ 264 getBluetoothDevices() { 265 console.log("獲取藍牙設備"); 266 uni.getBluetoothDevices({ 267 success: res => { 268 console.log('獲取藍牙設備成功:' + res); 269 this.bluetooth = res.devices; 270 console.log('獲取藍牙設備成功this.bluetooth:' + this.bluetooth); 271 this.bluetooth.forEach((item)=>{ 272 this.isLink.push(0) 273 }) 274 275 } 276 }); 277 }, 278 //斷開藍牙連接 279 closeBLEConnection(deviceId,index){ 280 uni.closeBLEConnection({ 281 deviceId:deviceId, 282 success:res=> { 283 this.isLink.splice(index,1,4) 284 console.log(res) 285 } 286 }) 287 }, 288 289 290 291 292 // 啟用 notify 功能 293 notifyBLECharacteristicValueChange(deviceId){ 294 uni.notifyBLECharacteristicValueChange({ 295 state: true, // 啟用 notify 功能 296 // 這里的 deviceId 需要已經通過 createBLEConnection 與對應設備建立鏈接 297 deviceId:deviceId, 298 // 這里的 serviceId 需要在 getBLEDeviceServices 接口中獲取 299 serviceId:this.serviceId, 300 // 這里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中獲取 301 characteristicId:this.characteristicId, 302 success:(res)=> { 303 console.log('notifyBLECharacteristicValueChange success', res.errMsg) 304 // this.onBLECharacteristicValueChange(this.deviceId); 305 }, 306 fail:(res)=> { 307 console.log('notifyBLECharacteristicValueChange success', res.errMsg) 308 } 309 }) 310 }, 311 ab2hex(buffer) { 312 const hexArr = Array.prototype.map.call( 313 new Uint8Array(buffer), 314 function (bit) { 315 return ('00' + bit.toString(16)).slice(-2) 316 } 317 ) 318 return hexArr.join('') 319 }, 320 // 監聽低功耗藍牙設備的特征值變化 321 onBLECharacteristicValueChange(deviceId){ 322 uni.onBLECharacteristicValueChange((res)=> { 323 console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`) 324 console.log(this.ab2hex(res.value)) 325 this.macAddress = res.deviceId; 326 this.macValue = this.ab2hex(res.value); 327 // this.readBLECharacteristicValue(this.deviceId) 328 }) 329 }, 330 // 讀取設備二進制數據 331 readBLECharacteristicValue(){ 332 // console.log('進入讀取'); 333 // setTimeout(()=>{ 334 uni.readBLECharacteristicValue({ 335 // 這里的 deviceId 需要已經通過 createBLEConnection 與對應設備建立鏈接 336 deviceId:this.deviceId, 337 // 這里的 serviceId 需要在 getBLEDeviceServices 接口中獲取 338 serviceId:this.serviceId, 339 // 這里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中獲取 340 characteristicId:this.characteristicId, 341 success:(res)=> { 342 console.log('readBLECharacteristicValue:', res) 343 this.readCode = res.errCode; 344 this.readCodeMsg = res.errMsg; 345 this.onBLECharacteristicValueChange(this.deviceId); 346 }, 347 fail:(res)=> { 348 console.log('readBLECharacteristicValue:', res) 349 this.readCode = res.errCode; 350 this.readCodeMsg = res.errMsg; 351 this.onBLECharacteristicValueChange(this.deviceId); 352 } 353 }) 354 // },200) 355 356 }, 357 358 // **********************************暫時未用 end************************************************************ 359
開始操作:
1 // 添加-保存 操作 2 barClick(e) { 3 var doc = this; 4 if(e.name=="打印"){ 5 doc.getInvstr().then(res => {//請求接口拿到需要數據后開始請求打印 6 this.WriteBLECharacteristicValue()//請求成功后會出紙 7 8 }) 9 } 10 },
記得在頁面加載時候初始化藍牙適配器
研究了三天的成果希望可以幫助到大家
將以上步驟直接考過去,缺少定義的字段自己改一下就ok了