]> www.average.org Git - loctrkd.git/blob - gps303/googlemaps.py
bb19a64578a071958bc0fe577a7a4fcec48d0236
[loctrkd.git] / gps303 / googlemaps.py
1 import googlemaps as gmaps
2 from sqlite3 import connect
3
4 gclient = None
5
6
7 def init(conf):
8     global gclient
9     with open(conf["googlemaps"]["accesstoken"], encoding="ascii") as fl:
10         token = fl.read().rstrip()
11     gclient = gmaps.Client(key=token)
12
13
14 def lookup(mcc, mnc, gsm_cells, wifi_aps):
15     kwargs = {
16         "home_mobile_country_code": mcc,
17         "home_mobile_network_code": mnc,
18         "radio_type": "gsm",
19         "carrier": "O2",
20         "consider_ip": False,
21         "cell_towers": [
22             {
23                 "locationAreaCode": loc,
24                 "cellId": cellid,
25                 "signalStrength": sig,
26             }
27             for loc, cellid, sig in gsm_cells
28         ],
29         "wifi_access_points": [
30             {"macAddress": mac, "signalStrength": sig} for mac, sig in wifi_aps
31         ],
32     }
33     result = gclient.geolocate(**kwargs)
34     if "location" in result:
35         return result["location"]["lat"], result["location"]["lng"]
36     else:
37         raise ValueError("google geolocation: " + str(result))
38
39
40 if __name__.endswith("__main__"):
41     from datetime import datetime, timezone
42     import sys
43     from .gps303proto import *
44
45     db = connect(sys.argv[1])
46     c = db.cursor()
47     c.execute(
48         """select tstamp, packet from events
49             where proto in (?, ?)""",
50         (WIFI_POSITIONING.PROTO, WIFI_OFFLINE_POSITIONING.PROTO),
51     )
52     init({"googlemaps": {"accesstoken": sys.argv[2]}})
53     count = 0
54     for timestamp, packet in c:
55         obj = parse_message(packet)
56         print(obj)
57         avlat, avlon = lookup(obj.mcc, obj.mnc, obj.gsm_cells, obj.wifi_aps)
58         print(
59             "{} {:+#010.8g},{:+#010.8g}".format(
60                 datetime.fromtimestamp(timestamp), avlat, avlon
61             )
62         )
63         count += 1
64         if count > 10:
65             break