BLE.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. /** -姜枫 2021.06.13- **/
  2. import { addPrintNum } from "@/api/order";
  3. var util = require("@/pagesOrder/js/util.js");
  4. import drawQrcode from "@/pagesOrder/js/weapp.qrcode.esm";
  5. var toArrayBuffer = require('to-array-buffer');
  6. var PrinterJobs = require("@/pagesOrder/js/printerjobs.js");
  7. var printerUtil = require("@/pagesOrder/js/printerutil.js");
  8. export default {
  9. data() {
  10. return {
  11. BleVal:'',
  12. nameBLE:'未连接',
  13. devices: [],
  14. currDev: null,
  15. isAutoBle: false,
  16. connId: "",
  17. piaojuText: [''],
  18. };
  19. },
  20. onShow() {
  21. this.devices = [];
  22. this.isAutoBle = false;
  23. if(uni.getStorageSync('BLE')){
  24. this.nameBLE = uni.getStorageSync('BLE').name;
  25. }
  26. },
  27. methods: {
  28. //断开蓝牙链接
  29. destroyed(BleVal) {
  30. this.BleVal = BleVal;
  31. let that = this;
  32. if(!uni.getStorageSync('BLE')){
  33. that.$util.confirmModal({content:'请先连接蓝牙'},() => {
  34. uni.navigateTo({url:'/pagesOrder/print'});
  35. })
  36. return;
  37. }
  38. uni.closeBLEConnection({deviceId: uni.getStorageSync('BLE').deviceId,complete(res) {
  39. console.log(res);
  40. that.autoLinkBle(BleVal);
  41. }
  42. });
  43. // if (this.connId != "") {
  44. // uni.closeBLEConnection({deviceId: uni.getStorageSync('BLE').deviceId,success(res) {
  45. // this.autoLinkBle();
  46. // }
  47. // });
  48. // }
  49. },
  50. //初始化蓝牙
  51. searchBle() {
  52. uni.showToast({
  53. title: '搜索中...',
  54. duration: 2000
  55. });
  56. var that = this;
  57. that.isAutoBle = false;
  58. uni.openBluetoothAdapter({
  59. success(res) {
  60. console.log(res,"打开 蓝牙模块");
  61. //that.onDevice();//监听搜索新设备
  62. //获取本机蓝牙适配器状态。
  63. uni.getBluetoothAdapterState({
  64. success: function(res) {
  65. console.log(res);
  66. if (res.available) {
  67. if (res.discovering) {
  68. that.stopFindBule();
  69. }
  70. //搜索蓝牙
  71. //开始搜寻附近的蓝牙外围设备
  72. console.log("开始搜寻附近的蓝牙外围设备");
  73. uni.startBluetoothDevicesDiscovery({
  74. success(res) {
  75. console.log(res);
  76. that.getBluetoothDevices()
  77. }
  78. });
  79. } else {
  80. console.log("本机蓝牙不可用");
  81. }
  82. }
  83. });
  84. }
  85. });
  86. },
  87. getBluetoothDevices(){
  88. let that = this;
  89. uni.getBluetoothDevices({
  90. success: re => {
  91. //let devices = res.devices;
  92. console.log(re,'设备列表');
  93. //var re = JSON.parse(JSON.stringify(devices));
  94. if(re.devices && re.devices.length > 0){
  95. re.devices.forEach(function(item){
  96.   
  97. let name = item.name?item.name:'未知设备';
  98. if (name != "未知设备" && name != "") {
  99. let deviceId = item.deviceId;
  100. switch(uni.getSystemInfoSync().platform){
  101. case 'android':
  102. that.devices.push({name: name,deviceId: deviceId,services: []});
  103. break;
  104. case 'ios':
  105. for (let i=0;i<that.devices.length;i++){
  106. console.log(that.devices[i].name,'----',name)
  107. if (that.devices[i].name==name) {return}
  108. }
  109. that.devices.push({name: name,deviceId: deviceId,services: []});
  110. break;
  111. }
  112. }else{
  113. console.log('name',name)
  114. console.log('re.devices[0]',re.devices[0])
  115. }
  116. });
  117. }
  118. }
  119. });
  120. },
  121. // onDevice() {
  122. // var that = this;
  123. // //监听寻找到新设备的事件
  124. // uni.onBluetoothDeviceFound(function(devices) {
  125. // console.log(devices,'设备列表');
  126. // var re = JSON.parse(JSON.stringify(devices));
  127. // let name = re.devices[0].name?re.devices[0].name:'未知设备';
  128. // if (name != "未知设备" && name != "") {
  129. // let deviceId = re.devices[0].deviceId;
  130. // switch(uni.getSystemInfoSync().platform){
  131. // case 'android':
  132. // that.devices.push({name: name,deviceId: deviceId,services: []});
  133. // break;
  134. // case 'ios':
  135. // for (let i=0;i<that.devices.length;i++){
  136. // console.log(that.devices[i].name,'----',name)
  137. // if (that.devices[i].name==name) {return}
  138. // }
  139. // that.devices.push({name: name,deviceId: deviceId,services: []});
  140. // break;
  141. // }
  142. // // that.$nextTick(()=>{
  143. // // that.$util.unique(that.devices);
  144. // // })
  145. // }
  146. // });
  147. // },
  148. //自动链接蓝牙-初始化蓝牙模块
  149. autoLinkBle(BleVal){
  150. this.BleVal = BleVal;
  151. let that = this;
  152. if(!uni.getStorageSync('BLE')){
  153. that.$util.confirmModal({content:'请先连接蓝牙'},() => {
  154. uni.navigateTo({url:'/pagesOrder/print'})
  155. })
  156. return;
  157. }
  158. uni.showLoading({title: '打印中...'});
  159. that.isAutoBle = true;
  160. let deviceId = uni.getStorageSync('BLE');
  161. //初始化蓝牙模块
  162. uni.openBluetoothAdapter({
  163. success(res) {
  164. console.log('初始化成功',res)
  165. that.autoLinkBleFun(deviceId);
  166. },fail(e){
  167. console.log('初始化失败',e)
  168. }
  169. });
  170. },
  171. //自动链接蓝牙
  172. autoLinkBleFun(item) {
  173. console.log('自动链接 444444444444444444444444444444444444444444444444444')
  174. var that = this;
  175. let deviceId = item.deviceId;
  176. uni.createBLEConnection({
  177. deviceId: deviceId,
  178. complete(res) {
  179. console.log(res,'自动连接成功')
  180. if (res.errMsg == "createBLEConnection:ok") {
  181. uni.setStorageSync('BLE',item);
  182. setTimeout(function() {
  183. that.getBLEServices(deviceId);
  184. }, 2000);
  185. }
  186. }
  187. });
  188. },
  189. stopFindBule() {
  190. console.log("停止搜寻附近的蓝牙外围设备---------------");
  191. uni.stopBluetoothDevicesDiscovery({
  192. success(res) {
  193. console.log(res);
  194. }
  195. });
  196. },
  197. onConn(item) {
  198. console.log('正在连接 333333333333333333333333333333333333333333333333333333333333333333333333')
  199. uni.showLoading({title: '正在连接...'});
  200. var that = this;
  201. // console.log("连接蓝牙---------------" + item.deviceId);
  202. let deviceId = item.deviceId;
  203. uni.createBLEConnection({
  204. deviceId: deviceId,
  205. complete(res) {
  206. if (res.errMsg == "createBLEConnection:ok") {
  207. that.nameBLE = item.name;
  208. // console.log("连接蓝牙-[" + item.name + "]--成功");
  209. // that.$msg("连接蓝牙-[" + item.name + "]--成功");
  210. that.connId = deviceId;
  211. that.currDev = item;
  212. setTimeout(function() {
  213. that.getBLEServices(deviceId);
  214. }, 2000);
  215. } else {
  216. console.log(res);
  217. }
  218. //连接成功 关闭搜索
  219. that.stopFindBule();
  220. }
  221. });
  222. },
  223. getBLEServices(_deviceId) {
  224. var that = this;
  225. let deviceId = _deviceId;
  226. console.log("获取蓝牙设备所有服务(service)");
  227. console.log('获取蓝牙设备所有服务 222222222222222222222222222222222222222222222222222222222')
  228. uni.getBLEDeviceServices({
  229. // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
  230. deviceId: deviceId,
  231. success(res) {
  232. console.log('getBLEDeviceServices成功:',res)
  233. for (var s = 0; s < res.services.length; s++) {
  234. console.log(res.services[s].uuid);
  235. let serviceId = res.services[s].uuid;
  236. uni.getBLEDeviceCharacteristics({
  237. // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
  238. deviceId: deviceId,
  239. // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
  240. serviceId: serviceId,
  241. success(res) {
  242. var re = JSON.parse(JSON.stringify(res));
  243. console.log("deviceId = [" + deviceId + "] serviceId = [" + serviceId + "]")
  244. for (var c = 0; c < re.characteristics.length; c++) {
  245. if (re.characteristics[c].properties.write == true) {
  246. let uuid = re.characteristics[c].uuid;
  247. console.log(" deviceId = [" +deviceId +"] serviceId = [" +serviceId +"] characteristics = [" +uuid +"]");
  248. //是否是直接打印
  249. if(that.isAutoBle){
  250. console.log('打印订单 11111111111111111111111111111111111111111111111111111111111111')
  251. that.senBleLabel()
  252. uni.hideLoading()
  253. that.isAutoBle = false
  254. }
  255. for (var index in that.devices) {
  256. if (that.devices[index].deviceId == deviceId) {
  257. that.devices[index].services.push({serviceId: serviceId,characteristicId: uuid});
  258. that.$nextTick(()=>{
  259. uni.setStorageSync('BLE',that.devices[index]);
  260. that.$msg("连接蓝牙-[" + that.devices[index].name + "]--成功");
  261. })
  262. break;
  263. }
  264. }
  265. console.log(JSON.stringify(that.devices));
  266. }
  267. }
  268. }
  269. });
  270. }
  271. },
  272. fail(res) {
  273. console.log('getBLEDeviceServices失败:',res)
  274. uni.hideLoading()
  275. uni.showLoading({title:"打印失败..."})
  276. setTimeout(function(){
  277. uni.hideLoading()
  278. },2000)
  279. // if(res.errCode && res.errCode == 10004){
  280. // uni.showLoading({title:"重打中..."})
  281. // that.destroyed(that.BleVal)
  282. // }
  283. }
  284. });
  285. },
  286. _writeBLECharacteristicValue(data) {
  287. uni.writeBLECharacteristicValue({
  288. deviceId: data.deviceId,
  289. serviceId: data.serviceId,
  290. characteristicId: data.characteristicId,
  291. value: data.buffer,
  292. success(res) {
  293. console.log('writeBLECharacteristicValue success', res)
  294. },
  295. fail(res) {
  296. console.log('writeBLECharacteristicValue fail', res)
  297. }
  298. })
  299. },
  300. senBleLabel() {
  301. let BleVal = this.BleVal;
  302. let that = this;
  303. console.log(BleVal,'BleValBleVal')
  304. let currDev = uni.getStorageSync('BLE');
  305. let deviceId = currDev.deviceId;
  306. let serviceId = currDev.services[0].serviceId;
  307. let characteristicId = currDev.services[0].characteristicId;
  308. let currentRealPrice = BleVal.debt == 1 ? '0.00' : BleVal.realPrice;
  309. let printerJobs = new PrinterJobs();
  310. printerJobs
  311. .setSize(2, 2)
  312. .print(BleVal.sendNum)
  313. .setSize(1, 1)
  314. .print(printerUtil.fillLine())
  315. .setSize(2, 2)
  316. .print(BleVal.custom.fullAddress)
  317. .print(BleVal.custom.customName)
  318. .print(BleVal.custom.customMobile)
  319. .setSize(1, 1)
  320. .print("备注:")
  321. .setSize(2, 2)
  322. .print(BleVal.remark)
  323. .setSize(1, 1)
  324. .setAlign('lt')
  325. .print(printerUtil.fillAround('花材 数量 价格'));
  326. if(BleVal.product.length > 0){
  327. BleVal.product.forEach(function(currentItem){
  328. printerJobs.print(printerUtil.inline(currentItem.name+' '+currentItem.num, currentItem.price));
  329. })
  330. }
  331. printerJobs.print(printerUtil.fillLine());
  332. //printerJobs.setAlign('rt');
  333. printerJobs.setAlign('lt')
  334. if(BleVal.sendCost>0){
  335. printerJobs.print('运费:¥'+BleVal.sendCost);
  336. }
  337. printerJobs.print('总金额:¥'+BleVal.prePrice);
  338. if(BleVal.discountAmount > 0){
  339. printerJobs.print('优惠:¥'+BleVal.discountAmount);
  340. }
  341. printerJobs.print('应付金额:¥'+BleVal.realPrice);
  342. printerJobs.print('实付金额:¥'+currentRealPrice);
  343. if(BleVal.debtAmount > 0){
  344. printerJobs.print('累计欠款:¥'+BleVal.debtAmount);
  345. }
  346. printerJobs.print(printerUtil.fillLine());
  347. printerJobs.print('订单日期:'+BleVal.date);
  348. printerJobs.print('订单编号:'+BleVal.orderSn);
  349. printerJobs.print('门店名称:纯彩花艺');
  350. printerJobs.print('门店地址:'+BleVal.address);
  351. printerJobs.println().println();
  352. let buffer = printerJobs.buffer();
  353. // 1.并行调用多次会存在写失败的可能性
  354. // 2.建议每次写入不超过20字节
  355. // 分包处理,延时调用
  356. const maxChunk = 20;
  357. const delay = 20;
  358. for (let i = 0, j = 0, length = buffer.byteLength; i < length; i += maxChunk, j++) {
  359. let subPackage = buffer.slice(i, i + maxChunk <= length ? (i + maxChunk) : length);
  360. setTimeout(this._writeBLECharacteristicValue, j * delay, {deviceId:deviceId, serviceId:serviceId, characteristicId:characteristicId,buffer:subPackage});
  361. }
  362. //增加打印次数
  363. addPrintNum({id:that.orderId}).then(res=>{
  364. if(!that.$util.isEmpty(that.detailInfo)){
  365. that.detailInfo.printNum++;
  366. }
  367. if(!that.$util.isEmpty(that.list.data)){
  368. that.list.data.forEach(ele=>{
  369. if (ele.id==that.orderId) {
  370. ele.printNum++;
  371. }
  372. })
  373. }
  374. })
  375. // let arrPrint = [];
  376. // //初始化打印机
  377. // arrPrint.push(util.sendDirective([0x1B, 0x40])); //16进制
  378. // //正文
  379. // arrPrint.push(util.sendDirective([0x1B, 0x0E]));
  380. // //字体宽高加倍
  381. // arrPrint.push(util.sendDirective([0x1d, 0x21, 0x11]));
  382. // arrPrint.push(util.hexStringToBuff(BleVal.sendNum));
  383. // //字体不放大,宽高不再加倍
  384. // arrPrint.push(util.sendDirective([0x1d, 0x21, 0x00]));
  385. // arrPrint.push(util.sendDirective([0x1B, 0x14]));
  386. // arrPrint.push(util.hexStringToBuff(" |纯彩花艺\n"));
  387. // arrPrint.push(util.sendDirective([0x1B, 0x14]));
  388. // arrPrint.push(util.hexStringToBuff("--------------------------------\n"));
  389. // arrPrint.push(util.sendDirective([0x1B, 0x0E]));
  390. // //字体宽高加倍
  391. // arrPrint.push(util.sendDirective([0x1d, 0x21, 0x11]));
  392. // arrPrint.push(util.hexStringToBuff(BleVal.custom.fullAddress+ "\n"));
  393. // arrPrint.push(util.sendDirective([0x1B, 0x0E]));
  394. // arrPrint.push(util.hexStringToBuff(BleVal.custom.customName+"\n"+BleVal.custom.customMobile+ "\n"));
  395. // //字体不放大,宽高不再加倍
  396. // arrPrint.push(util.sendDirective([0x1d, 0x21, 0x00]));
  397. // if(BleVal.remark.length > 0){
  398. // arrPrint.push(util.sendDirective([0x1B, 0x14]));
  399. // arrPrint.push(util.hexStringToBuff("--------------------------------\n"));
  400. // arrPrint.push(util.hexStringToBuff("备注:\n"));
  401. // arrPrint.push(util.sendDirective([0x1B, 0x0E]));
  402. // //字体宽高加倍
  403. // arrPrint.push(util.sendDirective([0x1d, 0x21, 0x11]));
  404. // arrPrint.push(util.hexStringToBuff(BleVal.remark+"\n"));
  405. // //字体不放大,宽高不再加倍
  406. // arrPrint.push(util.sendDirective([0x1d, 0x21, 0x00]));
  407. // }
  408. // arrPrint.push(util.sendDirective([0x1B, 0x14]));
  409. // arrPrint.push(util.hexStringToBuff("--------------------------------\n"));
  410. // arrPrint.push(util.hexStringToBuff(util.printThreeData('花材', '数量', '价格')));
  411. // if(BleVal.product.length > 0){
  412. // BleVal.product.forEach(function(currentItem){
  413. // arrPrint.push(util.hexStringToBuff(util.printThreeData(currentItem.name, currentItem.num, currentItem.price)))
  414. // })
  415. // }
  416. // arrPrint.push(util.hexStringToBuff("--------------------------------\n"));
  417. // arrPrint.push(util.hexStringToBuff(util.printTwoData("运费:", BleVal.sendCost)));
  418. // arrPrint.push(util.hexStringToBuff(util.printTwoData("总金额:", BleVal.prePrice)));
  419. // arrPrint.push(util.hexStringToBuff(util.printTwoData("优惠:", BleVal.discountAmount)));
  420. // arrPrint.push(util.hexStringToBuff(util.printTwoData("应付金额:", BleVal.realPrice)));
  421. // arrPrint.push(util.hexStringToBuff(util.printTwoData("实付金额:", BleVal.debt == 1 ? '0.00' : BleVal.realPrice)));
  422. // if(BleVal.debtAmount > 0){
  423. // //加粗
  424. // //arrPrint.push(util.sendDirective([0x1b, 0x45, 0x01]));
  425. // arrPrint.push(util.hexStringToBuff(util.printTwoData("累计欠款:", BleVal.debtAmount)));
  426. // //取消加粗
  427. // //arrPrint.push(util.sendDirective([0x1b, 0x45, 0x00]));
  428. // }
  429. // arrPrint.push(util.hexStringToBuff(util.printTwoData("订单日期:", BleVal.date)));
  430. // arrPrint.push(util.hexStringToBuff(util.printTwoData("订单编号:", BleVal.orderSn)));
  431. // arrPrint.push(util.sendDirective([0x1B, 0x61, 0x00]));
  432. // arrPrint.push(util.hexStringToBuff("门店地址:"+BleVal.address+"\n"));
  433. // arrPrint.push(util.hexStringToBuff("\n\n\n\n"));
  434. // const ctx = uni.createCanvasContext('canvas');
  435. // ctx.clearRect(0, 0, 130, 130);
  436. // let tthis = this;
  437. // drawQrcode({
  438. // canvasId: 'canvas',
  439. // text: 'https://shop.huahb.cn/#/main/index',
  440. // width: 130,
  441. // height: 130,
  442. // callback(e) {
  443. // console.log(111111123)
  444. // setTimeout(() => {
  445. // // 获取图片数据
  446. // uni.canvasGetImageData({
  447. // canvasId: 'canvas',
  448. // x: 0,
  449. // y: 0,
  450. // width: 130,
  451. // height: 130,
  452. // success(res) {
  453. // let arr = tthis.convert4to1(res.data);
  454. // let data = tthis.convert8to1(arr);
  455. // const cmds = [].concat([27, 97, 1], [29, 118, 48, 0, 20, 0, 160, 0], data, [27, 74, 3], [27, 64]);
  456. // const buffer = toArrayBuffer(Buffer.from(cmds, 'gb2312'));
  457. // console.log(123456789)
  458. // arrPrint.push(util.sendDirective([0x1B, 0x40]));
  459. // for (let i = 0; i < buffer.byteLength; i = i + 20) {
  460. // arrPrint.push(buffer.slice(i, i + 20));
  461. // }
  462. // arrPrint.push(util.hexStringToBuff("\n"));
  463. // arrPrint.push(util.sendDirective([0x1B, 0x61, 0x01])); //居中
  464. // arrPrint.push(util.hexStringToBuff("扫码采购花材\n"));
  465. // arrPrint.push(util.hexStringToBuff("\n"));
  466. // arrPrint.push(util.hexStringToBuff("\n"));
  467. // }
  468. // })
  469. // }, 3000);
  470. // }
  471. // });
  472. // this.printInfo({deviceId:deviceId, serviceId:serviceId, characteristicId:characteristicId}, arrPrint);
  473. },
  474. //4合1
  475. convert4to1(res) {
  476. let arr = [];
  477. for (let i = 0; i < res.length; i++) {
  478. if (i % 4 == 0) {
  479. let rule = 0.29900 * res[i] + 0.58700 * res[i + 1] + 0.11400 * res[i + 2];
  480. if (rule > 200) {
  481. res[i] = 0;
  482. } else {
  483. res[i] = 1;
  484. }
  485. arr.push(res[i]);
  486. }
  487. }
  488. return arr;
  489. },
  490. //8合1
  491. convert8to1(arr) {
  492. let data = [];
  493. for (let k = 0; k < arr.length; k += 8) {
  494. let temp = arr[k] * 128 + arr[k + 1] * 64 + arr[k + 2] * 32 + arr[k + 3] * 16 + arr[k + 4] * 8 + arr[k + 5] * 4 +
  495. arr[k + 6] * 2 + arr[k + 7] * 1
  496. data.push(temp);
  497. }
  498. return data;
  499. },
  500. printInfo(device, arr, callback) {
  501. let tthis = this;
  502. if (arr.length > 0) {
  503. tthis.sendStr(device, arr[0], function(success) {
  504. arr.shift();
  505. tthis.printInfo(device, arr, callback);
  506. }, function(error) {
  507. console.log(error);
  508. });
  509. } else {
  510. callback ? callback() : '';
  511. }
  512. },
  513. //发送数据
  514. sendStr(device, bufferstr, success, fail) {
  515. let tthis = this;
  516. uni.writeBLECharacteristicValue({
  517. deviceId: device.deviceId,
  518. serviceId: device.serviceId,
  519. characteristicId: device.characteristicId,
  520. value: bufferstr,
  521. success: function(res) {
  522. success(res);
  523. console.log('sendStr', bufferstr)
  524. },
  525. failed: function(res) {
  526. fail(res)
  527. console.log("数据发送失败:" + JSON.stringify(res))
  528. }
  529. })
  530. },
  531. }
  532. }