uni-app 蓝牙连接热敏打印机
主要流程:
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了