@@ -207,12 +207,30 @@ def hello(self, local_ip_address=None) -> bool:
207207 discover_ip_port = self .host [1 ],
208208 )
209209 try :
210- devtype , host , mac , name , is_locked = next (responses )
211- except StopIteration :
212- raise e .exception (- 4000 ) # Network timeout.
213-
214- if (devtype , host , mac ) != (self .devtype , self .host , self .mac ):
215- raise e .exception (- 2040 ) # Device information is not intact.
210+ devtype , _ , mac , name , is_locked = next (responses )
211+
212+ except StopIteration as err :
213+ raise e .NetworkTimeoutError (
214+ - 4000 ,
215+ "Network timeout" ,
216+ f"No response received within { self .timeout } s" ,
217+ ) from err
218+
219+ if mac != self .mac :
220+ raise e .DataValidationError (
221+ - 2040 ,
222+ "Device information is not intact" ,
223+ "The MAC address is different" ,
224+ f"Expected { self .mac } and received { mac } " ,
225+ )
226+
227+ if devtype != self .devtype :
228+ raise e .DataValidationError (
229+ - 2040 ,
230+ "Device information is not intact" ,
231+ "The product ID is different" ,
232+ f"Expected { self .devtype } and received { devtype } " ,
233+ )
216234
217235 self .name = name
218236 self .is_locked = is_locked
@@ -292,15 +310,29 @@ def send_packet(self, packet_type: int, payload: bytes) -> bytes:
292310 try :
293311 resp = conn .recvfrom (2048 )[0 ]
294312 break
295- except socket .timeout :
313+ except socket .timeout as err :
296314 if (time .time () - start_time ) > timeout :
297- raise e .exception (- 4000 ) # Network timeout.
315+ raise e .NetworkTimeoutError (
316+ - 4000 ,
317+ "Network timeout" ,
318+ f"No response received within { timeout } s" ,
319+ ) from err
298320
299321 if len (resp ) < 0x30 :
300- raise e .exception (- 4007 ) # Length error.
301-
302- checksum = int .from_bytes (resp [0x20 :0x22 ], "little" )
303- if sum (resp , 0xBEAF ) - sum (resp [0x20 :0x22 ]) & 0xFFFF != checksum :
304- raise e .exception (- 4008 ) # Checksum error.
322+ raise e .DataValidationError (
323+ - 4007 ,
324+ "Received data packet length error" ,
325+ f"Expected at least 48 bytes and received { len (resp )} " ,
326+ )
327+
328+ nom_checksum = int .from_bytes (resp [0x20 :0x22 ], "little" )
329+ real_checksum = sum (resp , 0xBEAF ) - sum (resp [0x20 :0x22 ]) & 0xFFFF
330+
331+ if nom_checksum != real_checksum :
332+ raise e .DataValidationError (
333+ - 4008 ,
334+ "Received data packet check error" ,
335+ f"Expected a checksum of { nom_checksum } and received { real_checksum } " ,
336+ )
305337
306338 return resp
0 commit comments