]> www.average.org Git - loctrkd.git/blob - gps303/lookaside.py
cleanup and document config file a bit
[loctrkd.git] / gps303 / lookaside.py
1 """ Estimate coordinates from WIFI_POSITIONING and send back """
2
3 from datetime import datetime, timezone
4 from logging import getLogger
5 from os import umask
6 from struct import pack
7 import zmq
8
9 from . import common
10 from .gps303proto import parse_message, WIFI_POSITIONING
11 from .opencellid import qry_cell
12 from .zmsg import Bcast, Resp, topic
13
14 log = getLogger("gps303/lookaside")
15
16
17 def runserver(conf):
18     if conf.get("lookaside", "backend") != "opencellid":
19         raise NotImplementedError(
20             "Lookaside only implements opencellid backend"
21         )
22     zctx = zmq.Context()
23     zsub = zctx.socket(zmq.SUB)
24     zsub.connect(conf.get("collector", "publishurl"))
25     zsub.setsockopt(zmq.SUBSCRIBE, topic(WIFI_POSITIONING.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             lat, lon = qry_cell(
41                 conf["opencellid"]["dbfn"], msg.mcc, msg.gsm_cells
42             )
43             resp = Resp(
44                 imei=zmsg.imei,
45                 when=zmsg.when,  # not the current time, but the original!
46                 packet=msg.Out(latitude=lat, longitude=lon).packed,
47             )
48             log.debug("Response for lat=%s, lon=%s: %s", lat, lon, resp)
49             zpush.send(resp.packed)
50
51     except KeyboardInterrupt:
52         pass
53
54
55 if __name__.endswith("__main__"):
56     runserver(common.init(log))