1use std::time::Duration;
28
29use crate::channel::{Channel, ChannelMask};
30use crate::error::{Error, Result};
31use crate::kernel::{Kernel, MAX_DECIMATION_LOG2, SAMPLE_RATE_HZ};
32use crate::reg::{self, RegIo};
33
34pub const NUM_DETECTORS: usize = 4;
36
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42pub struct EdgeDetector {
43 pub channel: Channel,
45 pub rising: bool,
47 pub falling: bool,
49 pub threshold: i16,
51 pub hysteresis: u16,
53 pub min_interval: u32,
55}
56
57impl EdgeDetector {
58 pub fn rising(channel: Channel, threshold: i16) -> EdgeDetector {
60 EdgeDetector { channel, rising: true, falling: false, threshold, hysteresis: 200, min_interval: 0 }
61 }
62
63 pub fn falling(channel: Channel, threshold: i16) -> EdgeDetector {
65 EdgeDetector { rising: false, falling: true, ..EdgeDetector::rising(channel, threshold) }
66 }
67
68 pub fn both(channel: Channel, threshold: i16) -> EdgeDetector {
70 EdgeDetector { falling: true, ..EdgeDetector::rising(channel, threshold) }
71 }
72
73 pub fn hysteresis(mut self, codes: u16) -> EdgeDetector {
75 self.hysteresis = codes;
76 self
77 }
78
79 pub fn min_interval(mut self, samples: u32) -> EdgeDetector {
81 self.min_interval = samples;
82 self
83 }
84}
85
86#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
88pub struct Group {
89 pub sources: u8,
91 pub channels: ChannelMask,
93 pub timestamps: bool,
95}
96
97impl Group {
98 pub fn detector(mut self, d: usize) -> Group {
100 self.sources |= 1 << (d & 3);
101 self
102 }
103
104 pub fn generator(mut self) -> Group {
106 self.sources |= 1 << 4;
107 self
108 }
109
110 pub fn channels(mut self, channels: impl Into<ChannelMask>) -> Group {
112 self.channels = channels.into();
113 self
114 }
115
116 pub fn timestamps(mut self, on: bool) -> Group {
118 self.timestamps = on;
119 self
120 }
121
122 fn word(&self) -> u32 {
123 (self.channels.bits() as u32) << 16 | (self.timestamps as u32) << 8 | (self.sources & 0x1F) as u32
124 }
125}
126
127#[derive(Clone, Debug)]
133pub struct AcqConfig {
134 decimation_log2: u8,
135 kernel: Option<Kernel>,
136 time_cal: i16,
137 detectors: [Option<EdgeDetector>; NUM_DETECTORS],
138 generator_period: Option<u64>,
139 groups: [Group; 2],
140 points: u32,
141 merge_delay: u16,
142 packet_beats: u16,
143 flush: Duration,
144}
145
146impl Default for AcqConfig {
147 fn default() -> Self {
148 AcqConfig::new()
149 }
150}
151
152impl AcqConfig {
153 pub fn new() -> AcqConfig {
155 AcqConfig {
156 decimation_log2: 0,
157 kernel: None,
158 time_cal: 0,
159 detectors: [None; NUM_DETECTORS],
160 generator_period: None,
161 groups: [Group::default(); 2],
162 points: 0,
163 merge_delay: 16,
164 packet_beats: 1000,
165 flush: Duration::from_millis(1),
166 }
167 }
168
169 pub fn decimation_log2(mut self, r: u8) -> AcqConfig {
171 self.decimation_log2 = r;
172 self
173 }
174
175 pub fn kernel(mut self, kernel: Kernel) -> AcqConfig {
177 self.kernel = Some(kernel);
178 self
179 }
180
181 pub fn bandwidth(self, bandwidth_hz: f64) -> Result<AcqConfig> {
183 let (r, k) = Kernel::for_bandwidth(bandwidth_hz)?;
184 Ok(self.decimation_log2(r).kernel(k))
185 }
186
187 pub fn time_calibration(mut self, ticks: i16) -> AcqConfig {
189 self.time_cal = ticks;
190 self
191 }
192
193 pub fn detector(mut self, d: usize, det: EdgeDetector) -> AcqConfig {
195 if d < NUM_DETECTORS {
196 self.detectors[d] = Some(det);
197 }
198 self
199 }
200
201 pub fn detector_off(mut self, d: usize) -> AcqConfig {
203 if d < NUM_DETECTORS {
204 self.detectors[d] = None;
205 }
206 self
207 }
208
209 pub fn generator_period(mut self, samples: f64) -> AcqConfig {
213 self.generator_period = Some((samples * 16384.0).round().max(0.0) as u64);
214 self
215 }
216
217 pub fn generator_rate(self, points_per_second: f64) -> AcqConfig {
219 self.generator_period(SAMPLE_RATE_HZ / points_per_second)
220 }
221
222 pub fn group(mut self, g: usize, f: impl FnOnce(Group) -> Group) -> AcqConfig {
224 if g < 2 {
225 self.groups[g] = f(self.groups[g]);
226 }
227 self
228 }
229
230 pub fn points(mut self, n: u32) -> AcqConfig {
232 self.points = n;
233 self
234 }
235
236 pub fn merge_delay(mut self, samples: u16) -> AcqConfig {
239 self.merge_delay = samples;
240 self
241 }
242
243 pub fn jumbo_packets(mut self) -> AcqConfig {
245 self.packet_beats = 1000;
246 self
247 }
248
249 pub fn standard_mtu_packets(mut self) -> AcqConfig {
251 self.packet_beats = 180;
252 self
253 }
254
255 pub fn packet_beats(mut self, beats: u16) -> AcqConfig {
257 self.packet_beats = beats;
258 self
259 }
260
261 pub fn flush_timeout(mut self, t: Duration) -> AcqConfig {
263 self.flush = t;
264 self
265 }
266
267 pub fn total_points(&self) -> u32 {
269 self.points
270 }
271
272 pub fn decimation(&self) -> u8 {
274 self.decimation_log2
275 }
276
277 pub fn generator_period_samples(&self) -> Option<f64> {
279 self.generator_period.map(|p| p as f64 / 16384.0)
280 }
281
282 pub fn groups(&self) -> &[Group; 2] {
284 &self.groups
285 }
286
287 pub fn detectors(&self) -> &[Option<EdgeDetector>; NUM_DETECTORS] {
289 &self.detectors
290 }
291
292 pub fn validate(&self) -> Result<()> {
294 let bad = |s: String| Err(Error::InvalidArgument(s));
295 if self.decimation_log2 > MAX_DECIMATION_LOG2 {
296 return bad(format!("decimation r = {} (0..=4)", self.decimation_log2));
297 }
298 if !(8..=1020).contains(&self.packet_beats) {
299 return bad(format!("{} payload beats per packet (8..=1020)", self.packet_beats));
300 }
301 if self.merge_delay < 16 {
302 return bad(format!("merge delay {} samples (>= 16)", self.merge_delay));
303 }
304 for (d, det) in self.detectors.iter().enumerate() {
305 if let Some(det) = det {
306 if !det.rising && !det.falling {
307 return bad(format!("detector {d}: no edge selected"));
308 }
309 if !(-8192..=8191).contains(&det.threshold) || det.hysteresis > 8191 {
310 return bad(format!("detector {d}: threshold {} / hysteresis {} out of range", det.threshold, det.hysteresis));
311 }
312 }
313 }
314 for (g, grp) in self.groups.iter().enumerate() {
315 for d in 0..NUM_DETECTORS {
316 if grp.sources >> d & 1 != 0 && self.detectors[d].is_none() {
317 return bad(format!("group {g} uses detector {d}, which is not configured"));
318 }
319 }
320 if grp.sources & 0x10 != 0 {
321 let Some(p) = self.generator_period else {
322 return bad(format!("group {g} uses the generator, but no period is set"));
323 };
324 let taps = self.kernel.as_ref().map_or(32, |k| k.taps());
325 let min = ((taps / 4 + 3) * 16384) as u64;
326 if p < min && self.kernel.is_some() {
327 return bad(format!("generator period {:.3} samples is shorter than the engine needs for {taps} taps ({} samples per point)",
328 p as f64 / 16384.0, taps / 4 + 3));
329 }
330 if p >= 1 << 48 {
331 return bad("generator period too long".into());
332 }
333 }
334 if grp.sources != 0 && grp.channels.is_empty() {
335 return bad(format!("group {g} has sources but no channels"));
336 }
337 if (grp.channels.len() + 2 * grp.timestamps as usize + 3) / 4 > self.packet_beats as usize {
339 return bad(format!("group {g}: a point does not fit into {} beats", self.packet_beats));
340 }
341 }
342 Ok(())
343 }
344
345 pub fn apply<R: RegIo + ?Sized>(&self, io: &mut R) -> Result<()> {
350 self.validate()?;
351 ensure_idle(io)?;
352 let cal = (self.time_cal as u16 as u32) << 16;
353 let mut w: Vec<(u16, u32)> = vec![(reg::DEC, self.decimation_log2 as u32)];
354 match &self.kernel {
355 Some(k) => {
356 w.push((reg::RS_CFG, cal | (k.taps() / 4) as u32));
357 for (phase, row) in k.rows().iter().enumerate() {
358 w.push((reg::COEF_ADDR, (phase as u32) << 5));
359 w.extend(row.iter().map(|&c| (reg::COEF_DATA, c as u32 & 0x3FFFF)));
360 }
361 }
362 None => {
363 let cur = io.read_reg(reg::RS_CFG)?;
364 w.push((reg::RS_CFG, cal | (cur & 0xF)));
365 }
366 }
367 for (d, det) in self.detectors.iter().enumerate() {
368 let base = reg::EDGE_BASE + 0x10 * d as u16;
369 match det {
370 Some(det) => {
371 w.push((base + 4, (det.hysteresis as u32) << 16 | (det.threshold as u32 & 0x3FFF)));
372 w.push((base + 8, det.min_interval));
373 w.push((base, (det.channel.index() as u32) << 8 | (det.falling as u32) << 2 | (det.rising as u32) << 1 | 1));
374 }
375 None => w.push((base, 0)),
376 }
377 }
378 if let Some(p) = self.generator_period {
379 w.push((reg::GEN_PERIOD_LO, p as u32));
380 w.push((reg::GEN_PERIOD_HI, (p >> 32) as u32));
381 }
382 w.push((reg::GROUP0, self.groups[0].word()));
383 w.push((reg::GROUP1, self.groups[1].word()));
384 w.push((reg::MERGE_DLY, self.merge_delay as u32));
385 w.push((reg::GATE_N, self.points));
386 w.push((reg::PKT_BEATS, self.packet_beats as u32));
387 w.push((reg::PKT_FLUSH, (self.flush.as_nanos() / 8).clamp(1, u32::MAX as u128) as u32));
388 io.write_regs(&w)?;
389 Ok(())
390 }
391}
392
393#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
395pub struct AcqStatus {
396 pub busy: bool,
398 pub done: bool,
400 pub points: u32,
402 pub group_points: [u32; 2],
404 pub lost: u32,
406 pub late: u32,
408 pub dropped: u32,
410 pub rejected: bool,
412}
413
414impl AcqStatus {
415 pub fn read<R: RegIo + ?Sized>(io: &mut R) -> Result<AcqStatus> {
417 let v = io.read_regs(reg::GATE_CTRL, 6)?;
418 let dropped = io.read_reg(reg::NET_DROP)?;
419 Ok(AcqStatus {
420 busy: v[0] & reg::GATE_BUSY != 0,
421 done: v[0] & reg::GATE_DONE != 0,
422 points: v[1],
423 group_points: [v[2], v[3]],
424 lost: v[4],
425 late: v[5],
426 dropped,
427 rejected: v[0] & reg::GATE_REJECTED != 0,
428 })
429 }
430}
431
432pub(crate) fn ensure_idle<R: RegIo + ?Sized>(io: &mut R) -> Result<()> {
434 if io.read_reg(reg::GATE_CTRL)? & reg::GATE_BUSY != 0 {
435 return Err(Error::Busy("an acquisition is running; wait until it is done or stop it first".into()));
436 }
437 Ok(())
438}
439
440pub fn write_edge_lut<R: RegIo + ?Sized>(io: &mut R, detector: usize, table: &[i8; 128]) -> Result<()> {
445 if detector >= NUM_DETECTORS || table.iter().any(|v| !(-32..=31).contains(v)) {
446 return Err(Error::InvalidArgument("edge correction table: detector 0..=3, entries -32..=31".into()));
447 }
448 ensure_idle(io)?;
449 let mut w = vec![(reg::LUT_ADDR, (detector as u32) << 7)];
450 w.extend(table.iter().map(|&v| (reg::LUT_DATA, v as u32 & 0x3F)));
451 io.write_regs(&w)?;
452 Ok(())
453}
454
455#[cfg(test)]
456mod tests {
457 use super::*;
458
459 struct Mock(Vec<(u16, u32)>);
460 impl RegIo for Mock {
461 fn read_regs(&mut self, _addr: u16, n: usize) -> Result<Vec<u32>> {
462 Ok(vec![8; n])
463 }
464 fn write_regs(&mut self, pairs: &[(u16, u32)]) -> Result<Vec<u32>> {
465 self.0.extend_from_slice(pairs);
466 Ok(pairs.iter().map(|p| p.1).collect())
467 }
468 }
469
470 #[test]
471 fn register_image() {
472 let cfg = AcqConfig::new()
473 .decimation_log2(2)
474 .kernel(Kernel::identity())
475 .time_calibration(-3)
476 .detector(1, EdgeDetector::both(Channel::S1A, -100).hysteresis(400).min_interval(50))
477 .generator_period(16.5)
478 .group(0, |g| g.detector(1).channels(Channel::S0A).timestamps(true))
479 .group(1, |g| g.generator().channels(ChannelMask::ALL))
480 .points(1000)
481 .standard_mtu_packets()
482 .flush_timeout(Duration::from_micros(100));
483 let mut m = Mock(Vec::new());
484 cfg.apply(&mut m).unwrap();
485 let get = |a: u16| m.0.iter().rev().find(|p| p.0 == a).unwrap().1;
486 assert_eq!(get(reg::DEC), 2);
487 assert_eq!(get(reg::RS_CFG), 0xFFFD_0001);
488 assert_eq!(m.0.iter().filter(|p| p.0 == reg::COEF_DATA).count(), 256);
489 assert_eq!(get(reg::EDGE_BASE + 0x10), 4 << 8 | 0b111);
490 assert_eq!(get(reg::EDGE_BASE + 0x14), 400 << 16 | (-100i32 as u32 & 0x3FFF));
491 assert_eq!(get(reg::EDGE_BASE + 0x18), 50);
492 assert_eq!(get(reg::EDGE_BASE), 0);
493 assert_eq!((get(reg::GEN_PERIOD_LO), get(reg::GEN_PERIOD_HI)), (16 * 16384 + 8192, 0));
494 assert_eq!(get(reg::GROUP0), 1 << 16 | 1 << 8 | 0b00010);
495 assert_eq!(get(reg::GROUP1), 0xFFF << 16 | 0b10000);
496 assert_eq!((get(reg::GATE_N), get(reg::PKT_BEATS), get(reg::PKT_FLUSH)), (1000, 180, 12500));
497 }
498
499 #[test]
500 fn validation() {
501 assert!(AcqConfig::new().decimation_log2(5).validate().is_err());
502 assert!(AcqConfig::new().group(0, |g| g.detector(2).channels(Channel::S0A)).validate().is_err());
503 assert!(AcqConfig::new().group(0, |g| g.generator().channels(Channel::S0A)).validate().is_err());
504 let c = AcqConfig::new().kernel(Kernel::sinc(32, 0.2, 6.0).unwrap()).group(0, |g| g.generator().channels(Channel::S0A));
506 assert!(c.clone().generator_period(8.0).validate().is_err());
507 assert!(c.generator_period(11.0).validate().is_ok());
508 assert!(AcqConfig::new().bandwidth(2.5e6).unwrap().decimation() == 3);
509 }
510}