rustflexstack/facilities/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//! Location Service — GPS fix publisher.
5//!
6//! Mirrors `FlexStack/src/flexstack/utils/location_service.py`.
7//!
8//! [`LocationService`] acts as a fan-out hub: a GPS driver (GPSD thread,
9//! simulated sensor, hardware UART, …) calls [`LocationService::publish`]
10//! whenever a new fix arrives. Any number of subscribers may listen by
11//! calling [`LocationService::subscribe`], which returns a
12//! `Receiver<GpsFix>` that delivers every subsequent fix. Dead receivers
13//! (subscriber dropped) are pruned automatically on the next publish.
14//!
15//! # Example
16//! ```no_run
17//! use rustflexstack::facilities::location_service::{LocationService, GpsFix};
18//! use std::thread;
19//! use std::time::Duration;
20//!
21//! let mut svc = LocationService::new();
22//! let rx = svc.subscribe();
23//!
24//! // Simulate a GPS driver publishing fixes at 1 Hz
25//! thread::spawn(move || loop {
26//! thread::sleep(Duration::from_secs(1));
27//! svc.publish(GpsFix {
28//! latitude: 41.552,
29//! longitude: 2.134,
30//! altitude_m: 120.0,
31//! speed_mps: 0.0,
32//! heading_deg: 0.0,
33//! pai: true,
34//! fix_time_ms: None,
35//! });
36//! });
37//!
38//! while let Ok(fix) = rx.recv() {
39//! println!("lat={} lon={}", fix.latitude, fix.longitude);
40//! }
41//! ```
42
43use std::sync::mpsc::{self, Receiver, Sender};
44
45/// A single GPS position fix with the fields needed by the CA Basic Service
46/// and GeoNetworking position vector.
47///
48/// Field units match ETSI EN 302 636-4-1 and EN 302 637-2:
49///
50/// | Field | Unit |
51/// |---|---|
52/// | `latitude` / `longitude` | decimal degrees (WGS-84) |
53/// | `altitude_m` | metres above WGS-84 ellipsoid |
54/// | `speed_mps` | metres per second |
55/// | `heading_deg` | degrees clockwise from North (0–360) |
56/// | `pai` | Position Accuracy Indicator flag |
57#[derive(Debug, Clone, Copy)]
58pub struct GpsFix {
59 /// WGS-84 latitude in decimal degrees (positive = North).
60 pub latitude: f64,
61 /// WGS-84 longitude in decimal degrees (positive = East).
62 pub longitude: f64,
63 /// Altitude above the WGS-84 ellipsoid in metres.
64 pub altitude_m: f64,
65 /// Ground speed in m/s.
66 pub speed_mps: f64,
67 /// Track / heading in decimal degrees (0 = North, clockwise).
68 pub heading_deg: f64,
69 /// Position Accuracy Indicator — `true` when the position fix is
70 /// considered accurate (≤ 4 m, ETSI EN 302 636-4-1 §9.2.2.2).
71 pub pai: bool,
72 /// UTC time of the position acquisition in ms since the Unix epoch (the
73 /// gpsd TPV `time`); the GN position vector TST is set from it (ETSI TS
74 /// 103 836-4-1 clause 9.5.2.2). `None`: the time of reception.
75 pub fix_time_ms: Option<u64>,
76}
77
78impl Default for GpsFix {
79 fn default() -> Self {
80 GpsFix {
81 latitude: 0.0,
82 longitude: 0.0,
83 altitude_m: 0.0,
84 speed_mps: 0.0,
85 heading_deg: 0.0,
86 pai: false,
87 fix_time_ms: None,
88 }
89 }
90}
91
92/// Fan-out GPS fix publisher.
93///
94/// Call [`subscribe`](LocationService::subscribe) to obtain a
95/// `Receiver<GpsFix>`. Call [`publish`](LocationService::publish) from the
96/// GPS driver thread to deliver the fix to every active subscriber.
97pub struct LocationService {
98 /// One sender per active subscriber. Entries whose receivers have been
99 /// dropped are pruned lazily inside [`publish`].
100 senders: Vec<Sender<GpsFix>>,
101}
102
103impl LocationService {
104 /// Create a new, empty `LocationService` with no subscribers.
105 pub fn new() -> Self {
106 LocationService {
107 senders: Vec::new(),
108 }
109 }
110
111 /// Register a new subscriber.
112 ///
113 /// Returns a `Receiver<GpsFix>` that will receive every fix published
114 /// after this call. When the receiver is dropped the corresponding
115 /// internal sender is pruned on the next [`publish`] call.
116 pub fn subscribe(&mut self) -> Receiver<GpsFix> {
117 let (tx, rx) = mpsc::channel();
118 self.senders.push(tx);
119 rx
120 }
121
122 /// Publish `fix` to every active subscriber.
123 ///
124 /// Subscribers whose `Receiver` has been dropped are silently removed.
125 pub fn publish(&mut self, fix: GpsFix) {
126 // `retain` sends and keeps only the senders that are still connected.
127 self.senders.retain(|tx| tx.send(fix).is_ok());
128 }
129
130 /// Return the number of active (non-dropped) subscribers.
131 pub fn subscriber_count(&self) -> usize {
132 self.senders.len()
133 }
134}
135
136impl Default for LocationService {
137 fn default() -> Self {
138 Self::new()
139 }
140}
141
142#[cfg(test)]
143mod tests {
144 use super::*;
145
146 #[test]
147 fn new_has_no_subscribers() {
148 let svc = LocationService::new();
149 assert_eq!(svc.subscriber_count(), 0);
150 }
151
152 #[test]
153 fn default_same_as_new() {
154 let svc = LocationService::default();
155 assert_eq!(svc.subscriber_count(), 0);
156 }
157
158 #[test]
159 fn subscribe_increases_count() {
160 let mut svc = LocationService::new();
161 let _rx1 = svc.subscribe();
162 assert_eq!(svc.subscriber_count(), 1);
163 let _rx2 = svc.subscribe();
164 assert_eq!(svc.subscriber_count(), 2);
165 }
166
167 #[test]
168 fn publish_delivers_to_subscribers() {
169 let mut svc = LocationService::new();
170 let rx = svc.subscribe();
171 let fix = GpsFix {
172 latitude: 41.552,
173 longitude: 2.134,
174 altitude_m: 120.0,
175 speed_mps: 10.0,
176 heading_deg: 90.0,
177 pai: true,
178 fix_time_ms: None,
179 };
180 svc.publish(fix);
181 let received = rx.recv().unwrap();
182 assert!((received.latitude - 41.552).abs() < 1e-6);
183 assert!((received.longitude - 2.134).abs() < 1e-6);
184 assert!(received.pai);
185 }
186
187 #[test]
188 fn publish_to_multiple_subscribers() {
189 let mut svc = LocationService::new();
190 let rx1 = svc.subscribe();
191 let rx2 = svc.subscribe();
192 let fix = GpsFix::default();
193 svc.publish(fix);
194 assert!(rx1.recv().is_ok());
195 assert!(rx2.recv().is_ok());
196 }
197
198 #[test]
199 fn dead_receiver_pruned_on_publish() {
200 let mut svc = LocationService::new();
201 let rx = svc.subscribe();
202 assert_eq!(svc.subscriber_count(), 1);
203 drop(rx);
204 svc.publish(GpsFix::default());
205 assert_eq!(svc.subscriber_count(), 0);
206 }
207
208 #[test]
209 fn gps_fix_default() {
210 let fix = GpsFix::default();
211 assert_eq!(fix.latitude, 0.0);
212 assert_eq!(fix.longitude, 0.0);
213 assert_eq!(fix.speed_mps, 0.0);
214 assert!(!fix.pai);
215 }
216}