b12s.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. class BluetoothTools {
  2. constructor() {
  3. this.commands = {
  4. init: [0x1b, 0x40], // 清理buffer数据,重置模式;ASC2: ESC @
  5. print: [0x0a], //开始打印;
  6. printL5: [0x1b, 0x64, 0x05],
  7. printL6: [0x1b, 0x64, 0x06],
  8. printL8: [0x1b, 0x64, 0x08],
  9. printL10: [0x1b, 0x64, 0x10],
  10. }
  11. this.decimalData = []; //获取buffer之前的二进制数据集合;
  12. this.deviceId = null;
  13. this.initStatus = 0; //蓝牙初始化结果;0:初始化中,1-成功;2-失败;
  14. this.linked = false; //蓝牙是否为连接状态;
  15. this.timer = null;
  16. this.writeTime = 0;
  17. this.byteLength = this.isAndroid() ? 200 : 500;
  18. this.connectChangeHandler = null;
  19. }
  20. /**
  21. * 低功耗蓝牙API
  22. */
  23. // 根据deviceId 设置传输字节最大值;
  24. setMTU(deviceId) {
  25. return new Promise((resolve, reject) => {
  26. uni.setBLEMTU({
  27. deviceId: deviceId,
  28. mtu: 512,
  29. success: (res) => {
  30. console.log('设置MTu成功', res);
  31. resolve(res)
  32. },
  33. fail: (err) => {
  34. console.log('设置mtu失败', err);
  35. this.toaset('设置mtu失败!')
  36. reject(err)
  37. }
  38. })
  39. })
  40. }
  41. // 根据deviceId/mac地址 查询serviceId列表;
  42. getServiceId(deviceId) {
  43. return new Promise((resolve, reject) => {
  44. uni.getBLEDeviceServices({
  45. deviceId: deviceId,
  46. success: res => {
  47. resolve(res)
  48. },
  49. fail: err => {
  50. console.log('获取serviceId失败', err);
  51. reject(err)
  52. }
  53. })
  54. })
  55. }
  56. // 根据deviceId 和 serviceId 获取特征Id;
  57. getCharId(deviceId, serviceId) {
  58. return new Promise((resolve, reject) => {
  59. uni.getBLEDeviceCharacteristics({
  60. deviceId: deviceId,
  61. serviceId: serviceId,
  62. success: res => {
  63. resolve(res)
  64. },
  65. fail: err => {
  66. console.log('获取特征id失败', err);
  67. reject(err)
  68. }
  69. })
  70. })
  71. }
  72. // 写入数据;
  73. writeBLE(deviceId, serviceId, charId, buffer) {
  74. // console.log(deviceId, serviceId, charId, buffer.byteLength);
  75. // return;
  76. let _this = this;
  77. return new Promise((resolve, reject) => {
  78. uni.writeBLECharacteristicValue({
  79. deviceId: deviceId, //设备Id、mac地址;
  80. serviceId: serviceId, //服务id;
  81. characteristicId: charId, //特征id;
  82. value: buffer, //指令buffer数据;
  83. writeType: 'write', //'writeNoResponse',
  84. success: res => {
  85. // console.log('数据写入成功', res);
  86. _this.writeTime = 0;
  87. resolve(res)
  88. },
  89. fail: err => {
  90. console.log('写入失败:', Date.now());
  91. reject(err);
  92. }
  93. })
  94. })
  95. }
  96. /**
  97. * 具体功能实现
  98. */
  99. // 打印传入的位图信息
  100. async printImage(res) {
  101. if (!this.deviceId) {
  102. this.toast('未检测到蓝牙设备id');
  103. this.hideLoading()
  104. return;
  105. }
  106. this.isAndroid() && await this.setMTU(this.deviceId);
  107. const imgArr = this.getImgArray(res);
  108. // return;
  109. const { serviceId, charId } = await this.getWriteIds(this.deviceId);
  110. this.startPrint(this.deviceId, serviceId, charId, imgArr);
  111. }
  112. // 开始打印;
  113. async startPrint(deviceId, serviceId, charId, cmd) {
  114. // 初始化;
  115. let initArr = Array.from(this.commands.init).concat(Array.from(this.commands.print));
  116. let initBuffer = new Uint8Array(initArr).buffer;
  117. await this.writeMidWare(deviceId, serviceId, charId, initBuffer)
  118. // let cmds = Array.from(this.commands.init).concat(Array.from(cmd)).concat(Array.from(this.commands.printL10));
  119. // 分别传输指令;
  120. let cmds = Array.from(cmd);
  121. console.log(cmds.length);
  122. if (cmds.length > this.byteLength) {
  123. let cmdArrs = [];
  124. let newCmds = Array.from(cmds);
  125. let length = Math.ceil(cmds.length / this.byteLength);
  126. for (let i = 0; i < length; i++) {
  127. cmdArrs.push(newCmds.slice(this.byteLength * i, this.byteLength * (i + 1)));
  128. }
  129. for (let i = 0; i < cmdArrs.length; i++) {
  130. console.log(i, cmdArrs.length);
  131. let buffer = new Uint8Array(cmdArrs[i]).buffer;
  132. await this.writeMidWare(deviceId, serviceId, charId, buffer)
  133. }
  134. } else {
  135. let buffer = new Uint8Array(cmds).buffer;
  136. cmds.length && await this.writeMidWare(deviceId, serviceId, charId, buffer)
  137. }
  138. // 打印空行;
  139. let printLCmd = Array.from(this.commands.printL5);
  140. let printLBuffer = new Uint8Array(printLCmd).buffer;
  141. await this.writeMidWare(deviceId, serviceId, charId, printLBuffer);
  142. }
  143. // 处理安卓写入失败的问题;
  144. writeMidWare(deviceId, serviceId, charId, buffer) {
  145. let _this = this;
  146. return new Promise((resolve, reject) => {
  147. this.writeBLE(deviceId, serviceId, charId, buffer).then(res => {
  148. resolve(res)
  149. }).catch(err => {
  150. // console.log(111111, _this.writeTime);
  151. if (_this.writeTime < 50) {
  152. _this.writeTime++;
  153. return new Promise((reso, reje) => {
  154. clearTimeout(this.timer)
  155. this.timer = setTimeout(() => {
  156. reso(this.writeMidWare(deviceId, serviceId, charId, buffer))
  157. }, 100)
  158. })
  159. } else {
  160. _this.writeTime = 0;
  161. _this.hideLoading();
  162. _this.toast('数据写入失败,请走纸后重试!');
  163. reject(err);
  164. }
  165. }).then(res => {
  166. resolve(res)
  167. })
  168. })
  169. }
  170. // 位图信息转换为打印指令;
  171. getImgArray(res) {
  172. var w = res.width;
  173. var width = parseInt((res.width + 7) / 8 * 8 / 8);
  174. var height = res.height;
  175. let data = [29, 118, 48, 0];
  176. // let data = [0x1d, 0x76, 0x30, 0];
  177. data.push(parseInt(width % 256));
  178. data.push(parseInt(width / 256));
  179. data.push(parseInt(res.height % 256));
  180. data.push(parseInt(res.height / 256));
  181. var bits = new Uint8Array(height * width);
  182. for (let y = 0; y < height; y++) {
  183. for (let x = 0; x < w; x++) {
  184. var color = res.data[(y * w + x) * 4 + 1];
  185. if (color > 128) {
  186. bits[parseInt(y * width + x / 8)] |= (0x80 >> (x % 8));
  187. }
  188. }
  189. }
  190. for (let i = 0; i < bits.length; i++) {
  191. data.push((~bits[i]) & 0xFF)
  192. }
  193. return data;
  194. }
  195. // 获取写入数据需要的ids;
  196. async getWriteIds(deviceId) {
  197. return new Promise(async (resolve, reject) => {
  198. let serviceIdData = await this.getServiceId(deviceId);
  199. let services = serviceIdData.services;
  200. // console.log(services);
  201. let charId,
  202. serviceId;
  203. for (let i = 0; i < services.length; i++) {
  204. const chars = await this.getCharId(deviceId, services[i].uuid);
  205. // console.log(services[i].uuid, chars);
  206. const charItem = chars.characteristics.filter(item => item.properties.write)[0];
  207. if (charItem) {
  208. charId = charItem.uuid;
  209. serviceId = services[i].uuid;
  210. // break;
  211. // console.log(charId, serviceId);
  212. }
  213. }
  214. resolve({ charId: charId, serviceId: serviceId })
  215. })
  216. }
  217. isAndroid() {
  218. return uni.getSystemInfoSync().osName === 'android'
  219. }
  220. }
  221. export default BluetoothTools;