(Using python) I am looking to generate a bytes (or can be string that I convert to bytes) that is a message to send over TCP. The format is [Header][Length][Payload]
.
Within [Header]
is a [PayloadType]
which determines the content of [Payload]
.
Equally, I am looking to take a response message of a similar format that I can parse into a class/object for later use. Again, the content of the response would determine what 'properties' the class object would have.
My first thought was something like:
class message():
def __init__(self, payloadType, data, propA=None, propB=None):
self._payloadType = payloadType
self._data = data
self._header = '123456'
self._propA = propA
self._propB = propB
def createPacket(self):
if self._payloadType == 1:
return self._header + self._payloadType + self._propA + self._data
elif self._payloadType == 2:
return self._header + self._payloadType + self._propB + self._data
# etc
def parsePacket(self, packet)
payloadType = packet[4:6]
if payloadType == 1:
self._propA = packet[10:12]
# etc
The issues I see with this is there a number of payloadType
and each has some commonality in the header but could have a number of different properties.
This would lead to lots of optional arguments being passed, lots of properties in the class that are potentially unused...all making the code hard to read I feel.
I feel that there is a better pattern for this in Python but I can't figure out what it is - I've read about inheritance, mixins, dataclasses, @class_method, etc but not sure if any of those fit the bill.
Is there a standard pattern way of doing this?
EDIT - more details. This relates to DoIP protocol (some info here). In there, there are different messages that can be sent that are similar (see pg 25/26 of link). And the response can have different payloads. I have a Send()
function that just needs to be given a message
to send (should not care about type). But when a response is received, I'd like to parse it into a message
type format such that I can do things like message.nack_code
to read the properties. It also means that it is all defined in one place and if anything changes in the spec, it's easier to handle.
But the properties are different depending on the type of response so I could have one large message
class that can hold all properties or lots of (related) classes/objects that are specific to the type.