• 记录--uni-app实现蓝牙打印小票


    这里给大家分享我在网上总结出来的一些知识,希望对大家有所帮助

    说明

    基于uni-app开发,调用官方蓝牙相关api实现连接蓝牙与向蓝牙热敏打印机发送字节流,可打印文字,二维码,图片,调整字体大小等,本文提供大概思路

    结构

    image.png

    • bluetooth.js 蓝牙连接相关模块封装
    • commands.js 打印十六进制相关代码库
    • gbk.js 编码转换库地址
    • printerjobs.js 打印实现库

    bluetooth.js

    蓝牙连接相关封装代码

    1. class Bluetooth {
    2. constructor() {
    3. this.isOpenBle = false;
    4. this.deviceId = "";
    5. this.serviceId = "";
    6. this.writeId = "";
    7. this.notifyId = "";
    8. this.BluetoothConnectStatus = false this.printStatus = false this.init()
    9. }
    10. init() {
    11. this.closeBluetoothAdapter().then(() = >{
    12. console.log("init初始关闭蓝牙模块") this.openBluetoothAdapter().then(() = >{
    13. console.log("init初始化蓝牙模块") this.reconnect() //自动连接蓝牙设备
    14. })
    15. })
    16. }
    17. showToast(title) {
    18. uni.showToast({
    19. title: title,
    20. icon: 'none',
    21. 'duration': 2000
    22. });
    23. }
    24. openBluetoothAdapter() {
    25. return new Promise((resolve, reject) = >{
    26. uni.openBluetoothAdapter({
    27. success: res = >{
    28. this.isOpenBle = true;
    29. resolve(res);
    30. },
    31. fail: err = >{
    32. this.showToast(`蓝牙未打开`);
    33. reject(err);
    34. },
    35. });
    36. });
    37. }
    38. startBluetoothDevicesDiscovery() {
    39. if (!this.isOpenBle) {
    40. this.showToast(`初始化蓝牙模块失败`) return;
    41. }
    42. let self = this;
    43. uni.showLoading({
    44. title: '蓝牙搜索中'
    45. }) return new Promise((resolve, reject) = >{
    46. setTimeout(() = >{
    47. uni.startBluetoothDevicesDiscovery({
    48. success: res = >{
    49. resolve(res)
    50. },
    51. fail: res = >{
    52. self.showToast(`搜索设备失败` + JSON.stringify(err));
    53. reject(err);
    54. }
    55. })
    56. },
    57. 300);
    58. });
    59. }
    60. stopBluetoothDevicesDiscovery() {
    61. let self = this;
    62. return new Promise((resolve, reject) = >{
    63. uni.stopBluetoothDevicesDiscovery({
    64. success: e = >{
    65. uni.hideLoading();
    66. },
    67. fail: e = >{
    68. uni.hideLoading();
    69. self.showToast(`停止搜索蓝牙设备失败` + JSON.stringify(err));
    70. }
    71. })
    72. });
    73. }
    74. createBLEConnection() {
    75. //设备deviceId
    76. let deviceId = this.deviceId;
    77. let self = this;
    78. // uni.showLoading({
    79. // mask: true,
    80. // title: '设别连接中,请稍候...'
    81. // })
    82. console.log(this.deviceId);
    83. return new Promise((resolve, reject) = >{
    84. uni.createBLEConnection({
    85. deviceId,
    86. success: (res) = >{
    87. console.log("res:createBLEConnection " + JSON.stringify(res));
    88. resolve(res)
    89. },
    90. fail: err = >{
    91. uni.hideLoading();
    92. self.showToast(`停止搜索蓝牙设备失败` + JSON.stringify(err));
    93. reject(err);
    94. }
    95. })
    96. });
    97. }
    98. //获取蓝牙设备所有服务(service)
    99. getBLEDeviceServices() {
    100. let _serviceList = [];
    101. let deviceId = this.deviceId;
    102. let self = this;
    103. return new Promise((resolve, reject) = >{
    104. setTimeout(() = >{
    105. uni.getBLEDeviceServices({
    106. deviceId,
    107. success: res = >{
    108. for (let service of res.services) {
    109. if (service.isPrimary) {
    110. _serviceList.push(service);
    111. }
    112. }
    113. uni.hideLoading();
    114. console.log("_serviceList: " + JSON.stringify(_serviceList));
    115. resolve(_serviceList)
    116. },
    117. fail: err = >{
    118. uni.hideLoading();
    119. // self.showToast(`获取设备Services` + JSON.stringify(err));
    120. reject(err);
    121. },
    122. })
    123. },
    124. 500);
    125. });
    126. }
    127. //获取蓝牙设备某个服务中所有特征值(characteristic)
    128. getBLEDeviceCharacteristics() {
    129. // console.log("getBLEDeviceCharacteristics")
    130. let deviceId = this.deviceId;
    131. let serviceId = this.serviceId;
    132. let self = this;
    133. return new Promise((resolve, reject) = >{
    134. uni.getBLEDeviceCharacteristics({
    135. deviceId,
    136. serviceId,
    137. success: res = >{
    138. for (let _obj of res.characteristics) {
    139. //获取notify
    140. if (_obj.properties.notify) {
    141. self.notifyId = _obj.uuid;
    142. uni.setStorageSync('notifyId', self.notifyId);
    143. }
    144. //获取writeId
    145. if (_obj.properties.write) {
    146. self.writeId = _obj.uuid;
    147. uni.setStorageSync('writeId', self.writeId);
    148. }
    149. }
    150. //console.log("res:getBLEDeviceCharacteristics " + JSON.stringify(res));
    151. let result = {
    152. 'notifyId': self.notifyId,
    153. 'writeId': self.writeId
    154. };
    155. // self.showToast(`获取服务中所有特征值OK,${JSON.stringify(result)}`);
    156. this.BluetoothStatus = true resolve(result)
    157. },
    158. fail: err = >{
    159. self.showToast(`getBLEDeviceCharacteristics` + JSON.stringify(err));
    160. reject(err);
    161. }
    162. })
    163. });
    164. }
    165. //断开联链接
    166. closeBLEConnection() {
    167. let deviceId = this.deviceId;
    168. uni.closeBLEConnection({
    169. deviceId,
    170. success(res) {
    171. console.log("closeBLEConnection" + res)
    172. }
    173. })
    174. }
    175. notifyBLECharacteristicValue() {
    176. let deviceId = this.deviceId;
    177. let serviceId = this.serviceId;
    178. let characteristicId = this.notifyId;
    179. uni.notifyBLECharacteristicValueChange({
    180. state: true,
    181. // 启用 notify 功能
    182. deviceId,
    183. serviceId,
    184. characteristicId,
    185. success(res) {
    186. uni.onBLECharacteristicValueChange(function(res) {
    187. console.log('onBLECharacteristicValueChange', res);
    188. });
    189. },
    190. fail(res) {
    191. console.log('notifyBLECharacteristicValueChange failed:' + res.errMsg);
    192. }
    193. });
    194. }
    195. writeBLECharacteristicValue(buffer) {
    196. let deviceId = this.deviceId;
    197. let serviceId = this.serviceId;
    198. let characteristicId = this.writeId;
    199. // console.log(deviceId);
    200. // console.log(serviceId);
    201. // console.log(characteristicId);
    202. return new Promise((resolve, reject) = >{
    203. uni.writeBLECharacteristicValue({
    204. deviceId,
    205. serviceId,
    206. characteristicId,
    207. value: buffer,
    208. success(res) {
    209. // console.log('message发送成功', JSON.stringify(res));
    210. resolve(res);
    211. },
    212. fail(err) {
    213. // console.log('message发送失败', JSON.stringify(err));
    214. reject(err);
    215. }
    216. });
    217. });
    218. }
    219. closeBluetoothAdapter() {
    220. return new Promise((resolve, reject) = >{
    221. uni.closeBluetoothAdapter({
    222. success: res = >{
    223. resolve()
    224. }
    225. });
    226. })
    227. }
    228. //若APP在之前已有搜索过某个蓝牙设备,并成功建立连接,可直接传入之前搜索获取的 deviceId 直接尝试连接该设备,无需进行搜索操作。
    229. reconnect() { (async() = >{
    230. try {
    231. this.deviceId = this.deviceId || uni.getStorageSync("deviceId");
    232. this.serviceId = this.serviceId || uni.getStorageSync("serviceId");
    233. console.log("this.deviceId", this.deviceId) console.log("this.serviceId", this.serviceId) let result1 = await this.createBLEConnection();
    234. console.log("createBLEConnection: " + JSON.stringify(result1));
    235. let result2 = await this.getBLEDeviceServices();
    236. console.log("getBLEDeviceServices: " + JSON.stringify(result2));
    237. let result3 = await this.getBLEDeviceCharacteristics();
    238. console.log("getBLEDeviceCharacteristics: " + JSON.stringify(result3));
    239. this.BluetoothConnectStatus = true this.showToast("蓝牙打印设备连接成功")
    240. // this.writeId = uni.getStorageSync("writeId");
    241. // this.notifyId = uni.getStorageSync("notifyId");
    242. } catch(err) {
    243. console.log("err: " + err);
    244. // this.showToast("蓝牙打印设备连接失败")
    245. }
    246. })();
    247. }
    248. }
    249. export
    250. default Bluetooth;

    commands.js

    打印机ESC/POS十六进制编码库

    1. /**
    2. * 修改自https://github.com/song940/node-escpos/blob/master/commands.js
    3. * ESC/POS _ (Constants)
    4. */
    5. var _ = {
    6. LF: [0x0a],
    7. FS: [0x1c],
    8. FF: [0x0c],
    9. GS: [0x1d],
    10. DLE: [0x10],
    11. EOT: [0x04],
    12. NUL: [0x00],
    13. ESC: [0x1b],
    14. EOL: '\n',
    15. };
    16. /**
    17. * [FEED_CONTROL_SEQUENCES Feed control sequences]
    18. * @type {Object}
    19. */
    20. _.FEED_CONTROL_SEQUENCES = {
    21. CTL_LF: [0x0a], // Print and line feed
    22. CTL_GLF: [0x4a, 0x00], // Print and feed paper (without spaces between lines)
    23. CTL_FF: [0x0c], // Form feed
    24. CTL_CR: [0x0d], // Carriage return
    25. CTL_HT: [0x09], // Horizontal tab
    26. CTL_VT: [0x0b], // Vertical tab
    27. };
    28. _.CHARACTER_SPACING = {
    29. CS_DEFAULT: [0x1b, 0x20, 0x00],
    30. CS_SET: [0x1b, 0x20]
    31. };
    32. _.LINE_SPACING = {
    33. LS_DEFAULT: [0x1b, 0x32],
    34. LS_SET: [0x1b, 0x33]
    35. };
    36. /**
    37. * [HARDWARE Printer hardware]
    38. * @type {Object}
    39. */
    40. _.HARDWARE = {
    41. HW_INIT: [0x1b, 0x40], // Clear data in buffer and reset modes
    42. HW_SELECT: [0x1b, 0x3d, 0x01], // Printer select
    43. HW_RESET: [0x1b, 0x3f, 0x0a, 0x00], // Reset printer hardware
    44. Print:[0x1b, 0x64,0x01] //Print and feed paper
    45. };
    46. /**
    47. * [CASH_DRAWER Cash Drawer]
    48. * @type {Object}
    49. */
    50. _.CASH_DRAWER = {
    51. CD_KICK_2: [0x1b, 0x70, 0x00], // Sends a pulse to pin 2 []
    52. CD_KICK_5: [0x1b, 0x70, 0x01], // Sends a pulse to pin 5 []
    53. };
    54. /**
    55. * [MARGINS Margins sizes]
    56. * @type {Object}
    57. */
    58. _.MARGINS = {
    59. BOTTOM: [0x1b, 0x4f], // Fix bottom size
    60. LEFT: [0x1b, 0x6c], // Fix left size
    61. RIGHT: [0x1b, 0x51], // Fix right size
    62. };
    63. /**
    64. * [PAPER Paper]
    65. * @type {Object}
    66. */
    67. _.PAPER = {
    68. PAPER_FULL_CUT: [0x1d, 0x56, 0x00], // Full cut paper
    69. PAPER_PART_CUT: [0x1d, 0x56, 0x01], // Partial cut paper
    70. PAPER_CUT_A: [0x1d, 0x56, 0x41], // Partial cut paper
    71. PAPER_CUT_B: [0x1d, 0x56, 0x42], // Partial cut paper
    72. };
    73. /**
    74. * [TEXT_FORMAT Text format]
    75. * @type {Object}
    76. */
    77. _.TEXT_FORMAT = {
    78. TXT_NORMAL: [0x1b, 0x21, 0x00], // Normal text
    79. TXT_2HEIGHT: [0x1b, 0x21, 0x10], // Double height text
    80. TXT_2WIDTH: [0x1b, 0x21, 0x20], // Double width text
    81. TXT_4SQUARE: [0x1b, 0x21, 0x30], // Double width & height text
    82. TXT_UNDERL_OFF: [0x1b, 0x2d, 0x00], // Underline font OFF
    83. TXT_UNDERL_ON: [0x1b, 0x2d, 0x01], // Underline font 1-dot ON
    84. TXT_UNDERL2_ON: [0x1b, 0x2d, 0x02], // Underline font 2-dot ON
    85. TXT_BOLD_OFF: [0x1b, 0x45, 0x00], // Bold font OFF
    86. TXT_BOLD_ON: [0x1b, 0x45, 0x01], // Bold font ON
    87. TXT_ITALIC_OFF: [0x1b, 0x35], // Italic font ON
    88. TXT_ITALIC_ON: [0x1b, 0x34], // Italic font ON
    89. TXT_FONT_A: [0x1b, 0x4d, 0x00], // Font type A
    90. TXT_FONT_B: [0x1b, 0x4d, 0x01], // Font type B
    91. TXT_FONT_C: [0x1b, 0x4d, 0x02], // Font type C
    92. TXT_ALIGN_LT: [0x1b, 0x61, 0x00], // Left justification
    93. TXT_ALIGN_CT: [0x1b, 0x61, 0x01], // Centering
    94. TXT_ALIGN_RT: [0x1b, 0x61, 0x02], // Right justification
    95. };
    96. /**
    97. * [BARCODE_FORMAT Barcode format]
    98. * @type {Object}
    99. */
    100. _.BARCODE_FORMAT = {
    101. BARCODE_TXT_OFF: [0x1d, 0x48, 0x00], // HRI barcode chars OFF
    102. BARCODE_TXT_ABV: [0x1d, 0x48, 0x01], // HRI barcode chars above
    103. BARCODE_TXT_BLW: [0x1d, 0x48, 0x02], // HRI barcode chars below
    104. BARCODE_TXT_BTH: [0x1d, 0x48, 0x03], // HRI barcode chars both above and below
    105. BARCODE_FONT_A: [0x1d, 0x66, 0x00], // Font type A for HRI barcode chars
    106. BARCODE_FONT_B: [0x1d, 0x66, 0x01], // Font type B for HRI barcode chars
    107. BARCODE_HEIGHT: function (height) { // Barcode Height [1-255]
    108. return [0x1d, 0x68, height];
    109. },
    110. BARCODE_WIDTH: function (width) { // Barcode Width [2-6]
    111. return [0x1d, 0x77, width];
    112. },
    113. BARCODE_HEIGHT_DEFAULT: [0x1d, 0x68, 0x64], // Barcode height default:100
    114. BARCODE_WIDTH_DEFAULT: [0x1d, 0x77, 0x01], // Barcode width default:1
    115. BARCODE_UPC_A: [0x1d, 0x6b, 0x00], // Barcode type UPC-A
    116. BARCODE_UPC_E: [0x1d, 0x6b, 0x01], // Barcode type UPC-E
    117. BARCODE_EAN13: [0x1d, 0x6b, 0x02], // Barcode type EAN13
    118. BARCODE_EAN8: [0x1d, 0x6b, 0x03], // Barcode type EAN8
    119. BARCODE_CODE39: [0x1d, 0x6b, 0x04], // Barcode type CODE39
    120. BARCODE_ITF: [0x1d, 0x6b, 0x05], // Barcode type ITF
    121. BARCODE_NW7: [0x1d, 0x6b, 0x06], // Barcode type NW7
    122. BARCODE_CODE93: [0x1d, 0x6b, 0x48], // Barcode type CODE93
    123. BARCODE_CODE128: [0x1d, 0x6b, 0x49], // Barcode type CODE128
    124. };
    125. /**
    126. * [IMAGE_FORMAT Image format]
    127. * @type {Object}
    128. */
    129. _.IMAGE_FORMAT = {
    130. S_RASTER_N: [0x1d, 0x76, 0x30, 0x00], // Set raster image normal size
    131. S_RASTER_2W: [0x1d, 0x76, 0x30, 0x01], // Set raster image double width
    132. S_RASTER_2H: [0x1d, 0x76, 0x30, 0x02], // Set raster image double height
    133. S_RASTER_Q: [0x1d, 0x76, 0x30, 0x03], // Set raster image quadruple
    134. };
    135. /**
    136. * [BITMAP_FORMAT description]
    137. * @type {Object}
    138. */
    139. _.BITMAP_FORMAT = {
    140. BITMAP_S8: [0x1b, 0x2a, 0x00],
    141. BITMAP_D8: [0x1b, 0x2a, 0x01],
    142. BITMAP_S24: [0x1b, 0x2a, 0x20],
    143. BITMAP_D24: [0x1b, 0x2a, 0x21]
    144. };
    145. /**
    146. * [GSV0_FORMAT description]
    147. * @type {Object}
    148. */
    149. _.GSV0_FORMAT = {
    150. GSV0_NORMAL: [0x1d, 0x76, 0x30, 0x00],
    151. GSV0_DW: [0x1d, 0x76, 0x30, 0x01],
    152. GSV0_DH: [0x1d, 0x76, 0x30, 0x02],
    153. GSV0_DWDH: [0x1d, 0x76, 0x30, 0x03]
    154. };
    155. /**
    156. * [BEEP description]
    157. * @type {string}
    158. */
    159. _.BEEP = [0x1b, 0x42]; // Printer Buzzer pre hex
    160. /**
    161. * [COLOR description]
    162. * @type {Object}
    163. */
    164. _.COLOR = {
    165. 0: [0x1b, 0x72, 0x00], // black
    166. 1: [0x1b, 0x72, 0x01] // red
    167. };
    168. /**
    169. * [exports description]
    170. * @type {[type]}
    171. */
    172. module.exports = _;

    printerjobs.js

    1. const commands = require('./commands');
    2. const gbk = require('./gbk');
    3. const printerJobs = function() {
    4. this._queue = Array.from(commands.HARDWARE.HW_INIT);
    5. this._enqueue = function(cmd) {
    6. this._queue.push.apply(this._queue, cmd);
    7. }
    8. };
    9. /**
    10. * 增加打印内容
    11. * @param {string} content 文字内容
    12. */
    13. printerJobs.prototype.text = function(content) {
    14. if (content) {
    15. let uint8Array = gbk.encode(content);
    16. let encoded = Array.from(uint8Array);
    17. this._enqueue(encoded);
    18. }
    19. return this;
    20. };
    21. /**
    22. * 打印文字
    23. * @param {string} content 文字内容
    24. */
    25. printerJobs.prototype.print = function(content) {
    26. this.text(content);
    27. // this._enqueue(commands.LF);
    28. return this;
    29. };
    30. printerJobs.prototype.printL = function(content) {
    31. this.text(content);
    32. this._enqueue(commands.LF);
    33. return this;
    34. };
    35. printerJobs.prototype.printImage = function(content) {
    36. if (content) {
    37. const cmds = [].concat([29, 118, 48, 0], content);
    38. // console.log("cmds",cmds)
    39. this._enqueue(cmds);
    40. this._enqueue(commands.LF);
    41. }
    42. return this;
    43. };
    44. /**
    45. * 打印文字并换行
    46. * @param {string} content 文字内容
    47. */
    48. printerJobs.prototype.println = function(content = '') {
    49. return this.print(content + commands.EOL);
    50. };
    51. /**
    52. * 设置对齐方式
    53. * @param {string} align 对齐方式 LT/CT/RT
    54. */
    55. printerJobs.prototype.setAlign = function(align) {
    56. this._enqueue(commands.TEXT_FORMAT['TXT_ALIGN_' + align.toUpperCase()]);
    57. return this;
    58. };
    59. /**
    60. * 设置字体
    61. * @param {string} family A/B/C
    62. */
    63. printerJobs.prototype.setFont = function(family) {
    64. this._enqueue(commands.TEXT_FORMAT['TXT_FONT_' + family.toUpperCase()]);
    65. return this;
    66. };
    67. /**
    68. * 设定字体尺寸
    69. * @param {number} width 字体宽度 1~2
    70. * @param {number} height 字体高度 1~2
    71. */
    72. printerJobs.prototype.setSize = function(width, height) {
    73. if (2 >= width && 2 >= height) {
    74. this._enqueue(commands.TEXT_FORMAT.TXT_NORMAL);
    75. if (2 === width && 2 === height) {
    76. this._enqueue(commands.TEXT_FORMAT.TXT_4SQUARE);
    77. } else if (1 === width && 2 === height) {
    78. this._enqueue(commands.TEXT_FORMAT.TXT_2HEIGHT);
    79. } else if (2 === width && 1 === height) {
    80. this._enqueue(commands.TEXT_FORMAT.TXT_2WIDTH);
    81. }
    82. }
    83. return this;
    84. };
    85. /**
    86. * 设定字体是否加粗
    87. * @param {boolean} bold
    88. */
    89. printerJobs.prototype.setBold = function(bold) {
    90. if (typeof bold !== 'boolean') {
    91. bold = true;
    92. }
    93. this._enqueue(bold ? commands.TEXT_FORMAT.TXT_BOLD_ON : commands.TEXT_FORMAT.TXT_BOLD_OFF);
    94. return this;
    95. };
    96. /**
    97. * 设定是否开启下划线
    98. * @param {boolean} underline
    99. */
    100. printerJobs.prototype.setUnderline = function(underline) {
    101. if (typeof underline !== 'boolean') {
    102. underline = true;
    103. }
    104. this._enqueue(underline ? commands.TEXT_FORMAT.TXT_UNDERL_ON : commands.TEXT_FORMAT.TXT_UNDERL_OFF);
    105. return this;
    106. };
    107. /**
    108. * 设置行间距为 n 点行,默认值行间距是 30 点
    109. * @param {number} n 0≤n≤255
    110. */
    111. printerJobs.prototype.setLineSpacing = function(n) {
    112. if (n === undefined || n === null) {
    113. this._enqueue(commands.LINE_SPACING.LS_DEFAULT);
    114. } else {
    115. this._enqueue(commands.LINE_SPACING.LS_SET);
    116. this._enqueue([n]);
    117. }
    118. return this;
    119. };
    120. /**
    121. * 打印空行
    122. * @param {number} n
    123. */
    124. printerJobs.prototype.lineFeed = function(n = 1) {
    125. return this.print(new Array(n).fill(commands.EOL).join(''));
    126. };
    127. /**
    128. * 设置字体颜色,需要打印机支持
    129. * @param {number} color - 0 默认颜色黑色 1 红色
    130. */
    131. printerJobs.prototype.setColor = function(color) {
    132. this._enqueue(commands.COLOR[color === 1 ? 1 : 0]);
    133. return this;
    134. };
    135. /**
    136. * https://support.loyverse.com/hardware/printers/use-the-beeper-in-a-escpos-printers
    137. * 蜂鸣警报,需要打印机支持
    138. * @param {number} n 蜂鸣次数,1-9
    139. * @param {number} t 蜂鸣长短,1-9
    140. */
    141. printerJobs.prototype.beep = function(n, t) {
    142. this._enqueue(commands.BEEP);
    143. this._enqueue([n, t]);
    144. return this;
    145. };
    146. /**
    147. * 清空任务
    148. */
    149. printerJobs.prototype.clear = function() {
    150. this._queue = Array.from(commands.HARDWARE.HW_RESET);
    151. // this._enqueue(commands.HARDWARE.Print);
    152. return this;
    153. };
    154. /**
    155. * 返回ArrayBuffer
    156. */
    157. printerJobs.prototype.buffer = function() {
    158. return new Uint8Array(this._queue).buffer;
    159. };
    160. module.exports = printerJobs;

    代码实现

    封装蓝牙连接,搜索,断开相关操作模块

    蓝牙搜索

    1. startBluetoothDeviceDiscovery() {
    2. let self = this;
    3. self.tempDeviceList = [];
    4. uni.startBluetoothDevicesDiscovery({
    5. success: res = >{
    6. uni.onBluetoothDeviceFound(devices = >{
    7. // console.log("发现设备: " + JSON.stringify(devices));
    8. if (!self.tempDeviceList.some(item = >{
    9. return item.deviceId === devices.devices[0].deviceId || item.name === devices.devices[0].name
    10. })) {
    11. // console.log("new", devices.devices)
    12. self.tempDeviceList.push(devices.devices[0])
    13. }
    14. });
    15. this.connect = false this.$refs.popup.open()
    16. },
    17. fail: err = >{
    18. uni.showToast({
    19. title: '搜索设备失败' + JSON.stringify(err),
    20. icon: 'none'
    21. })
    22. }
    23. })
    24. },

    搜索完成选择设备

    1. async select_deviceId(item) {
    2. this.deviceId = item.deviceId;
    3. this.$bluetooth.deviceId = item.deviceId;
    4. uni.setStorageSync('deviceId', this.$bluetooth.deviceId);
    5. this.serviceList = [];
    6. try {
    7. //1.链接设备
    8. let result = await this.$bluetooth.createBLEConnection();
    9. //2.寻找服务
    10. let result2 = null setTimeout(async() = >{
    11. result2 = await this.$bluetooth.getBLEDeviceServices();
    12. console.log("获取服务: " + JSON.stringify(result2));
    13. this.serviceList = result2;
    14. console.log("serviceList", this.serviceList.length)
    15. if (this.serviceList[2].uuid) {
    16. this.select_service(this.serviceList[2].uuid)
    17. } else {
    18. uni.showToast({
    19. title: '不是打印设备',
    20. icon: 'none'
    21. })
    22. }
    23. },
    24. 1000)
    25. } catch(e) {
    26. //TODO handle the exception
    27. console.log("e: " + JSON.stringify(e));
    28. }
    29. },

    选中服务

    1. async select_service(res) {
    2. console.log("select_service", res)
    3. this.$bluetooth.serviceId = res;
    4. console.log("this.$bluetooth.serviceId", this.$bluetooth.serviceId) uni.setStorageSync('serviceId', res);
    5. try {
    6. let result = await this.$bluetooth.getBLEDeviceCharacteristics();
    7. console.log("resultresult", result) this.$refs.popup.close()
    8. uni.showToast({
    9. title: "连接成功"
    10. })
    11. // this.pickUpOnce()
    12. } catch(e) {
    13. //TODO handle the exception
    14. console.log("e: " + JSON.stringify(e));
    15. }
    16. },

    打印内容组合

    1. async writeBLECharacteristicValueTongzhishu() {
    2. let Qrcode_res = await this.get_Qrcode()
    3. let sign = await this.getSign()
    4. console.log("sign")
    5. let printerJobs = new PrinterJobs()
    6. let p = printerJobs.setAlign('ct')
    7. .setBold(true)
    8. .printL("打印测试")
    9. let buffer = printerJobs.buffer();
    10. this.printbuffs(buffer);
    11. },

    打印内容组合

    主要是实现打印编码推送循环,手机蓝牙可能出现编码发送失败情况,这个时候就是要循环保证每个字节准确推送

    1. printbuffs(buffer, fun) {
    2. console.log("printbuffs", buffer.byteLength) const maxChunk = 8;
    3. let p = Promise.resolve();
    4. for (let i = 0, j = 0, length = buffer.byteLength; i < length; i += maxChunk, j++) {
    5. let subPackage = buffer.slice(i, i + maxChunk <= length ? (i + maxChunk) : length);
    6. p = p.then(() = >{
    7. if (i == 0) {
    8. this.$bluetooth.printStatus = true this.$refs.loading.open();
    9. }
    10. if ((i + maxChunk) >= length) {
    11. console.log("printEnd")
    12. setTimeout(() = >{
    13. this.$bluetooth.printStatus = false this.$refs.loading.close();
    14. },
    15. 1000)
    16. }
    17. return this.printbuff(subPackage)
    18. })
    19. }
    20. p = p.then(() = >{
    21. console.log("printEve") fun()
    22. })
    23. },
    24. async printbuff(buffer) {
    25. while (true) {
    26. try {
    27. await this.$bluetooth.writeBLECharacteristicValue(buffer);
    28. break;
    29. } catch(e) {}
    30. }
    31. },

    本文转载于:

    https://juejin.cn/post/7001752261722537991

    如果对您有所帮助,欢迎您点个关注,我会定时更新技术文档,大家一起讨论学习,一起进步。

     

  • 相关阅读:
    BP神经网络的梯度公式推导(三层结构)
    C语言 —— 函数栈帧的创建和销毁
    Java项目:ssm汽车租赁系统
    java基础-并发编程-CountDownLatch(JDK1.8)源码学习
    想考PMP,符合报名条件么?怎么报考?
    使用pyQt5和matplotlib绘制图表
    【开发经验】客户端互踢实现思路
    【C语言】关键字的补充
    从GFS到GPT,AI Infra的激荡20年
    1003 - 编程求1+3+5+...+n
  • 原文地址:https://blog.csdn.net/qq_40716795/article/details/126837982