开发基于uni-app的蓝牙BLE接口对接蓝牙打印碰到的现象记录

uni-app 同时被 2 个专栏收录
1 篇文章 0 订阅
1 篇文章 0 订阅

原创文章,转载请写明转载地址:https://blog.csdn.net/michelsn/article/details/88232476

 

开发环境:HBuilderX + uni-app

蓝牙打印机:驰腾PD36 和 GPrinter佳博GP-Q80

Andorid环境下打印没什么问题,主要描述下IOS环境下的情况

-----------------------------------------------------------------------------------

问题描述:先搜索蓝牙设备,并把搜索到的蓝牙设备记录下来,然后关闭重启APP,选择之前搜索到的蓝牙设备DeviceID,点击连接并打印,结果会出现 no device 错误;

解决方案:每一次执行uni.openBluetoothAdapter后,都需要去执行uni.startBluetoothDevicesDiscovery,搜索到之前记录的蓝牙设备,然后再根据DeviceID去连接蓝牙设备即可。

-----------------------------------------------------------------------------------

以下贴出这几天研究APP对接蓝牙打印的代码,希望可以帮助有需要的朋友,少经历点坑。

	sendDataToBLE: function(deviceId, serviceId, characteristicId, msg, callbackIfFinish) {

		function encode_utf8(s) {
			return unescape(encodeURIComponent(s));
		}

		function str2ab(str) {
			var s = encode_utf8(str);
			var buf = new ArrayBuffer(s.length);
			var bufView = new Uint8Array(buf);
			for (var i = 0, strLen = s.length; i < strLen; i++) {
				bufView[i] = s.charCodeAt(i);
			}
			return bufView;
		}

		function split_array(arr, len) {
			var a_len = arr.length;
			var result = []
			for (var i = 0; i < a_len; i += len) {
				result.push(arr.slice(i, i + len))
			}
			return result;
		}
		//var uint8Buf = str2ab(msg);		
		var uint8Array = new textencoding.TextEncoder("gb2312", {
			NONSTANDARD_allowLegacyEncoding: true
		}).encode(msg);
		var uint8Buf = Array.from(uint8Array);
		//拆分数组 每20个元素组成一个新数组 
		var sendloop = split_array(uint8Buf, 20);

		function realWriteData(sendloop, i) {
			if (i >= sendloop.length) {
				if (callbackIfFinish) {
					callbackIfFinish(1, "");
				}
				return;
			}
			var tagName = "DeviceID:" + deviceId + " ServiceID:" + serviceId + " CharcWriteID:" + characteristicId + " -> 第【" +
				+"】次写入 => ";
			var newsenddata = sendloop[i]
			let buffer = new ArrayBuffer(newsenddata.length)
			let dataView = new DataView(buffer)
			for (var j = 0; j < newsenddata.length; j++) {
				dataView.setUint8(j, newsenddata[j]);
			}
			uni.writeBLECharacteristicValue({
				deviceId: deviceId,
				serviceId: serviceId,
				characteristicId: characteristicId,
				// 这里的value是ArrayBuffer类型
				value: buffer,
				success: function(res) {
					realWriteData(sendloop, i + 1);
				},
				fail: function(err) {
					emaosoft.show_none_toast_20sec(tagName + err.errMsg);
					if (callbackIfFinish) {
						callbackIfFinish(0, tagName + err.errMsg);
					}
				}
			})
		}
		var i = 0;
		realWriteData(sendloop, 0);
	},

	closeBLEConnectionAndAdapter: function(deviceId) {
		uni.closeBLEConnection({
			deviceId: deviceId,
			success: function(res) {
				emaosoft.console_log("closeBLEConnection 成功");
			},
			fail: function() {
				emaosoft.console_log("closeBLEConnection 失败");
			},
			complete: function() {}
		});
	},

	printByBluetoothPrinterAsBLE4: function(deviceId, printDataArray, calbackForLog, callbackIfFinish) {
		//emaosoft.console_log(JSON.stringify(printDataArray));
		var that = this;
		emaosoft.console_log("蓝牙设备deviceId:" + deviceId);
		var maxTryCount = 10;
		var curTryIndex = 0;
		//建立与设备的连接
		function connectToBLEDevice() {
			calbackForLog("正在连接蓝牙设备 " + deviceId + " ...");
			uni.createBLEConnection({
				// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
				deviceId,
				success: function(res) {
					emaosoft.console_log('createBLEConnection:' + JSON.stringify(res));
					//emaosoft.show_none_toast("DeviceID:" + deviceId + "成功与蓝牙设备建立连接:" + JSON.stringify(res));			
				},
				fail: function(err) {
					emaosoft.console_log(JSON.stringify(err));
					calbackForLog("连接蓝牙设备失败:" + err.errMsg);
					//emaosoft.show_none_toast(err.errMsg);
					app_intf.closeBLEConnectionAndAdapter(deviceId);
				}
			});
		}
		//  监听低功耗蓝牙设备连接状态变化 
		uni.onBLEConnectionStateChange(function(e) {
			emaosoft.console_log('onBLEConnectionStateChange: ' + JSON.stringify(e));
			if (e.deviceId == deviceId) {
				if (e.connected) {
					calbackForLog("连接蓝牙设备 " + deviceId + " 成功.");
					function getBLEDeviceServicesIfZeroDeviceServices() {
						setTimeout(function() {
							calbackForLog("正在获取蓝牙设备的BLE设备服务信息 ...");
							uni.getBLEDeviceServices({
								// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
								deviceId,
								success: function(res) {
									emaosoft.console_log('getBLEDeviceServices:' + JSON.stringify(res));
									calbackForLog("共获取到蓝牙设备的" + res.services.length + "个BLE设备服务信息");
									if(res.services.length == 0) {
										app_intf.closeBLEConnectionAndAdapter(deviceId);
										curTryIndex++;
										if(curTryIndex < maxTryCount) {
											setTimeout(function (){
												calbackForLog("#第" + curTryIndex + "次尝试重新连接蓝牙设备以获取蓝牙设备的BLE设备服务信息 ...");
												connectToBLEDevice();
											}, 2000);
										} else {
											calbackForLog("连续" + maxTryCount + "次获取蓝牙设备的BLE设备服务信息失败,请重新连接蓝牙设备");
										}
									} else {
										//emaosoft.show_none_toast("DeviceID:" + deviceId + " 获取BLE设备所有服务:" + JSON.stringify(res));
										var tipMessage = "DeviceID:" + deviceId + " 获取BLE设备所有服务:" + JSON.stringify(res);
										var serviceId = "";
										for (var s = 0; s < res.services.length; s++) {
											var curServiceID = "" + res.services[s].uuid;
											curServiceID = curServiceID.toUpperCase();
											if (curServiceID == '49535343-FE7D-4AE5-8FA9-9FAFD205E455') {
												serviceId = res.services[s].uuid;
											} else if (curServiceID.indexOf('FE7D') != -1) {
												serviceId = res.services[s].uuid;
											}
										}
										if (serviceId == "") {
											serviceId = res.services[0].uuid;
										}
										calbackForLog("正在获取蓝牙设备BLE设备服务 " + serviceId + " 的特征值 ...");
										setTimeout(function() {
											uni.getBLEDeviceCharacteristics({
												// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
												deviceId,
												// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
												serviceId,
												success: function(res) {
													emaosoft.console_log('getBLEDeviceCharacteristics:' + JSON.stringify(res));
													//emaosoft.show_none_toast("DeviceID:" + deviceId + " ServiceID:" + serviceId + " 获取蓝牙设备指定服务中所有特征值:" + JSON.stringify(res));
													tipMessage += "\nDeviceID:" + deviceId + " ServiceID:" + serviceId +
														" 获取蓝牙设备指定服务中所有特征值:" + JSON.stringify(res);
													//emaosoft.show_none_toast_20sec(tipMessage);

													var characteristicNotifyId = "";
													var characteristicReadId = "";
													var characteristicWriteId = "";
													if (res.characteristics && res.characteristics.length > 0) {
														for (var i = 0; i < res.characteristics.length; i++) {
															var curCharc = res.characteristics[i];
															if (curCharc.properties.notify) {
																characteristicNotifyId = curCharc.uuid;
															}
															if (curCharc.properties.read) {
																characteristicReadId = curCharc.uuid;
															}
															if (curCharc.properties.write) {
																characteristicWriteId = curCharc.uuid;
															}
														}
														if (!characteristicWriteId || characteristicWriteId == '') {
															characteristicWriteId = res.characteristics[0].uuid;
														}
													}
													calbackForLog("正在打印 ...");
													var printerText = that.buildTSPLCommandsForPrintData(printDataArray);
													that.sendDataToBLE(deviceId, serviceId, characteristicWriteId, printerText, function(success,
														msg) {
														//关闭与设备的连接
														app_intf.closeBLEConnectionAndAdapter(deviceId);
														if (success == 1) {
															emaosoft.show_none_toast("打印完成");
															calbackForLog("打印完成 ...");
															if (callbackIfFinish) {
																callbackIfFinish();
															}
														} else {
															//emaosoft.show_none_toast("打印失败:" + msg);
															calbackForLog("打印失败:" + msg);
														}
													});
												},
												fail: function(err) {
													emaosoft.console_log(JSON.stringify(err));
													//emaosoft.show_none_toast(err.errMsg);
													calbackForLog("正在获取蓝牙设备BLE设备服务 " + serviceId + " 的特征值失败:" + err.errMsg);
													app_intf.closeBLEConnectionAndAdapter(deviceId);
												}
											});
										}, 1000);
									}
								},
								fail: function(err) {
									emaosoft.console_log(JSON.stringify(err));
									//emaosoft.show_none_toast(err.errMsg);
									calbackForLog("获取蓝牙设备的BLE设备服务信息失败:" + err.errMsg);
									app_intf.closeBLEConnectionAndAdapter(deviceId);
								}
							});
						}, 1000);
					}
					getBLEDeviceServicesIfZeroDeviceServices();
				} else {
					calbackForLog("断开与蓝牙设备 " + deviceId + " 的连接.");
				}
			}
		});

		connectToBLEDevice();
	}

 

  • 5
    点赞
  • 11
    评论
  • 8
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值