77 MESSAGE_LARGE ,
88 MESSAGE_SMALL ,
99)
10- from plugwise .exceptions import ProtocolError
10+ from plugwise .exceptions import (
11+ InvalidMessageChecksum ,
12+ InvalidMessageFooter ,
13+ InvalidMessageHeader ,
14+ InvalidMessageLength ,
15+ )
1116from plugwise .messages import PlugwiseMessage
1217from plugwise .util import (
1318 DateTime ,
@@ -31,7 +36,6 @@ def __init__(self, format_size=None):
3136 super ().__init__ ()
3237 self .format_size = format_size
3338 self .params = []
34- self .mac = None
3539 self .timestamp = None
3640 self .seq_id = None
3741 self .msg_id = None
@@ -45,13 +49,36 @@ def __init__(self, format_size=None):
4549
4650 def deserialize (self , response ):
4751 self .timestamp = datetime .now ()
48- if len (response ) != len (self ):
49- raise ProtocolError (
50- "message doesn't have expected length, expected %d bytes got %d"
51- % (len (self ), len (response ))
52+ _msg_length = len (response )
53+ if _msg_length != len (self ):
54+ raise InvalidMessageLength (
55+ "Invalid message length received for %s, expected %s bytes got %s" ,
56+ self .__class__ .__name__ ,
57+ str (len (self )),
58+ str (_msg_length ),
5259 )
5360 if response [:4 ] != MESSAGE_HEADER :
54- raise ProtocolError ("Invalid message header" )
61+ raise InvalidMessageHeader (
62+ "Invalid message header %s for %s" ,
63+ str (response [:4 ]),
64+ self .__class__ .__name__ ,
65+ )
66+ if response [_msg_length - 2 :] != MESSAGE_FOOTER :
67+ raise InvalidMessageFooter (
68+ "Invalid message footer %s for %s" ,
69+ str (response [_msg_length - 2 :]),
70+ self .__class__ .__name__ ,
71+ )
72+ _calculated_checksum = self .calculate_checksum (response [4 : _msg_length - 6 ])
73+ _message_checksum = response [_msg_length - 6 : _msg_length - 2 ]
74+ if _calculated_checksum != _message_checksum :
75+ raise InvalidMessageChecksum (
76+ "Invalid checksum for %s, expected %s got %s" ,
77+ self .__class__ .__name__ ,
78+ str (_calculated_checksum ),
79+ str (_message_checksum ),
80+ )
81+
5582 self .msg_id = response [4 :8 ]
5683 self .seq_id = response [8 :12 ]
5784 response = response [12 :]
@@ -61,13 +88,13 @@ def deserialize(self, response):
6188 if self .format_size != MESSAGE_SMALL :
6289 self .mac = response [:16 ]
6390 response = response [16 :]
64-
6591 response = self ._parse_params (response )
66- # TODO: unused crc
67- # crc = response[:4]
6892
69- if response [4 :] != MESSAGE_FOOTER :
70- raise ProtocolError ("Invalid message footer" )
93+ _args = b"" .join (a .serialize () for a in self .args )
94+ msg = self .ID
95+ if self .mac != "" :
96+ msg += self .mac
97+ msg += _args
7198
7299 def _parse_params (self , response ):
73100 for p in self .params :
0 commit comments