BLE.js 18 KB

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