You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Python byteArray转为Flutter蓝牙特征写入所需整数列表?

Python Bleak的bytearray转Flutter flutter_blue_plus整数列表问题

问题背景

我使用Python Bleak库向蓝牙设备特征写入的bytearray为:

bytearray(b'3\x01\x00-\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x1f')

现在要切换到Flutter的flutter_blue_plus包,该包要求传入整数列表来写入特征,示例写法为:

await c.write([0x12, 0x34]) 

需要把Python的bytearray转换成对应的整数列表,且之前的尝试未成功。

已尝试的失败案例

尝试1

写入代码:

await c.write([3, 1, 0, 45, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 31]);

设备响应:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

尝试2

写入代码:

await c.write([51, 1, 0, 45, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 31]);

设备响应:

[51, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50]
[238, 1, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 231]

Python Bleak成功时的设备响应

bytearray(b'\x00\x04S\x08')
bytearray(b'\x00\x04S\t')
bytearray(b'\x00\x04S\t')
bytearray(b'\x00\x04S\x08')
bytearray(b'\x00\x04O\x1f')
bytearray(b'\x00\x04O"')
bytearray(b'\x00\x04O"')
bytearray(b'\x00\x04O\x1f')
bytearray(b'\x00\x04O ')
bytearray(b'\x00\x04O\x1f')
bytearray(b'\x00\x04O ')
bytearray(b'\x00\x04O!')
bytearray(b'\x00\x04O ')
bytearray(b'\x00\x04O ')
bytearray(b'\x00\x04O!')
bytearray(b'\x00\x04O#')
bytearray(b'\x00\x04O$')
bytearray(b'\x00\x04O%')

正确转换方法及注意事项

1. 准确转换bytearray到整数列表

Python的bytearray中每个元素对应一个字节,转换为Flutter的整数列表时,需要将每个字节转为十进制整数:

  • 字符'3'的ASCII码是十进制51(而非数值3)
  • \x01对应十进制1
  • \x00对应十进制0
  • 字符'-'的ASCII码是十进制45
  • 最后的\x1f对应十进制31

原bytearray的完整整数列表为:

[51, 1, 0, 45, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 31]

(注意:原bytearray长度为21字节,之前的尝试少了一个0,导致长度不匹配)

2. 检查蓝牙写入类型

flutter_blue_plus的write方法默认使用WriteType.withoutResponse,而Python Bleak可能默认使用带响应的写入类型。尝试指定写入类型为带响应:

await c.write(
  [51, 1, 0, 45, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 31],
  writeType: WriteType.withResponse
);

3. 验证字节长度

确保写入的整数列表长度和Python中bytearray的长度完全一致,蓝牙设备通常对数据包长度有严格要求,长度不匹配会导致设备无法正确响应。

内容的提问来源于stack exchange,提问作者Abdullah Saeed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 08:36:33