blob: 6e033422ce1c43561a24328d13f1ff3d6efbe033 (
plain)
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
import crc16
import struct
class PacketWriter(object):
MAX_PAYLOAD = 1584
MIN_LEN = 6
MAX_LEN = 1590
SOF = 0x01
OFFSET_SOF = 0
OFFSET_LENGTH = 1
OFFSET_CMD = 3
OFFSET_PAYLOAD = 4
def __init__(self):
self._packet = None
def Clear(self):
self._packet = None
def NewSOF(self, v):
self._packet[0] = chr(v)
def PacketString(self):
return ''.join(self._packet)
def AppendCrc(self):
self.SetLength()
ps = self.PacketString()
crc = crc16.crc16(ps, 0, len(ps))
for x in struct.pack('H', crc):
self._packet.append(x)
def SetLength(self):
self._packet[1] = chr(len(self._packet) + 2)
def _Add(self, x):
try:
len(x)
for y in x:
self._Add(y)
except:
self._packet.append(x)
def ComposePacket(self, command, payload=None):
assert self._packet is None
self._packet = ["\x01", None, "\x00", chr(command)]
if payload:
self._Add(payload)
self.AppendCrc()
|