labstream_proto/
timesync.rs1pub fn build_probe(wave_id: i32, t0: f64) -> Vec<u8> {
10 format!("LSL:timedata\r\n{wave_id} {t0:.16}\r\n").into_bytes()
11}
12
13#[derive(Debug, Clone, Copy, PartialEq)]
15pub struct Probe {
16 pub wave_id: i32,
18 pub t0: f64,
20}
21
22pub fn parse_probe(buf: &[u8]) -> Option<Probe> {
24 let text = String::from_utf8_lossy(buf);
25 let mut lines = text.split('\n');
26 if lines.next()?.trim_end_matches('\r').trim() != "LSL:timedata" {
27 return None;
28 }
29 let mut parts = lines.next()?.split_whitespace();
30 Some(Probe {
31 wave_id: parts.next()?.parse().ok()?,
32 t0: parts.next()?.parse().ok()?,
33 })
34}
35
36pub fn build_answer(wave_id: i32, t0: f64, t1: f64, t2: f64) -> Vec<u8> {
41 format!(" {wave_id} {t0:.16} {t1:.16} {t2:.16}").into_bytes()
42}
43
44#[derive(Debug, Clone, Copy, PartialEq)]
46pub struct Answer {
47 pub wave_id: i32,
49 pub t0: f64,
51 pub t1: f64,
53 pub t2: f64,
55}
56
57pub fn parse_answer(buf: &[u8]) -> Option<Answer> {
59 let text = String::from_utf8_lossy(buf);
60 let mut parts = text.split_whitespace();
61 Some(Answer {
62 wave_id: parts.next()?.parse().ok()?,
63 t0: parts.next()?.parse().ok()?,
64 t1: parts.next()?.parse().ok()?,
65 t2: parts.next()?.parse().ok()?,
66 })
67}
68
69#[derive(Debug, Clone, Copy, PartialEq)]
71pub struct Estimate {
72 pub rtt: f64,
74 pub offset: f64,
76}
77
78pub fn estimate(a: &Answer, t3: f64) -> Estimate {
82 Estimate {
83 rtt: (t3 - a.t0) - (a.t2 - a.t1),
84 offset: ((a.t1 - a.t0) + (a.t2 - t3)) / 2.0,
85 }
86}
87
88#[derive(Debug, Clone)]
94pub struct Burst {
95 wave_id: i32,
96 best: Option<(Estimate, f64)>,
97 seen: usize,
98}
99
100impl Burst {
101 pub fn new(wave_id: i32) -> Self {
103 Burst {
104 wave_id,
105 best: None,
106 seen: 0,
107 }
108 }
109
110 pub fn wave_id(&self) -> i32 {
112 self.wave_id
113 }
114
115 pub fn accepted(&self) -> usize {
117 self.seen
118 }
119
120 pub fn accept(&mut self, a: &Answer, t3: f64) -> bool {
125 if a.wave_id != self.wave_id {
126 return false;
127 }
128 let e = estimate(a, t3);
129 let local_mid = 0.5 * (a.t0 + t3);
130 self.seen += 1;
131 match self.best {
132 Some((b, _)) if b.rtt <= e.rtt => {}
133 _ => self.best = Some((e, local_mid)),
134 }
135 true
136 }
137
138 pub fn time_offset(&self) -> Option<f64> {
143 self.best.map(|(e, _)| -e.offset)
144 }
145
146 pub fn uncertainty(&self) -> Option<f64> {
149 self.best.map(|(e, _)| e.rtt)
150 }
151
152 pub fn local_time(&self) -> Option<f64> {
155 self.best.map(|(_, t)| t)
156 }
157}
158
159#[cfg(test)]
160mod tests {
161 use super::*;
162
163 #[test]
164 fn a_probe_round_trips() {
165 let bytes = build_probe(12345, 1.5);
166 let p = parse_probe(&bytes).expect("a probe");
167 assert_eq!(p.wave_id, 12345);
168 assert!((p.t0 - 1.5).abs() < 1e-12);
169 }
170
171 #[test]
172 fn an_answer_starts_with_a_space() {
173 let bytes = build_answer(7, 1.0, 2.0, 3.0);
174 assert_eq!(bytes[0], b' ');
175 let a = parse_answer(&bytes).expect("an answer");
176 assert_eq!(a.wave_id, 7);
177 }
178
179 #[test]
180 fn the_captured_answer_parses() {
181 let raw = b" 12345 7958.920835802 7958.921048403 7958.921142721";
183 let a = parse_answer(raw).expect("an answer");
184 assert_eq!(a.wave_id, 12345);
185 assert!((a.t1 - 7958.921048403).abs() < 1e-9);
186 }
187
188 #[test]
189 fn a_symmetric_exchange_shows_the_offset() {
190 let a = Answer {
193 wave_id: 1,
194 t0: 0.0,
195 t1: 11.0,
196 t2: 11.0,
197 };
198 let e = estimate(&a, 2.0);
199 assert!((e.rtt - 2.0).abs() < 1e-12);
200 assert!((e.offset - 10.0).abs() < 1e-12);
201 }
202
203 #[test]
204 fn the_burst_keeps_the_lowest_round_trip_time() {
205 let mut b = Burst::new(9);
206 b.accept(
208 &Answer {
209 wave_id: 9,
210 t0: 0.0,
211 t1: 15.0,
212 t2: 15.0,
213 },
214 10.0,
215 );
216 b.accept(
217 &Answer {
218 wave_id: 9,
219 t0: 0.0,
220 t1: 10.5,
221 t2: 10.5,
222 },
223 1.0,
224 );
225 assert_eq!(b.accepted(), 2);
226 assert!((b.uncertainty().unwrap() - 1.0).abs() < 1e-12);
227 assert!((b.time_offset().unwrap() + 10.0).abs() < 1e-12);
228 }
229
230 #[test]
231 fn a_late_answer_from_an_earlier_burst_is_dropped() {
232 let mut b = Burst::new(9);
233 assert!(!b.accept(
234 &Answer {
235 wave_id: 8,
236 t0: 0.0,
237 t1: 1.0,
238 t2: 1.0
239 },
240 2.0
241 ));
242 assert_eq!(b.accepted(), 0);
243 assert_eq!(b.time_offset(), None);
244 }
245
246 #[test]
247 fn the_stored_offset_carries_the_opposite_sign() {
248 let mut b = Burst::new(1);
249 b.accept(
250 &Answer {
251 wave_id: 1,
252 t0: 0.0,
253 t1: 5.0,
254 t2: 5.0,
255 },
256 0.0,
257 );
258 assert!((b.time_offset().unwrap() + 5.0).abs() < 1e-12);
260 }
261}