]> www.average.org Git - loctrkd.git/blob - gps303/lookaside.py
6924757ec344a7992b8b3aed510f536ecef2c66a
[loctrkd.git] / gps303 / lookaside.py
1 """ Estimate coordinates from WIFI_POSITIONING and send back """
2
3 from datetime import datetime, timezone
4 from importlib import import_module
5 from logging import getLogger
6 from os import umask
7 from struct import pack
8 import zmq
9
10 from . import common
11 from .gps303proto import parse_message, WIFI_POSITIONING
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         qry = import_module(".opencellid", __package__)
20     else:
21         raise NotImplementedError(
22             "Lookaside only implements opencellid backend"
23         )
24     qry.init(conf)
25     zctx = zmq.Context()
26     zsub = zctx.socket(zmq.SUB)
27     zsub.connect(conf.get("collector", "publishurl"))
28     zsub.setsockopt(zmq.SUBSCRIBE, topic(WIFI_POSITIONING.PROTO))
29     zpush = zctx.socket(zmq.PUSH)
30     zpush.connect(conf.get("collector", "listenurl"))
31
32     try:
33         while True:
34             zmsg = Bcast(zsub.recv())
35             msg = parse_message(zmsg.packet)
36             log.debug(
37                 "IMEI %s from %s at %s: %s",
38                 zmsg.imei,
39                 zmsg.peeraddr,
40                 datetime.fromtimestamp(zmsg.when).astimezone(tz=timezone.utc),
41                 msg,
42             )
43             lat, lon = qry.lookup(msg.mcc, msg.gsm_cells, msg.wifi_aps)
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
52     except KeyboardInterrupt:
53         pass
54
55
56 if __name__.endswith("__main__"):
57     runserver(common.init(log))