如何解码BleManager.read方法返回的蓝牙特征值响应数据?
蓝牙GATT特征值解码方案
错误原因
- 你当前使用
buffer.toString()直接转译的逻辑错误:蓝牙GATT特征值返回的是结构化二进制数据,不是普通UTF-8编码的字符串,强制转字符串必然出现乱码,这也是你读取任意特征值都得到类似乱码的核心原因。 - 所有蓝牙标准特征值都有固定的字节结构定义,需要按照对应的规则逐段解析字段。
2A08日期时间特征值字节规范
2A08属于蓝牙联盟定义的标准特征值,长度为7字节,采用小端序存储,结构如下:
| 字节位置 | 字段含义 | 数据类型 | 取值范围 |
|---|---|---|---|
| 0-1 | 年份 | Uint16 | 1582-9999 |
| 2 | 月份 | Uint8 | 1-12 |
| 3 | 日期 | Uint8 | 1-31 |
| 4 | 小时 | Uint8 | 0-23 |
| 5 | 分钟 | Uint8 | 0-59 |
| 6 | 秒 | Uint8 | 0-59 |
以你给出的示例返回值[229, 7, 7, 27, 12, 19, 0]为例,对应的日期为2021年7月27日12时19分0秒。
修正后的代码
const readGlucose = (id, serviceUUID, charasteristicUUID) => { BleManager.read(id, serviceUUID, charasteristicUUID) .then(res => { console.log('read response', res); // [229, 7, 7, 27, 12, 19, 0] if (res && res.length === 7) { const buffer = Buffer.from(res); // 按小端序解析对应字段 const year = buffer.readUInt16LE(0); const month = buffer.readUInt8(2); const day = buffer.readUInt8(3); const hour = buffer.readUInt8(4); const minute = buffer.readUInt8(5); const second = buffer.readUInt8(6); // 组合成日期对象或自定义格式化字符串 const dateTime = new Date(year, month - 1, day, hour, minute, second); console.log('解析后的时间:', dateTime); } }) .catch(error => { console.log('read err', error); }); };
其他特征值解析说明
不同GATT特征值的字节结构不同,解析前需要先确认对应特征值的官方定义,再按照对应的字节规则解析,不要统一使用toString()方法转译。
内容的提问来源于stack exchange,提问作者Marcus Vinicius
相关产品推荐
相关产品推荐

