]> www.average.org Git - loctrkd.git/blob - gps303/lookaside.py
136ade9aeccf51e836062e8bfb0e83130c9544a4
[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     zctx = zmq.Context()
19     zsub = zctx.socket(zmq.SUB)
20     zsub.connect(conf.get("collector", "publishurl"))
21     zsub.setsockopt(zmq.SUBSCRIBE, topic(WIFI_POSITIONING.PROTO))
22     zpush = zctx.socket(zmq.PUSH)
23     zpush.connect(conf.get("collector", "listenurl"))
24
25     try:
26         while True:
27             zmsg = Bcast(zsub.recv())
28             msg = parse_message(zmsg.packet)
29             log.debug(
30                 "IMEI %s from %s at %s: %s",
31                 zmsg.imei,
32                 zmsg.peeraddr,
33                 datetime.fromtimestamp(zmsg.when).astimezone(tz=timezone.utc),
34                 msg,
35             )
36             lat, lon = qry_cell(
37                 conf["opencellid"]["dbfn"], msg.mcc, msg.gsm_cells
38             )
39             resp = Resp(
40                 imei=zmsg.imei,
41                 when=zmsg.when,  # not the current time, but the original!
42                 packet=msg.Out(latitude=lat, longitude=lon).packed,
43             )
44             log.debug("Response for lat=%s, lon=%s: %s", lat, lon, resp)
45             zpush.send(resp.packed)
46
47     except KeyboardInterrupt:
48         pass
49
50
51 if __name__.endswith("__main__"):
52     runserver(common.init(log))