微信小程序蓝牙打印开发全攻略:从入门到精通
微信小程序蓝牙打印指北:开发全流程解析
一、开发前准备:环境与权限配置
1.1 基础环境要求
微信小程序蓝牙打印需满足以下条件:
- 基础库版本≥2.11.0(支持蓝牙4.0+设备)
- 小程序已通过微信认证(部分权限需企业资质)
- 开发工具使用最新稳定版(避免兼容性问题)
关键配置步骤:
在
app.json
中声明蓝牙权限:{
"permission": {
"scope.bluetooth": {
"desc": "需要蓝牙权限以连接打印机"
}
},
"requiredPrivateInfos": ["getBluetoothDevices", "connectBluetoothDevice"]
}
用户授权处理:
wx.openBluetoothAdapter({
success: () => console.log('蓝牙适配器初始化成功'),
fail: (err) => {
if (err.errCode === 10001) {
wx.showModal({
title: '提示',
content: '请开启手机蓝牙功能',
showCancel: false
});
}
}
});
1.2 设备兼容性测试
建议开发前进行设备矩阵测试:
- 安卓系统:华为、小米、OPPO等主流机型
- iOS系统:iOS 12+设备(需单独测试权限弹窗逻辑)
- 打印机型号:支持BLE协议的热敏打印机(如佳博、汉印等)
二、核心开发流程:从扫描到打印
2.1 设备发现与连接
完整代码示例:
// 1. 启动蓝牙适配器
wx.openBluetoothAdapter({
success: async () => {
// 2. 开始搜索设备
const devices = await searchDevices();
// 3. 过滤打印机设备(根据名称或Service UUID)
const printer = devices.find(d => d.name.includes('Printer'));
// 4. 连接设备
await connectDevice(printer.deviceId);
}
});
function searchDevices() {
return new Promise((resolve) => {
wx.startBluetoothDevicesDiscovery({
services: ['0000FFE0-0000-1000-8000-00805F9B34FB'], // 常见打印机服务UUID
success: () => {
setTimeout(() => {
wx.getBluetoothDevices({
success: (res) => resolve(res.devices)
});
}, 1000); // 留1秒搜索时间
}
});
});
}
function connectDevice(deviceId) {
return new Promise((resolve, reject) => {
wx.createBLEConnection({
deviceId,
success: resolve,
fail: reject
});
});
}
2.2 服务与特征值操作
关键步骤:
获取设备服务列表:
wx.getBLEDeviceServices({
deviceId,
success: (res) => {
const service = res.services.find(s => s.isPrimary);
getCharacteristics(deviceId, service.uuid);
}
});
获取特征值并写入数据:
```javascript
function getCharacteristics(deviceId, serviceUuid) {
wx.getBLEDeviceCharacteristics({
deviceId,
serviceId: serviceUuid,
success: (res) => {
const writeChar = res.characteristics.find(c =>c.properties.indexOf('write') > -1
);
sendPrintData(deviceId, serviceUuid, writeChar.uuid);
}
});
}
function sendPrintData(deviceId, serviceUuid, charUuid) {
const printData = new Uint8Array([…]); // 转换为字节数组
wx.writeBLECharacteristicValue({
deviceId,
serviceId: serviceUuid,
characteristicId: charUuid,
value: printData.buffer,
success: () => console.log(‘数据发送成功’),
fail: (err) => console.error(‘写入失败:’, err)
});
}
## 三、高级功能实现
### 3.1 打印指令封装
**ESC/POS指令示例**:
```javascript
class PrintCommand {
static init() {
return new Uint8Array([0x1B, 0x40]); // 初始化打印机
}
static setFont(bold) {
return bold ? new Uint8Array([0x1B, 0x45, 0x01]) :
new Uint8Array([0x1B, 0x45, 0x00]);
}
static printText(text) {
const encoder = new TextEncoder();
return encoder.encode(text);
}
static cutPaper() {
return new Uint8Array([0x1D, 0x56, 0x41, 0x10]); // 完全切纸
}
}
3.2 状态管理与重试机制
实现方案:
class PrinterManager {
constructor() {
this.retryCount = 0;
this.maxRetries = 3;
}
async printWithRetry(commands) {
while (this.retryCount < this.maxRetries) {
try {
await this.executePrint(commands);
break;
} catch (err) {
this.retryCount++;
if (this.retryCount === this.maxRetries) throw err;
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
}
async executePrint(commands) {
// 实现具体的打印逻辑
}
}
四、常见问题解决方案
4.1 连接失败处理
排查清单:
- 检查设备是否已被其他应用连接
- 验证服务UUID和特征值UUID是否正确
- 安卓设备需开启位置权限(蓝牙扫描需要)
- iOS设备需在设置中手动授权蓝牙权限
4.2 打印乱码问题
解决方案:
- 确认打印机支持的字符编码(通常为GBK或UTF-8)
- 使用TextEncoder进行正确编码:
function encodeGBK(str) {
// 实现GBK编码转换(可使用第三方库如iconv-lite)
}
4.3 性能优化建议
- 批量发送数据(单次写入建议不超过20字节)
- 使用Web Worker处理复杂打印指令
- 对长文档进行分片传输
五、安全与合规注意事项
用户隐私保护:
- 明确告知用户蓝牙权限使用目的
- 提供便捷的蓝牙设备断开功能
数据传输安全:
- 敏感数据建议加密后传输
- 避免在打印指令中包含用户个人信息
异常处理规范:
- 所有蓝牙操作需有fail回调处理
- 提供友好的错误提示界面
六、实战案例:小票打印实现
完整实现代码:
// page/print/index.js
Page({
data: {
connected: false
},
async connectPrinter() {
try {
const deviceId = await this.selectDevice();
await this.initPrinter(deviceId);
this.setData({ connected: true });
} catch (err) {
wx.showToast({ title: '连接失败', icon: 'none' });
}
},
async printReceipt() {
if (!this.data.connected) {
wx.showToast({ title: '请先连接打印机', icon: 'none' });
return;
}
const commands = this.buildReceiptCommands();
try {
await this.sendCommands(commands);
wx.showToast({ title: '打印成功' });
} catch (err) {
wx.showToast({ title: '打印失败', icon: 'none' });
}
},
buildReceiptCommands() {
return [
...PrintCommand.init(),
...PrintCommand.setFont(true),
PrintCommand.printText('=== 销售小票 ===\n'),
...PrintCommand.setFont(false),
PrintCommand.printText('商品名称: 测试商品\n'),
PrintCommand.printText('数量: 1\n'),
PrintCommand.printText('单价: 100.00元\n'),
PrintCommand.printText('总计: 100.00元\n'),
PrintCommand.printText('\n感谢惠顾!\n'),
...PrintCommand.cutPaper()
];
},
// 其他辅助方法实现...
});
七、未来发展趋势
- 蓝牙5.0的普及将提升传输速度和稳定性
- 微信生态将提供更完善的蓝牙设备管理API
- 云打印服务与本地蓝牙打印的融合方案
- 跨平台打印解决方案的标准化
结语:微信小程序蓝牙打印开发需要系统掌握蓝牙协议、设备通信和异常处理等关键技术。通过本文介绍的完整开发流程和实战经验,开发者可以高效实现稳定的蓝牙打印功能,为用户提供优质的打印体验。建议在实际开发中结合具体打印机型号进行调试优化,并持续关注微信官方API的更新动态。