]> www.average.org Git - loctrkd.git/blob - gps303/termconfig.py
fill in `when` in Resp packet
[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, topic
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         tosub = topic(proto_by_name(protoname))
26         zsub.setsockopt(zmq.SUBSCRIBE, tosub)
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.RESPOND is not Respond.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(
67                 imei=zmsg.imei, when=zmsg.when, packet=msg.Out(**kwargs).packed
68             )
69             log.debug("Response: %s", resp)
70             zpush.send(resp.packed)
71
72     except KeyboardInterrupt:
73         pass
74
75
76 if __name__.endswith("__main__"):
77     runserver(common.init(log))