]> www.average.org Git - loctrkd.git/blob - gps303/termconfig.py
the whole shebang is working now
[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 parse_message, proto_by_name
10 from .zmsg import Bcast, Resp
11
12 log = getLogger("gps303/termconfig")
13
14
15 def runserver(conf):
16     zctx = zmq.Context()
17     zsub = zctx.socket(zmq.SUB)
18     zsub.connect(conf.get("collector", "publishurl"))
19     for protoname in (
20         "SUPERVISION",
21         "STATUS",
22         "RESET",
23         "WHITELIST_TOTAL",
24         "PROHIBIT_LBS",
25         "SETUP",
26         "POSITION_UPLOAD_INTERVAL",
27     ):
28         topic = pack("B", proto_by_name(protoname))
29         zsub.setsockopt(zmq.SUBSCRIBE, topic)
30     zpush = zctx.socket(zmq.PUSH)
31     zpush.connect(conf.get("collector", "listenurl"))
32
33     try:
34         while True:
35             zmsg = Bcast(zsub.recv())
36             msg = parse_message(zmsg.packet)
37             log.debug(
38                 "IMEI %s from %s at %s: %s",
39                 zmsg.imei,
40                 zmsg.peeraddr,
41                 datetime.fromtimestamp(zmsg.when).astimezone(tz=timezone.utc),
42                 msg,
43             )
44             # TODO get data from the config
45             resp = Resp(imei=zmsg.imei, packet=msg.response())
46             log.debug("Response: %s", resp)
47             zpush.send(resp.packed)
48
49     except KeyboardInterrupt:
50         pass
51
52
53 if __name__.endswith("__main__"):
54     runserver(common.init(log))