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