2 # -*- coding: iso-8859-15 -*-
7 from pycrc.crc_algorithms import Crc
9 class ByteError(Exception):
10 def __init__(self, value):
11 Exception.__init__(self)
14 return "Byte Error, got 0x%x" % self.value
16 class CRCError(Exception):
20 class TimeoutException(Exception):
24 class NAKReceived(Exception):
28 class PackageTooBigException(Exception):
30 return "Package too long"
43 def __init__(self, conn):
45 self.lock = threading.Lock()
46 self.crc = Crc(width = 8, poly = 0x07, reflect_in = False, xor_in = 0x0, reflect_out = False, xor_out = 0x00)
59 raise TimeoutException()
61 if c not in (self.ACK, self.NAK):
65 def send(self, addr, msg, bSlitMsg=False):
66 msg_len = 3 + len(msg) + 1
67 if bSlitMsg and msg_len > self.MAX_LEN:
68 num_per_packet = self.MAX_LEN - 3 - 1
69 num_packets = math.ceil(len(msg)/float(num_per_packet))
70 self.send(addr, "%cSplit %d" % (self.DC1, num_packets))
71 for i in range(0, len(msg), num_per_packet):
72 msg_part = msg[i:i+num_per_packet]
73 self.send(addr, msg_part)
77 if msg_len > self.MAX_LEN:
78 raise PackageTooBigException()
79 packet = struct.pack("<BBB%ds" % len(msg), self.ENQ, msg_len, addr, msg)
80 packet+=chr(self.crc.bit_by_bit_fast(packet))
81 self.conn.write(packet)
82 if not self.__get_ack():
89 def write(self, addr, msg):
90 return self.send(addr, msg)
92 def __reply_ack(self):
93 self.conn.write(chr(self.ACK))
95 def __reply_nak(self):
96 self.conn.write(chr(self.NAK))
101 state = self.STATE_DEFAULT
105 c = self.conn.read(1)
108 if state == self.STATE_DEFAULT:
109 if ord(c) != self.ENQ:
111 raise ByteError(ord(c))
112 state = self.STATE_LEN
114 elif state == self.STATE_LEN:
115 if ord(c) > self.MAX_LEN:
117 raise PackageTooBigException()
118 state = self.STATE_READ
121 elif state == self.STATE_READ:
125 if self.crc.bit_by_bit_fast(packet) == 0:
127 msgtype, msglen, addr, msg, crc = struct.unpack("<BBB%dsB" % (len(packet)-3-1), packet)
138 addr, msg = self.receive()
139 if msg[0] == chr(self.DC1) and len(msg) > 1:
140 lCmd = msg[1:].split()
141 if len(lCmd) == 2 and lCmd[0] == "Split":
145 addr_part, msg_part = self.receive()
146 if addr_part == addr:
150 if __name__ == "__main__":
152 if (len(sys.argv) > 2):
154 with open(sys.argv[1], "a+") as f:
156 p.write(int(sys.argv[2]), sys.argv[3])
159 with open(sys.argv[1], "a+") as f: