opencellid 0.1.0

Rust client library for the OpenCellID API — sync and async clients with tracing, structured errors, and bounded I/O.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
//! Domain types: cells, bounding boxes, radio technologies, measurements.

use serde::{Deserialize, Deserializer, Serialize};

use crate::error::{Error, Result};

/// Mobile Country Code (100..=999).
///
/// A `pub type` alias rather than a newtype to keep call-site ergonomics simple.
/// Range checks are not enforced at the type level; out-of-range values are
/// rejected by the OpenCellID server.
pub type Mcc = u16;
/// Mobile Network Code (0..=999 for GSM/UMTS/LTE/NR/NB-IoT, 0..=32767 for CDMA).
pub type Mnc = u16;
/// Location / Tracking Area Code.
pub type Lac = u32;
/// Cell identifier. Width depends on technology (up to 36 bits for NR).
pub type CellId = u64;

/// Radio access technology of a cell.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
#[non_exhaustive]
pub enum Radio {
    /// 2G GSM.
    Gsm,
    /// 3G UMTS / WCDMA.
    Umts,
    /// 4G LTE.
    Lte,
    /// Narrowband IoT.
    #[serde(rename = "NBIOT")]
    NbIot,
    /// 5G New Radio.
    Nr,
    /// CDMA family.
    Cdma,
}

impl Radio {
    /// String value accepted by the OpenCellID API.
    pub fn as_api_str(self) -> &'static str {
        match self {
            Self::Gsm => "GSM",
            Self::Umts => "UMTS",
            Self::Lte => "LTE",
            Self::NbIot => "NBIOT",
            Self::Nr => "NR",
            Self::Cdma => "CDMA",
        }
    }
}

/// Identifies a single cell tower.
///
/// Bundling the four-tuple into a struct prevents accidental swaps of `mcc` and `mnc`
/// at call sites (a common mistake when both are bare integers).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct CellKey {
    /// Mobile country code.
    pub mcc: Mcc,
    /// Mobile network code.
    pub mnc: Mnc,
    /// Location / tracking area code.
    pub lac: Lac,
    /// Cell identifier.
    pub cell_id: CellId,
    /// Optional radio technology to disambiguate cells that share identifiers.
    pub radio: Option<Radio>,
}

impl CellKey {
    /// Construct a key without a radio hint.
    ///
    /// # Examples
    ///
    /// ```
    /// use opencellid::{CellKey, Radio};
    /// let key = CellKey::new(250, 1, 7800, 12345).with_radio(Radio::Lte);
    /// assert_eq!(key.mcc, 250);
    /// ```
    pub fn new(mcc: Mcc, mnc: Mnc, lac: Lac, cell_id: CellId) -> Self {
        Self { mcc, mnc, lac, cell_id, radio: None }
    }

    /// Add a radio technology hint.
    pub fn with_radio(mut self, radio: Radio) -> Self {
        self.radio = Some(radio);
        self
    }
}

/// Geographic bounding box. Latitudes in `[-90, 90]`, longitudes in `[-180, 180]`.
///
/// Construct via [`Bbox::new`], which enforces the invariant
/// `lat_min < lat_max && lon_min < lon_max`. Fields are accessor-only because the
/// invariant must hold for any value of this type.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Bbox {
    lat_min: f64,
    lon_min: f64,
    lat_max: f64,
    lon_max: f64,
}

impl Bbox {
    /// Construct and validate a bounding box.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidInput`] if any coordinate is out of range or if the
    /// minimum coordinates are not strictly less than the maxima.
    ///
    /// # Examples
    ///
    /// ```
    /// use opencellid::Bbox;
    /// let bbox = Bbox::new(55.0, 37.0, 56.0, 38.0)?;
    /// assert_eq!(bbox.lat_min(), 55.0);
    /// # Ok::<(), opencellid::Error>(())
    /// ```
    pub fn new(lat_min: f64, lon_min: f64, lat_max: f64, lon_max: f64) -> Result<Self> {
        if !lat_min.is_finite() || !lat_max.is_finite() || !lon_min.is_finite() || !lon_max.is_finite() {
            return Err(Error::InvalidInput("bbox coordinates must be finite".into()));
        }
        if !(-90.0..=90.0).contains(&lat_min) || !(-90.0..=90.0).contains(&lat_max) {
            return Err(Error::InvalidInput("latitude out of range".into()));
        }
        if !(-180.0..=180.0).contains(&lon_min) || !(-180.0..=180.0).contains(&lon_max) {
            return Err(Error::InvalidInput("longitude out of range".into()));
        }
        if lat_min >= lat_max || lon_min >= lon_max {
            return Err(Error::InvalidInput(
                "min coordinates must be strictly less than max".into(),
            ));
        }
        Ok(Self { lat_min, lon_min, lat_max, lon_max })
    }

    /// Minimum latitude (south).
    pub fn lat_min(&self) -> f64 { self.lat_min }
    /// Minimum longitude (west).
    pub fn lon_min(&self) -> f64 { self.lon_min }
    /// Maximum latitude (north).
    pub fn lat_max(&self) -> f64 { self.lat_max }
    /// Maximum longitude (east).
    pub fn lon_max(&self) -> f64 { self.lon_max }

    /// Format as `latmin,lonmin,latmax,lonmax` (the wire format expected by `BBOX=`).
    pub fn to_query_value(self) -> String {
        format!(
            "{},{},{},{}",
            format_coordinate(self.lat_min),
            format_coordinate(self.lon_min),
            format_coordinate(self.lat_max),
            format_coordinate(self.lon_max),
        )
    }
}

/// Format a finite floating-point coordinate without scientific notation so that the
/// OpenCellID server accepts it. Trims trailing zeros from a fixed-precision rendering.
pub(crate) fn format_coordinate(v: f64) -> String {
    let mut s = format!("{v:.7}");
    if s.contains('.') {
        // Strip trailing zeros, then a trailing dot if any.
        while s.ends_with('0') {
            s.pop();
        }
        if s.ends_with('.') {
            s.pop();
        }
    }
    s
}

/// Deserialise OpenCellID's integer-encoded boolean (`0`/`1`) into a Rust `bool`.
fn deserialize_bool_from_int<'de, D>(d: D) -> std::result::Result<bool, D::Error>
where
    D: Deserializer<'de>,
{
    use serde::de::Error as _;
    let v = serde_json::Value::deserialize(d)?;
    match v {
        serde_json::Value::Bool(b) => Ok(b),
        serde_json::Value::Number(n) => match n.as_u64() {
            Some(0) => Ok(false),
            Some(1) => Ok(true),
            _ => Err(D::Error::custom("expected 0 or 1 for boolean field")),
        },
        serde_json::Value::String(s) => match s.as_str() {
            "0" => Ok(false),
            "1" => Ok(true),
            other => Err(D::Error::custom(format!("expected 0/1, got {other:?}"))),
        },
        other => Err(D::Error::custom(format!("expected boolean, got {other}"))),
    }
}

/// A cell tower record returned by `cell/get` and `cell/getInArea`.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[non_exhaustive]
pub struct Cell {
    /// Latitude of the cell position.
    pub lat: f64,
    /// Longitude of the cell position.
    pub lon: f64,
    /// Mobile country code.
    pub mcc: Mcc,
    /// Mobile network code.
    pub mnc: Mnc,
    /// Location / tracking area code.
    pub lac: Lac,
    /// Cell identifier.
    #[serde(rename = "cellid", alias = "cellId")]
    pub cell_id: CellId,
    /// Estimated coverage range in meters.
    #[serde(default)]
    pub range: u32,
    /// Number of measurements aggregated for this position.
    #[serde(default)]
    pub samples: u32,
    /// `true` if the position is community-derived (may shift with new measurements);
    /// `false` if it is operator-precise.
    #[serde(default, deserialize_with = "deserialize_bool_from_int")]
    pub changeable: bool,
    /// Average signal strength in dBm (negative for received signal strength).
    #[serde(rename = "averageSignalStrength", default)]
    pub avg_signal: i32,
    /// Radio access technology, when available.
    #[serde(default)]
    pub radio: Option<Radio>,
}

/// Result of `cell/getInAreaSize` — number of cells matching a query.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[non_exhaustive]
pub struct CellCount {
    /// Number of cells in the requested area.
    pub count: u64,
}

/// A single cell measurement payload for `measure/add` / `measure/uploadJson`.
///
/// Construct via [`Measurement::new`] and chain optional fields through the
/// `with_*` setters.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[non_exhaustive]
pub struct Measurement {
    /// Latitude where the cell was observed.
    pub lat: f64,
    /// Longitude where the cell was observed.
    pub lon: f64,
    /// Mobile country code.
    pub mcc: Mcc,
    /// Mobile network code.
    pub mnc: Mnc,
    /// Location area code.
    pub lac: Lac,
    /// Cell identifier.
    #[serde(rename = "cellid")]
    pub cell_id: CellId,
    /// Radio technology — sent on the wire as `act`.
    #[serde(rename = "act", serialize_with = "serialize_radio_as_str")]
    pub radio: Radio,
    /// Signal strength in dBm.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signal: Option<i32>,
    /// Measurement timestamp (`yyyy-MM-dd HH:mm:ss` or epoch milliseconds as string).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub measured_at: Option<String>,
    /// GPS accuracy rating (0..=35000 meters).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rating: Option<u32>,
    /// Speed at measurement time (m/s).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub speed: Option<f32>,
    /// Heading at measurement time (degrees).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub direction: Option<f32>,
    /// Timing advance (GSM/LTE).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ta: Option<u32>,
    /// Primary scrambling code (UMTS).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub psc: Option<u16>,
    /// Tracking area code (LTE / NR).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tac: Option<u32>,
    /// Physical cell identifier (LTE).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pci: Option<u16>,
}

fn serialize_radio_as_str<S>(r: &Radio, s: S) -> std::result::Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    s.serialize_str(r.as_api_str())
}

impl Measurement {
    /// Build a measurement with the required fields.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidInput`] if `lat` or `lon` is non-finite.
    pub fn new(
        lat: f64,
        lon: f64,
        mcc: Mcc,
        mnc: Mnc,
        lac: Lac,
        cell_id: CellId,
        radio: Radio,
    ) -> Result<Self> {
        if !lat.is_finite() || !lon.is_finite() {
            return Err(Error::InvalidInput("lat/lon must be finite".into()));
        }
        Ok(Self {
            lat, lon, mcc, mnc, lac, cell_id, radio,
            signal: None, measured_at: None, rating: None, speed: None,
            direction: None, ta: None, psc: None, tac: None, pci: None,
        })
    }

    /// Attach a signal-strength measurement (dBm).
    pub fn with_signal(mut self, signal: i32) -> Self {
        self.signal = Some(signal);
        self
    }

    /// Attach a measurement timestamp.
    pub fn with_measured_at(mut self, ts: impl Into<String>) -> Self {
        self.measured_at = Some(ts.into());
        self
    }

    /// Attach a GPS rating in meters.
    pub fn with_rating(mut self, rating: u32) -> Self {
        self.rating = Some(rating);
        self
    }

    /// Attach speed (m/s). Non-finite values are rejected at submission time
    /// via [`Self::validate`] rather than here, keeping the builder chain
    /// infallible.
    pub fn with_speed(mut self, speed: f32) -> Self {
        self.speed = Some(speed);
        self
    }

    /// Attach heading in degrees. See [`Self::with_speed`] for finiteness
    /// handling.
    pub fn with_direction(mut self, direction: f32) -> Self {
        self.direction = Some(direction);
        self
    }

    /// Validate that all numeric fields are finite. Called by the client
    /// before serialising the request; downstream code may also call it
    /// explicitly.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidInput`] if any optional float field is
    /// non-finite. (Required `lat`/`lon` are checked in [`Self::new`].)
    pub fn validate(&self) -> Result<()> {
        for (name, v) in [("speed", self.speed), ("direction", self.direction)] {
            if let Some(v) = v {
                if !v.is_finite() {
                    return Err(Error::InvalidInput(format!("{name} must be finite")));
                }
            }
        }
        Ok(())
    }

    /// Attach a Timing Advance value (GSM/LTE).
    pub fn with_ta(mut self, ta: u32) -> Self {
        self.ta = Some(ta);
        self
    }

    /// Attach a Primary Scrambling Code (UMTS).
    pub fn with_psc(mut self, psc: u16) -> Self {
        self.psc = Some(psc);
        self
    }

    /// Attach a Tracking Area Code (LTE / NR).
    pub fn with_tac(mut self, tac: u32) -> Self {
        self.tac = Some(tac);
        self
    }

    /// Attach a Physical Cell ID (LTE).
    pub fn with_pci(mut self, pci: u16) -> Self {
        self.pci = Some(pci);
        self
    }
}

/// Wrapper for `measure/uploadJson` payloads.
///
/// The `measurements` field is intentionally public so that callers can build
/// the batch with normal `Vec` ergonomics (`push`, `extend`, etc.). The total
/// serialised size is bounded by the upload endpoint at ~2 MiB; very large
/// batches are rejected when [`crate::Client::upload_json`] is called.
#[derive(Debug, Clone, Default, Serialize)]
#[non_exhaustive]
pub struct MeasurementsPayload {
    /// Array of measurements.
    pub measurements: Vec<Measurement>,
}

impl MeasurementsPayload {
    /// Create an empty payload.
    pub fn new() -> Self {
        Self::default()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use proptest::prelude::*;

    #[test]
    fn bbox_validates_ranges() {
        assert!(Bbox::new(0.0, 0.0, 1.0, 1.0).is_ok());
        assert!(Bbox::new(-91.0, 0.0, 0.0, 1.0).is_err());
        assert!(Bbox::new(1.0, 0.0, 0.0, 1.0).is_err());
        assert!(Bbox::new(f64::NAN, 0.0, 1.0, 1.0).is_err());
    }

    #[test]
    fn bbox_query_format() {
        let b = Bbox::new(10.0, 20.0, 11.0, 21.0).unwrap();
        assert_eq!(b.to_query_value(), "10,20,11,21");
    }

    #[test]
    fn radio_serializes_uppercase() {
        assert_eq!(serde_json::to_string(&Radio::NbIot).unwrap(), "\"NBIOT\"");
        assert_eq!(serde_json::to_string(&Radio::Lte).unwrap(), "\"LTE\"");
    }

    #[test]
    fn cell_changeable_accepts_int_and_bool() {
        let body = r#"{"lat":1.0,"lon":2.0,"mcc":1,"mnc":1,"lac":1,"cellid":1,"changeable":1}"#;
        let c: Cell = serde_json::from_str(body).unwrap();
        assert!(c.changeable);

        let body = r#"{"lat":1.0,"lon":2.0,"mcc":1,"mnc":1,"lac":1,"cellid":1,"changeable":false}"#;
        let c: Cell = serde_json::from_str(body).unwrap();
        assert!(!c.changeable);
    }

    #[test]
    fn cell_id_alias() {
        for body in [
            r#"{"lat":1.0,"lon":2.0,"mcc":1,"mnc":1,"lac":1,"cellid":42}"#,
            r#"{"lat":1.0,"lon":2.0,"mcc":1,"mnc":1,"lac":1,"cellId":42}"#,
        ] {
            let c: Cell = serde_json::from_str(body).unwrap();
            assert_eq!(c.cell_id, 42);
        }
    }

    #[test]
    fn measurement_serializes_act_and_cellid() {
        let m = Measurement::new(1.0, 2.0, 250, 1, 7, 42, Radio::Lte).unwrap();
        let json = serde_json::to_value(&m).unwrap();
        assert_eq!(json["cellid"], 42);
        assert_eq!(json["act"], "LTE");
        assert!(json.get("signal").is_none(), "None fields must be skipped");
    }

    #[test]
    fn measurement_rejects_non_finite_position() {
        assert!(Measurement::new(f64::NAN, 0.0, 1, 1, 1, 1, Radio::Lte).is_err());
        assert!(Measurement::new(0.0, f64::INFINITY, 1, 1, 1, 1, Radio::Lte).is_err());
    }

    #[test]
    fn measurement_with_setters_compose() {
        let m = Measurement::new(1.0, 2.0, 250, 1, 7, 42, Radio::Lte)
            .unwrap()
            .with_signal(-95)
            .with_rating(50)
            .with_ta(3)
            .with_speed(12.5);
        assert_eq!(m.signal, Some(-95));
        assert_eq!(m.rating, Some(50));
        assert_eq!(m.ta, Some(3));
        assert_eq!(m.speed, Some(12.5));
    }

    #[test]
    fn measurement_validate_catches_non_finite_optional_fields() {
        let m = Measurement::new(1.0, 2.0, 250, 1, 7, 42, Radio::Lte)
            .unwrap()
            .with_speed(f32::NAN);
        assert!(m.validate().is_err());

        let m = Measurement::new(1.0, 2.0, 250, 1, 7, 42, Radio::Lte)
            .unwrap()
            .with_direction(f32::INFINITY);
        assert!(m.validate().is_err());

        let m = Measurement::new(1.0, 2.0, 250, 1, 7, 42, Radio::Lte)
            .unwrap()
            .with_speed(12.5)
            .with_direction(180.0);
        assert!(m.validate().is_ok());
    }

    #[test]
    fn format_coordinate_avoids_scientific() {
        assert_eq!(format_coordinate(1e-7), "0.0000001");
        assert_eq!(format_coordinate(1.0), "1");
        assert_eq!(format_coordinate(55.7558), "55.7558");
        assert_eq!(format_coordinate(-180.0), "-180");
    }

    proptest! {
        #[test]
        fn bbox_invariant_holds_when_constructor_succeeds(
            lat_min in -90.0f64..90.0,
            lat_max in -90.0f64..90.0,
            lon_min in -180.0f64..180.0,
            lon_max in -180.0f64..180.0,
        ) {
            if let Ok(b) = Bbox::new(lat_min, lon_min, lat_max, lon_max) {
                prop_assert!(b.lat_min() < b.lat_max());
                prop_assert!(b.lon_min() < b.lon_max());
                prop_assert!((-90.0..=90.0).contains(&b.lat_min()));
                prop_assert!((-90.0..=90.0).contains(&b.lat_max()));
                prop_assert!((-180.0..=180.0).contains(&b.lon_min()));
                prop_assert!((-180.0..=180.0).contains(&b.lon_max()));
            }
        }

        #[test]
        fn bbox_rejects_inverted(
            lat in -90.0f64..90.0,
            lon in -180.0f64..180.0,
        ) {
            prop_assert!(Bbox::new(lat, lon, lat, lon).is_err());
            prop_assert!(Bbox::new(lat + 1.0, lon, lat, lon + 1.0).is_err());
        }
    }
}