]> www.average.org Git - loctrkd.git/blob - gps303/lookaside.py
Accept various arg formats for `Out` construction
[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 struct import pack
6 import zmq
7
8 from . import common
9 from .gps303proto import parse_message, proto_by_name, WIFI_POSITIONING
10 from .opencellid import qry_cell
11 from .zmsg import Bcast, Resp
12
13 log = getLogger("gps303/lookaside")
14
15
16 def runserver(conf):
17     zctx = zmq.Context()
18     zsub = zctx.socket(zmq.SUB)
19     zsub.connect(conf.get("collector", "publishurl"))
20     topic = pack("B", proto_by_name("WIFI_POSITIONING"))
21     zsub.setsockopt(zmq.SUBSCRIBE, topic)
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             if not isinstance(msg, WIFI_POSITIONING):
37                 log.error(
38                     "IMEI %s from %s at %s: %s",
39                     zmsg.imei,
40                     zmsg.peeraddr,
41                     datetime.fromtimestamp(zmsg.when).astimezone(
42                         tz=timezone.utc
43                     ),
44                     msg,
45                 )
46                 continue
47             lat, lon = qry_cell(
48                 conf["opencellid"]["dbfn"], msg.mcc, msg.gsm_cells
49             )
50             resp = Resp(imei=zmsg.imei, packet=msg.Out(lat=lat, lon=lon).packed)
51             log.debug("Response for lat=%s, lon=%s: %s", lat, lon, resp)
52             zpush.send(resp.packed)
53
54     except KeyboardInterrupt:
55         pass
56
57
58 if __name__.endswith("__main__"):
59     runserver(common.init(log))