X-Git-Url: http://www.average.org/gitweb/?a=blobdiff_plain;f=gps303%2Fgps303proto.py;h=e597b2bbc564da0e24e37f39aa69b5e725b68e2b;hb=037939789ccc7ed56059cf9bc7522d3cd7e840a8;hp=e6a80fe5118f4df0c8370539290a13c44e6de821;hpb=2ad23fd8e9afe8d6c46263124ecd88ea28fd3059;p=loctrkd.git diff --git a/gps303/gps303proto.py b/gps303/gps303proto.py index e6a80fe..e597b2b 100755 --- a/gps303/gps303proto.py +++ b/gps303/gps303proto.py @@ -33,7 +33,6 @@ from typing import ( __all__ = ( "GPS303Conn", - "StreamError", "class_by_prefix", "inline_response", "parse_message", @@ -85,10 +84,6 @@ __all__ = ( MAXBUFFER: int = 4096 -class StreamError(Exception): - pass - - class GPS303Conn: def __init__(self) -> None: self.buffer = b"" @@ -97,25 +92,27 @@ class GPS303Conn: def enframe(buffer: bytes) -> bytes: return b"xx" + buffer + b"\r\n" - def recv(self, segment: bytes) -> List[bytes]: + def recv(self, segment: bytes) -> List[Union[bytes, str]]: + """ + Process next segment of the stream. Return successfully deframed + packets as `bytes` and error messages as `str`. + """ when = time() self.buffer += segment if len(self.buffer) > MAXBUFFER: # We are receiving junk. Let's drop it or we run out of memory. self.buffer = b"" - raise StreamError( - f"More than {MAXBUFFER} unparseable data, dropping" - ) - msgs = [] + return [f"More than {MAXBUFFER} unparseable data, dropping"] + msgs: List[Union[bytes, str]] = [] while True: framestart = self.buffer.find(b"xx") if framestart == -1: # No frames, return whatever we have break if framestart > 0: # Should not happen, report - self.buffer = self.buffer[framestart:] - raise StreamError( + msgs.append( f'Undecodable data ({framestart}) "{self.buffer[:framestart][:64].hex()}"' ) + self.buffer = self.buffer[framestart:] # At this point, buffer starts with a packet if len(self.buffer) < 6: # no len and proto - cannot proceed break @@ -138,8 +135,9 @@ class GPS303Conn: packet = self.buffer[2:frameend] self.buffer = self.buffer[frameend + 2 :] if len(packet) < 2: # frameend comes too early - raise StreamError(f"Packet too short: {packet.hex()}") - msgs.append(packet) + msgs.append(f"Packet too short: {packet.hex()}") + else: + msgs.append(packet) return msgs def close(self) -> bytes: @@ -881,6 +879,18 @@ def proto_of_message(packet: bytes) -> int: return packet[1] +def imei_from_packet(packet: bytes) -> Optional[str]: + if proto_of_message(packet) == LOGIN.PROTO: + msg = parse_message(packet) + if isinstance(msg, LOGIN): + return msg.imei + return None + + +def is_goodbye_packet(packet: bytes) -> bool: + return proto_of_message(packet) == HIBERNATION.PROTO + + def inline_response(packet: bytes) -> Optional[bytes]: proto = proto_of_message(packet) if proto in CLASSES: