-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodec.py
More file actions
31 lines (28 loc) · 956 Bytes
/
codec.py
File metadata and controls
31 lines (28 loc) · 956 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import struct
class Codec(object):
"""
Base class for SARP message encoding/decoding
"""
def __init__(self, msg_schema):
self.msg_schema = msg_schema
fmt_str = '!' + ''.join([self.msg_schema[k] for k in self.msg_schema])
self.struct = struct.Struct(fmt_str)
def encode(self, msg):
"""
Args:
msg: a dictionary of channels:values matching the msg_schema
Returns: a bytestring formatted packet
"""
msg_vals = [msg[channel] for channel in self.msg_schema]
return self.struct.pack(*msg_vals)
def decode(self, packet):
"""
Args:
packet: a bytestring formatted packet
Returns: a dictionary of channels:values matching the msg_schema
"""
msg_vals = self.struct.unpack(packet)
msg = {}
for name, value in zip(self.msg_schema, msg_vals):
msg[name] = value
return msg