]> www.average.org Git - loctrkd.git/blob - gps303/lookaside.py
typing: annotate lookaside.py
[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, 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(WIFI_POSITIONING.PROTO))
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(msg.mcc, msg.mnc, msg.gsm_cells, msg.wifi_aps)
42                 resp = Resp(
43                     imei=zmsg.imei,
44                     when=zmsg.when,  # not the current time, but the original!
45                     packet=msg.Out(latitude=lat, longitude=lon).packed,
46                 )
47                 log.debug("Response for lat=%s, lon=%s: %s", lat, lon, resp)
48                 zpush.send(resp.packed)
49             except Exception as e:
50                 log.warning("Lookup for %s resulted in %s", msg, e)
51
52     except KeyboardInterrupt:
53         pass
54
55
56 if __name__.endswith("__main__"):
57     runserver(common.init(log))