]> www.average.org Git - loctrkd.git/blob - gps303/termconfig.py
fix zmq subscription topics
[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 proto in (
21         STATUS.PROTO,
22         SETUP.PROTO,
23         POSITION_UPLOAD_INTERVAL.PROTO,
24     ):
25         zsub.setsockopt(zmq.SUBSCRIBE, topic(proto))
26     zpush = zctx.socket(zmq.PUSH)
27     zpush.connect(conf.get("collector", "listenurl"))
28
29     try:
30         while True:
31             zmsg = Bcast(zsub.recv())
32             msg = parse_message(zmsg.packet)
33             log.debug(
34                 "IMEI %s from %s at %s: %s",
35                 zmsg.imei,
36                 zmsg.peeraddr,
37                 datetime.fromtimestamp(zmsg.when).astimezone(tz=timezone.utc),
38                 msg,
39             )
40             if msg.RESPOND is not Respond.EXT:
41                 log.error(
42                     "%s does not expect externally provided response", msg
43                 )
44             kwargs = {}
45             if isinstance(msg, STATUS):
46                 kwargs = {
47                     "upload_interval": termconfig.get(
48                         "statusintervalminutes", 25
49                     )
50                 }
51             elif isinstance(msg, SETUP):
52                 for key in (
53                     "uploadintervalseconds",
54                     "binaryswitch",
55                     "alarms",
56                     "dndtimeswitch",
57                     "dndtimes",
58                     "gpstimeswitch",
59                     "gpstimestart",
60                     "gpstimestop",
61                     "phonenumbers",
62                 ):
63                     if key in termconfig:
64                         kwargs[key] = termconfig[key]
65             resp = Resp(
66                 imei=zmsg.imei, when=zmsg.when, packet=msg.Out(**kwargs).packed
67             )
68             log.debug("Response: %s", resp)
69             zpush.send(resp.packed)
70
71     except KeyboardInterrupt:
72         pass
73
74
75 if __name__.endswith("__main__"):
76     runserver(common.init(log))