seekdas/
monitor.rs

1//! 不经过 CONV 数据通路的监视手段:旁路统计窗口和 1024 点原始采集缓冲。
2//!
3//! 两者都只用寄存器访问,接口对任何 [`RegIo`] 通用,但实际应走光口([`Device`](crate::Device)):
4//! 串口上读采集缓冲要八千多条指令(约两分钟),统计窗口则应改用
5//! [`AtClient::read`](crate::at::AtClient::read) / [`AtClient::statistics`](crate::at::AtClient::statistics)。
6
7use std::thread::sleep;
8use std::time::Duration;
9
10use crate::channel::{Channel, NUM_CHANNELS};
11use crate::error::{Error, Result};
12use crate::reg::{self, RegIo};
13
14/// 统计窗口。设备对每路输入连续计算三个嵌套窗口的统计量。
15#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
16pub enum Window {
17    /// 10^5 个采样,1 ms。
18    Ms1,
19    /// 10^7 个采样,100 ms。
20    Ms100,
21    /// 10^8 个采样,1 s。
22    S1,
23}
24
25impl Window {
26    /// 窗口号 0..=2(AT 指令和寄存器里使用)。
27    pub fn index(self) -> usize {
28        self as usize
29    }
30
31    /// 由窗口号构造。
32    pub fn from_index(i: usize) -> Result<Window> {
33        [Window::Ms1, Window::Ms100, Window::S1].get(i).copied().ok_or_else(|| Error::InvalidArgument(format!("window {i} (0..=2)")))
34    }
35
36    /// 窗口内的采样数。
37    pub fn samples(self) -> u64 {
38        [100_000, 10_000_000, 100_000_000][self.index()]
39    }
40}
41
42/// 一路输入在一个统计窗口内的读数,单位 ADC 码。
43#[derive(Clone, Copy, Debug, PartialEq)]
44pub struct WindowStats {
45    /// 均值。
46    pub mean: f64,
47    /// 标准差(去掉均值后的 rms)。
48    pub rms: f64,
49    /// 最小值(分辨率 0.25 码)。
50    pub min: f64,
51    /// 最大值。
52    pub max: f64,
53}
54
55/// 读一路输入最近一个已完成窗口的统计量。数据面没有运行(ADC 未上电或未对齐)时返回错误。
56///
57/// 设备每 1 ms 更新一次统计结果,读记录前后要各读一次更新序号来确认没有读到更新中途的数据。
58/// 光口上一次读取远短于 1 ms,没有问题;**串口上一次寄存器访问就要约 10 ms,这个确认总是失败**,
59/// 所以串口上请改用 [`AtClient::read`](crate::at::AtClient::read)(由板上的管理程序完成同样的读取)。
60///
61/// 统计来源(原始样点或采集路径滤波器的输出)由寄存器 `STAT_CTRL` /
62/// [`AtClient::set_stat_source`](crate::at::AtClient::set_stat_source) 选择。
63pub fn read_window<R: RegIo + ?Sized>(io: &mut R, window: Window, ch: Channel) -> Result<WindowStats> {
64    let base = reg::STAT_BASE + ((window.index() * 16 + ch.index()) * 0x20) as u16;
65    for _ in 0..20 {
66        // seqlock: the record is valid if the sequence number is even and unchanged across the read
67        let s0 = io.read_reg(reg::STAT_SEQ)?;
68        let v = io.read_regs(base, 5)?;
69        let s1 = io.read_reg(reg::STAT_SEQ)?;
70        if s0 & 1 != 0 || s0 != s1 {
71            continue;
72        }
73        let n = window.samples() as f64;
74        let sum = ((v[1] as u64) << 32 | v[0] as u64) as i64 as f64;
75        let sq = ((v[3] as u64) << 32 | v[2] as u64) as f64;
76        let mean = sum / n;
77        // samples are ADC code x 4
78        return Ok(WindowStats {
79            mean: mean / 4.0,
80            rms: (sq / n - mean * mean).max(0.0).sqrt() / 4.0,
81            min: (v[4] as u16 as i16) as f64 / 4.0,
82            max: ((v[4] >> 16) as u16 as i16) as f64 / 4.0,
83        });
84    }
85    Err(Error::Device("statistics record changed during every read (register access slower than 1 ms: use AT+READ on the serial port)".into()))
86}
87
88/// 原始采集缓冲的一次采集:12 路各 1024 个连续采样。
89#[derive(Clone, Debug)]
90pub struct RawCapture {
91    /// 抽取指数:采样间隔为 2^n 个采样周期(等间隔抽取,不滤波)。
92    pub decimation_log2: u8,
93    /// `samples[通道序号][i]`,ADC 码。
94    pub samples: Vec<Vec<i16>>,
95}
96
97impl RawCapture {
98    /// 一路输入的 1024 个采样。
99    pub fn channel(&self, ch: Channel) -> &[i16] {
100        &self.samples[ch.index()]
101    }
102
103    /// 采样率(Hz),`sample_rate_hz` 为 ADC 采样率(标称 100 MHz)。
104    pub fn rate_hz(&self, sample_rate_hz: f64) -> f64 {
105        sample_rate_hz / (1u64 << self.decimation_log2) as f64
106    }
107}
108
109/// 触发一次原始采集并读回:12 路同时刻的 1024 个采样,间隔 2^`decimation_log2` 个采样周期(0..=15)。
110///
111/// 这是 CONV 数据通路之外的调试手段:数据取自 ADC 接收之后(经采集路径滤波器,默认旁路),
112/// 不经抽取和重采样。
113pub fn raw_capture<R: RegIo + ?Sized>(io: &mut R, decimation_log2: u8) -> Result<RawCapture> {
114    if decimation_log2 > 15 {
115        return Err(Error::InvalidArgument(format!("capture decimation 2^{decimation_log2} (0..=15)")));
116    }
117    io.write_regs(&[(reg::CAP_CTRL, (decimation_log2 as u32) << 4), (reg::CAP_CMD, 1)])?;
118    sleep(Duration::from_micros(30_000 + 1024 * (10u64 << decimation_log2) / 1000));
119    let mut busy = true;
120    for _ in 0..400 {
121        if io.read_reg(reg::BOARD)? >> 26 & 1 == 0 {
122            busy = false;
123            break;
124        }
125        sleep(Duration::from_millis(5));
126    }
127    if busy {
128        return Err(Error::Timeout("capture buffer still busy (data plane not running?)".into()));
129    }
130    let mut samples: Vec<Vec<i16>> = (0..NUM_CHANNELS).map(|_| Vec::with_capacity(1024)).collect();
131    // 8 words per sample, 6 of them used: two inputs per word, the even input in the low half
132    for block in 0..16u16 {
133        let w = io.read_regs(reg::CAP_BASE + block * 0x800, 512)?;
134        for i in 0..64 {
135            for (c, col) in samples.iter_mut().enumerate() {
136                let v = (w[8 * i + c / 2] >> (16 * (c & 1))) as u16 as i16;
137                col.push(v >> 2);
138            }
139        }
140    }
141    Ok(RawCapture { decimation_log2, samples })
142}