Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
main ▾

Modern-Apps.git / scripts / networklocation / wps_harvest / src / bin / wps_cellcrawl.rs

wps_cellcrawl.rs204 lines · 7.5 KiBRaw
1//! `wps_cellcrawl --out SHARD --seed MCC,MNC,TAC,CID [--seed ...] [options]`
2//!
3//! Snowball crawl of LTE cells through gs-loc. A cell request is answered with the asked-for
4//! tower plus its surrounding LTE cells (around 120 when the request does not cap them), each
5//! with its own position, so a few seeds from a phone's cell list cover a whole neighbourhood.
6//! Cells nearest the first resolved seed are queried first, so a bounded run fills in the area
7//! around the phone rather than wandering off along a motorway.
8
9use std::cmp::Reverse;
10use std::collections::{BinaryHeap, HashSet};
11use std::fs::OpenOptions;
12use std::io::BufWriter;
13use std::path::PathBuf;
14use std::process::ExitCode;
15use std::time::Duration;
16
17use wps_harvest::gsloc::{CellFix, Client};
18use wps_harvest::keys::{self, CellId, RadioType};
19use wps_harvest::record::{Record, RecordWriter, Source, ACC_UNKNOWN, ALT_UNKNOWN};
20
21const USAGE: &str = "\
22Usage: wps_cellcrawl --out SHARD --seed MCC,MNC,TAC,CID [--seed ...] [options]
23
24 --out record shard to append to
25 --seed an LTE cell to start from, e.g. from the phone's cell list (repeatable)
26 --max-queries N stop after N requests (default 50)
27 --radius-km R only expand into cells within R km of the first resolved seed (default 15)
28 --interval MS minimum milliseconds between requests (default 1000)";
29
30/// Consecutive failed requests after which the crawl gives up rather than hammering a
31/// service that is refusing it.
32const MAX_CONSECUTIVE_ERRORS: u32 = 5;
33
34/// One cell identity on the frontier: `(mcc, mnc, tac, cid)`.
35type CellTuple = (u32, u32, u32, u32);
36/// Cells waiting to be queried, nearest-first by distance from the centre.
37type Frontier = BinaryHeap<(Reverse<u64>, CellTuple)>;
38
39struct Args {
40 out: PathBuf,
41 seeds: Vec<(u32, u32, u32, u32)>,
42 max_queries: u32,
43 radius_m: f64,
44 interval: Duration,
45}
46
47fn parse_seed(s: &str) -> Result<(u32, u32, u32, u32), String> {
48 let p: Vec<u32> = s
49 .split(',')
50 .map(|v| v.trim().parse::<u32>().map_err(|e| format!("bad seed '{s}': {e}")))
51 .collect::<Result<_, _>>()?;
52 match p[..] {
53 [mcc, mnc, tac, cid] => Ok((mcc, mnc, tac, cid)),
54 _ => Err(format!("seed '{s}' must be MCC,MNC,TAC,CID")),
55 }
56}
57
58fn parse_args(argv: &[String]) -> Result<Args, String> {
59 let mut out = None;
60 let mut seeds = Vec::new();
61 let mut max_queries = 50u32;
62 let mut radius_km = 15.0f64;
63 let mut interval_ms = 1000u64;
64 let mut i = 0;
65 while i < argv.len() {
66 let a = argv[i].as_str();
67 let value = || argv.get(i + 1).cloned().ok_or_else(|| format!("{a} needs a value"));
68 match a {
69 "--out" => out = Some(PathBuf::from(value()?)),
70 "--seed" => seeds.push(parse_seed(&value()?)?),
71 "--max-queries" => max_queries = value()?.parse().map_err(|e| format!("{e}"))?,
72 "--radius-km" => radius_km = value()?.parse().map_err(|e| format!("{e}"))?,
73 "--interval" => interval_ms = value()?.parse().map_err(|e| format!("{e}"))?,
74 "-h" | "--help" => return Err("help".to_string()),
75 other => return Err(format!("unknown argument: {other}")),
76 }
77 i += 2;
78 }
79 if seeds.is_empty() {
80 return Err("at least one --seed is required".to_string());
81 }
82 Ok(Args {
83 out: out.ok_or("--out is required")?,
84 seeds,
85 max_queries,
86 radius_m: radius_km * 1000.0,
87 interval: Duration::from_millis(interval_ms),
88 })
89}
90
91/// Great-circle distance in metres between two e8 coordinates.
92fn distance_m(a: (i64, i64), b: (i64, i64)) -> f64 {
93 let (lat1, lon1) = ((a.0 as f64 / 1e8).to_radians(), (a.1 as f64 / 1e8).to_radians());
94 let (lat2, lon2) = ((b.0 as f64 / 1e8).to_radians(), (b.1 as f64 / 1e8).to_radians());
95 let h = ((lat2 - lat1) / 2.0).sin().powi(2)
96 + lat1.cos() * lat2.cos() * ((lon2 - lon1) / 2.0).sin().powi(2);
97 2.0 * 6_371_000.0 * h.sqrt().asin()
98}
99
100fn to_record(f: &CellFix) -> Option<Record> {
101 let id = CellId {
102 mcc: u16::try_from(f.mcc).ok()?,
103 mnc: u16::try_from(f.mnc).ok()?,
104 radio: RadioType::Lte,
105 cell_id: u64::try_from(f.cell_id).ok()?,
106 area: u32::try_from(f.area).ok()?,
107 };
108 if !keys::cell_fits(&id) {
109 return None;
110 }
111 let accuracy_m = if f.accuracy_m < 0 {
112 ACC_UNKNOWN
113 } else {
114 f.accuracy_m.min(i32::from(ACC_UNKNOWN - 1)) as u16
115 };
116 let r = Record {
117 key: keys::cell_key(&id),
118 lat_e8: f.lat_e8,
119 lon_e8: f.lon_e8,
120 accuracy_m,
121 altitude_m: ALT_UNKNOWN,
122 source: Source::Gsloc,
123 };
124 r.in_range().then_some(r)
125}
126
127fn run(args: &Args) -> std::io::Result<()> {
128 let file = OpenOptions::new().create(true).append(true).open(&args.out)?;
129 let mut writer = RecordWriter::new(BufWriter::new(file));
130 let mut client = Client::new(args.interval);
131
132 // Seeds go first regardless of distance, in the order given; everything learned later is
133 // ordered by distance from the first seed that resolved.
134 let mut seeds: Vec<(u32, u32, u32, u32)> = args.seeds.clone();
135 seeds.reverse();
136 let mut frontier: Frontier = BinaryHeap::new();
137 let mut queried: HashSet<CellTuple> = HashSet::new();
138 let mut written: HashSet<u128> = HashSet::new();
139 let mut center: Option<(i64, i64)> = None;
140 let (mut queries, mut errors) = (0u32, 0u32);
141
142 while queries < args.max_queries {
143 let Some(next) = seeds.pop().or_else(|| frontier.pop().map(|(_, c)| c)) else { break };
144 if !queried.insert(next) {
145 continue;
146 }
147 let (mcc, mnc, tac, cid) = next;
148 queries += 1;
149 let fixes = match client.query_cell(mcc, mnc, cid, tac) {
150 Ok(f) => {
151 errors = 0;
152 f
153 }
154 Err(e) => {
155 errors += 1;
156 eprintln!("query {queries}: {mcc}/{mnc} tac {tac} cid {cid}: {e}");
157 if errors >= MAX_CONSECUTIVE_ERRORS {
158 eprintln!("giving up after {errors} consecutive errors");
159 break;
160 }
161 continue;
162 }
163 };
164
165 let asked = fixes.iter().find(|f| f.cell_id == i64::from(cid) && f.area == tac as i32);
166 if center.is_none() {
167 center = asked.map(|f| (f.lat_e8, f.lon_e8));
168 }
169 let mut fresh = 0;
170 for f in &fixes {
171 let Some(r) = to_record(f) else { continue };
172 if written.insert(r.key) {
173 writer.push(&r)?;
174 fresh += 1;
175 }
176 if let (Some(c), Ok(m), Ok(n), Ok(t), Ok(i)) = (
177 center,
178 u32::try_from(f.mcc),
179 u32::try_from(f.mnc),
180 u32::try_from(f.area),
181 u32::try_from(f.cell_id),
182 ) {
183 let d = distance_m(c, (f.lat_e8, f.lon_e8));
184 if d <= args.radius_m && !queried.contains(&(m, n, t, i)) {
185 frontier.push((Reverse(d as u64), (m, n, t, i)));
186 }
187 }
188 }
189 println!(
190 "query {queries}: {mcc}/{mnc} tac {tac} cid {cid} -> {} cells ({fresh} new){}; {} total, {} queued",
191 fixes.len(),
192 if asked.is_some() { "" } else { ", asked-for cell unknown" },
193 written.len(),
194 frontier.len(),
195 );
196 }
197 let n = writer.finish()?;
198 println!("Done: {queries} request(s), {n} cell record(s) appended to {}", args.out.display());
199 Ok(())
200}
201
202fn main() -> ExitCode {
203 wps_harvest::run_main(parse_args, USAGE, run)
204}