uniapp蓝牙设备对接实战:从打印机编码转换到电子秤数据监听
1. 蓝牙设备对接的核心挑战
在移动应用开发中,蓝牙设备对接一直是让开发者头疼的问题。我做过不少uniapp项目,发现对接打印机和电子秤时,真正的难点往往不是基础连接,而是后续的数据处理。打印机需要处理GBK编码转换,电子秤要实时监听数据流,这两个需求看似简单,实际开发中却暗藏玄机。
先说打印机,市面上80%的热敏打印机都采用GBK编码,而我们的uniapp默认使用UTF-8。这就好比两个人在对话,一个说中文,一个说俄语,完全对不上频道。更麻烦的是,手机端无法直接使用浏览器的TextDecoder API,这个坑我当初踩了整整两天。
电子秤的难点在于数据监听机制。不同于打印机单向发送指令,电子秤需要持续接收数据变化。很多新手会遇到数据丢包、延迟显示的问题,其实是因为没处理好蓝牙特征值的订阅机制。我见过最夸张的案例,电子秤数值要等5秒才刷新,用户体验直接崩盘。
2. 蓝牙连接全流程解析
2.1 初始化蓝牙模块
蓝牙对接的第一步永远是初始化,这个环节最容易出现权限问题。在安卓6.0以上系统,必须动态申请位置权限,因为蓝牙扫描需要用到定位服务。下面是经过实战检验的初始化代码:
uni.openBluetoothAdapter({
success: (res) => {
console.log('蓝牙适配器初始化成功');
this.startDiscovery();
},
fail: (err) => {
if (err.errCode === 10001) {
uni.showToast({ title: '请开启蓝牙功能', icon: 'none' });
}
}
});
关键点:一定要处理10001错误码,这是用户没开蓝牙的情况。我建议在fail回调里增加引导开启蓝牙的UI提示,比干巴巴的报错友好得多。
2.2 设备发现与连接
搜索设备时有个隐藏坑点:不同平台的表现差异。iOS会返回所有蓝牙设备,而安卓只返回可连接设备。建议增加设备过滤逻辑:
uni.onBluetoothDeviceFound((res) => {
res.devices.forEach(device => {
if (device.name?.includes('MPT-II') || device.localName?.includes('ANDZ')) {
this.targetDevice = device;
uni.stopBluetoothDevicesDiscovery();
}
});
});
连接阶段最易出错的是服务发现。很多开发者会直接获取服务,结果返回空列表。这是因为蓝牙连接需要时间协商,必须加延迟:
setTimeout(() => {
uni.getBLEDeviceServices({
deviceId: deviceId,
success: (res) => {
res.services.forEach(service => {
this.getCharacteristics(deviceId, service.uuid);
});
}
});
}, 800); // 实测800ms是最稳的等待时间
3. 打印机编码转换实战
3.1 GBK编码解决方案
经过多次踩坑,我总结出三种编码转换方案:
- TextDecoder方案(仅限浏览器):
// 不推荐!手机端不支持
const decoder = new TextDecoder('gbk');
const result = decoder.decode(uint8Array);
- encoding.js方案(Vue2可用):
// Vue3会报require错误
const encode = require('./encoding.js');
- 改良版GBK.js方案(推荐): 我修改过的GBK.js直接内置编码表,完美解决兼容性问题。使用方式:
import gbk from './gbk.js';
const gbkArray = gbk("需要打印的内容");
// 返回[213, 226, 202, 199,...]这样的十进制数组
性能对比:
| 方案 | 兼容性 | 体积 | 速度 |
|---|---|---|---|
| TextDecoder | 差 | 0KB | 快 |
| encoding.js | 中 | 45KB | 中 |
| 改良版GBK.js | 优 | 28KB | 快 |
3.2 打印指令拆分发送
蓝牙单次传输有20字节限制,长文本必须拆分发送。我封装了个智能拆分方法:
function sendChunkedData(deviceId, serviceId, charId, data) {
const chunkSize = 20;
for (let i = 0; i < data.length; i += chunkSize) {
const chunk = data.slice(i, i + chunkSize);
const buffer = new ArrayBuffer(chunk.length);
const view = new Uint8Array(buffer);
chunk.forEach((v, j) => view[j] = v);
uni.writeBLECharacteristicValue({
deviceId,
serviceId,
characteristicId: charId,
value: buffer,
writeType: 'writeNoResponse' // 提升发送速度
});
}
}
避坑指南:
- 发送间隔建议保持在50-100ms,间隔太短会导致数据丢失
- 一定要用writeNoResponse模式,否则每次等待应答会严重拖慢速度
- 复杂格式(如二维码)需要先发送控制指令,再发送数据
4. 电子秤数据监听技巧
4.1 特征值订阅
电子秤的核心是启用notify特性,这个配置错了数据就收不到:
uni.notifyBLECharacteristicValueChange({
state: true,
deviceId: this.deviceId,
serviceId: this.serviceId,
characteristicId: this.charId,
success: () => {
uni.onBLECharacteristicValueChange((res) => {
this.parseScaleData(res.value);
});
}
});
4.2 数据解析方案
不同厂家的电子秤协议各异,常见的有三种数据格式:
- ASCII模式:直接返回"1.23kg"这样的字符串
- 二进制模式:需要按字节解析,比如第3-4字节表示重量
- 自定义协议:需要厂商提供协议文档
这是我常用的通用解析方法:
function parseScaleData(buffer) {
// 方案1:尝试ASCII解码
const asciiStr = String.fromCharCode.apply(null, new Uint8Array(buffer));
if (/^\d+\.?\d*[kgKG]$/.test(asciiStr)) {
return parseFloat(asciiStr);
}
// 方案2:二进制解析
const view = new DataView(buffer);
const weight = view.getUint16(2, false) / 100;
if (!isNaN(weight)) {
return weight;
}
// 方案3:自定义协议处理
// ...
}
调试技巧:
- 先用
console.log(Array.from(new Uint8Array(buffer)))打印原始数据 - 用微信开发者工具的蓝牙调试功能实时监控数据
- 如果数据波动大,可以增加防抖处理
5. 完整实现案例
5.1 打印机模块封装
class BluetoothPrinter {
constructor() {
this.queue = [];
this.isSending = false;
}
async print(text, options = {}) {
const { fontSize = 1, align = 'left' } = options;
const gbkData = gbk(text);
const commands = [
...this.getFontCommand(fontSize),
...this.getAlignCommand(align),
...gbkData,
0x0A // 换行
];
this.queue.push(...commands);
this.processQueue();
}
processQueue() {
if (this.isSending || this.queue.length === 0) return;
this.isSending = true;
const chunk = this.queue.splice(0, 20);
uni.writeBLECharacteristicValue({
deviceId: this.deviceId,
serviceId: this.serviceId,
characteristicId: this.charId,
value: new Uint8Array(chunk).buffer,
success: () => {
setTimeout(() => {
this.isSending = false;
this.processQueue();
}, 50);
}
});
}
}
5.2 电子秤组件实现
<template>
<view class="scale-container">
<text class="weight">{{ formattedWeight }}</text>
<view class="log" v-if="debugMode">
<text v-for="(msg, i) in logs" :key="i">{{ msg }}</text>
</view>
</view>
</template>
<script>
export default {
data() {
return {
rawWeight: 0,
logs: [],
debugMode: true
}
},
computed: {
formattedWeight() {
return this.rawWeight.toFixed(2) + ' kg';
}
},
methods: {
startListen() {
this.connect().then(() => {
this.subscribeData();
});
},
subscribeData() {
uni.notifyBLECharacteristicValueChange({
state: true,
deviceId: this.deviceId,
serviceId: this.serviceId,
characteristicId: this.charId,
success: () => {
uni.onBLECharacteristicValueChange((res) => {
this.handleScaleData(res.value);
});
}
});
},
handleScaleData(buffer) {
const dataView = new DataView(buffer);
// 假设协议:前2字节头 0xAA 0xBB,接着4字节重量(单位克)
if (dataView.getUint8(0) === 0xAA && dataView.getUint8(1) === 0xBB) {
const weight = dataView.getUint32(2, false) / 1000;
this.rawWeight = weight;
if (this.debugMode) {
this.logs.unshift(`[${new Date().toLocaleTimeString()}] ${weight}kg`);
if (this.logs.length > 10) this.logs.pop();
}
}
}
}
}
</script>
6. 常见问题排查指南
连接失败排查步骤:
- 检查手机蓝牙是否开启
- 确认设备未被其他应用占用
- 查看设备是否支持BLE协议(老设备可能只支持经典蓝牙)
- 在系统设置里忘记设备后重试
数据乱码解决方案:
- 确认打印机编码设置为GBK
- 检查GBK转换是否成功(打印十六进制数据验证)
- 尝试发送纯英文测试(排除中文编码问题)
电子秤数据不更新处理:
- 确认已正确订阅notify特征
- 检查电子秤是否处于稳定状态(部分设备静止时不发送数据)
- 尝试重启电子秤蓝牙模块
性能优化建议:
- 批量发送打印指令时,建议合并多条内容后统一转换编码
- 电子秤数据更新使用防抖处理(如500ms内只更新一次UI)
- 页面销毁时务必关闭蓝牙连接,避免资源泄漏
7. 进阶技巧与优化
对于需要同时连接多个设备的场景,建议采用连接池管理:
class BluetoothManager {
constructor() {
this.connections = new Map();
}
async getConnection(deviceName) {
if (this.connections.has(deviceName)) {
return this.connections.get(deviceName);
}
const conn = new DeviceConnection(deviceName);
await conn.connect();
this.connections.set(deviceName, conn);
return conn;
}
}
重连机制实现:
function setupReconnect(deviceId, maxRetry = 3) {
let retryCount = 0;
const reconnect = () => {
if (retryCount >= maxRetry) return;
uni.createBLEConnection({
deviceId,
success: () => {
retryCount = 0;
},
fail: () => {
retryCount++;
setTimeout(reconnect, 1000 * retryCount);
}
});
};
uni.onBLEConnectionStateChange((res) => {
if (!res.connected) {
reconnect();
}
});
}
数据传输优化方案:
- 对于频繁更新的电子秤数据,使用WebWorker处理数据解析
- 打印机采用队列机制避免指令冲突
- 关键操作添加事务ID确保顺序执行
更多推荐

所有评论(0)