]> www.average.org Git - loctrkd.git/blob - loctrkd/rectifier.py
1da57528d733a52df0be0955f18d7d29ce86d49b
[loctrkd.git] / loctrkd / rectifier.py
1 """ Estimate coordinates from WIFI_POSITIONING and send back """
2
3 from configparser import ConfigParser
4 from datetime import datetime, timezone
5 from importlib import import_module
6 from logging import getLogger
7 from os import umask
8 from struct import pack
9 from typing import cast, List, Tuple
10 import zmq
11
12 from . import common
13 from .common import CoordReport, HintReport, StatusReport, Report
14 from .zmsg import Bcast, Rept, Resp, topic
15
16 log = getLogger("loctrkd/rectifier")
17
18
19 class QryModule:
20     @staticmethod
21     def init(conf: ConfigParser) -> None:
22         ...
23
24     @staticmethod
25     def shut() -> None:
26         ...
27
28     @staticmethod
29     def lookup(
30         mcc: int,
31         mnc: int,
32         gsm_cells: List[Tuple[int, int, int]],
33         wifi_aps: List[Tuple[str, int]],
34     ) -> Tuple[float, float]:
35         ...
36
37
38 def runserver(conf: ConfigParser) -> None:
39     qry = cast(
40         QryModule,
41         import_module("." + conf.get("rectifier", "lookaside"), __package__),
42     )
43     qry.init(conf)
44     proto_needanswer = dict(common.exposed_protos())
45     # Is this https://github.com/zeromq/pyzmq/issues/1627 still not fixed?!
46     zctx = zmq.Context()  # type: ignore
47     zsub = zctx.socket(zmq.SUB)  # type: ignore
48     zsub.connect(conf.get("collector", "publishurl"))
49     for proto in proto_needanswer.keys():
50         zsub.setsockopt(zmq.SUBSCRIBE, topic(proto))
51     zpush = zctx.socket(zmq.PUSH)  # type: ignore
52     zpush.connect(conf.get("collector", "listenurl"))
53     zpub = zctx.socket(zmq.PUB)  # type: ignore
54     zpub.bind(conf.get("rectifier", "publishurl"))
55
56     try:
57         while True:
58             zmsg = Bcast(zsub.recv())
59             msg = common.parse_message(
60                 zmsg.proto, zmsg.packet, is_incoming=zmsg.is_incoming
61             )
62             log.debug(
63                 "IMEI %s from %s at %s: %s",
64                 zmsg.imei,
65                 zmsg.peeraddr,
66                 datetime.fromtimestamp(zmsg.when).astimezone(tz=timezone.utc),
67                 msg,
68             )
69             rect: Report = msg.rectified()
70             log.debug("rectified: %s", rect)
71             if isinstance(rect, (CoordReport, StatusReport)):
72                 zpub.send(Rept(imei=zmsg.imei, payload=rect.json).packed)
73             elif isinstance(rect, HintReport):
74                 try:
75                     lat, lon = qry.lookup(
76                         rect.mcc,
77                         rect.mnc,
78                         rect.gsm_cells,
79                         list((mac, strng) for _, mac, strng in rect.wifi_aps),
80                     )
81                     log.debug(
82                         "Approximated lat=%s, lon=%s for %s", lat, lon, rect
83                     )
84                     if proto_needanswer.get(zmsg.proto, False):
85                         resp = Resp(
86                             imei=zmsg.imei,
87                             when=zmsg.when,  # not the current time, but the original!
88                             packet=msg.Out(latitude=lat, longitude=lon).packed,
89                         )
90                         log.debug("Sending reponse %s", resp)
91                         zpush.send(resp.packed)
92                     rept = CoordReport(
93                         devtime=rect.devtime,
94                         battery_percentage=rect.battery_percentage,
95                         accuracy=-1,
96                         altitude=-1,
97                         speed=-1,
98                         direction=-1,
99                         latitude=lat,
100                         longitude=lon,
101                     )
102                     log.debug("Sending report %s", rept)
103                     zpub.send(
104                         Rept(
105                             imei=zmsg.imei,
106                             payload=rept.json,
107                         ).packed
108                     )
109                 except Exception as e:
110                     log.warning(
111                         "Lookup for %s rectified as %s resulted in %s",
112                         msg,
113                         rect,
114                         e,
115                     )
116
117     except KeyboardInterrupt:
118         zsub.close()
119         zpub.close()
120         zpush.close()
121         zctx.destroy()  # type: ignore
122         qry.shut()
123
124
125 if __name__.endswith("__main__"):
126     runserver(common.init(log))