Browse Source

蓝牙打印可用

shish 5 years ago
parent
commit
c7633bd8c2

+ 76 - 71
ghsApp/src/mixins/BLE.js

@@ -1,6 +1,7 @@
 /** -姜枫 2021.06.13- **/
 var tsc = require("@/pagesOrder/js/gprint/tsc.js");
 var esc = require("@/pagesOrder/js/gprint/esc.js");
+var util = require("@/pagesOrder/js/util.js");
 export default {
 	data() {
 		return {
@@ -10,7 +11,7 @@ export default {
 			currDev: null,
 			isAutoBle: false,
 			connId: "",
-			piaojuText: ['测试测试测试测试傻老大傻老大','测试测试测试测试傻老大傻老大','测试测试测试测试傻老大傻老大'],
+			piaojuText: [''],
 		};
 	},
 	onShow() {
@@ -43,7 +44,6 @@ export default {
 			});
 			// if (this.connId != "") {
 			// 	uni.closeBLEConnection({deviceId: uni.getStorageSync('BLE').deviceId,success(res) {
-			// 			console.log(res);
 			// 			this.autoLinkBle();
 			// 		}
 			// 	});
@@ -142,6 +142,7 @@ export default {
 		},
 		//自动链接蓝牙
 		autoLinkBleFun(item) {
+			console.log('自动链接 444444444444444444444444444444444444444444444444444')
 			var that = this;
 			let deviceId = item.deviceId;
 			uni.createBLEConnection({
@@ -166,6 +167,7 @@ export default {
 			});
 		},
 		onConn(item) {
+			console.log('正在连接 333333333333333333333333333333333333333333333333333333333333333333333333')
 			uni.showLoading({title: '正在连接...'});
 			var that = this;
 			// console.log("连接蓝牙---------------" + item.deviceId);
@@ -196,13 +198,13 @@ export default {
 			let deviceId = _deviceId;
 			console.log("获取蓝牙设备所有服务(service)");
 
+			console.log('获取蓝牙设备所有服务 222222222222222222222222222222222222222222222222222222222')
+
 			uni.getBLEDeviceServices({
 				// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
 				deviceId: deviceId,
 				complete(res) {
-					console.log(res);
-					let serviceId = "";
-
+					console.log(res)
 					for (var s = 0; s < res.services.length; s++) {
 						console.log(res.services[s].uuid);
 						let serviceId = res.services[s].uuid;
@@ -214,13 +216,19 @@ export default {
 							success(res) {
 								var re = JSON.parse(JSON.stringify(res));
 
-								console.log("deviceId = [" + deviceId + "]  serviceId = [" + serviceId + "]");
+								console.log("deviceId = [" + deviceId + "]  serviceId = [" + serviceId + "]")
+
 								for (var c = 0; c < re.characteristics.length; c++) {
 									if (re.characteristics[c].properties.write == true) {
 										let uuid = re.characteristics[c].uuid;
-										console.log(" deviceId = [" +deviceId +"]  serviceId = [" +serviceId +"] characteristics=[" +uuid);
+										console.log(" deviceId = [" +deviceId +"]  serviceId = [" +serviceId +"] characteristics = [" +uuid +"]");
 										//是否是直接打印
-										if(that.isAutoBle){that.senBleLabel();return}
+										if(that.isAutoBle){
+											console.log('打印订单 11111111111111111111111111111111111111111111111111111111111111')
+											that.senBleLabel()
+											uni.hideLoading()
+											that.isAutoBle = false
+										}
 										for (var index in that.devices) {
 											if (that.devices[index].deviceId == deviceId) {
 												that.devices[index].services.push({serviceId: serviceId,characteristicId: uuid});
@@ -231,7 +239,6 @@ export default {
 												break;
 											}
 										}
-
 										console.log(JSON.stringify(that.devices));
 									}
 								}
@@ -244,46 +251,6 @@ export default {
 				}
 			});
 		},
-		senBlData(deviceId, serviceId, characteristicId, uint8Array) {
-			console.log("************deviceId = [" +deviceId +"]  serviceId = [" +serviceId +"] characteristics=[" +characteristicId +"]");
-			var uint8Buf = Array.from(uint8Array);
-			function split_array(datas, size) {
-				var result = {};
-				var j = 0;
-				for (var i = 0; i < datas.length; i += size) {
-					result[j] = datas.slice(i, i + size);
-					j++;
-				}
-				console.log(result);
-				return result;
-			}
-			var sendloop = split_array(uint8Buf, 20);
-			// console.log(sendloop.length)
-			function realWriteData(sendloop, i) {
-				var data = sendloop[i];
-				if (typeof data == "undefined") {
-					return;
-				}
-				console.log("第【" + i + "】次写数据" + data);
-				var buffer = new ArrayBuffer(data.length);
-				var dataView = new DataView(buffer);
-				for (var j = 0; j < data.length; j++) {
-					dataView.setUint8(j, data[j]);
-				}
-				uni.hideLoading();
-				uni.writeBLECharacteristicValue({
-					deviceId,
-					serviceId,
-					characteristicId,
-					value: buffer,
-					success(res) {
-						realWriteData(sendloop, i + 1);
-					}
-				});
-			}
-			var i = 0;
-			realWriteData(sendloop, i);
-		},
 		senBleLabel() {
 			let BleVal = this.BleVal;
 			console.log(BleVal,'BleValBleVal')
@@ -292,29 +259,67 @@ export default {
 			let deviceId = currDev.deviceId;
 			let serviceId = currDev.services[0].serviceId;
 			let characteristicId = currDev.services[0].characteristicId;
-			var command = tsc.jpPrinter.createNew();
-			command.setSize(40, 60);
-			command.setGap(2);
-			command.setCls();
-			for (let i=0;i<BleVal.length;i++){
-				command.setText(BleVal[i].name);
-				command.setText(BleVal[i].phone);
-			}
 
-			command.setPagePrint();
-			this.senBlData(deviceId, serviceId, characteristicId, command.getData());
+			let arrPrint = [];
+			//初始化打印机
+			arrPrint.push(util.sendDirective([0x1B, 0x40])); //16进制
+			//居中对齐
+			arrPrint.push(util.sendDirective([0x1B, 0x61, 0x01])); //居中
+			//正文
+			arrPrint.push(util.sendDirective([0x1B, 0x0E]));
+			arrPrint.push(util.hexStringToBuff("\n葵花生活\n\n"));
+			arrPrint.push(util.sendDirective([0x1B, 0x14]));
+			arrPrint.push(util.hexStringToBuff('葵花生活测试门店1号店' + "\n"));
+			arrPrint.push(util.hexStringToBuff("订单号" + 'W20154221212222' + "\n"));
+			arrPrint.push(util.hexStringToBuff("--------------------------------\n"));
+			arrPrint.push(util.hexStringToBuff(util.printThreeData('名称', '数量', '价格')));
+			arrPrint.push(util.hexStringToBuff(util.printThreeData('衣物', 10, '3元')))
+			arrPrint.push(util.hexStringToBuff("--------------------------------\n"));
+			arrPrint.push(util.hexStringToBuff(util.printTwoData("总金额:", '3元')));
+			arrPrint.push(util.hexStringToBuff(util.printTwoData("优惠券:", '3元')));
+			arrPrint.push(util.hexStringToBuff(util.printTwoData("实付金额:", '3元')));
+			arrPrint.push(util.hexStringToBuff(util.printTwoData("下单:", '2019-10-20 12:20:20')));
+			arrPrint.push(util.hexStringToBuff(util.printTwoData("支付:", '已支付')));
+			arrPrint.push(util.hexStringToBuff(util.printTwoData("客户:", '张三')));
+			arrPrint.push(util.hexStringToBuff(util.printTwoData("电话:", '13880253762')));
+			arrPrint.push(util.sendDirective([0x1B, 0x61, 0x00]));
+			arrPrint.push(util.hexStringToBuff("1.请妥善保管票单,凭票取物;\n"));
+			arrPrint.push(util.hexStringToBuff("2.顾客购意见及建议,请及时提出,本店积极采纳,全心全意为顾客服务\n"));
+			arrPrint.push(util.hexStringToBuff("\n\n\n"));
+
+			this.printInfo({deviceId:deviceId, serviceId:serviceId, characteristicId:characteristicId}, arrPrint);
+
+		},
+		printInfo(device, arr, callback) {
+			let tthis = this;
+			if (arr.length > 0) {
+				tthis.sendStr(device, arr[0], function(success) {
+					arr.shift();
+					tthis.printInfo(device, arr, callback);
+				}, function(error) {
+					console.log(error);
+				});
+			} else {
+				callback ? callback() : '';
+			}
+		},
+		//发送数据
+		sendStr(device, bufferstr, success, fail) {
+			let tthis = this;
+			uni.writeBLECharacteristicValue({
+				deviceId: device.deviceId,
+				serviceId: device.serviceId,
+				characteristicId: device.characteristicId,
+				value: bufferstr,
+				success: function(res) {
+					success(res);
+					console.log('sendStr', bufferstr)
+				},
+				failed: function(res) {
+					fail(res)
+					console.log("数据发送失败:" + JSON.stringify(res))
+				}
+			})
 		},
-		billPrint() {
-			let currDev = uni.getStorageSync('BLE');
-			//票据模式
-			let deviceId = currDev.deviceId;
-			let serviceId = currDev.services[0].serviceId;
-			let characteristicId = currDev.services[0].characteristicId;
-			var command = esc.jpPrinter.createNew();
-			command.init();
-			command.setText(this.piaojuText);
-			command.setPrintAndFeedRow(1);
-			this.senBlData(deviceId, serviceId, characteristicId, command.getData());
-		}
 	}
 }

File diff suppressed because it is too large
+ 21 - 0
ghsApp/src/pagesOrder/js/gbk.js


+ 61 - 0
ghsApp/src/pagesOrder/js/index.js

@@ -0,0 +1,61 @@
+/**
+ * @module  to-array-buffer
+ */
+
+'use strict'
+
+var str2ab = require('string-to-arraybuffer')
+var flat = require('flatten-vertex-data')
+// var isBlob = require('is-blob')
+
+
+module.exports = function toArrayBuffer (arg) {
+	//zero-length or undefined-like
+	if (!arg) return null
+
+	//array buffer
+	if (arg instanceof ArrayBuffer) return arg
+
+	//try to decode data-uri
+	if (typeof arg === 'string') {
+		return str2ab(arg)
+	}
+
+	// File & Blob
+	// if (isBlob(src) || (src instanceof global.File)) {
+		// FIXME: we cannot use it here bc FileReader is async
+	// }
+
+	//array buffer view: TypedArray, DataView, Buffer etc
+	if (ArrayBuffer.isView(arg)) {
+		// if byteOffset is not 0, return sub-reference (slice is the only way)
+		if (arg.byteOffset) {
+			return arg.buffer.slice(arg.byteOffset, arg.byteOffset + arg.byteLength)
+		}
+		return arg.buffer
+	}
+
+	//buffer/data nested: NDArray, ImageData etc.
+	//FIXME: NDArrays with custom data type may be invalid for this procedure
+	if (arg.buffer || arg.data || arg._data) {
+		var result = toArrayBuffer(arg.buffer || arg.data || arg._data)
+		return result
+	}
+
+	// detect if flat
+	if (Array.isArray(arg)) {
+		for (var i = 0; i < arg.length; i++) {
+			if (arg[i].length != null) {
+				arg = flat(arg)
+				break
+			}
+		}
+	}
+
+	//array-like or unknown
+	//consider Uint8Array knows how to treat the input
+	var result = new Uint8Array(arg)
+
+	if (!result.length) return null
+	return result.buffer
+}

+ 234 - 0
ghsApp/src/pagesOrder/js/util.js

@@ -0,0 +1,234 @@
+const gbk = require('./gbk.js');
+const formatTime = date => {
+  const year = date.getFullYear()
+  const month = date.getMonth() + 1
+  const day = date.getDate()
+  const hour = date.getHours()
+  const minute = date.getMinutes()
+  const second = date.getSeconds()
+
+  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
+}
+
+const formatNumber = n => {
+  n = n.toString()
+  return n[1] ? n : '0' + n
+}
+
+
+const hexStringToBuff = str => { //str='中国:WXHSH'
+  //const buffer = new ArrayBuffer((sumStrLength(str)) * 4)
+  const buffer = new ArrayBuffer((sumStrLength(str)) + 1);
+  const dataView = new DataView(buffer)
+  var data = str.toString();
+  var p = 0; //ArrayBuffer 偏移量
+  for (var i = 0; i < data.length; i++) {
+    if (isCN(data[i])) { //是中文
+      //调用GBK 转码
+			// console.log(29,data[i])
+      var t = gbk.encode(data[i]);
+      for (var j = 0; j < 2; j++) {
+        //var code = t[j * 2] + t[j * 2 + 1];
+        var code = t[j * 3 + 1] + t[j * 3 + 2];
+        var temp = parseInt(code, 16)
+        //var temp = strToHexCharCode(code);
+        dataView.setUint8(p++, temp)
+      }
+    } else {
+      var temp = data.charCodeAt(i);
+      dataView.setUint8(p++, temp)
+    }
+  }
+  return buffer;
+}
+
+function toUnicode(s) {
+  var str = "";
+  for (var i = 0; i < s.length; i++) {
+    str += "\\u" + s.charCodeAt(i).toString(16) + "\t";
+  }
+  return str;
+}
+
+function strToHexCharCode(str) {
+  if (str === "")
+    return "";
+  var hexCharCode = [];
+  hexCharCode.push("0x");
+  for (var i = 0; i < str.length; i++) {
+    hexCharCode.push((str.charCodeAt(i)).toString(16));
+  }
+  return hexCharCode.join("");
+}
+
+function sumStrLength(str) {
+  var length = 0;
+  var data = str.toString();
+  for (var i = 0; i < data.length; i++) {
+    if (isCN(data[i])) { //是中文
+      length += 2;
+    } else {
+      length += 1;
+    }
+  }
+  return length;
+}
+
+function isCN(str) {
+	let characterA =/^[\u4e00-\u9fa5]+$/
+	let characterB = /^[\uFF01]|[\uFF0C-\uFF0E]|[\uFF1A-\uFF1B]|[\uFF1F]|[\uFF08-\uFF09]|[\u3001-\u3002]|[\u3010-\u3011]|[\u201C-\u201D]|[\u2013-\u2014]|[\u2018-\u2019]|[\u2026]|[\u3008-\u300F]|[\u3014-\u3015]+$/
+  if (characterA.test(str) || characterB.test(str)) {
+    return true;
+  } else {
+    return false;
+  }
+}
+
+//汉字转码
+function hexStringToArrayBuffer(str) {
+  const buffer = new ArrayBuffer((str.length / 2) + 1)
+  const dataView = new DataView(buffer)
+  for (var i = 0; i < str.length / 2; i++) {
+    var temp = parseInt(str[i * 2] + str[i * 2 + 1], 16)
+    dataView.setUint8(i, temp)
+  }
+  dataView.setUint8((str.length / 2), 0x0a)
+  return buffer;
+}
+
+//返回八位数组
+function subString(str) {
+  var arr = [];
+  if (str.length > 8) { //大于8
+    for (var i = 0;
+      (i * 8) < str.length; i++) {
+      var temp = str.substring(i * 8, 8 * i + 8);
+      arr.push(temp)
+    }
+    return arr;
+  } else {
+    return str
+  }
+}
+
+//不带有汉字
+function hexStringToArrayBufferstr(str) {
+  let val = ""
+  for (let i = 0; i < str.length; i++) {
+    if (val === '') {
+      val = str.charCodeAt(i).toString(16)
+    } else {
+      val += ',' + str.charCodeAt(i).toString(16)
+    }
+  }
+  val += "," + "0x0a";
+  console.log(val)
+  // 将16进制转化为ArrayBuffer
+  return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function(h) {
+    return parseInt(h, 16)
+  })).buffer
+}
+
+//换行符号
+function send0X0A() {
+  const buffer = new ArrayBuffer(1)
+  const dataView = new DataView(buffer)
+  dataView.setUint8(0, 0x0a)
+  return buffer;
+}
+
+function sendDirective(arr) {
+  const buffer = new ArrayBuffer(arr.length)
+  const dataView = new DataView(buffer)
+  for (let i in arr) {
+    dataView.setUint8(i, arr[i])
+  }
+  return buffer;
+}
+
+function replaceStr(str) {
+  str = str.toString();
+  // console.log(147, str)
+  if (str) {
+    let len = getBytesLength(str);
+    let minLen = 4;
+    if (len < minLen) {
+      let nstr='';
+      for (let i = 0; i < minLen-len; i++) {
+        nstr = nstr + ' ';
+      }
+      str = nstr + str;
+    } else {
+      str = str;
+    }
+  } else {
+    str = ''
+  }
+  console.log(163, str);
+  return str
+}
+
+//计算打印的位置
+function printTwoData(leftText, rightText) {
+  let sb = '';
+  let maxLen = 32;
+  let leftTextLength = getBytesLength(leftText);
+  let rightTextLength = getBytesLength(rightText);
+  let spaceLen = maxLen - leftTextLength - rightTextLength;
+  sb = sb + leftText;
+  for (let i = 0; i < spaceLen; i++) {
+    sb = sb + ' ';
+  }
+  sb = sb + rightText + '\n';
+  return sb.toString();
+}
+
+function printThreeData(leftText, centerText, rightText) {
+  let sb = '';
+  let maxLen = 32;
+  
+  leftText = replaceStr(leftText);
+  centerText = replaceStr(centerText);
+  rightText = replaceStr(rightText);
+  
+  let leftTextLength = getBytesLength(leftText);
+  let centerTextLength = getBytesLength(centerText);
+  let rightTextLength = getBytesLength(rightText);
+  let spaceLeft = maxLen/2 - leftTextLength - centerTextLength/2;
+  let spaceRight = maxLen/2 - centerTextLength/2 - rightTextLength;
+   
+  console.log(168, leftTextLength, centerTextLength, rightTextLength, spaceLeft,spaceRight);
+  sb = sb + leftText;
+  for (let i = 0; i < spaceLeft; i++) {
+    sb = sb + ' ';
+  }
+  sb = sb + centerText;
+  for (let i = 0; i < spaceRight; i++) {
+    sb = sb + ' ';
+  }
+  sb = sb + rightText + '\n';
+  console.log('printThreeData', sb);
+  return sb.toString();
+}
+
+function getBytesLength(val) {
+  var str = new String(val);
+  var bytesCount = 0;
+  for (var i = 0, n = str.length; i < n; i++) {
+    var c = str.charCodeAt(i);
+    if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
+      bytesCount += 1;
+    } else {
+      bytesCount += 2;
+    }
+  }
+  return bytesCount;
+}
+
+module.exports = {
+  hexStringToArrayBuffer: hexStringToArrayBuffer,
+  hexStringToBuff: hexStringToBuff,
+  sendDirective: sendDirective,
+  printTwoData: printTwoData,
+  printThreeData: printThreeData
+}

File diff suppressed because it is too large
+ 4 - 0
ghsApp/src/pagesOrder/js/weapp.qrcode.esm.js


Some files were not shown because too many files changed in this diff