seekdas/
capture.rs

1//! 把一次采集的点包汇集成按通道排列的数组。
2
3use std::io::Write;
4
5use crate::channel::{Channel, ChannelMask};
6use crate::error::{Error, Result};
7use crate::proto::PointPacket;
8use crate::stream::RunSummary;
9
10/// 一组在一次采集中的全部数据。
11#[derive(Clone, Debug, Default)]
12pub struct GroupData {
13    channels: ChannelMask,
14    columns: Vec<Vec<i16>>,
15    /// 每个点的 CONV 时刻,单位 T/64(T = 采样周期)。该组未开启时间字时为空。
16    pub times: Vec<u64>,
17    /// 每个点的来源:0..=3 为边沿检测器,4 为内部发生器。未开启时间字时为空。
18    pub sources: Vec<u8>,
19    /// 无效点(late 或饱和)的序号。未开启时间字时设备不逐点上报,恒为空。
20    pub bad_points: Vec<u32>,
21    /// 第一个点的时刻(T/64),不论是否开启时间字都有。没有点时为 `None`。
22    pub t0: Option<u64>,
23    points: usize,
24}
25
26impl GroupData {
27    /// 点数。
28    pub fn len(&self) -> usize {
29        self.points
30    }
31
32    /// 是否没有点。
33    pub fn is_empty(&self) -> bool {
34        self.points == 0
35    }
36
37    /// 该组包含的通道。
38    pub fn channels(&self) -> ChannelMask {
39        self.channels
40    }
41
42    /// 一路输入的全部点(ADC 码,−8192..=8191);该组不含这一路时为 `None`。
43    pub fn channel(&self, ch: Channel) -> Option<&[i16]> {
44        let col = self.channels.iter().position(|c| c == ch)?;
45        Some(&self.columns[col])
46    }
47
48    /// 相邻两点的平均间隔,单位为采样周期;需要时间字且至少两个点。
49    pub fn mean_interval_samples(&self) -> Option<f64> {
50        let (first, last) = (self.times.first()?, self.times.last()?);
51        (self.times.len() > 1).then(|| (last - first) as f64 / 64.0 / (self.times.len() - 1) as f64)
52    }
53}
54
55/// 一次采集的结果:两组数据和运行汇总。由 [`Device::acquire`](crate::Device::acquire) 返回,
56/// 也可以自己用 [`Capture::push`] 从 [`Stream`](crate::Stream) 收到的包拼出来。
57#[derive(Clone, Debug, Default)]
58pub struct Capture {
59    groups: [GroupData; 2],
60    /// 运行汇总(设备计数器和接收统计)。
61    pub summary: RunSummary,
62}
63
64impl Capture {
65    /// 空的结果。
66    pub fn new() -> Capture {
67        Capture::default()
68    }
69
70    /// 组 `g`(0 或 1)的数据。
71    pub fn group(&self, g: usize) -> &GroupData {
72        &self.groups[g & 1]
73    }
74
75    /// 加入一个点包。包必须按 [`Stream::recv`](crate::Stream::recv) 交付的顺序加入;序号不连续时返回错误。
76    pub fn push(&mut self, p: &PointPacket) -> Result<()> {
77        let g = &mut self.groups[p.group as usize & 1];
78        if g.points == 0 && g.columns.is_empty() {
79            g.channels = p.channels;
80            g.columns = vec![Vec::new(); p.channels.len()];
81        }
82        if p.channels != g.channels {
83            return Err(Error::Protocol(format!("group {}: channel mask changed within a run", p.group)));
84        }
85        if p.first_index as usize != g.points {
86            return Err(Error::Protocol(format!("group {}: packet starts at point {}, expected {}", p.group, p.first_index, g.points)));
87        }
88        if p.is_empty() {
89            return Ok(());
90        }
91        if g.t0.is_none() {
92            g.t0 = Some(p.t0);
93        }
94        for (col, v) in g.columns.iter_mut().enumerate() {
95            v.extend(p.column(col));
96        }
97        if p.has_time {
98            for pt in p.points() {
99                g.times.push(pt.time.unwrap_or(0));
100                g.sources.push(pt.source.unwrap_or(0));
101                if pt.bad {
102                    g.bad_points.push(pt.index);
103                }
104            }
105        }
106        g.points += p.len();
107        Ok(())
108    }
109
110    /// 记录运行汇总,并检查设备侧的计数与收到的点数一致、没有丢失。
111    pub fn finish(mut self, summary: RunSummary) -> Result<Capture> {
112        let d = &summary.device;
113        self.summary = summary;
114        if d.lost != 0 || d.dropped != 0 {
115            return Err(Error::Device(format!("{} events lost in the engine (CONV rate too high for the kernel), {} records dropped before the network",
116                                             d.lost, d.dropped)));
117        }
118        for g in 0..2 {
119            if self.groups[g].points != d.group_points[g] as usize {
120                return Err(Error::Protocol(format!("group {g}: {} points received, device reports {}", self.groups[g].points, d.group_points[g])));
121            }
122        }
123        Ok(self)
124    }
125
126    /// 写成 CSV:`group,index,time,source,<通道...>`,每点一行,先组 0 后组 1。时间单位 T/64,没有时间字的点留空。
127    pub fn write_csv<W: Write>(&self, mut w: W) -> Result<()> {
128        let all = ChannelMask::from_bits(self.groups[0].channels.bits() | self.groups[1].channels.bits());
129        write!(w, "group,index,time,source")?;
130        for c in all.iter() {
131            write!(w, ",{c}")?;
132        }
133        writeln!(w)?;
134        for (gi, g) in self.groups.iter().enumerate() {
135            for i in 0..g.points {
136                write!(w, "{gi},{i},")?;
137                match (g.times.get(i), g.sources.get(i)) {
138                    (Some(t), Some(s)) => write!(w, "{t},{s}")?,
139                    _ => write!(w, ",")?,
140                }
141                for c in all.iter() {
142                    match g.channel(c) {
143                        Some(v) => write!(w, ",{}", v[i])?,
144                        None => write!(w, ",")?,
145                    }
146                }
147                writeln!(w)?;
148            }
149        }
150        Ok(())
151    }
152}