1

I'm using Python to communicate with with a hardware device. The communications protocol generally follow as such:

{header bytes}
{data bytes}
{CRC bytes}

ctypes works very well for the communication protocol because I can define things like:

class Header( BigEndianStructure ):
    _pack_ = 1
    _fields_ = [("Address",         c_ubyte,    8),
                ("MessageLength",   c_ubyte,    8),
                ("MessageType",     c_ubyte,    8)]

    def __init__(self):
        pass

This takes care of the header. All message bodies can then inherit this message header, reducing redundancy.

class Body( Header):

    _fields_ = [("Data", c_ubyte, 8)]

    def __init__(self):
        super().__init__()

The problem: I don't want to have to define ("CRC8", c_ubyte, 8) in every single subclass.

I'd like to be able to have each subclass automatically generated when the object is created. That way, I don't have to add the trailing bytes manually for each message.

user2654735
  • 323
  • 5
  • 19
  • How come `Body` subclasses `Header`? How about a different module that is in charged of bringing the different parts together? – drum Aug 28 '19 at 03:58
  • I need to have ctypes (C/C++ types data structures) because it relates 1:1 with the datastructures used in our C/C++ code. In this way, we can relates bitfields, unsigned vs signed, 32 bit vs 16 bit vs 8 bit, in a 1:1 relationship. It is very useful for our field. – user2654735 Aug 28 '19 at 04:46
  • As for your question, in the python world, it makes much more sense to have a "header" object define the bits in a COM message, so that I don't have to redefine those header bits for every message. When interpreting the bits, every message can automatically figure out the header bits via inheritance. – user2654735 Aug 28 '19 at 04:46
  • How about posting the *C* structures as well? Because *Body* extending *Header* simply seams wrong.There should be a *Message* class containing a *Header*, *Body* and *CRC*. Or if you started this way why not `_fields_ = [("Data", c_ubyte, 8), ("CRC", c_uint32)]`? What are all the subclasses? Also note that *Body* only has one byte. One question: what's the purpose of the bit fields usage? `unsigned char` is 8 bits long anyway. – CristiFati Aug 28 '19 at 06:14

0 Answers0