]> www.average.org Git - loctrkd.git/blob - loctrkd/__main__.py
Update changelog for 2.00 release
[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 def main(
21     conf: ConfigParser, opts: List[Tuple[str, str]], args: List[str]
22 ) -> None:
23     # Is this https://github.com/zeromq/pyzmq/issues/1627 still not fixed?!
24     zctx = zmq.Context()  # type: ignore
25     zpush = zctx.socket(zmq.PUSH)  # type: ignore
26     zpush.connect(conf.get("collector", "listenurl"))
27
28     if len(args) < 2:
29         raise ValueError(
30             "Too few args, need IMEI and command min: " + str(args)
31         )
32     imei = args[0]
33     cmd = args[1]
34     args = args[2:]
35     pmod = common.pmod_for_proto(cmd)
36     if pmod is None:
37         raise NotImplementedError(f"No protocol can handle {cmd}")
38     cls = pmod.class_by_prefix(cmd)
39     if isinstance(cls, list):
40         raise ValueError("Prefix does not select a single class: " + str(cls))
41     kwargs = dict([arg.split("=") for arg in args])
42     for arg in args:
43         k, v = arg.split("=")
44         kwargs[k] = v
45     resp = Resp(imei=imei, when=time(), packet=cls.Out(**kwargs).packed)
46     log.debug("Response: %s", resp)
47     zpush.send(resp.packed)
48
49
50 if __name__.endswith("__main__"):
51     opts, args = getopt(argv[1:], "c:d")
52     main(common.init(log, opts=opts), opts, args)