2 Google Maps location service lookaside backend
5 from configparser import ConfigParser
6 import googlemaps as gmaps
7 from typing import Any, Callable, Dict, List, Tuple
12 def init(conf: ConfigParser) -> None:
14 with open(conf["googlemaps"]["accesstoken"], encoding="ascii") as fl:
15 token = fl.read().rstrip()
16 gclient = gmaps.Client(key=token)
26 gsm_cells: List[Tuple[int, int, int]],
27 wifi_aps: List[Tuple[str, int]],
29 assert gclient is not None
31 "home_mobile_country_code": mcc,
32 "home_mobile_network_code": mnc,
38 "locationAreaCode": loc,
40 "signalStrength": sig,
42 for loc, cellid, sig in gsm_cells
44 "wifi_access_points": [
45 {"macAddress": mac, "signalStrength": sig} for mac, sig in wifi_aps
48 return gclient.geolocate(**kwargs)
54 gsm_cells: List[Tuple[int, int, int]],
55 wifi_aps: List[Tuple[str, int]],
56 ) -> Tuple[float, float]:
57 result = _lookup(mcc, mnc, gsm_cells, wifi_aps)
58 if "location" in result:
59 return result["location"]["lat"], result["location"]["lng"]
61 raise ValueError("google geolocation: " + str(result))
64 if __name__.endswith("__main__"):
65 from getopt import getopt
66 from json import loads
67 from logging import getLogger
71 def cell_list(s: str) -> List[Tuple[int, int, int]]:
72 return [(int(ac), int(ci), int(sg)) for [ac, ci, sg] in loads(s)]
74 def ap_list(s: str) -> List[Tuple[str, int]]:
75 return [(mac, int(sg)) for [mac, sg] in loads(s)]
77 log = getLogger("loctrkd/googlemaps")
78 opts, args = getopt(argv[1:], "c:d")
79 conf = common.init(log, opts=opts)
82 needed: Dict[str, Callable[[Any], Any]] = {
85 "gsm_cells": cell_list,
88 parms = {k: needed.pop(k)(v) for k, v in [arg.split("=") for arg in args]}
90 raise ValueError(f"still needed: {needed}")
91 print(_lookup(**parms))