]> www.average.org Git - loctrkd.git/blob - loctrkd/watch.py
cleanup framing/deframing of beesure
[loctrkd.git] / loctrkd / watch.py
1 """ Watch for locevt and print them """
2
3 from configparser import ConfigParser
4 from datetime import datetime, timezone
5 from importlib import import_module
6 from logging import getLogger
7 from typing import Any, cast, List
8 import zmq
9
10 from . import common
11 from .zmsg import Bcast
12
13 log = getLogger("loctrkd/watch")
14
15
16 class ProtoModule:
17     PROTO_PREFIX: str
18
19     @staticmethod
20     def parse_message(packet: bytes, is_incoming: bool = True) -> Any:
21         ...
22
23
24 pmods: List[ProtoModule] = []
25
26
27 def runserver(conf: ConfigParser) -> None:
28     global pmods
29     pmods = [
30         cast(ProtoModule, import_module("." + modnm, __package__))
31         for modnm in conf.get("collector", "protocols").split(",")
32     ]
33     # Is this https://github.com/zeromq/pyzmq/issues/1627 still not fixed?!
34     zctx = zmq.Context()  # type: ignore
35     zsub = zctx.socket(zmq.SUB)  # type: ignore
36     zsub.connect(conf.get("collector", "publishurl"))
37     zsub.setsockopt(zmq.SUBSCRIBE, b"")
38
39     try:
40         while True:
41             zmsg = Bcast(zsub.recv())
42             print("I" if zmsg.is_incoming else "O", zmsg.proto, zmsg.imei)
43             for pmod in pmods:
44                 if zmsg.proto.startswith(pmod.PROTO_PREFIX):
45                     msg = pmod.parse_message(zmsg.packet, zmsg.is_incoming)
46                     print(msg)
47     except KeyboardInterrupt:
48         pass
49
50
51 if __name__.endswith("__main__"):
52     runserver(common.init(log))