receipt.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. var app = getApp();
  2. var esc = require("../../utils/esc.js");
  3. var encode = require("../../utils/encoding.js");
  4. function inArray(arr, key, val) {
  5. for (let i = 0; i < arr.length; i++) {
  6. if (arr[i][key] === val) {
  7. return i;
  8. }
  9. }
  10. return -1;
  11. }
  12. // ArrayBuffer转16进度字符串示例
  13. function ab2hex(buffer) {
  14. var hexArr = Array.prototype.map.call(
  15. new Uint8Array(buffer),
  16. function(bit) {
  17. return ('00' + bit.toString(16)).slice(-2)
  18. }
  19. )
  20. return hexArr.join('');
  21. }
  22. function convertToGrayscale(data) {
  23. let g = 0
  24. for (let i = 0; i < data.length; i += 4) {
  25. g = (data[i] * 0.3 + data[i + 1] * 0.59 + data[i + 2] * 0.11)
  26. data[i] = g
  27. data[i + 1] = g
  28. data[i + 2] = g
  29. }
  30. return data
  31. }
  32. function setPixel(data, offset, value) {
  33. data[offset] = value;
  34. data[offset + 1] = value;
  35. data[offset + 2] = value;
  36. }
  37. function adjustPixel(data, offset, value) {
  38. data[offset] += value;
  39. }
  40. // 彩色图转成单色图
  41. function convertToMonoImage(width, height, data, shake) {
  42. let g = 0
  43. let e = 0
  44. for (let i = 0; i < data.length; i += 4) {
  45. data[i] = (data[i] * 0.3 + data[i + 1] * 0.59 + data[i + 2] * 0.11);
  46. }
  47. for (let y = 0; y < height; y++) {
  48. for (let x = 0; x < width; x++) {
  49. let dataOffset = (width * y + x) * 4;
  50. g = data[dataOffset];
  51. if (g >= 150) { // 灰色转黑白的阈值, 可以调整打印效果
  52. e = g - 255;
  53. setPixel(data, dataOffset, 255);
  54. } else {
  55. e = g;
  56. setPixel(data, dataOffset, 0);
  57. }
  58. if (!shake)
  59. continue;
  60. if (x < width - 1 && y < height - 1) {
  61. //右边像素处理
  62. data[(width * y + x + 1) * 4] += 7 * e / 16;
  63. //下
  64. data[(width * (y + 1) + x) * 4] += 5 * e / 16;
  65. //右下
  66. data[(width * (y + 1) + x + 1) * 4] += e / 16;
  67. //左下
  68. if (x > 0) {
  69. data[(width * (y + 1) + x - 1) * 4] += 3 * e / 16;
  70. }
  71. } else if (x == width - 1 && y < height - 1) {
  72. //下方像素处理
  73. data[(width * (y + 1) + x) * 4] += 5 * e / 16;
  74. } else if (x < width - 1 && y == height - 1) {
  75. //右边像素处理
  76. data[(width * y + x + 1) * 4] += 7 * e / 16;
  77. }
  78. }
  79. }
  80. return data
  81. }
  82. Page({
  83. /**
  84. * 页面的初始数据
  85. */
  86. data: {
  87. looptime: 0,
  88. currentTime: 1,
  89. lastData: 0,
  90. oneTimeData: 0,
  91. buffSize: [],
  92. buffIndex: 0, //发送字节数下标
  93. printNum: [],
  94. printNumIndex: 0,
  95. printerNum: 1,
  96. currentPrint: 1,
  97. isReceiptSend: false,
  98. isQuery: false,
  99. imageSrc: '../../imags/wechat.png',
  100. jpgSrc: '../../imags/flower2.jpg',
  101. canvasWidth: 100,
  102. canvasHeight: 100,
  103. jpgWidth: 200,
  104. jpgHeight: 200,
  105. },
  106. /**
  107. * 生命周期函数--监听页面加载
  108. */
  109. onLoad: function(options) {
  110. // this.canvas();
  111. },
  112. initPhoto: function() { //初始化画布数据
  113. //创建一个png格式
  114. var that = this
  115. const ctx_out = wx.createCanvasContext('canvasOut', this);
  116. var png = that.data.imageSrc;
  117. wx.getImageInfo({
  118. src: png,
  119. success(res) {
  120. that.setData({
  121. canvasWidth: res.width,
  122. canvasHeight: res.height,
  123. });
  124. console.log("画布宽度" + res.width, "画布高度" + res.height);
  125. ctx_out.drawImage(png, 0, 0, res.width, res.height);
  126. ctx_out.draw();
  127. }
  128. })
  129. //创建一个jpg格式图片
  130. const ctx_jpg = wx.createCanvasContext('canvasJPG', this);
  131. var jpg_width = that.data.jpgWidth;
  132. var jpg_height = that.data.jpgHeight;
  133. var img = that.data.jpgSrc;
  134. wx.getImageInfo({
  135. src: img,
  136. success(res) {
  137. that.setData({
  138. jpgWidth: res.width,
  139. jpgHeight: res.height,
  140. });
  141. console.log("JPG画布宽度" + res.width, "JPG画布高度" + res.height);
  142. ctx_jpg.drawImage(img, 0, 0, res.width, res.height);
  143. ctx_jpg.draw();
  144. }
  145. })
  146. },
  147. receiptTest: function() { //票据测试
  148. var that = this;
  149. var canvasWidth = that.data.canvasWidth
  150. var canvasHeight = that.data.canvasHeight
  151. var command = esc.jpPrinter.createNew()
  152. command.init() //初始化打印机
  153. command.setSelectJustification(1) //居中
  154. command.setCharacterSize(17); //设置倍高倍宽
  155. command.setText("票据测试");
  156. command.setPrint(); //打印并换行
  157. command.setCharacterSize(0); //设置正常大小
  158. command.setSelectJustification(0) //设置居左
  159. command.setText("打印对齐方式测试:")
  160. command.setPrint() //打印并换行
  161. command.setSelectJustification(0) //设置居左
  162. command.setText("居左")
  163. command.setPrint() //打印并换行
  164. command.setSelectJustification(1) //设置居中
  165. command.setText("居中")
  166. command.setPrint()
  167. command.setSelectJustification(2)
  168. command.setText("居右");
  169. command.setPrint()
  170. command.setSelectJustification(0)
  171. command.setText("同行打印位置测试:");
  172. command.setPrint()
  173. command.setText("居左");
  174. command.setAbsolutePrintPosition(168)
  175. command.setText("居中");
  176. command.setAbsolutePrintPosition(336)
  177. command.setText("居右");
  178. command.setPrint()
  179. command.init() //初始化打印机
  180. command.setPrint()
  181. command.setText("条码打印");
  182. command.setPrint()
  183. command.setHRIPosition(2) //设置HRI位置
  184. command.setHRIFont(0) //HRI字体大小
  185. command.setBarcodeHeight(60) //条码高度
  186. command.setBarcodeWidth(2) //设置条码宽度
  187. command.setAbsolutePrintPosition(24)
  188. command.setCode128("{A12345678"); //code128 A类型
  189. command.setPrint()
  190. command.setText("二维码测试:")
  191. command.setPrint()
  192. command.setSelectSizeOfModuleForQRCode(5)
  193. command.setSelectErrorCorrectionLevelForQRCode(49)
  194. command.setStoreQRCodeData("http://www.howbest.cn/cn/")
  195. command.setPrintQRCode()
  196. command.setPrint()
  197. command.setPrint()
  198. command.setPrint()
  199. command.setPrint()
  200. that.prepareSend(command.getData()) //准备发送数据
  201. },
  202. printPhoto: function() { //打印bitmap,图片内容不建议太大,小程序限制传输的字节数为20byte
  203. var that = this;
  204. var canvasWidth = that.data.canvasWidth
  205. var canvasHeight = that.data.canvasHeight
  206. var command = esc.jpPrinter.createNew()
  207. command.init() //初始化打印机
  208. wx.canvasGetImageData({
  209. canvasId: 'canvasOut',
  210. x: 0,
  211. y: 0,
  212. width: canvasWidth,
  213. height: canvasHeight,
  214. success: function(res) {
  215. console.log("获取画布数据成功")
  216. command.setBitmap(res)
  217. command.setPrint()
  218. that.prepareSend(command.getData()) //发送数据
  219. },
  220. complete: function(res) {
  221. console.log("finish")
  222. },
  223. fail: function(res) {
  224. console.log(res)
  225. wx.showToast({
  226. title: '获取画布数据失败',
  227. icon: 'none',
  228. })
  229. }
  230. })
  231. },
  232. printJPGPhoto: function() {
  233. var that = this;
  234. var canvasWidth = that.data.jpgWidth
  235. var canvasHeight = that.data.jpgHeight
  236. //抖动处理JPG图片
  237. const cfg = {
  238. x: 0,
  239. y: 0,
  240. width: canvasWidth,
  241. height: canvasHeight,
  242. }
  243. wx.canvasGetImageData({
  244. canvasId: 'canvasJPG',
  245. ...cfg,
  246. success: (res) => {
  247. //const data = convertToGrayscale(res.data)
  248. const data = convertToMonoImage(res.width, res.height, res.data, true);
  249. wx.canvasPutImageData({
  250. canvasId: 'canvasJPG',
  251. data,
  252. ...cfg,
  253. success: (res) => {
  254. console.log(res)
  255. console.log('deal graphic width: ' + cfg.width)
  256. console.log('deal graphic width: ' + cfg.height)
  257. that.printerJPG();
  258. },
  259. fail: (err) => {
  260. console.error(err)
  261. }
  262. })
  263. },
  264. fail: (err) => {
  265. console.error(err)
  266. }
  267. })
  268. },
  269. printerJPG: function() {
  270. var that = this;
  271. var canvasWidth = that.data.jpgWidth
  272. var canvasHeight = that.data.jpgHeight
  273. var command = esc.jpPrinter.createNew()
  274. command.init() //初始化打印机
  275. wx.canvasGetImageData({
  276. canvasId: 'canvasJPG',
  277. x: 0,
  278. y: 0,
  279. width: canvasWidth,
  280. height: canvasHeight,
  281. success: function(res) {
  282. console.log("获取画布数据成功")
  283. command.setBitmap(res)
  284. command.setPrint()
  285. that.prepareSend(command.getData()) //发送数据
  286. },
  287. complete: function(res) {
  288. console.log("finish")
  289. },
  290. fail: function(res) {
  291. console.log(res)
  292. wx.showToast({
  293. title: '获取画布数据失败',
  294. icon: 'none',
  295. })
  296. }
  297. })
  298. },
  299. prepareSend: function(buff) { //准备发送,根据每次发送字节数来处理分包数量
  300. //console.log(buff)
  301. var that = this
  302. var time = that.data.oneTimeData
  303. var looptime = parseInt(buff.length / time);
  304. var lastData = parseInt(buff.length % time);
  305. //console.log(looptime + "---" + lastData)
  306. that.setData({
  307. looptime: looptime + 1,
  308. lastData: lastData,
  309. currentTime: 1,
  310. })
  311. that.Send(buff)
  312. },
  313. queryStatus: function() { //查询打印机状态
  314. var that = this
  315. var buf;
  316. var dateView;
  317. /*
  318. n = 1:传送打印机状态
  319. n = 2:传送脱机状态
  320. n = 3:传送错误状态
  321. n = 4:传送纸传感器状态
  322. */
  323. buf = new ArrayBuffer(3)
  324. dateView = new DataView(buf)
  325. dateView.setUint8(0, 16)
  326. dateView.setUint8(1, 4)
  327. dateView.setUint8(2, 2)
  328. wx.writeBLECharacteristicValue({
  329. deviceId: app.BLEInformation.deviceId,
  330. serviceId: app.BLEInformation.writeServiceId,
  331. characteristicId: app.BLEInformation.writeCharaterId,
  332. value: buf,
  333. success: function(res) {
  334. console.log("发送成功")
  335. that.setData({
  336. isQuery: true
  337. })
  338. },
  339. fail: function(e) {
  340. wx.showToast({
  341. title: '发送失败',
  342. icon: 'none',
  343. })
  344. //console.log(e)
  345. return;
  346. },
  347. complete: function() {
  348. }
  349. })
  350. wx.notifyBLECharacteristicValueChange({
  351. deviceId: app.BLEInformation.deviceId,
  352. serviceId: app.BLEInformation.notifyServiceId,
  353. characteristicId: app.BLEInformation.notifyCharaterId,
  354. state: true,
  355. success: function(res) {
  356. wx.onBLECharacteristicValueChange(function(r) {
  357. console.log(
  358. `characteristic ${r.characteristicId} has changed, now is ${r}`
  359. )
  360. var result = ab2hex(r.value)
  361. console.log("返回" + result)
  362. var tip = ''
  363. if (result == 12) { //正常
  364. tip = "正常"
  365. } else if (result == 32) { //缺纸
  366. tip = "缺纸"
  367. } else if (result == 36) { //开盖、缺纸
  368. tip = "开盖、缺纸"
  369. } else if (result == 16) {
  370. tip = "开盖"
  371. } else if (result == 40) { //其他错误
  372. tip = "其他错误"
  373. } else { //未处理错误
  374. tip = "未知错误"
  375. }
  376. wx.showModal({
  377. title: '打印机状态',
  378. content: tip,
  379. showCancel: false
  380. })
  381. })
  382. },
  383. fail: function(e) {
  384. wx.showModal({
  385. title: '打印机状态',
  386. content: '获取失败',
  387. showCancel: false
  388. })
  389. console.log(e)
  390. },
  391. complete: function(e) {
  392. that.setData({
  393. isQuery: false
  394. })
  395. console.log("执行完成")
  396. }
  397. })
  398. },
  399. Send: function(buff) { //分包发送
  400. var that = this
  401. var currentTime = that.data.currentTime
  402. var loopTime = that.data.looptime
  403. var lastData = that.data.lastData
  404. var onTimeData = that.data.oneTimeData
  405. var printNum = that.data.printerNum
  406. var currentPrint = that.data.currentPrint
  407. var buf
  408. var dataView
  409. if (currentTime < loopTime) {
  410. buf = new ArrayBuffer(onTimeData)
  411. dataView = new DataView(buf)
  412. for (var i = 0; i < onTimeData; ++i) {
  413. dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
  414. }
  415. } else {
  416. buf = new ArrayBuffer(lastData)
  417. dataView = new DataView(buf)
  418. for (var i = 0; i < lastData; ++i) {
  419. dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
  420. }
  421. }
  422. //console.log("第" + currentTime + "次发送数据大小为:" + buf.byteLength)
  423. wx.writeBLECharacteristicValue({
  424. deviceId: app.BLEInformation.deviceId,
  425. serviceId: app.BLEInformation.writeServiceId,
  426. characteristicId: app.BLEInformation.writeCharaterId,
  427. value: buf,
  428. success: function(res) {
  429. if (currentTime <= loopTime) {
  430. // wx.showLoading({
  431. // title: '传输中...',
  432. // })
  433. } else {
  434. wx.showToast({
  435. title: '已打印第' + currentPrint + '张成功',
  436. })
  437. }
  438. //console.log(res)
  439. },
  440. fail: function(e) {
  441. wx.showToast({
  442. title: '打印第' + currentPrint + '张失败',
  443. icon: 'none',
  444. })
  445. //console.log(e)
  446. },
  447. complete: function() {
  448. currentTime++
  449. if (currentTime <= loopTime) {
  450. that.setData({
  451. currentTime: currentTime
  452. })
  453. that.Send(buff)
  454. } else {
  455. if (currentPrint == printNum) {
  456. that.setData({
  457. looptime: 0,
  458. lastData: 0,
  459. currentTime: 1,
  460. isReceiptSend: false,
  461. currentPrint: 1
  462. })
  463. } else {
  464. currentPrint++
  465. that.setData({
  466. currentPrint: currentPrint,
  467. currentTime: 1,
  468. })
  469. that.Send(buff)
  470. }
  471. }
  472. }
  473. })
  474. },
  475. /**
  476. * 生命周期函数--监听页面初次渲染完成
  477. */
  478. onReady: function() {
  479. var list = []
  480. var numList = []
  481. var j = 0
  482. for (var i = 20; i < 200; i += 10) {
  483. list[j] = i;
  484. j++
  485. }
  486. for (var i = 1; i < 10; i++) {
  487. numList[i - 1] = i
  488. }
  489. this.setData({
  490. buffSize: list,
  491. oneTimeData: list[0],
  492. printNum: numList,
  493. printerNum: numList[0]
  494. })
  495. this.initPhoto();
  496. },
  497. buffBindChange: function(res) { //更改打印字节数
  498. var index = res.detail.value
  499. var time = this.data.buffSize[index]
  500. this.setData({
  501. buffIndex: index,
  502. oneTimeData: time
  503. })
  504. },
  505. printNumBindChange: function(res) { //更改打印份数
  506. var index = res.detail.value
  507. var num = this.data.printNum[index]
  508. this.setData({
  509. printNumIndex: index,
  510. printerNum: num
  511. })
  512. },
  513. /**
  514. * 生命周期函数--监听页面显示
  515. */
  516. onShow: function() {
  517. },
  518. /**
  519. * 生命周期函数--监听页面隐藏
  520. */
  521. onHide: function() {
  522. },
  523. /**
  524. * 生命周期函数--监听页面卸载
  525. */
  526. onUnload: function() {
  527. //关闭蓝牙连接
  528. // wx.closeBLEConnection({
  529. // deviceId: app.BLEInformation.deviceId,
  530. // success: function(res) {
  531. // console.log("关闭蓝牙成功")
  532. // },
  533. // })
  534. },
  535. /**
  536. * 页面相关事件处理函数--监听用户下拉动作
  537. */
  538. onPullDownRefresh: function() {
  539. },
  540. /**
  541. * 页面上拉触底事件的处理函数
  542. */
  543. onReachBottom: function() {
  544. },
  545. /**
  546. * 用户点击右上角分享
  547. */
  548. onShareAppMessage: function() {
  549. }
  550. })