]> www.average.org Git - loctrkd.git/blobdiff - gps303/gps303proto.py
Multiprotocol support in zmq messages and storage
[loctrkd.git] / gps303 / gps303proto.py
index e597b2bbc564da0e24e37f39aa69b5e725b68e2b..efb02d249f6c118185ce2a66b23675c9acf85efd 100755 (executable)
@@ -32,11 +32,13 @@ from typing import (
 )
 
 __all__ = (
-    "GPS303Conn",
+    "Stream",
     "class_by_prefix",
     "inline_response",
     "parse_message",
+    "probe_buffer",
     "proto_by_name",
+    "proto_name",
     "DecodeError",
     "Respond",
     "GPS303Pkt",
@@ -79,12 +81,14 @@ __all__ = (
     "UNKNOWN_B3",
 )
 
+PROTO_PREFIX = "ZX"
+
 ### Deframer ###
 
 MAXBUFFER: int = 4096
 
 
-class GPS303Conn:
+class Stream:
     def __init__(self) -> None:
         self.buffer = b""
 
@@ -871,16 +875,28 @@ def class_by_prefix(
     return CLASSES[proto]
 
 
+def proto_name(obj: Union[MetaPkt, GPS303Pkt]) -> str:
+    return (
+        PROTO_PREFIX
+        + ":"
+        + (
+            obj.__class__.__name__
+            if isinstance(obj, GPS303Pkt)
+            else obj.__name__
+        )
+    ).ljust(16, "\0")[:16]
+
+
 def proto_by_name(name: str) -> int:
     return PROTOS.get(name, -1)
 
 
-def proto_of_message(packet: bytes) -> int:
-    return packet[1]
+def proto_of_message(packet: bytes) -> str:
+    return proto_name(CLASSES.get(packet[1], UNKNOWN))
 
 
 def imei_from_packet(packet: bytes) -> Optional[str]:
-    if proto_of_message(packet) == LOGIN.PROTO:
+    if packet[1] == LOGIN.PROTO:
         msg = parse_message(packet)
         if isinstance(msg, LOGIN):
             return msg.imei
@@ -888,11 +904,11 @@ def imei_from_packet(packet: bytes) -> Optional[str]:
 
 
 def is_goodbye_packet(packet: bytes) -> bool:
-    return proto_of_message(packet) == HIBERNATION.PROTO
+    return packet[1] == HIBERNATION.PROTO
 
 
 def inline_response(packet: bytes) -> Optional[bytes]:
-    proto = proto_of_message(packet)
+    proto = packet[1]
     if proto in CLASSES:
         cls = CLASSES[proto]
         if cls.RESPOND is Respond.INL:
@@ -900,6 +916,15 @@ def inline_response(packet: bytes) -> Optional[bytes]:
     return None
 
 
+def probe_buffer(buffer: bytes) -> bool:
+    framestart = buffer.find(b"xx")
+    if framestart < 0:
+        return False
+    if len(buffer) - framestart < 6:
+        return False
+    return True
+
+
 def parse_message(packet: bytes, is_incoming: bool = True) -> GPS303Pkt:
     """From a packet (without framing bytes) derive the XXX.In object"""
     length, proto = unpack("BB", packet[:2])