diff options
Diffstat (limited to 'dexcom_reader/packetwriter.py')
-rw-r--r-- | dexcom_reader/packetwriter.py | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/dexcom_reader/packetwriter.py b/dexcom_reader/packetwriter.py new file mode 100644 index 0000000..6e03342 --- /dev/null +++ b/dexcom_reader/packetwriter.py | |||
@@ -0,0 +1,49 @@ | |||
1 | import crc16 | ||
2 | import struct | ||
3 | |||
4 | class PacketWriter(object): | ||
5 | MAX_PAYLOAD = 1584 | ||
6 | MIN_LEN = 6 | ||
7 | MAX_LEN = 1590 | ||
8 | SOF = 0x01 | ||
9 | OFFSET_SOF = 0 | ||
10 | OFFSET_LENGTH = 1 | ||
11 | OFFSET_CMD = 3 | ||
12 | OFFSET_PAYLOAD = 4 | ||
13 | |||
14 | def __init__(self): | ||
15 | self._packet = None | ||
16 | |||
17 | def Clear(self): | ||
18 | self._packet = None | ||
19 | |||
20 | def NewSOF(self, v): | ||
21 | self._packet[0] = chr(v) | ||
22 | |||
23 | def PacketString(self): | ||
24 | return ''.join(self._packet) | ||
25 | |||
26 | def AppendCrc(self): | ||
27 | self.SetLength() | ||
28 | ps = self.PacketString() | ||
29 | crc = crc16.crc16(ps, 0, len(ps)) | ||
30 | for x in struct.pack('H', crc): | ||
31 | self._packet.append(x) | ||
32 | |||
33 | def SetLength(self): | ||
34 | self._packet[1] = chr(len(self._packet) + 2) | ||
35 | |||
36 | def _Add(self, x): | ||
37 | try: | ||
38 | len(x) | ||
39 | for y in x: | ||
40 | self._Add(y) | ||
41 | except: | ||
42 | self._packet.append(x) | ||
43 | |||
44 | def ComposePacket(self, command, payload=None): | ||
45 | assert self._packet is None | ||
46 | self._packet = ["\x01", None, "\x00", chr(command)] | ||
47 | if payload: | ||
48 | self._Add(payload) | ||
49 | self.AppendCrc() | ||