seekdas/
acq.rs

1//! 采集配置:CONV 来源、分组、抽取与滤波、点数。
2//!
3//! # 概念
4//!
5//! - **CONV 事件**:一次"取一个点"的请求。来源有两种:
6//!   - **边沿检测器**(4 个):把某一路模拟输入当作转换时钟,信号过阈值的时刻(插值到 1/64 采样周期)产生一个事件;
7//!   - **内部发生器**:按固定周期产生事件,周期可以是非整数个采样周期。
8//! - **组**(2 个):每组选若干来源(合并成一个事件序列)和若干数据通道。每个事件,
9//!   该组的每个通道输出一个值——重采样滤波器在事件时刻算出的结果。
10//! - **点**:一个事件在一组里的输出(各通道各一个 14 bit 码值,可选带时间戳和来源编号)。
11//!
12//! 两组共用抽取指数 r 和滤波核,共用点数上限:两组合计输出 N 点后一起停止。
13//!
14//! ```
15//! use seekdas::{AcqConfig, Channel, ChannelMask, EdgeDetector, Kernel};
16//!
17//! // S1A 上的 1 MHz 方波上升沿作转换时钟,采 S0 槽的 4 路,带时间戳
18//! let cfg = AcqConfig::new()
19//!     .decimation_log2(2)
20//!     .kernel(Kernel::least_squares(32, 0.2, 0.35, 2).unwrap())
21//!     .detector(0, EdgeDetector::rising(Channel::S1A, 1400))
22//!     .group(0, |g| g.detector(0).channels(ChannelMask::slot(0).unwrap()).timestamps(true))
23//!     .points(65536);
24//! assert!(cfg.validate().is_ok());
25//! ```
26
27use 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
34/// 边沿检测器的个数。
35pub const NUM_DETECTORS: usize = 4;
36
37/// 一个边沿检测器的设置:把一路模拟输入当作 CONV 时钟。
38///
39/// 阈值和迟滞的单位是 ADC 码(14 bit 有符号,±10 V 档下 1400 码约 2.2 V)。
40/// 信号过阈值后要再走过迟滞量才确认一个边沿,用来抑制噪声造成的重复触发。
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42pub struct EdgeDetector {
43    /// 作为 CONV 时钟的输入。
44    pub channel: Channel,
45    /// 上升沿产生事件。
46    pub rising: bool,
47    /// 下降沿产生事件。
48    pub falling: bool,
49    /// 阈值(ADC 码,−8192..=8191)。
50    pub threshold: i16,
51    /// 迟滞(ADC 码,0..=8191)。
52    pub hysteresis: u16,
53    /// 两个事件之间的最小间隔(采样周期数),0 = 不限制。
54    pub min_interval: u32,
55}
56
57impl EdgeDetector {
58    /// 上升沿检测,迟滞 200 码。
59    pub fn rising(channel: Channel, threshold: i16) -> EdgeDetector {
60        EdgeDetector { channel, rising: true, falling: false, threshold, hysteresis: 200, min_interval: 0 }
61    }
62
63    /// 下降沿检测,迟滞 200 码。
64    pub fn falling(channel: Channel, threshold: i16) -> EdgeDetector {
65        EdgeDetector { rising: false, falling: true, ..EdgeDetector::rising(channel, threshold) }
66    }
67
68    /// 双沿检测,迟滞 200 码。
69    pub fn both(channel: Channel, threshold: i16) -> EdgeDetector {
70        EdgeDetector { falling: true, ..EdgeDetector::rising(channel, threshold) }
71    }
72
73    /// 修改迟滞。
74    pub fn hysteresis(mut self, codes: u16) -> EdgeDetector {
75        self.hysteresis = codes;
76        self
77    }
78
79    /// 修改最小间隔。
80    pub fn min_interval(mut self, samples: u32) -> EdgeDetector {
81        self.min_interval = samples;
82        self
83    }
84}
85
86/// 一组的设置:来源、数据通道、是否带时间字。在 [`AcqConfig::group`] 的闭包里用链式方法填写。
87#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
88pub struct Group {
89    /// 来源掩码:bit0..3 = 边沿检测器 0..3,bit4 = 内部发生器。
90    pub sources: u8,
91    /// 输出的数据通道。
92    pub channels: ChannelMask,
93    /// 每个点是否带时间字(时刻、来源编号、无效标志)。每点多占 4 字节。
94    pub timestamps: bool,
95}
96
97impl Group {
98    /// 加入边沿检测器 `d`(0..=3)作为来源。
99    pub fn detector(mut self, d: usize) -> Group {
100        self.sources |= 1 << (d & 3);
101        self
102    }
103
104    /// 加入内部发生器作为来源。
105    pub fn generator(mut self) -> Group {
106        self.sources |= 1 << 4;
107        self
108    }
109
110    /// 设置输出的数据通道。
111    pub fn channels(mut self, channels: impl Into<ChannelMask>) -> Group {
112        self.channels = channels.into();
113        self
114    }
115
116    /// 每个点是否带时间字。
117    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/// 一次采集的完整配置。用链式方法构造,[`Device::configure`](crate::Device::configure) 或
128/// [`AcqConfig::apply`] 写入设备。
129///
130/// 默认值:不抽取(r = 0),不改设备里已有的滤波核,4 个检测器全关,两组都没有来源和通道,
131/// 点数不限,8 KB 数据包(需要巨帧)。
132#[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    /// 默认配置。
154    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    /// 抽取指数 r(0..=4),重采样之前先做 R = 2^r 倍抽取。
170    pub fn decimation_log2(mut self, r: u8) -> AcqConfig {
171        self.decimation_log2 = r;
172        self
173    }
174
175    /// 重采样滤波核。不设置时沿用设备里已装入的系数(上电后未装入过则为全 0,输出恒为 0)。
176    pub fn kernel(mut self, kernel: Kernel) -> AcqConfig {
177        self.kernel = Some(kernel);
178        self
179    }
180
181    /// 按信号带宽同时设置抽取指数和滤波核,见 [`Kernel::for_bandwidth`]。
182    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    /// 时间校准(单位 T/64,有符号):补偿 CONV 输入到 ADC 采样时刻的固定延迟,加到所有检测器的边沿时刻上。
188    pub fn time_calibration(mut self, ticks: i16) -> AcqConfig {
189        self.time_cal = ticks;
190        self
191    }
192
193    /// 设置边沿检测器 `d`(0..=3)。检测器还需要在某一组的来源里选中才起作用。
194    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    /// 关闭边沿检测器 `d`(默认即关闭)。
202    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    /// 内部发生器的周期,单位为采样周期,可以是小数(分辨率 1/16384)。
210    ///
211    /// 整数周期时每个点落在同一个插值相位上;配合 [`Kernel::identity`] 和 r = 0 即"每 N 个采样取一个"。
212    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    /// 内部发生器的速率(点/秒),按标称采样率 100 MSPS 换算成周期。
218    pub fn generator_rate(self, points_per_second: f64) -> AcqConfig {
219        self.generator_period(SAMPLE_RATE_HZ / points_per_second)
220    }
221
222    /// 设置组 `g`(0 或 1)。闭包拿到该组当前的设置,返回修改后的设置。
223    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    /// 两组合计的点数,达到后自动停止;0 = 不限,直到 STOP。
231    pub fn points(mut self, n: u32) -> AcqConfig {
232        self.points = n;
233        self
234    }
235
236    /// 合并延迟(采样周期数,≥ 16):多个来源的事件按时刻排序时等待的时间。
237    /// 用作 CONV 的边沿很慢(从阈值走到迟滞电平超过这个时间)时需要加大。
238    pub fn merge_delay(mut self, samples: u16) -> AcqConfig {
239        self.merge_delay = samples;
240        self
241    }
242
243    /// 使用 8 KB 数据包(默认)。主机网卡和交换机的 MTU 需 ≥ 8100。
244    pub fn jumbo_packets(mut self) -> AcqConfig {
245        self.packet_beats = 1000;
246        self
247    }
248
249    /// 使用标准 MTU(1500)能通过的数据包(1472 字节)。包数约为巨帧的 5.6 倍。
250    pub fn standard_mtu_packets(mut self) -> AcqConfig {
251        self.packet_beats = 180;
252        self
253    }
254
255    /// 每个数据包的载荷拍数(8..=1020,每拍 8 字节,数据报 = 32 + 8 × 拍数 字节)。
256    pub fn packet_beats(mut self, beats: u16) -> AcqConfig {
257        self.packet_beats = beats;
258        self
259    }
260
261    /// 未装满的数据包最长等待多久就发出(默认 1 ms)。点速率很低时决定数据到达主机的延迟。
262    pub fn flush_timeout(mut self, t: Duration) -> AcqConfig {
263        self.flush = t;
264        self
265    }
266
267    /// 配置的点数(0 = 不限)。
268    pub fn total_points(&self) -> u32 {
269        self.points
270    }
271
272    /// 配置的抽取指数 r。
273    pub fn decimation(&self) -> u8 {
274        self.decimation_log2
275    }
276
277    /// 内部发生器的周期(采样周期数);未设置时为 `None`。
278    pub fn generator_period_samples(&self) -> Option<f64> {
279        self.generator_period.map(|p| p as f64 / 16384.0)
280    }
281
282    /// 两组的设置。
283    pub fn groups(&self) -> &[Group; 2] {
284        &self.groups
285    }
286
287    /// 4 个边沿检测器的设置(`None` = 关闭)。
288    pub fn detectors(&self) -> &[Option<EdgeDetector>; NUM_DETECTORS] {
289        &self.detectors
290    }
291
292    /// 检查配置是否在设备允许的范围内。[`apply`](Self::apply) 会先调用它。
293    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            // one point must fit into a packet
338            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    /// 把配置写入设备(不启动)。`io` 可以是 [`Device`](crate::Device),也可以是串口上的
346    /// [`AtClient`](crate::at::AtClient)(装入滤波核要写两千多个寄存器,串口上约需一分钟)。
347    ///
348    /// 设备正在采集时返回 [`Error::Busy`],不写任何寄存器。
349    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/// 采集状态和本次运行的计数器。
394#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
395pub struct AcqStatus {
396    /// 正在运行(含仍在途中的记录)。
397    pub busy: bool,
398    /// 上一次运行已完成。
399    pub done: bool,
400    /// 两组合计已输出的点数。
401    pub points: u32,
402    /// 组 0 / 组 1 各自的点数。
403    pub group_points: [u32; 2],
404    /// 因引擎来不及处理而丢失的事件数(CONV 速率超过了滤波核抽头数允许的上限)。
405    pub lost: u32,
406    /// 所需历史已被覆盖的事件数(输出无效)。
407    pub late: u32,
408    /// 送往网络之前被丢弃的记录数(主机长时间不收,环形缓冲满)。
409    pub dropped: u32,
410    /// 运行期间有 START 或配置写入被设备拒绝过(PL 0.2.1 起;更早的固件恒为 `false`)。
411    pub rejected: bool,
412}
413
414impl AcqStatus {
415    /// 从设备读出。
416    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
432/// 设备正在采集时返回 [`Error::Busy`]。
433pub(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
440/// 写入边沿时刻修正表(每个检测器 128 项:下标 = 下降沿 × 64 + 边沿在两个采样点之间的小数位置,
441/// 内容为有符号修正量,单位 T/64,范围 −32..=31)。上电为全 0。
442///
443/// 修正表补偿"边沿只有一两个采样点宽"时线性插值的系统误差,随 CONV 信号的幅度、边沿速度和阈值而变。
444pub 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        // 32 taps need 11 samples per point
505        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}