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