]>
Commit | Line | Data |
---|---|---|
39037602 A |
1 | import logging |
2 | ||
3 | ||
4 | class Message(object): | |
5 | """represents a message of Remote serial protocol""" | |
6 | def __init__(self, data): | |
7 | super(Message, self).__init__() | |
8 | self.data = data | |
9 | ||
10 | def __str__(self): | |
11 | return "Message: %s" % (self.data) | |
12 | ||
13 | def getData(self): | |
14 | #TODO need to parse data and unescape | |
15 | return self.data | |
16 | ||
17 | def getRSPByteData(self): | |
18 | retval = ''.join(['$',self.data,'#']) | |
19 | checksum = 0 | |
20 | for i in self.data: | |
21 | checksum += ord(i) | |
22 | checksum = checksum % 0x100 | |
23 | checksum_str = "{:02x}".format(checksum) | |
24 | retval += checksum_str | |
25 | return retval | |
26 | ||
27 | @classmethod | |
28 | def fromRSPByteData(cls, bytedata): | |
29 | data_begin = 0 | |
30 | data_end = 0 | |
31 | try: | |
32 | data_begin = bytedata.index('$') | |
33 | data_end = bytedata.index('#') | |
34 | except ValueError, e: | |
35 | logging.error('Invalid bytedata considered as message %s' % bytedata) | |
36 | return None | |
37 | ||
38 | #validate the data | |
39 | if data_begin + 1 >= data_end: | |
40 | logging.debug("empty message %s"%bytedata) | |
41 | data_begin -= 1 | |
42 | ||
43 | data_begin += 1 | |
44 | logging.debug("Creating message from data %s" % bytedata[data_begin:data_end]) | |
45 | ret_obj = cls(bytedata[data_begin:data_end]) | |
46 | return ret_obj | |
47 | ||
48 | class ProtocolAcknowledgement(Message): | |
49 | """Ack Messages""" | |
50 | def __init__(self, ack_str): | |
51 | super(ProtocolAcknowledgement, self).__init__(ack_str) | |
52 | self.data = ack_str | |
53 | ||
54 | def getRSPByteData(self): | |
55 | return self.data | |
56 | ||
57 | ||
58 | OKMessage = Message('OK') | |
59 | ||
60 | AckMessage = ProtocolAcknowledgement('+') | |
61 | NAckMessage = ProtocolAcknowledgement('-') | |
62 | UnSupportedMessage = Message('') |