seekdas/
trigger.rs

1//! 触发采集:在指定的通道上各采 N 点,取点时刻(CONV)由一路或几路模拟输入的边沿给出。
2//!
3//! 这是 [`AcqConfig`] 之上的一层简化接口,覆盖最常见的用法:
4//!
5//! 1. **触发目标**([`Trigger::target`]):要采的通道和每个通道的点数 N;
6//! 2. **CONV 通道**([`Trigger::conv_channel`] / [`Trigger::add_conv_channel`]):哪一路输入当作转换时钟,
7//!    上升沿 / 下降沿 / 双沿,阈值(ADC 码);
8//! 3. **启动和管理**([`Device::start_trigger`]、[`Device::trigger_state`]):启动后可随时读运行状态;
9//!    运行中再次启动返回 [`Error::Busy`]。
10//!
11//! ```no_run
12//! use seekdas::{Channel, ChannelMask, Device, Edge, Trigger};
13//! use std::time::Duration;
14//!
15//! # fn main() -> seekdas::Result<()> {
16//! let mut dev = Device::open("192.168.1.128".parse().unwrap())?;
17//! let trig = Trigger::new()
18//!     .target(ChannelMask::from_iter([Channel::S0A, Channel::S0B]), 10_000)?   // S0A、S0B 各 1 万点
19//!     .conv_channel(Channel::S2A, Edge::Rising, 1400)?;                          // S2A 上升沿,阈值 1400 码
20//!
21//! let mut run = dev.start_trigger(&trig)?;
22//! let state = run.device().trigger_state()?;
23//! assert!(state.running && !state.start_allowed);
24//! let cap = run.collect(Duration::from_secs(10))?;                                 // 收完整个运行
25//! assert_eq!(cap.group(0).channel(Channel::S0A).unwrap().len(), 10_000);
26//! # Ok(()) }
27//! ```
28//!
29//! # 和底层配置的对应关系
30//!
31//! 触发只用组 0:数据通道 = 目标通道,来源 = 各 CONV 通道各占一个边沿检测器(最多 4 个,事件按时刻合并),
32//! 点数上限 = N。所以每个 CONV 事件给每个目标通道各一个值,运行结束时每个通道正好 N 点。
33//! 组 1 和内部发生器不用。需要两组或内部发生器时直接用 [`AcqConfig`]。
34//!
35//! 默认的滤波是全带宽(20 MHz)重采样核:输出是信号在 CONV 时刻(分辨率 1/64 采样周期)的带限插值。
36//! [`Trigger::raw`] 改成不滤波、取 CONV 时刻之前最近的一个采样;[`Trigger::bandwidth`] 选更窄的带宽(噪声更低)。
37//!
38//! # 运行中
39//!
40//! 从启动到设备上本次运行的最后一个点处理完,设备处于"忙"状态([`TriggerState::running`])。这期间:
41//!
42//! - 再次启动(本机或别的主机)返回 [`Error::Busy`],正在进行的运行不受影响;
43//! - 修改采集配置([`AcqConfig::apply`]、串口 `AT+CONV=` 等)同样被拒绝;
44//! - [`Device::stop`] 随时有效,已产生的点照常发完。
45//!
46//! PL 0.2.1 起设备自身也执行这条规则(忙时忽略 START 和配置写入,置位 [`TriggerState::rejected`]);
47//! 更早的固件只有主机侧的检查。另一个程序在运行中打开设备([`Device::open`])可以读状态,但不会把数据流改道到自己。
48//!
49//! # 边沿与阈值
50//!
51//! 检测器在信号越过 `阈值 ± 迟滞` 时确认一个边沿,时刻取最近一次越过阈值的位置(线性插值,1/64 采样周期)。
52//! 从越过阈值到越过 `阈值 ± 迟滞` 的时间不能超过约 20 µs × R(R 为抽取倍数;PL 0.2.0 为 5 µs × R),
53//! 否则该点所需的历史数据已被覆盖:输出无效,计入 [`AcqStatus::late`],并在 [`GroupData::bad_points`](crate::GroupData::bad_points)
54//! 里列出。TTL / 方波类的 CONV 信号远在这个限制之内;很慢的边沿用较小的迟滞,或较窄的带宽(R 更大)。
55
56use std::time::Duration;
57
58use crate::acq::{AcqConfig, AcqStatus, EdgeDetector, NUM_DETECTORS};
59use crate::capture::Capture;
60use crate::channel::{Channel, ChannelMask};
61use crate::device::Device;
62use crate::error::{Error, Result};
63use crate::kernel::Kernel;
64use crate::reg::{self, RegIo};
65use crate::stream::Stream;
66
67/// 触发边沿。
68#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
69pub enum Edge {
70    /// 上升沿:信号自下而上穿过阈值。
71    Rising,
72    /// 下降沿:信号自上而下穿过阈值。
73    Falling,
74    /// 双沿。
75    Both,
76}
77
78impl Edge {
79    fn flags(self) -> (bool, bool) {
80        match self {
81            Edge::Rising => (true, false),
82            Edge::Falling => (false, true),
83            Edge::Both => (true, true),
84        }
85    }
86}
87
88/// 一路 CONV 通道:把一路模拟输入当作转换时钟。
89#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90pub struct ConvChannel {
91    /// 作为转换时钟的输入。
92    pub channel: Channel,
93    /// 触发边沿。
94    pub edge: Edge,
95    /// 阈值(ADC 码,−8192..=8191;±10 V 档下约 637 码/V,1400 码约 2.2 V,适合 TTL)。
96    pub threshold: i16,
97    /// 迟滞(ADC 码,0..=8191,默认 200):信号过阈值后还要再走过这么多才确认一个边沿,抑制噪声造成的重复触发。
98    pub hysteresis: u16,
99    /// 两个边沿之间的最小间隔(采样周期数),0 = 不限制(默认)。
100    pub min_interval: u32,
101}
102
103impl ConvChannel {
104    /// 迟滞 200 码,不限最小间隔。
105    pub fn new(channel: Channel, edge: Edge, threshold: i16) -> ConvChannel {
106        ConvChannel { channel, edge, threshold, hysteresis: 200, min_interval: 0 }
107    }
108
109    /// 修改迟滞。
110    pub fn hysteresis(mut self, codes: u16) -> ConvChannel {
111        self.hysteresis = codes;
112        self
113    }
114
115    /// 修改最小间隔。
116    pub fn min_interval(mut self, samples: u32) -> ConvChannel {
117        self.min_interval = samples;
118        self
119    }
120
121    fn check(&self) -> Result<()> {
122        if !(-8192..=8191).contains(&self.threshold) || self.hysteresis > 8191 {
123            return Err(Error::InvalidArgument(format!("CONV channel {}: threshold {} (-8192..=8191) / hysteresis {} (0..=8191)",
124                                                      self.channel, self.threshold, self.hysteresis)));
125        }
126        Ok(())
127    }
128
129    fn detector(&self) -> EdgeDetector {
130        let (rising, falling) = self.edge.flags();
131        EdgeDetector { channel: self.channel, rising, falling, threshold: self.threshold, hysteresis: self.hysteresis, min_interval: self.min_interval }
132    }
133}
134
135#[derive(Clone, Debug)]
136enum Filter {
137    Bandwidth(f64),
138    Raw,
139    Kernel(u8, Kernel),
140}
141
142/// 一次触发采集的设置。用链式方法构造,[`Device::start_trigger`] 启动。
143///
144/// 默认值:没有目标、没有 CONV 通道(启动前两者都必须设置),全带宽滤波,每点带时间戳,8 KB 数据包。
145#[derive(Clone, Debug)]
146pub struct Trigger {
147    target: Option<(ChannelMask, u32)>,
148    conv: Vec<ConvChannel>,
149    filter: Filter,
150    timestamps: bool,
151    packet_beats: u16,
152    time_cal: i16,
153}
154
155impl Default for Trigger {
156    fn default() -> Self {
157        Trigger::new()
158    }
159}
160
161impl Trigger {
162    /// 默认设置。
163    pub fn new() -> Trigger {
164        Trigger { target: None, conv: Vec::new(), filter: Filter::Bandwidth(20.0e6), timestamps: true, packet_beats: 1000, time_cal: 0 }
165    }
166
167    /// 触发目标:在 `channels` 的每个通道上各采 `points_per_channel` 点(≥ 1)。
168    pub fn target(mut self, channels: impl Into<ChannelMask>, points_per_channel: u32) -> Result<Trigger> {
169        let channels = channels.into();
170        if channels.is_empty() {
171            return Err(Error::InvalidArgument("trigger target: no channel".into()));
172        }
173        if points_per_channel == 0 {
174            return Err(Error::InvalidArgument("trigger target: points per channel must be >= 1".into()));
175        }
176        self.target = Some((channels, points_per_channel));
177        Ok(self)
178    }
179
180    /// 只用这一路 CONV 通道(替换已设置的全部),迟滞 200 码。
181    pub fn conv_channel(self, channel: Channel, edge: Edge, threshold: i16) -> Result<Trigger> {
182        self.clear_conv_channels().add_conv_channel(ConvChannel::new(channel, edge, threshold))
183    }
184
185    /// 增加一路 CONV 通道(最多 4 路,各路的边沿按时刻合并成一个事件序列)。该输入已在列表里时就地修改。
186    pub fn add_conv_channel(mut self, conv: ConvChannel) -> Result<Trigger> {
187        conv.check()?;
188        if let Some(c) = self.conv.iter_mut().find(|c| c.channel == conv.channel) {
189            *c = conv;
190        } else if self.conv.len() == NUM_DETECTORS {
191            return Err(Error::InvalidArgument(format!("at most {NUM_DETECTORS} CONV channels")));
192        } else {
193            self.conv.push(conv);
194        }
195        Ok(self)
196    }
197
198    /// 去掉一路 CONV 通道(不在列表里时什么也不做)。
199    pub fn remove_conv_channel(mut self, channel: Channel) -> Trigger {
200        self.conv.retain(|c| c.channel != channel);
201        self
202    }
203
204    /// 去掉全部 CONV 通道。
205    pub fn clear_conv_channels(mut self) -> Trigger {
206        self.conv.clear();
207        self
208    }
209
210    /// 按信号带宽选抽取和滤波核([`Kernel::for_bandwidth`],最高 20 MHz,即默认值)。
211    pub fn bandwidth(mut self, bandwidth_hz: f64) -> Result<Trigger> {
212        Kernel::for_bandwidth(bandwidth_hz)?;
213        self.filter = Filter::Bandwidth(bandwidth_hz);
214        Ok(self)
215    }
216
217    /// 不滤波:每个点是 CONV 时刻之前最近的一个原始采样([`Kernel::identity`],r = 0)。
218    pub fn raw(mut self) -> Trigger {
219        self.filter = Filter::Raw;
220        self
221    }
222
223    /// 指定抽取指数 r(0..=4)和滤波核。
224    pub fn kernel(mut self, decimation_log2: u8, kernel: Kernel) -> Trigger {
225        self.filter = Filter::Kernel(decimation_log2, kernel);
226        self
227    }
228
229    /// 每个点是否带时间戳(默认带,每点多 4 字节)。
230    pub fn timestamps(mut self, on: bool) -> Trigger {
231        self.timestamps = on;
232        self
233    }
234
235    /// 使用标准 MTU(1500)能通过的数据包。默认 8 KB 包,需要巨帧。
236    pub fn standard_mtu_packets(mut self) -> Trigger {
237        self.packet_beats = 180;
238        self
239    }
240
241    /// 每个数据包的载荷拍数(8..=1020)。
242    pub fn packet_beats(mut self, beats: u16) -> Trigger {
243        self.packet_beats = beats;
244        self
245    }
246
247    /// 时间校准(T/64,有符号),见 [`AcqConfig::time_calibration`]。
248    pub fn time_calibration(mut self, ticks: i16) -> Trigger {
249        self.time_cal = ticks;
250        self
251    }
252
253    /// 目标通道和每通道点数;未设置时为 `None`。
254    pub fn target_spec(&self) -> Option<(ChannelMask, u32)> {
255        self.target
256    }
257
258    /// 已设置的 CONV 通道。
259    pub fn conv_channels(&self) -> &[ConvChannel] {
260        &self.conv
261    }
262
263    /// 生成对应的底层配置(同时做完整检查)。
264    pub fn to_config(&self) -> Result<AcqConfig> {
265        let Some((channels, n)) = self.target else {
266            return Err(Error::InvalidArgument("no trigger target: set the channels and the number of points first".into()));
267        };
268        if self.conv.is_empty() {
269            return Err(Error::InvalidArgument("no CONV channel set".into()));
270        }
271        let mut cfg = match &self.filter {
272            Filter::Bandwidth(b) => AcqConfig::new().bandwidth(*b)?,
273            Filter::Raw => AcqConfig::new().decimation_log2(0).kernel(Kernel::identity()),
274            Filter::Kernel(r, k) => AcqConfig::new().decimation_log2(*r).kernel(k.clone()),
275        };
276        cfg = cfg.time_calibration(self.time_cal).packet_beats(self.packet_beats).points(n);
277        let mut sources = 0u8;
278        for d in 0..NUM_DETECTORS {
279            match self.conv.get(d) {
280                Some(c) => {
281                    cfg = cfg.detector(d, c.detector());
282                    sources |= 1 << d;
283                }
284                None => cfg = cfg.detector_off(d),
285            }
286        }
287        let ts = self.timestamps;
288        cfg = cfg.group(0, |_| crate::acq::Group { sources, channels, timestamps: ts })
289                 .group(1, |_| crate::acq::Group::default());
290        cfg.validate()?;
291        Ok(cfg)
292    }
293}
294
295/// 运行阶段。
296#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
297pub enum RunState {
298    /// 上电后还没有运行过。
299    Idle,
300    /// 运行中(从启动到最后一个点处理完)。
301    Running,
302    /// 上一次运行已结束(采满或被停止)。
303    Done,
304}
305
306/// 触发的运行状态,见 [`Device::trigger_state`]。
307#[derive(Clone, Copy, Debug, PartialEq, Eq)]
308pub struct TriggerState {
309    /// 运行阶段。
310    pub state: RunState,
311    /// 运行中(= `state == RunState::Running`)。
312    pub running: bool,
313    /// 现在可以启动新的触发(= 不在运行中)。
314    pub start_allowed: bool,
315    /// 每个目标通道已采到的点数(设备侧计数)。
316    pub points: u32,
317    /// 每个目标通道的目标点数 N(设备里当前的设置;0 = 不限)。
318    pub target_points: u32,
319    /// 目标通道(设备里组 0 当前的通道掩码)。
320    pub channels: ChannelMask,
321    /// 运行已结束且采满了 N 点(没有被提前停止)。
322    pub complete: bool,
323    /// 运行中有 START 或配置写入被设备拒绝过(PL 0.2.1 起)。
324    pub rejected: bool,
325    /// 4 个边沿检测器自上电以来检测到的边沿数(启用的检测器才计数)。
326    pub conv_edges: [u32; NUM_DETECTORS],
327    /// 采集计数器(丢失、late、丢弃等)。
328    pub counters: AcqStatus,
329}
330
331impl TriggerState {
332    /// 从设备读出(光口或串口均可)。
333    pub fn read<R: RegIo + ?Sized>(io: &mut R) -> Result<TriggerState> {
334        let counters = AcqStatus::read(io)?;
335        let n = io.read_reg(reg::GATE_N)?;
336        let g0 = io.read_reg(reg::GROUP0)?;
337        let mut conv_edges = [0u32; NUM_DETECTORS];
338        for (d, e) in conv_edges.iter_mut().enumerate() {
339            *e = io.read_reg(reg::EDGE_BASE + 0x10 * d as u16 + 0xC)?;
340        }
341        let state = if counters.busy { RunState::Running } else if counters.done { RunState::Done } else { RunState::Idle };
342        let points = counters.group_points[0];
343        Ok(TriggerState {
344            state,
345            running: counters.busy,
346            start_allowed: !counters.busy,
347            points,
348            target_points: n,
349            channels: ChannelMask::from_bits((g0 >> 16) as u16 & 0xFFF),
350            complete: state == RunState::Done && n != 0 && counters.points >= n,
351            rejected: counters.rejected,
352            conv_edges,
353            counters,
354        })
355    }
356}
357
358impl Device {
359    /// 写入触发设置并启动,返回接收数据的 [`Stream`](用 [`Stream::collect`] 收完,或 [`Stream::recv`] 逐包处理)。
360    ///
361    /// 设备正在运行(本机或别的主机启动的)时返回 [`Error::Busy`],什么也不改。
362    pub fn start_trigger(&mut self, trigger: &Trigger) -> Result<Stream<'_>> {
363        let cfg = trigger.to_config()?;
364        self.configure(&cfg)?;
365        self.start()
366    }
367
368    /// 启动触发并收完整个运行(连续 10 s 没有数据时返回 [`Error::Timeout`],例如 CONV 输入上没有信号)。
369    pub fn trigger(&mut self, trigger: &Trigger) -> Result<Capture> {
370        self.start_trigger(trigger)?.collect(Duration::from_secs(10))
371    }
372
373    /// 触发的运行状态。数据流存续期间经 [`Stream::device`] 调用。
374    pub fn trigger_state(&mut self) -> Result<TriggerState> {
375        TriggerState::read(self)
376    }
377}
378
379#[cfg(test)]
380mod tests {
381    use super::*;
382
383    #[test]
384    fn config_image() {
385        let t = Trigger::new()
386            .target(ChannelMask::from_iter([Channel::S0A, Channel::S1C]), 5000).unwrap()
387            .conv_channel(Channel::S2A, Edge::Falling, -300).unwrap()
388            .add_conv_channel(ConvChannel::new(Channel::S2B, Edge::Both, 1400).hysteresis(50)).unwrap()
389            .raw();
390        let cfg = t.to_config().unwrap();
391        assert_eq!(cfg.total_points(), 5000);
392        assert_eq!(cfg.groups()[0].sources, 0b11);
393        assert_eq!(cfg.groups()[0].channels.bits(), 0b100_0001);
394        assert!(cfg.groups()[0].timestamps);
395        assert_eq!(cfg.groups()[1].sources, 0);
396        assert_eq!(cfg.detectors()[0], Some(EdgeDetector::falling(Channel::S2A, -300)));
397        assert_eq!(cfg.detectors()[1], Some(EdgeDetector::both(Channel::S2B, 1400).hysteresis(50)));
398        assert_eq!(cfg.detectors()[2], None);
399        // same input again: changed in place
400        let t = t.add_conv_channel(ConvChannel::new(Channel::S2A, Edge::Rising, 10)).unwrap();
401        assert_eq!(t.conv_channels().len(), 2);
402        assert_eq!(t.conv_channels()[0].edge, Edge::Rising);
403    }
404
405    #[test]
406    fn validation() {
407        assert!(Trigger::new().to_config().is_err());
408        assert!(Trigger::new().target(ChannelMask::NONE, 10).is_err());
409        assert!(Trigger::new().target(Channel::S0A, 0).is_err());
410        let t = Trigger::new().target(Channel::S0A, 10).unwrap();
411        assert!(t.to_config().is_err(), "no CONV channel");
412        assert!(t.clone().conv_channel(Channel::S0B, Edge::Rising, 9000).is_err());
413        let mut t = t;
414        for c in [Channel::S2A, Channel::S2B, Channel::S2C, Channel::S2D] {
415            t = t.add_conv_channel(ConvChannel::new(c, Edge::Rising, 0)).unwrap();
416        }
417        assert!(t.clone().add_conv_channel(ConvChannel::new(Channel::S1A, Edge::Rising, 0)).is_err());
418        assert!(t.to_config().is_ok());
419        assert!(Trigger::new().bandwidth(50e6).is_err());
420    }
421}