Skip to main content

rustflexstack/facilities/
gpsd_location_service.rs

1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2024 Fundació Privada Internet i Innovació Digital a Catalunya (i2CAT)
3
4//! GPSD-backed Location Service.
5//!
6//! [`GpsdLocationService`] connects to a running
7//! [gpsd](https://gpsd.io/) daemon over its JSON TCP protocol and publishes
8//! real GPS fixes to every subscriber, exactly like
9//! [`super::location_service::LocationService`] but sourcing data from a
10//! real GNSS receiver instead of software-injected fixes.
11//!
12//! # Usage
13//!
14//! ```no_run
15//! use rustflexstack::facilities::gpsd_location_service::GpsdLocationService;
16//!
17//! let mut svc = GpsdLocationService::new("127.0.0.1:2947");
18//! let rx = svc.subscribe();
19//!
20//! svc.start();  // spawns background thread
21//!
22//! while let Ok(fix) = rx.recv() {
23//!     println!("lat={:.6} lon={:.6} speed={:.1} m/s",
24//!              fix.latitude, fix.longitude, fix.speed_mps);
25//! }
26//! ```
27//!
28//! # gpsd JSON protocol (subset used)
29//!
30//! After connecting we send `?WATCH={"enable":true,"json":true}\n` and then
31//! read newline-delimited JSON objects.  We only care about objects whose
32//! `"class"` field is `"TPV"` (Time-Position-Velocity).
33
34use super::location_service::{GpsFix, LocationService};
35use std::io::{BufRead, BufReader, Write};
36use std::net::{TcpStream, ToSocketAddrs};
37use std::sync::mpsc::Receiver;
38use std::thread;
39use std::time::Duration;
40
41/// A location service that reads real positions from a gpsd daemon.
42///
43/// Internally it wraps a [`LocationService`] and adds a background thread
44/// that connects to gpsd, parses TPV sentences, and calls
45/// [`LocationService::publish`] for each valid fix.
46pub struct GpsdLocationService {
47    inner: LocationService,
48    addr: String,
49}
50
51impl GpsdLocationService {
52    /// Create a new `GpsdLocationService` targeting the given gpsd address.
53    ///
54    /// The address is typically `"127.0.0.1:2947"` or `"localhost:2947"`.
55    /// No connection is made until [`start`](Self::start) is called.
56    pub fn new(addr: &str) -> Self {
57        GpsdLocationService {
58            inner: LocationService::new(),
59            addr: addr.to_string(),
60        }
61    }
62
63    /// Register a new subscriber (delegates to [`LocationService::subscribe`]).
64    pub fn subscribe(&mut self) -> Receiver<GpsFix> {
65        self.inner.subscribe()
66    }
67
68    /// Return the number of active subscribers.
69    pub fn subscriber_count(&self) -> usize {
70        self.inner.subscriber_count()
71    }
72
73    /// Start the gpsd reader thread.
74    ///
75    /// This **consumes** `self` because the inner `LocationService` (which
76    /// owns the `Sender` halves) must be moved into the background thread.
77    /// Subscribers obtained before this call remain valid.
78    ///
79    /// The thread reconnects automatically if the connection to gpsd drops.
80    pub fn start(self) {
81        let addr = self.addr;
82        let mut inner = self.inner;
83
84        thread::spawn(move || {
85            loop {
86                if let Ok(reader) = connect_and_watch(&addr) {
87                    for line in reader.lines() {
88                        match line {
89                            Ok(line) => {
90                                if let Some(fix) = parse_tpv(&line) {
91                                    inner.publish(fix);
92                                }
93                            }
94                            Err(_) => {
95                                break;
96                            }
97                        }
98                    }
99                }
100
101                // Back-off before reconnecting
102                thread::sleep(Duration::from_secs(2));
103            }
104        });
105    }
106}
107
108/// Open a TCP connection to gpsd and send the WATCH command.
109///
110/// Returns a `BufReader` over the stream ready for line-by-line reading.
111fn connect_and_watch(addr: &str) -> Result<BufReader<TcpStream>, std::io::Error> {
112    let sock_addr = addr
113        .to_socket_addrs()?
114        .next()
115        .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidInput, "bad address"))?;
116
117    let mut stream = TcpStream::connect_timeout(&sock_addr, Duration::from_secs(5))?;
118
119    // gpsd expects the WATCH command to start streaming
120    stream.write_all(b"?WATCH={\"enable\":true,\"json\":true}\n")?;
121    stream.flush()?;
122
123    // Set a read timeout so we can detect a dead connection
124    stream.set_read_timeout(Some(Duration::from_secs(10)))?;
125
126    Ok(BufReader::new(stream))
127}
128
129/// Try to parse a gpsd JSON line as a TPV object.
130///
131/// Returns `Some(GpsFix)` if the line is a valid TPV with at least lat/lon,
132/// otherwise `None`.
133///
134/// We do minimal JSON parsing with string matching to avoid pulling in
135/// serde_json as a dependency.  The TPV object has a well-known, stable
136/// format:
137///
138/// ```json
139/// {"class":"TPV","mode":3,"lat":41.552,"lon":2.134,"alt":120.0,
140///  "speed":0.0,"track":0.0,"epx":15.0,"epy":15.0,...}
141/// ```
142fn parse_tpv(line: &str) -> Option<GpsFix> {
143    // Quick reject: must be a TPV class
144    if !line.contains("\"class\":\"TPV\"") {
145        return None;
146    }
147
148    // mode >= 2 means at least a 2D fix
149    let mode = extract_f64(line, "mode").unwrap_or(0.0) as u8;
150    if mode < 2 {
151        return None;
152    }
153
154    let lat = extract_f64(line, "lat")?;
155    let lon = extract_f64(line, "lon")?;
156    let alt = extract_f64(line, "alt").unwrap_or(0.0);
157    // gpsd uses "speed" in m/s and "track" in degrees
158    let speed = extract_f64(line, "speed").unwrap_or(0.0);
159    let track = extract_f64(line, "track").unwrap_or(0.0);
160
161    // PAI: consider the fix accurate if EPX and EPY are both ≤ 4 m
162    let epx = extract_f64(line, "epx").unwrap_or(f64::MAX);
163    let epy = extract_f64(line, "epy").unwrap_or(f64::MAX);
164    let pai = epx <= 4.0 && epy <= 4.0;
165
166    Some(GpsFix {
167        latitude: lat,
168        longitude: lon,
169        altitude_m: alt,
170        speed_mps: speed,
171        heading_deg: track,
172        pai,
173        fix_time_ms: extract_str(line, "time").and_then(parse_iso8601_ms),
174    })
175}
176
177/// Extract a string value for `"key":"value"` from a JSON line.
178fn extract_str<'a>(json: &'a str, key: &str) -> Option<&'a str> {
179    let pattern = format!("\"{}\":\"", key);
180    let start = json.find(&pattern)? + pattern.len();
181    let rest = &json[start..];
182    Some(&rest[..rest.find('"')?])
183}
184
185/// Unix time in ms of a gpsd ISO 8601 UTC time, e.g.
186/// `2026-11-17T10:00:00.250Z` (fraction optional).
187fn parse_iso8601_ms(time: &str) -> Option<u64> {
188    let time = time.strip_suffix('Z')?;
189    let (date, clock) = time.split_once('T')?;
190    let mut date = date.splitn(3, '-').map(|v| v.parse::<i64>().ok());
191    let (year, month, day) = (date.next()??, date.next()??, date.next()??);
192    let (hms, fraction) = clock.split_once('.').unwrap_or((clock, ""));
193    let mut hms = hms.splitn(3, ':').map(|v| v.parse::<i64>().ok());
194    let (hour, minute, second) = (hms.next()??, hms.next()??, hms.next()??);
195    let millis = if fraction.is_empty() {
196        0
197    } else {
198        format!("{:0<3}", &fraction[..fraction.len().min(3)])
199            .parse::<i64>()
200            .ok()?
201    };
202    // Days from civil (H. Hinnant), proleptic Gregorian calendar.
203    let y = if month <= 2 { year - 1 } else { year };
204    let era = y.div_euclid(400);
205    let yoe = y - era * 400;
206    let doy = (153 * (month + if month > 2 { -3 } else { 9 }) + 2) / 5 + day - 1;
207    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
208    let days = era * 146_097 + doe - 719_468;
209    let ms = ((days * 86_400 + hour * 3600 + minute * 60 + second) * 1000) + millis;
210    u64::try_from(ms).ok()
211}
212
213/// Extract a numeric value for `"key":value` from a JSON line.
214///
215/// This is intentionally simple — it handles the subset of gpsd TPV output
216/// where values are bare numbers (no quoting, no nesting).
217fn extract_f64(json: &str, key: &str) -> Option<f64> {
218    // Build the search pattern: "key":
219    let pattern = format!("\"{}\":", key);
220    let start = json.find(&pattern)? + pattern.len();
221    let rest = &json[start..];
222
223    // Skip optional whitespace
224    let rest = rest.trim_start();
225
226    // Find the end of the number: next comma, closing brace, or end of string
227    let end = rest
228        .find(|c: char| c == ',' || c == '}' || c == ']' || c.is_whitespace())
229        .unwrap_or(rest.len());
230
231    let num_str = &rest[..end];
232    num_str.parse::<f64>().ok()
233}
234
235#[cfg(test)]
236mod tests {
237    use super::*;
238
239    /// The TPV `time` (UTC, ms included) becomes the fix acquisition time,
240    /// used as GN TST (ETSI TS 103 836-4-1 clause 9.5.2.2).
241    #[test]
242    fn parse_tpv_acquisition_time() {
243        let line =
244            r#"{"class":"TPV","mode":3,"time":"2026-11-17T10:00:00.250Z","lat":41.5,"lon":2.1}"#;
245        // 2026-11-17T10:00:00.250Z = 1_794_909_600_250 ms since the Unix epoch
246        assert_eq!(
247            parse_tpv(line).unwrap().fix_time_ms,
248            Some(1_794_909_600_250)
249        );
250        assert_eq!(parse_iso8601_ms("1970-01-01T00:00:00Z"), Some(0));
251        assert_eq!(
252            parse_iso8601_ms("2000-03-01T00:00:01.5Z"),
253            Some(951_868_801_500)
254        );
255        let no_time = r#"{"class":"TPV","mode":3,"lat":41.5,"lon":2.1}"#;
256        assert_eq!(parse_tpv(no_time).unwrap().fix_time_ms, None);
257    }
258
259    #[test]
260    fn parse_tpv_valid_3d_fix() {
261        let line = r#"{"class":"TPV","mode":3,"time":"2024-01-01T00:00:00.000Z","lat":41.552000,"lon":2.134000,"alt":120.5,"speed":10.2,"track":90.0,"epx":2.0,"epy":1.5}"#;
262        let fix = parse_tpv(line).unwrap();
263        assert!((fix.latitude - 41.552).abs() < 1e-6);
264        assert!((fix.longitude - 2.134).abs() < 1e-6);
265        assert!((fix.altitude_m - 120.5).abs() < 1e-1);
266        assert!((fix.speed_mps - 10.2).abs() < 1e-1);
267        assert!((fix.heading_deg - 90.0).abs() < 1e-1);
268        assert!(fix.pai);
269    }
270
271    #[test]
272    fn parse_tpv_2d_fix_no_alt() {
273        let line = r#"{"class":"TPV","mode":2,"lat":41.0,"lon":2.0,"speed":5.0,"track":180.0}"#;
274        let fix = parse_tpv(line).unwrap();
275        assert!((fix.latitude - 41.0).abs() < 1e-6);
276        assert!((fix.altitude_m).abs() < 1e-6); // defaults to 0
277        assert!(!fix.pai); // no epx/epy → not accurate
278    }
279
280    #[test]
281    fn parse_tpv_mode_1_rejected() {
282        let line = r#"{"class":"TPV","mode":1}"#;
283        assert!(parse_tpv(line).is_none());
284    }
285
286    #[test]
287    fn parse_tpv_non_tpv_rejected() {
288        let line = r#"{"class":"SKY","satellites":[]}"#;
289        assert!(parse_tpv(line).is_none());
290    }
291
292    #[test]
293    fn extract_f64_works() {
294        let json = r#"{"lat":41.552,"lon":2.134,"speed":10.5}"#;
295        assert!((extract_f64(json, "lat").unwrap() - 41.552).abs() < 1e-6);
296        assert!((extract_f64(json, "lon").unwrap() - 2.134).abs() < 1e-6);
297        assert!((extract_f64(json, "speed").unwrap() - 10.5).abs() < 1e-1);
298        assert!(extract_f64(json, "missing").is_none());
299    }
300
301    #[test]
302    fn extract_f64_negative() {
303        let json = r#"{"lat":-33.86,"lon":151.21}"#;
304        assert!((extract_f64(json, "lat").unwrap() - (-33.86)).abs() < 1e-6);
305    }
306
307    #[test]
308    fn parse_tpv_inaccurate_position() {
309        let line = r#"{"class":"TPV","mode":3,"lat":41.0,"lon":2.0,"epx":20.0,"epy":15.0}"#;
310        let fix = parse_tpv(line).unwrap();
311        assert!(!fix.pai);
312    }
313}