繁体   English   中英

在python中使用struct反序列化来自串行的字节数组

[英]Use struct in python to deserialize a byte array coming from serial

我有一个包含各种数据的类,例如:

class UARTMessage:
    Identification1 = int(0) #byte 0
    Timestamp1 = int(0) #bytes [1:5]
    Voltage1 = int(0) #bytes [6:7]
    Current1 = int(0) #bytes [8:9]
    Signal1= int(0) #bytes [10:11]
    Identification2 = int(0) #byte 12
    Timestamp2 = int(0) #bytes [13:17]
    Voltage2 = int(0) #bytes [18:19]
    Current2 = int(0) #bytes [20:21]
    Signal = int(0) #bytes [22:23]
    Identification3 = int(0) #byte 24   

填充此结构的数据将来自串行。 我需要以这种结构的形式反序列化来自串行的数据。 我正在从串行40字节数据块读取数据,我需要将其拆分。 我尝试了pickle库,但似乎不完全适合反序列化此类数据。 我找到了struct,但在这种情况下我无法理解如何正确使用它。
正如结构中的注释一样,我需要对数据块进行反序列化处理,例如:第一个字节是Identificator,包含的从1到5的字节是时间戳等等。
您有什么想法可以实现吗?
谢谢

首先,我们需要根据以下列表声明传入字节的格式: https : //docs.python.org/3/library/struct.html?highlight= struct#format- characters

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默认值(通常是小端),如果需要使用网络大端put ! 每个后续字符代表一种来自字节流的数据类型。

接下来,在初始化程序中,我根据fmt的配方将字节解包到fields元组中。 接下来,我将元组的值分配给对象属性。 时间戳记的长度异常为5个字节,因此需要特殊处理。 它以5个字节的字符串(在fmt中为5s )获取,并使用int.from_bytes函数以系统默认字节顺序(如果需要其他字节顺序,请输入'big''little'作为第二个参数)转换为int)。

当您要创建结构时,请将字节序列传递给构造函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM