protlib
protlib copied to clipboard
subclassing with new fields
Hi! This is a great project! I have been playing with it, and I cannot accomplish the following thing: I would need to define some protocol packets, each having the same header, but different fields. I did something like this:
class Header(protlib.CStruct):
id = protlib.CUChar(default=0)
timestamp = protlib.CUInt(default=0x44332211)
class SomePacket(protlib.CStruct):
header = Header(id=1).get_type()
some_payload_data = protlib.CUChar(default=0)
other_payload_data = protlib.CChar(default=-1)
p = SomePacket(header=Header())
print(p)
print(' '.join('%.2X' % b for b in p.serialize()))
that gives
SomePacket(header=Header(id=0, timestamp=1144201745), some_payload_data=0, other_payload_data=-1)
00 44 33 22 11 00 FF
so the id is not set properly. I can do the following, which works, but it is not so nice:
class SomePacket(protlib.CStruct):
header = Header.get_type()
some_payload_data = protlib.CUChar(default=0)
other_payload_data = protlib.CChar(default=-1)
p = SomePacket(header=Header(id=1))
it gives the expected bytestream:
SomePacket(header=Header(id=1, timestamp=1144201745), some_payload_data=0, other_payload_data=-1)
01 44 33 22 11 00 FF
I wonder, if it would be possible to define the packet like this, without having to specify
class SomePacket(protlib.CStruct):
header = Header(id=1)
some_payload_data = protlib.CUChar(default=0)
other_payload_data = protlib.CChar(default=-1)
p = SomePacket()
Thanks, and again, nice job!
Hi @waszil I had the similar issue. Wondering if this could help you:
class Header(protlib.CStruct):
id = protlib.CUChar(default=0)
timestamp = protlib.CUInt(default=0x44332211)
class SomePacket(protlib.CStruct):
header = Header().get_type(default=Header(id=1))
some_payload_data = protlib.CUChar(default=0)
other_payload_data = protlib.CChar(default=-1)
p = SomePacket()
print(p)
print(' '.join('%.2X' % b for b in p.serialize()))
which yields
01 44 33 22 11 00 FF