// store/modules/bluetoothPrint.js import tscEncoder from '@/core/utils/tsc.js'; // 导入你的TSC指令生成器 import http from '@/core/request/index' const state = () => ({ bluetoothAvailable: false, // 设备状态 bluetoothDevices: [], currentDevice: null, connectionStatus: 'disconnected', // disconnected/scanning/connecting/connected/error deviceServices: [], template: null, discovering: false, // TSC打印机状态 printer: null, // TSC打印机实例 printerConfig: { dpi: 203, // 打印机DPI: 203/300 width: 40, // 标签宽度(mm) height: 30, // 标签高度(mm) gap: 2, // 标签间隙(mm) direction: 0, // 打印方向 reference: [0, 0], // 参考坐标原点 density: 8, // 打印浓度 1-15 speed: 3, // 打印速度 1-6 }, // 打印控制 isPrinting: false, printQueue: [], printHistory: [], // 连接管理 autoReconnect: true, reconnectAttempts: 0, maxReconnectAttempts: 3, // 错误与日志 lastError: null, operationLogs: [] }); const getters = { // 连接状态 isConnected: state => state.connectionStatus === 'connected', isReadyToPrint: state => state.connectionStatus === 'connected' && !state.isPrinting, // 设备信息 connectedDeviceInfo: state => ({ name: state.currentDevice?.name || '未连接', id: state.currentDevice?.id ? state.currentDevice.id.substring(0, 8) + '...' : '', status: state.connectionStatus }), // 打印机配置 printerDPI: state => state.printerConfig.dpi, mmToDot: (state, getters) => (mm) => { // 根据DPI将毫米转换为点数 return Math.floor(mm * (getters.printerDPI / 25.4)); }, // 队列状态 queueLength: state => state.printQueue.length, hasPendingTasks: state => state.printQueue.length > 0 }; const mutations = { // 设备管理 SET_DEVICES(state, devices) { state.bluetoothDevices = devices; }, ADD_DEVICE(state, device) { if (!state.bluetoothDevices.some(d => d.deviceId === device.deviceId)) { state.bluetoothDevices.push({ ...device, isTSCPrinter: device.name && ( device.name.includes('TSC') || device.name.includes('打印机') || device.name.includes('PRT') ) }); } }, SET_CURRENT_DEVICE(state, device) { state.currentDevice = device; }, SET_CONNECTION_STATUS(state, status) { state.connectionStatus = status; }, // 打印机实例 INIT_PRINTER_INSTANCE(state) { if (!state.printer) { state.printer = tscEncoder.jpPrinter.createNew(); } }, UPDATE_PRINTER_CONFIG(state, config) { state.printerConfig = { ...state.printerConfig, ...config }; }, // 打印状态 SET_PRINTING(state, printing) { state.isPrinting = printing; }, // 队列管理 ADD_TO_QUEUE(state, task) { const taskWithId = { ...task, id: Math.random(), createdAt: new Date().toISOString(), status: 'pending' }; state.printQueue.push(taskWithId); }, REMOVE_FROM_QUEUE(state, taskId) { state.printQueue = state.printQueue.filter(task => task.id !== taskId); }, UPDATE_TASK_STATUS(state, { taskId, status }) { const task = state.printQueue.find(t => t.id === taskId); if (task) task.status = status; }, // 历史记录 ADD_TO_HISTORY(state, task) { state.printHistory.unshift({ ...task, printedAt: new Date().toISOString() }); // 保持最多50条历史记录 if (state.printHistory.length > 50) { state.printHistory.pop(); } }, // 重连管理 SET_RECONNECT_ATTEMPTS(state, attempts) { state.reconnectAttempts = attempts; }, // 错误与日志 SET_ERROR(state, error) { state.lastError = error; if (error) { state.operationLogs.unshift({ type: 'error', message: error.message || error.errMsg || String(error), timestamp: new Date().toISOString() }); } }, ADD_LOG(state, log) { state.operationLogs.unshift({ ...log, timestamp: new Date().toISOString() }); if (state.operationLogs.length > 100) { state.operationLogs.pop(); } }, // 重置状态 RESET_SCAN(state) { state.bluetoothDevices = []; }, RESET_CONNECTION(state) { state.currentDevice = null; state.connectionStatus = 'disconnected'; state.deviceServices = []; state.reconnectAttempts = 0; }, CLEAR_QUEUE(state) { state.printQueue = []; }, AVAILABLE(state, status) { state.bluetoothAvailable = status }, DISCOVERING(state, status) { state.discovering = status } }; const actions = { /** * 初始化蓝牙适配器 */ async initializeBluetooth({ commit, dispatch, state }) { try { const [fail] = await uni.openBluetoothAdapter(); if (fail) { commit('AVAILABLE', false); } else { commit('AVAILABLE', true); } uni.onBluetoothAdapterStateChange(function(res) { commit('AVAILABLE', res.available); commit('DISCOVERING', res.discovering); }) uni.onBluetoothDeviceFound(async function(devices) { console.log("新设备加入列表"); commit('ADD_DEVICE', devices.devices[0]); }) uni.onBLEConnectionStateChange(async function(res) { }) } catch (error) { commit('AVAILABLE', false); } }, async getPrintTemplate({ commit, state }, businessType) { return new Promise((resolve, reject) => { http('common.listTemplatesByType', { businessType: businessType }).then(res => { console.log(res); resolve(res); }).then(() => { }) .catch(e => { reject(e) }) }) }, /** * 开启或关闭搜索 */ async scanDevices({ commit, state }, status) { if (status) { commit('RESET_SCAN'); await uni.startBluetoothDevicesDiscovery(); } else { await uni.stopBluetoothDevicesDiscovery(); } }, /** * 连接TSC打印机 */ async connectDevice({ commit, state, dispatch }, device) { commit('SET_CONNECTION_STATUS', 'connecting'); commit('ADD_LOG', { type: 'info', message: `正在连接: ${device.name}` }); console.log(`正在连接: ${device.name}`); try { // 1. 创建BLE连接 const connection = await uni.createBLEConnection({ deviceId: device.deviceId, timeout: 10000 }); console.log('连接建立:', connection); // 2. 获取服务 const [error, servicesRes] = await uni.getBLEDeviceServices({ deviceId: device.deviceId }); if (error || !servicesRes || !servicesRes.services || servicesRes.services.length === 0) { throw new Error('未发现设备服务'); } console.log('发现服务:', servicesRes.services); // 3. 查找TSC打印机服务(参考代码使用 49535343) // TSC蓝牙打印机通常使用特定的服务UUID,如: // 49535343-FE7D-4AE5-8FA9-9FAFD205E455 或其他类似的 let targetService = null; // 首先尝试查找包含特定标识的服务 for (const service of servicesRes.services) { // 方法1: 检查是否包含TSC打印机特征标识 if (service.uuid.includes('49535343')) { targetService = service; console.log('找到TSC服务 (49535343):', service); break; } // 方法2: 检查是否为通用打印服务 if (service.uuid.toLowerCase().includes('fff0') || service.uuid.toLowerCase().includes('ae30')) { targetService = service; console.log('找到通用打印服务:', service); } } // 如果没有找到特定服务,使用第一个服务 if (!targetService && servicesRes.services.length > 0) { targetService = servicesRes.services[0]; console.log('使用第一个服务:', targetService); } if (!targetService) { throw new Error('未找到可用的打印机服务'); } // 4. 获取该服务的特征值 const [charError, characteristicsRes] = await uni.getBLEDeviceCharacteristics({ deviceId: device.deviceId, serviceId: targetService.uuid }); if (charError || !characteristicsRes || !characteristicsRes.characteristics) { throw new Error('未发现特征值'); } console.log('发现特征值:', characteristicsRes.characteristics); // 5. 查找读写特征 let writeChar = null; let notifyChar = null; let readChar = null; for (const char of characteristicsRes.characteristics) { console.log(`特征值 ${char.uuid}:`, char.properties); // 查找写入特征(有write属性) if (char.properties.write || char.properties.writeWithoutResponse) { if (!writeChar) { writeChar = char; } // 优先选择 writeWithoutResponse if (char.properties.writeWithoutResponse) { writeChar = char; } } // 查找通知特征 if (char.properties.notify || char.properties.indicate) { if (!notifyChar) { notifyChar = char; } } // 查找读取特征 if (char.properties.read) { if (!readChar) { readChar = char; } } } if (!writeChar) { throw new Error('未找到可写的特征值'); } console.log('选择写入特征:', writeChar); console.log('选择通知特征:', notifyChar); // 6. 如果需要,开启通知 if (notifyChar) { try { await uni.notifyBLECharacteristicValueChange({ deviceId: device.deviceId, serviceId: targetService.uuid, characteristicId: notifyChar.uuid, state: true }); console.log('已开启通知'); } catch (notifyError) { console.warn('无法开启通知:', notifyError); } } // 7. 保存设备信息 commit('SET_CURRENT_DEVICE', { id: device.deviceId, name: device.name || '未知设备', serviceId: targetService.uuid, characteristicId: writeChar.uuid, notifyId: notifyChar ? notifyChar.uuid : null, readId: readChar ? readChar.uuid : null, writeType: writeChar.properties.writeWithoutResponse ? 'writeWithoutResponse' : 'write', properties: writeChar.properties }); commit('SET_CONNECTION_STATUS', 'connected'); commit('ADD_LOG', { type: 'success', message: `连接成功: ${device.name || device.deviceId}` }); // 8. 监听连接状态变化 uni.onBLEConnectionStateChange((changeRes) => { console.log('连接状态变化:', changeRes); if (!changeRes.connected && state.currentDevice?.id === changeRes.deviceId) { commit('ADD_LOG', { type: 'warning', message: '蓝牙连接已断开' }); commit('SET_CONNECTION_STATUS', 'disconnected'); if (state.autoReconnect && state.reconnectAttempts < state.maxReconnectAttempts) { dispatch('attemptReconnect'); } } }); // 9. 监听特征值变化(如果有通知) if (notifyChar) { uni.onBLECharacteristicValueChange((res) => { console.log('收到特征值变化:', res); // 这里可以处理打印机返回的数据 }); } return true; } catch (error) { console.error('连接失败:', error); commit('SET_CONNECTION_STATUS', 'error'); commit('SET_ERROR', error); commit('ADD_LOG', { type: 'error', message: `连接失败: ${error.message || error.errMsg || '未知错误'}` }); return false; } }, /** * 发送打印数据到TSC打印机 */ async sendPrintData({ commit, state, dispatch }, printTask) { if (state.connectionStatus !== 'connected') { throw new Error('打印机未连接'); } if (state.isPrinting) { // 加入队列等待 commit('ADD_TO_QUEUE', printTask); return { queued: true, taskId: state.printQueue[state.printQueue.length - 1].id }; } commit('INIT_PRINTER_INSTANCE'); commit('SET_PRINTING', true); const taskId = printTask.id || Math.random(); try { commit('ADD_LOG', { type: 'info', message: `开始打印任务: ${printTask.title || '未命名'}` }); // 1. 准备TSC指令 const printer = state.printer; printer.clear(); // 清空缓冲区 if (printTask.size) { commit('ADD_LOG', { type: 'info', message: `重设大小${printTask.size.width} * ${printTask.size.height}` }); console.log(`重设大小${printTask.size.width} * ${printTask.size.height}`); printer.setSize(printTask.size.width,printTask.size.height); } console.log("printTask",printTask); printer.setBitmap(0, 0, 0, printTask); commit('ADD_LOG', { type: 'info', message: `生成打印任务内容: ${printTask.title || '未命名'}` }); // 3. 添加打印指令 printer.setPrint(printTask.copies || 1); // 4. 获取二进制数据 const commandData = printer.getData(); // 5. 分片发送(BLE限制) const chunkSize = 20; // BLE MTU通常为20字节 const chunks = []; // 确保 commandData 是 Uint8Array 或 ArrayBuffer let dataArray; if (typeof commandData === 'string') { // 如果是字符串,转换为 Uint8Array const encoder = new TextEncoder(); dataArray = encoder.encode(commandData); } else if (commandData instanceof ArrayBuffer) { dataArray = new Uint8Array(commandData); } else if (commandData instanceof Uint8Array) { dataArray = commandData; } else { // 尝试其他类型转换 dataArray = new Uint8Array(commandData); } for (let i = 0; i < dataArray.length; i += chunkSize) { const chunk = dataArray.slice(i, Math.min(i + chunkSize, dataArray.length)); chunks.push(chunk); } // 6. 发送数据 for (let i = 0; i < chunks.length; i++) { const chunk = chunks[i]; await uni.writeBLECharacteristicValue({ deviceId: state.currentDevice.id, serviceId: state.currentDevice.serviceId, characteristicId: state.currentDevice.characteristicId, value: chunk.buffer, // 直接传递 ArrayBuffer writeType: state.currentDevice.writeType }); // 添加延迟,避免发送过快 if (i < chunks.length - 1) { await delay(20); } } // 7. 记录成功 commit('ADD_TO_HISTORY', { ...printTask, id: taskId, success: true }); commit('ADD_LOG', { type: 'success', message: `打印完成: ${printTask.title || '任务'}` }); return { success: true, taskId }; } catch (error) { commit('SET_ERROR', error); commit('ADD_LOG', { type: 'error', message: `打印失败: ${error.errMsg || error.message}` }); // 记录失败历史 commit('ADD_TO_HISTORY', { ...printTask, id: taskId, success: false, error: error.message }); throw error; } finally { commit('SET_PRINTING', false); // 检查并处理下一个队列任务 if (state.printQueue.length > 0) { const nextTask = state.printQueue[0]; commit('REMOVE_FROM_QUEUE', nextTask.id); setTimeout(() => { dispatch('sendPrintData', nextTask); }, 500); } } }, /** * 生成标签内容 */ async generateLabelContent({ getters, commit, state }, { printer, data, size }) { printer.setCls(); commit('ADD_LOG', { type: 'info', message: `开始生成标签` }); const mmToDot = getters.mmToDot; // 设置标签尺寸 printer.setSize(size.width, size.height); commit('ADD_LOG', { type: 'info', message: `设置标签大小完成${size.width}, ${size.height}` }); // 添加文本 if (data.texts) { data.texts.forEach(text => { printer.setText( mmToDot(text.x || 10), mmToDot(text.y || 10), text.font || 'TSS24.BF2', text.rotation || 0, text.xScale || 1, text.yScale || 1, text.content ); }); } // 添加条形码 if (data.barcodes) { data.barcodes.forEach(barcode => { printer.setBarCode( mmToDot(barcode.x || 10), mmToDot(barcode.y || 40), barcode.type || '128', mmToDot(barcode.height || 20), barcode.readable ? 1 : 0, barcode.rotation || 0, barcode.narrow || 2, barcode.wide || 4, barcode.content ); }); } // 添加二维码 if (data.qrcodes) { data.qrcodes.forEach(qrcode => { printer.setQrcode( mmToDot(qrcode.x || 10), mmToDot(qrcode.y || 70), qrcode.level || 'M', qrcode.width || 4, qrcode.mode || 'A', qrcode.rotation || 0, qrcode.model || "M1", qrcode.mask || "S7", qrcode.content ); }); } // 添加线条 if (data.bars) { data.bars.forEach(bar => { printer.setBar( mmToDot(bar.x || 10), mmToDot(bar.y || 10), mmToDot(bar.width || 50), mmToDot(bar.height || 2) ); }); } // 添加方框 if (data.boxes) { data.boxes.forEach(box => { printer.setBox( mmToDot(box.x1 || 10), mmToDot(box.y1 || 10), mmToDot(box.x2 || 60), mmToDot(box.y2 || 40), mmToDot(box.thickness || 1) ); }); } commit('ADD_LOG', { type: 'info', message: `开始生成标签完成` }); }, /** * 打印商品标签(示例) */ async printProductLabel({ dispatch }, productData) { const task = { type: 'label', title: `商品标签-${productData.code}`, copies: productData.copies || 1, size: { width: 70, height: 20 }, data: { texts: [{ x: 25, y: 2, font: 'TSS24.BF2', content: productData.name, rotation: 0 }, { x: 25, y: 5, font: 'TSS24.BF2', content: `型号:${productData.model}`, rotation: 0 }, { x: 25, y: 8, font: 'TSS24.BF2', content: `价格¥${productData.price}`, xScale: 2, yScale: 2, rotation: 0 }, ], qrcodes: [{ x: 2, y: 2, width: 7, content: productData.code, readable: true, }], } }; return dispatch('sendPrintData', task); }, /** * 打印canvas */ async printCanvas({ dispatch }, canvasData) { return dispatch('sendPrintData', canvasData); console.log("canvasData",canvasData); }, /** * 断开连接 */ async disconnectDevice({ commit, state }) { if (!state.currentDevice) return; try { await uni.closeBLEConnection({ deviceId: state.currentDevice.id }); commit('RESET_CONNECTION'); commit('ADD_LOG', { type: 'info', message: '已断开连接' }); return true; } catch (error) { commit('SET_ERROR', error); return false; } }, /** * 尝试重连 */ async attemptReconnect({ commit, state, dispatch }) { if (!state.autoReconnect || !state.currentDevice || state.reconnectAttempts >= state.maxReconnectAttempts) { return; } commit('SET_RECONNECT_ATTEMPTS', state.reconnectAttempts + 1); commit('ADD_LOG', { type: 'info', message: `重连尝试 (${state.reconnectAttempts}/${state.maxReconnectAttempts})` }); setTimeout(async () => { const success = await dispatch('connectDevice', state.currentDevice); if (!success) { dispatch('attemptReconnect'); } else { commit('SET_RECONNECT_ATTEMPTS', 0); } }, 2000); }, /** * 清空打印队列 */ clearPrintQueue({ commit }) { commit('CLEAR_QUEUE'); commit('ADD_LOG', { type: 'info', message: '打印队列已清空' }); }, /** * 重置模块状态 */ resetModule({ commit }) { commit('RESET_CONNECTION'); commit('RESET_SCAN'); commit('CLEAR_QUEUE'); commit('SET_PRINTING', false); commit('SET_ERROR', null); commit('SET_RECONNECT_ATTEMPTS', 0); commit('ADD_LOG', { type: 'info', message: '模块状态已重置' }); } }; // 工具函数 function arrayBufferToBase64(buffer) { let binary = ''; const bytes = new Uint8Array(buffer); for (let i = 0; i < bytes.length; i++) { binary += String.fromCharCode(bytes[i]); } return uni.arrayBufferToBase64 ? uni.arrayBufferToBase64(binary) : btoa(binary); } function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } export default { namespaced: true, state, getters, mutations, actions };