]> www.average.org Git - loctrkd.git/blob - gps303/lookaside.py
Partly revert "Broadcast location, gps and approximated"
[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, proto_by_name, WIFI_POSITIONING
11 from .opencellid import qry_cell
12 from .zmsg import Bcast, Resp
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     topic = pack("B", proto_by_name("WIFI_POSITIONING"))
22     zsub.setsockopt(zmq.SUBSCRIBE, topic)
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             if not isinstance(msg, WIFI_POSITIONING):
38                 log.error(
39                     "IMEI %s from %s at %s: %s",
40                     zmsg.imei,
41                     zmsg.peeraddr,
42                     datetime.fromtimestamp(zmsg.when).astimezone(
43                         tz=timezone.utc
44                     ),
45                     msg,
46                 )
47                 continue
48             lat, lon = qry_cell(
49                 conf["opencellid"]["dbfn"], msg.mcc, msg.gsm_cells
50             )
51             resp = Resp(imei=zmsg.imei, packet=msg.Out(lat=lat, lon=lon).packed)
52             log.debug("Response for lat=%s, lon=%s: %s", lat, lon, resp)
53             zpush.send(resp.packed)
54
55     except KeyboardInterrupt:
56         pass
57
58
59 if __name__.endswith("__main__"):
60     runserver(common.init(log))