]> www.average.org Git - loctrkd.git/blob - loctrkd/__main__.py
Revive command sender and implement some commands
[loctrkd.git] / loctrkd / __main__.py
1 """ Command line tool for sending requests to the terminal """
2
3 from configparser import ConfigParser
4 from datetime import datetime, timezone
5 from getopt import getopt
6 from importlib import import_module
7 from logging import getLogger
8 from sys import argv
9 from time import time
10 from typing import Any, cast, List, Tuple, Type, Union
11 import zmq
12
13 from . import common
14 from .zmsg import Bcast, Resp
15
16 log = getLogger("loctrkd")
17
18
19 class ProtoModule:
20     @staticmethod
21     def proto_handled(proto: str) -> bool:
22         ...
23
24     @staticmethod
25     def class_by_prefix(prefix: str) -> Any:
26         ...
27
28
29 pmods: List[ProtoModule] = []
30
31
32 def main(
33     conf: ConfigParser, opts: List[Tuple[str, str]], args: List[str]
34 ) -> None:
35     global pmods
36     pmods = [
37         cast(ProtoModule, import_module("." + modnm, __package__))
38         for modnm in conf.get("collector", "protocols").split(",")
39     ]
40     # Is this https://github.com/zeromq/pyzmq/issues/1627 still not fixed?!
41     zctx = zmq.Context()  # type: ignore
42     zpush = zctx.socket(zmq.PUSH)  # type: ignore
43     zpush.connect(conf.get("collector", "listenurl"))
44
45     if len(args) < 2:
46         raise ValueError(
47             "Too few args, need IMEI and command min: " + str(args)
48         )
49     imei = args[0]
50     cmd = args[1]
51     args = args[2:]
52     handled = False
53     for pmod in pmods:
54         if pmod.proto_handled(cmd):
55             handled = True
56             break
57     if not handled:
58         raise NotImplementedError(f"No protocol can handle {cmd}")
59     cls = pmod.class_by_prefix(cmd)
60     if isinstance(cls, list):
61         raise ValueError("Prefix does not select a single class: " + str(cls))
62     kwargs = dict([arg.split("=") for arg in args])
63     for arg in args:
64         k, v = arg.split("=")
65         kwargs[k] = v
66     resp = Resp(imei=imei, when=time(), packet=cls.Out(**kwargs).packed)
67     log.debug("Response: %s", resp)
68     zpush.send(resp.packed)
69
70
71 if __name__.endswith("__main__"):
72     opts, args = getopt(argv[1:], "c:d")
73     main(common.init(log, opts=opts), opts, args)