]> www.average.org Git - loctrkd.git/blob - gps303/termconfig.py
typechecking: annotate termconfig.py
[loctrkd.git] / gps303 / termconfig.py
1 """ For when responding to the terminal is not trivial """
2
3 from configparser import ConfigParser
4 from datetime import datetime, timezone
5 from logging import getLogger
6 from struct import pack
7 import zmq
8
9 from . import common
10 from .gps303proto import *
11 from .zmsg import Bcast, Resp, topic
12
13 log = getLogger("gps303/termconfig")
14
15
16 def runserver(conf: ConfigParser) -> None:
17     termconfig = common.normconf(conf["termconfig"])
18     # Is this https://github.com/zeromq/pyzmq/issues/1627 still not fixed?!
19     zctx = zmq.Context()  # type: ignore
20     zsub = zctx.socket(zmq.SUB)  # type: ignore
21     zsub.connect(conf.get("collector", "publishurl"))
22     for proto in (
23         STATUS.PROTO,
24         SETUP.PROTO,
25         POSITION_UPLOAD_INTERVAL.PROTO,
26     ):
27         zsub.setsockopt(zmq.SUBSCRIBE, topic(proto))
28     zpush = zctx.socket(zmq.PUSH)  # type: ignore
29     zpush.connect(conf.get("collector", "listenurl"))
30
31     try:
32         while True:
33             zmsg = Bcast(zsub.recv())
34             msg = parse_message(zmsg.packet)
35             log.debug(
36                 "IMEI %s from %s at %s: %s",
37                 zmsg.imei,
38                 zmsg.peeraddr,
39                 datetime.fromtimestamp(zmsg.when).astimezone(tz=timezone.utc),
40                 msg,
41             )
42             if msg.RESPOND is not Respond.EXT:
43                 log.error(
44                     "%s does not expect externally provided response", msg
45                 )
46             kwargs = {}
47             if isinstance(msg, STATUS):
48                 kwargs = {
49                     "upload_interval": termconfig.get(
50                         "statusintervalminutes", 25
51                     )
52                 }
53             elif isinstance(msg, SETUP):
54                 for key in (
55                     "uploadintervalseconds",
56                     "binaryswitch",
57                     "alarms",
58                     "dndtimeswitch",
59                     "dndtimes",
60                     "gpstimeswitch",
61                     "gpstimestart",
62                     "gpstimestop",
63                     "phonenumbers",
64                 ):
65                     if key in termconfig:
66                         kwargs[key] = termconfig[key]
67             resp = Resp(
68                 imei=zmsg.imei, when=zmsg.when, packet=msg.Out(**kwargs).packed
69             )
70             log.debug("Response: %s", resp)
71             zpush.send(resp.packed)
72
73     except KeyboardInterrupt:
74         pass
75
76
77 if __name__.endswith("__main__"):
78     runserver(common.init(log))