]> www.average.org Git - loctrkd.git/blob - gps303/lookaside.py
Multiprotocol support in zmq messages and storage
[loctrkd.git] / gps303 / lookaside.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 .gps303proto import parse_message, proto_name, WIFI_POSITIONING
13 from .zmsg import Bcast, Resp, topic
14
15 log = getLogger("gps303/lookaside")
16
17
18 def runserver(conf: ConfigParser) -> None:
19     qry = import_module("." + conf.get("lookaside", "backend"), __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
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             try:
41                 lat, lon = qry.lookup(
42                     msg.mcc, msg.mnc, msg.gsm_cells, msg.wifi_aps
43                 )
44                 resp = Resp(
45                     imei=zmsg.imei,
46                     when=zmsg.when,  # not the current time, but the original!
47                     packet=msg.Out(latitude=lat, longitude=lon).packed,
48                 )
49                 log.debug("Response for lat=%s, lon=%s: %s", lat, lon, resp)
50                 zpush.send(resp.packed)
51             except Exception as e:
52                 log.warning("Lookup for %s resulted in %s", msg, e)
53
54     except KeyboardInterrupt:
55         zsub.close()
56         zpush.close()
57         zctx.destroy()  # type: ignore
58         qry.shut()
59
60
61 if __name__.endswith("__main__"):
62     runserver(common.init(log))