import struct
import sys
class UARTMessage:
fmt = '@B5shhhB5shhhB'
def __init__(self, data_bytes):
fields = struct.unpack(self.fmt, data_bytes)
(self.Identification1,
self.Timestamp1,
self.Voltage1,
self.Current1,
self.Signal1,
self.Identification2,
self.Timestamp2,
self.Voltage2,
self.Current2,
self.Signal2,
self.Identification3) = fields
self.Timestamp1 = int.from_bytes(self.Timestamp1, sys.byteorder)
self.Timestamp2 = int.from_bytes(self.Timestamp2, sys.byteorder)
self.Timestamp3 = int.from_bytes(self.Timestamp3, sys.byteorder)
fmt的第一个字符是字节顺序。@是python的默认值(通常是little-endian),如果您需要使用network big-endian-put!。每个后续字符表示来自字节流的数据类型。在
接下来,在初始值设定项中,我根据fmt中的配方将字节解压到fields元组中。接下来,我将元组的值赋给对象属性。时间戳的异常长度为5个字节,因此需要特殊处理。它作为5字节字符串(fmt中的5s)被获取,并使用系统默认字节顺序的int.from_bytes函数转换为int(如果需要不同的字节顺序,请输入'big'或{}作为第二个参数)。在
当你想创建你的结构时,把字节序列传递给构造函数。在