]> www.average.org Git - loctrkd.git/blob - gps303/lookaside.py
set umask for group-writable unix domain sockets
[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, LocEvt, Resp
13
14 log = getLogger("gps303/lookaside")
15
16
17 def runserver(conf):
18     zctx = zmq.Context()
19     zpub = zctx.socket(zmq.PUB)
20     oldmask = umask(0o117)
21     zpub.bind(conf.get("lookaside", "publishurl"))
22     umask(oldmask)
23     zsub = zctx.socket(zmq.SUB)
24     zsub.connect(conf.get("collector", "publishurl"))
25     for protoname in (
26         "GPS_POSITIONING",
27         "GPS_OFFLINE_POSITIONING",
28         "WIFI_POSITIONING",
29     ):
30         topic = pack("B", proto_by_name(protoname))
31         zsub.setsockopt(zmq.SUBSCRIBE, topic)
32     zpush = zctx.socket(zmq.PUSH)
33     zpush.connect(conf.get("collector", "listenurl"))
34
35     try:
36         while True:
37             zmsg = Bcast(zsub.recv())
38             msg = parse_message(zmsg.packet)
39             log.debug(
40                 "IMEI %s from %s at %s: %s",
41                 zmsg.imei,
42                 zmsg.peeraddr,
43                 datetime.fromtimestamp(zmsg.when).astimezone(tz=timezone.utc),
44                 msg,
45             )
46             if isinstance(msg, WIFI_POSITIONING):
47                 is_gps = False
48                 lat, lon = qry_cell(
49                     conf["opencellid"]["dbfn"], msg.mcc, msg.gsm_cells
50                 )
51                 resp = Resp(
52                     imei=zmsg.imei, packet=msg.Out(lat=lat, lon=lon).packed
53                 )
54                 log.debug("Response for lat=%s, lon=%s: %s", lat, lon, resp)
55                 zpush.send(resp.packed)
56             else:
57                 is_gps = True
58                 lat = msg.latitude
59                 lon = msg.longitude
60             zpub.send(
61                 LocEvt(
62                     imei=zmsg.imei,
63                     devtime=msg.devtime,
64                     is_gps=is_gps,
65                     lat=lat,
66                     lon=lon,
67                 ).packed
68             )
69
70     except KeyboardInterrupt:
71         pass
72
73
74 if __name__.endswith("__main__"):
75     runserver(common.init(log))