]> www.average.org Git - loctrkd.git/blob - loctrkd/__main__.py
bba38ff1f1321f3ac76a62e69eefebe7db8c0bc9
[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 .protomodule import ProtoModule
15 from .zmsg import Bcast, Resp
16
17 log = getLogger("loctrkd")
18
19
20 pmods: List[ProtoModule] = []
21
22
23 def main(
24     conf: ConfigParser, opts: List[Tuple[str, str]], args: List[str]
25 ) -> None:
26     global pmods
27     pmods = [
28         cast(ProtoModule, import_module("." + modnm, __package__))
29         for modnm in conf.get("common", "protocols").split(",")
30     ]
31     # Is this https://github.com/zeromq/pyzmq/issues/1627 still not fixed?!
32     zctx = zmq.Context()  # type: ignore
33     zpush = zctx.socket(zmq.PUSH)  # type: ignore
34     zpush.connect(conf.get("collector", "listenurl"))
35
36     if len(args) < 2:
37         raise ValueError(
38             "Too few args, need IMEI and command min: " + str(args)
39         )
40     imei = args[0]
41     cmd = args[1]
42     args = args[2:]
43     handled = False
44     for pmod in pmods:
45         if pmod.proto_handled(cmd):
46             handled = True
47             break
48     if not handled:
49         raise NotImplementedError(f"No protocol can handle {cmd}")
50     cls = pmod.class_by_prefix(cmd)
51     if isinstance(cls, list):
52         raise ValueError("Prefix does not select a single class: " + str(cls))
53     kwargs = dict([arg.split("=") for arg in args])
54     for arg in args:
55         k, v = arg.split("=")
56         kwargs[k] = v
57     resp = Resp(imei=imei, when=time(), packet=cls.Out(**kwargs).packed)
58     log.debug("Response: %s", resp)
59     zpush.send(resp.packed)
60
61
62 if __name__.endswith("__main__"):
63     opts, args = getopt(argv[1:], "c:d")
64     main(common.init(log, opts=opts), opts, args)