]> www.average.org Git - loctrkd.git/blob - gps303/lookaside.py
7655f55e4bb095655b41d525aba89cf0a4b12c87
[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     qry = import_module("." + conf.get("lookaside", "backend"), __package__)
19     qry.init(conf)
20     zctx = zmq.Context()
21     zsub = zctx.socket(zmq.SUB)
22     zsub.connect(conf.get("collector", "publishurl"))
23     zsub.setsockopt(zmq.SUBSCRIBE, topic(WIFI_POSITIONING.PROTO))
24     zpush = zctx.socket(zmq.PUSH)
25     zpush.connect(conf.get("collector", "listenurl"))
26
27     try:
28         while True:
29             zmsg = Bcast(zsub.recv())
30             msg = parse_message(zmsg.packet)
31             log.debug(
32                 "IMEI %s from %s at %s: %s",
33                 zmsg.imei,
34                 zmsg.peeraddr,
35                 datetime.fromtimestamp(zmsg.when).astimezone(tz=timezone.utc),
36                 msg,
37             )
38             try:
39                 lat, lon = qry.lookup(msg.mcc, msg.mnc, msg.gsm_cells, msg.wifi_aps)
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             except Exception as e:
48                 log.warning("Lookup for %s resulted in %s", msg, e)
49
50     except KeyboardInterrupt:
51         pass
52
53
54 if __name__.endswith("__main__"):
55     runserver(common.init(log))