@@ -73,10 +73,9 @@ def from_bytes(cls, packet):
73
73
"""
74
74
if len (packet ) < 3 :
75
75
raise ValueError ("Packet too short" )
76
- header = packet [0 :2 ]
77
- packet_class = cls ._type_to_class .get (header , None )
76
+ packet_class = cls ._type_to_class .get (packet [0 :2 ], None )
78
77
if not packet_class :
79
- raise ValueError ("Unknown packet header '{}' " .format (header ))
78
+ raise ValueError ("Unregistered packet type {} " .format (packet [ 0 : 2 ] ))
80
79
81
80
# In case this was called from a subclass, make sure the parsed
82
81
# type matches up with the current class.
@@ -103,14 +102,28 @@ def from_stream(cls, stream):
103
102
:param stream stream: an input stream that provides standard stream read operations,
104
103
such as ``ble.UARTServer`` or ``busio.UART``.
105
104
"""
106
- header = stream .read (2 )
107
- if len (header ) != 2 or header [0 ] != ord (b'!' ):
108
- # Remove any other junk already read.
109
- stream .reset_input_buffer ()
110
- return None
105
+ # Loop looking for a b'!' packet start. If the buffer has overflowed,
106
+ # or there's been some other problem, we may need to skip some characters
107
+ # to get to a packet start.
108
+ while True :
109
+ start = stream .read (1 )
110
+ if not start :
111
+ # Timeout: nothing read.
112
+ return None
113
+ if start == b'!' :
114
+ # Found start of packet.
115
+ packet_type = stream .read (1 )
116
+ if not packet_type :
117
+ # Timeout: nothing more read.
118
+ return None
119
+ else :
120
+ break
121
+ # Didn't find a packet start. Loop and try again.
122
+
123
+ header = start + packet_type
111
124
packet_class = cls ._type_to_class .get (header , None )
112
125
if not packet_class :
113
- raise ValueError ("Unknown packet header {}" .format (header ))
126
+ raise ValueError ("Unregistered packet type {}" .format (header ))
114
127
packet = header + stream .read (packet_class .PACKET_LENGTH - 2 )
115
128
return cls .from_bytes (packet )
116
129
0 commit comments