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