serialization - Use struct in python to deserialize a byte array coming from serial -


i have class sorts of data in it, like:

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    

the data fill structure come serial. need deserialize data coming serial in shape of structure. reading serial 40 bytes data chunks , need split itit. tried pickle library seems it's not fitted deserializing type of data. found struct cannot understand how use proprely in case.
comments in struct, need desearilize chunks of data like: first byte identificator, bytes 1 5 included timestamp , on....
have ideea how can achieve this?
thanks

first of all, need declare format of incoming bytes according list: 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) 

first character of fmt byte order. @ python default (usually little endian), if need use network big-endian put !. each subsequent character represents data type comes bytes stream.

next, in initializer, unpack bytes according recipe in fmt fields tuple. next, assign values of tuple object attributes. timestamp has unusual length of 5 bytes, requires special treatment. fetched 5-bytes string (5s in fmt) , converted int using int.from_bytes function system default bytes order (if need different bytes order enter 'big' or 'little' second argument).

when want create structure, pass sequence of bytes constructor.


Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -