编码温度以通过蓝牙进行交换
Enconding temperature for exchange over bluetooth
我正在尝试了解如何对一些数据进行编码以便通过 BLE(低功耗蓝牙)进行传输。
具体来说,我对这一行感兴趣:
来自片段:
temp = Temp.read()
temp = temp * 100
char_temp.write(bytearray([temp & 0xFF, temp >> 8]))
在我们进入为什么部分之前,我需要了解如何。在此代码段中,温度从传感器读取为浮点数,以摄氏度为单位。让我们暂时说“20.00”。然后我们乘以100,然后是编码部分:
2000 & 0xFF -> 208
2000 >> 8 -> 7
所以我们基本上是发送:
>>> bytearray([208, 7])
bytearray(b'\xd0\x07')
这是正确的吗?我会这么说,我用我自己的设备检查过,这似乎是正在发送的数据,它也有效,我可以读取从我的 BLE 设备发送的温度。
我不明白的是为什么需要所有这些位操作。例如,我试图只发送 bytearray([hex(20)])
但它不起作用(当试图从我的 phone 读取温度时,数据不能是 parsed/converted)。
能否解释一下发送数据的格式?
如 tests 所示,在 Python 中进行转换的直接方法是使用 to_bytes
和 from_bytes
功能
使用您的数据,字节将指向 int 方向:
>>> int.from_bytes([208, 7], byteorder='little', signed=True)
2000
从整数到字节:
>>> int(2000).to_bytes(2, byteorder='little', signed=True)
b'\xd0\x07'
或者从读取到字节:
>>> int(20.00*100).to_bytes(2, byteorder='little', signed=True)
b'\xd0\x07'
蓝牙数据应该是 little endian format. Each integer in the list needs to represent an octet 中的列表或字节数组。
从你链接到的来源我可以看到特征 UUID 是 0x2A6E
:
uuid_temp = UUID("0x2A6E") # Temperature characteristic
这是官方 UUID,因此在 https://www.bluetooth.com/specifications/assigned-numbers/
的“16 位 UUID 数字文档”中进行了描述
Bluetooth SIG 网站上的 GATT Specification Supplement 文档中的“2:值和表示值”部分有更详细的解释。在该文档中,它还解释了如何以这种方式表示温度:
我正在尝试了解如何对一些数据进行编码以便通过 BLE(低功耗蓝牙)进行传输。 具体来说,我对这一行感兴趣:
来自片段:
temp = Temp.read()
temp = temp * 100
char_temp.write(bytearray([temp & 0xFF, temp >> 8]))
在我们进入为什么部分之前,我需要了解如何。在此代码段中,温度从传感器读取为浮点数,以摄氏度为单位。让我们暂时说“20.00”。然后我们乘以100,然后是编码部分:
2000 & 0xFF -> 208
2000 >> 8 -> 7
所以我们基本上是发送:
>>> bytearray([208, 7])
bytearray(b'\xd0\x07')
这是正确的吗?我会这么说,我用我自己的设备检查过,这似乎是正在发送的数据,它也有效,我可以读取从我的 BLE 设备发送的温度。
我不明白的是为什么需要所有这些位操作。例如,我试图只发送 bytearray([hex(20)])
但它不起作用(当试图从我的 phone 读取温度时,数据不能是 parsed/converted)。
能否解释一下发送数据的格式?
如 tests 所示,在 Python 中进行转换的直接方法是使用 to_bytes
和 from_bytes
功能
使用您的数据,字节将指向 int 方向:
>>> int.from_bytes([208, 7], byteorder='little', signed=True)
2000
从整数到字节:
>>> int(2000).to_bytes(2, byteorder='little', signed=True)
b'\xd0\x07'
或者从读取到字节:
>>> int(20.00*100).to_bytes(2, byteorder='little', signed=True)
b'\xd0\x07'
蓝牙数据应该是 little endian format. Each integer in the list needs to represent an octet 中的列表或字节数组。
从你链接到的来源我可以看到特征 UUID 是 0x2A6E
:
uuid_temp = UUID("0x2A6E") # Temperature characteristic
这是官方 UUID,因此在 https://www.bluetooth.com/specifications/assigned-numbers/
的“16 位 UUID 数字文档”中进行了描述Bluetooth SIG 网站上的 GATT Specification Supplement 文档中的“2:值和表示值”部分有更详细的解释。在该文档中,它还解释了如何以这种方式表示温度: