]> www.average.org Git - loctrkd.git/blobdiff - gps303/termconfig.py
Multiprotocol support in zmq messages and storage
[loctrkd.git] / gps303 / termconfig.py
index fe1f2cd78f2410696ee53fe7ff8a11ef1f063dbc..6ec43fdc1c25f5063096121b459008d6fc3c5511 100644 (file)
@@ -1,5 +1,6 @@
 """ For when responding to the terminal is not trivial """
 
+from configparser import ConfigParser
 from datetime import datetime, timezone
 from logging import getLogger
 from struct import pack
@@ -7,24 +8,23 @@ import zmq
 
 from . import common
 from .gps303proto import *
-from .zmsg import Bcast, Resp
+from .zmsg import Bcast, Resp, topic
 
 log = getLogger("gps303/termconfig")
 
 
-def runserver(conf):
-    termconfig = common.normconf(conf["termconfig"])
-    zctx = zmq.Context()
-    zsub = zctx.socket(zmq.SUB)
+def runserver(conf: ConfigParser) -> None:
+    # Is this https://github.com/zeromq/pyzmq/issues/1627 still not fixed?!
+    zctx = zmq.Context()  # type: ignore
+    zsub = zctx.socket(zmq.SUB)  # type: ignore
     zsub.connect(conf.get("collector", "publishurl"))
-    for protoname in (
-        "STATUS",
-        "SETUP",
-        "POSITION_UPLOAD_INTERVAL",
+    for proto in (
+        proto_name(STATUS),
+        proto_name(SETUP),
+        proto_name(POSITION_UPLOAD_INTERVAL),
     ):
-        topic = pack("B", proto_by_name(protoname))
-        zsub.setsockopt(zmq.SUBSCRIBE, topic)
-    zpush = zctx.socket(zmq.PUSH)
+        zsub.setsockopt(zmq.SUBSCRIBE, topic(proto))
+    zpush = zctx.socket(zmq.PUSH)  # type: ignore
     zpush.connect(conf.get("collector", "listenurl"))
 
     try:
@@ -38,10 +38,16 @@ def runserver(conf):
                 datetime.fromtimestamp(zmsg.when).astimezone(tz=timezone.utc),
                 msg,
             )
-            if msg.DIR is not Dir.EXT:
+            if msg.RESPOND is not Respond.EXT:
                 log.error(
                     "%s does not expect externally provided response", msg
                 )
+            if zmsg.imei is not None and conf.has_section(zmsg.imei):
+                termconfig = common.normconf(conf[zmsg.imei])
+            elif conf.has_section("termconfig"):
+                termconfig = common.normconf(conf["termconfig"])
+            else:
+                termconfig = {}
             kwargs = {}
             if isinstance(msg, STATUS):
                 kwargs = {
@@ -63,12 +69,16 @@ def runserver(conf):
                 ):
                     if key in termconfig:
                         kwargs[key] = termconfig[key]
-            resp = Resp(imei=zmsg.imei, packet=msg.response(**kwargs))
+            resp = Resp(
+                imei=zmsg.imei, when=zmsg.when, packet=msg.Out(**kwargs).packed
+            )
             log.debug("Response: %s", resp)
             zpush.send(resp.packed)
 
     except KeyboardInterrupt:
-        pass
+        zsub.close()
+        zpush.close()
+        zctx.destroy()  # type: ignore
 
 
 if __name__.endswith("__main__"):