const STORAGE_KEY = 'canteen.blePrinter'; const WRITE_PROPS = { write: true, writeNoResponse: true, }; function loadSavedPrinter() { try { const raw = wx.getStorageSync(STORAGE_KEY); if (raw && raw.deviceId) { return { deviceId: String(raw.deviceId), name: String(raw.name || '热敏打印机'), }; } } catch { // ignore } return null; } function savePrinter(device) { if (!device || !device.deviceId) return; wx.setStorageSync(STORAGE_KEY, { deviceId: device.deviceId, name: device.name || device.localName || '热敏打印机', }); } function clearPrinter() { try { wx.removeStorageSync(STORAGE_KEY); } catch { // ignore } } function promisify(api, options = {}) { return new Promise((resolve, reject) => { api({ ...options, success: resolve, fail: (err) => reject(new Error((err && err.errMsg) || '蓝牙操作失败')), }); }); } async function ensureBluetoothAuth() { if (typeof wx.authorize !== 'function') return; try { await promisify(wx.authorize, { scope: 'scope.bluetooth' }); } catch { // 用户拒绝时后续 openAdapter 会给出更明确错误 } } async function openAdapter() { await ensureBluetoothAuth(); try { await promisify(wx.openBluetoothAdapter); } catch (err) { const msg = err.message || ''; if (msg.indexOf('10001') >= 0 || /not available|未打开/i.test(msg)) { throw new Error('请先打开手机蓝牙'); } if (/system permission denied|permission denied/i.test(msg)) { throw new Error('系统未允许微信使用蓝牙。请用真机,并在系统设置里打开微信的蓝牙权限;开发者工具模拟器无法搜蓝牙。得力 M1022W 请选「A4 文档」打印'); } throw err; } } function closeAdapter() { try { wx.closeBluetoothAdapter(); } catch { // ignore } } function startScan() { return promisify(wx.startBluetoothDevicesDiscovery, { allowDuplicatesKey: true, }); } function stopScan() { try { wx.stopBluetoothDevicesDiscovery(); } catch { // ignore } } function deviceLabel(device) { return String(device.name || device.localName || '').trim(); } function isWritable(char) { const props = char && char.properties; if (!props) return false; return !!(props.write || props.writeNoResponse); } async function findWritableChar(deviceId) { const servicesRes = await promisify(wx.getBLEDeviceServices, { deviceId }); const services = servicesRes.services || []; for (const service of services) { if (!service.uuid) continue; const charsRes = await promisify(wx.getBLEDeviceCharacteristics, { deviceId, serviceId: service.uuid, }); const chars = charsRes.characteristics || []; const writable = chars.find(isWritable); if (writable) { return { serviceId: service.uuid, characteristicId: writable.uuid, writeNoResponse: !!(writable.properties && writable.properties.writeNoResponse), }; } } throw new Error('未找到可写特征,请确认是 BLE 热敏机而非 A4 激光机'); } async function createConnection(deviceId) { try { await promisify(wx.createBLEConnection, { deviceId, timeout: 8000 }); } catch (err) { const msg = err.message || ''; if (/already connect|已经连接/i.test(msg)) return; throw new Error('连接打印机失败,请靠近设备后重试'); } } function closeConnection(deviceId) { return new Promise((resolve) => { wx.closeBLEConnection({ deviceId, complete: resolve, }); }); } async function writeChunks(deviceId, target, bytes) { let mtu = 20; try { const mtuRes = await promisify(wx.setBLEMTU, { deviceId, mtu: 185 }); if (mtuRes && mtuRes.mtu) mtu = Math.max(20, mtuRes.mtu - 3); } catch { mtu = 20; } const chunk = Math.max(20, Math.min(mtu, 180)); for (let offset = 0; offset < bytes.length; offset += chunk) { const slice = bytes.slice(offset, offset + chunk); await promisify(wx.writeBLECharacteristicValue, { deviceId, serviceId: target.serviceId, characteristicId: target.characteristicId, value: slice.buffer.slice(slice.byteOffset, slice.byteOffset + slice.byteLength), }); // 部分热敏机没有可靠的发送缓冲区,给设备一个极短的处理时间。 if (offset + chunk < bytes.length) { await new Promise((resolve) => setTimeout(resolve, 8)); } } } let printing = false; async function connectAndWrite(device, bytes) { if (printing) throw new Error('打印任务正在进行,请稍候'); if (!device || !device.deviceId) throw new Error('未选择打印机'); if (!bytes || !bytes.length) throw new Error('没有可打印的内容'); printing = true; let connected = false; try { await openAdapter(); await createConnection(device.deviceId); connected = true; const target = await findWritableChar(device.deviceId); await writeChunks(device.deviceId, target, bytes); } finally { if (connected) { try { // 等待打印机消费最后一包数据,避免立即断开导致尾部丢失。 await new Promise((resolve) => setTimeout(resolve, 150)); await closeConnection(device.deviceId); } finally { printing = false; } } else { printing = false; } } } module.exports = { STORAGE_KEY, WRITE_PROPS, loadSavedPrinter, savePrinter, clearPrinter, openAdapter, closeAdapter, startScan, stopScan, deviceLabel, connectAndWrite, };