]> www.average.org Git - loctrkd.git/blob - loctrkd/opencellid.py
opencellid: use temp table rather than memory db
[loctrkd.git] / loctrkd / opencellid.py
1 """
2 Lookaside backend to query local opencellid database
3 """
4
5 from configparser import ConfigParser
6 from sqlite3 import connect
7 from typing import Any, Dict, List, Tuple
8
9 __all__ = "init", "lookup"
10
11 ldb = None
12
13
14 def init(conf: ConfigParser) -> None:
15     global ldb
16     ldb = connect(conf["opencellid"]["dbfn"])
17     ldb.execute("create temp table seen (locac int, cellid int, signal int)")
18
19
20 def shut() -> None:
21     if ldb is not None:
22         ldb.close()
23
24
25 def lookup(
26     mcc: int, mnc: int, gsm_cells: List[Tuple[int, int, int]], __: Any
27 ) -> Tuple[float, float, float]:
28     assert ldb is not None
29     lc = ldb.cursor()
30     lc.executemany(
31         "insert into seen (locac, cellid, signal) values (?, ?, ?)",
32         gsm_cells,
33     )
34     ldb.commit()
35     lc.execute(
36         """select c.lat, c.lon, s.signal
37                   from cells c, seen s
38                   where c.mcc = ?
39                   and c.net = ?
40                   and c.area = s.locac
41                   and c.cell = s.cellid""",
42         (mcc, mnc),
43     )
44     data = list(lc.fetchall())
45     # This should be faster than dropping and recreating the temp table
46     # https://www.sqlite.org/lang_delete.html#the_truncate_optimization
47     lc.execute("delete from seen")
48     lc.close()
49     if not data:
50         raise ValueError("No location data found in opencellid")
51     sumsig = sum([1 / sig for _, _, sig in data])
52     nsigs = [1 / sig / sumsig for _, _, sig in data]
53     avlat = sum([lat * nsig for (lat, _, _), nsig in zip(data, nsigs)])
54     avlon = sum([lon * nsig for (_, lon, _), nsig in zip(data, nsigs)])
55     return avlat, avlon, 99.9  # TODO estimate accuracy for real