]> www.average.org Git - loctrkd.git/blob - loctrkd/rectifier.py
rectifier: add PUB zmq socket
[loctrkd.git] / loctrkd / rectifier.py
1 """ Estimate coordinates from WIFI_POSITIONING and send back """
2
3 from configparser import ConfigParser
4 from datetime import datetime, timezone
5 from importlib import import_module
6 from logging import getLogger
7 from os import umask
8 from struct import pack
9 import zmq
10
11 from . import common
12 from .zx303proto import parse_message, proto_name, WIFI_POSITIONING
13 from .zmsg import Bcast, Resp, topic
14
15 log = getLogger("loctrkd/rectifier")
16
17
18 def runserver(conf: ConfigParser) -> None:
19     qry = import_module("." + conf.get("rectifier", "lookaside"), __package__)
20     qry.init(conf)
21     # Is this https://github.com/zeromq/pyzmq/issues/1627 still not fixed?!
22     zctx = zmq.Context()  # type: ignore
23     zsub = zctx.socket(zmq.SUB)  # type: ignore
24     zsub.connect(conf.get("collector", "publishurl"))
25     zsub.setsockopt(zmq.SUBSCRIBE, topic(proto_name(WIFI_POSITIONING)))
26     zpush = zctx.socket(zmq.PUSH)  # type: ignore
27     zpush.connect(conf.get("collector", "listenurl"))
28     zpub = zctx.socket(zmq.PUB)  # type: ignore
29     zpub.connect(conf.get("rectifier", "publishurl"))
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             try:
43                 lat, lon = qry.lookup(
44                     msg.mcc, msg.mnc, msg.gsm_cells, msg.wifi_aps
45                 )
46                 resp = Resp(
47                     imei=zmsg.imei,
48                     when=zmsg.when,  # not the current time, but the original!
49                     packet=msg.Out(latitude=lat, longitude=lon).packed,
50                 )
51                 log.debug("Response for lat=%s, lon=%s: %s", lat, lon, resp)
52                 zpush.send(resp.packed)
53             except Exception as e:
54                 log.warning("Lookup for %s resulted in %s", msg, e)
55
56     except KeyboardInterrupt:
57         zsub.close()
58         zpub.close()
59         zpush.close()
60         zctx.destroy()  # type: ignore
61         qry.shut()
62
63
64 if __name__.endswith("__main__"):
65     runserver(common.init(log))