autd3_driver/firmware/fpga/
sampling_config.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
use std::{fmt::Debug, time::Duration};

use autd3_derive::Builder;

use crate::{
    defined::{Freq, Hz, ULTRASOUND_FREQ, ULTRASOUND_PERIOD},
    error::AUTDDriverError,
    utils::float::is_integer,
};

/// The configuration for sampling.
#[derive(Clone, Copy, Debug, PartialEq, Builder)]
#[repr(C)]
pub struct SamplingConfig {
    #[get]
    /// The division number of the sampling frequency.
    ///
    /// The sampling frequency is [`ULTRASOUND_FREQ`] / `division`.
    division: u16,
}

pub trait IntoSamplingConfig {
    fn into_sampling_config(self) -> Result<SamplingConfig, AUTDDriverError>;
}

impl IntoSamplingConfig for u16 {
    fn into_sampling_config(self) -> Result<SamplingConfig, AUTDDriverError> {
        if self == 0 {
            return Err(AUTDDriverError::SamplingDivisionInvalid(self));
        }
        Ok(SamplingConfig { division: self })
    }
}

impl IntoSamplingConfig for Freq<u32> {
    fn into_sampling_config(self) -> Result<SamplingConfig, AUTDDriverError> {
        if !(FREQ_MIN..=FREQ_MAX).contains(&self) {
            return Err(AUTDDriverError::SamplingFreqOutOfRange(
                self, FREQ_MIN, FREQ_MAX,
            ));
        }
        if ULTRASOUND_FREQ.hz() % self.hz() != 0 {
            return Err(AUTDDriverError::SamplingFreqInvalid(self));
        }
        Ok(SamplingConfig {
            division: (ULTRASOUND_FREQ.hz() / self.hz()) as _,
        })
    }
}

impl IntoSamplingConfig for Freq<f32> {
    fn into_sampling_config(self) -> Result<SamplingConfig, AUTDDriverError> {
        if !(FREQ_MIN_F..=FREQ_MAX_F).contains(&self) {
            return Err(AUTDDriverError::SamplingFreqOutOfRangeF(
                self, FREQ_MIN_F, FREQ_MAX_F,
            ));
        }
        let div = ULTRASOUND_FREQ.hz() as f32 / self.hz();
        if !is_integer(div as _) {
            return Err(AUTDDriverError::SamplingFreqInvalidF(self));
        }
        Ok(SamplingConfig { division: div as _ })
    }
}

impl IntoSamplingConfig for Duration {
    fn into_sampling_config(self) -> Result<SamplingConfig, AUTDDriverError> {
        if !(PERIOD_MIN..=PERIOD_MAX).contains(&self) {
            return Err(AUTDDriverError::SamplingPeriodOutOfRange(
                self, PERIOD_MIN, PERIOD_MAX,
            ));
        }
        if self.as_nanos() % ULTRASOUND_PERIOD.as_nanos() != 0 {
            return Err(AUTDDriverError::SamplingPeriodInvalid(self));
        }
        Ok(SamplingConfig {
            division: (self.as_nanos() / ULTRASOUND_PERIOD.as_nanos()) as _,
        })
    }
}

pub trait IntoSamplingConfigNearest {
    fn into_sampling_config_nearest(self) -> SamplingConfig;
}

impl IntoSamplingConfigNearest for Freq<f32> {
    fn into_sampling_config_nearest(self) -> SamplingConfig {
        SamplingConfig::new(
            (ULTRASOUND_FREQ.hz() as f32 / self.hz())
                .clamp(1.0, u16::MAX as f32)
                .round() as u16,
        )
        .unwrap()
    }
}

impl IntoSamplingConfigNearest for Freq<u32> {
    fn into_sampling_config_nearest(self) -> SamplingConfig {
        SamplingConfig::new(
            (ULTRASOUND_FREQ.hz() + self.hz() / 2)
                .checked_div(self.hz())
                .unwrap_or(u32::MAX)
                .clamp(1, u16::MAX as u32) as u16,
        )
        .unwrap()
    }
}

impl IntoSamplingConfigNearest for Duration {
    fn into_sampling_config_nearest(self) -> SamplingConfig {
        SamplingConfig::new(
            ((self.as_nanos() + ULTRASOUND_PERIOD.as_nanos() / 2) / ULTRASOUND_PERIOD.as_nanos())
                .clamp(1, u16::MAX as u128) as u16,
        )
        .unwrap()
    }
}

const FREQ_MIN: Freq<u32> = Freq { freq: 1 };
const FREQ_MAX: Freq<u32> = ULTRASOUND_FREQ;
const FREQ_MIN_F: Freq<f32> = Freq {
    freq: 40000. / u16::MAX as f32,
};
const FREQ_MAX_F: Freq<f32> = Freq { freq: 40000. };
const PERIOD_MIN: Duration = ULTRASOUND_PERIOD;
const PERIOD_MAX: Duration =
    Duration::from_micros(u16::MAX as u64 * ULTRASOUND_PERIOD.as_micros() as u64);

impl SamplingConfig {
    /// A [`SamplingConfig`] of 40kHz.
    pub const FREQ_40K: SamplingConfig = SamplingConfig { division: 1 };
    /// A [`SamplingConfig`] of 4kHz.
    pub const FREQ_4K: SamplingConfig = SamplingConfig { division: 10 };
    /// A [`SamplingConfig`] of the minimum frequency.
    pub const FREQ_MIN: SamplingConfig = SamplingConfig { division: u16::MAX };

    /// Creates a new [`SamplingConfig`].
    pub fn new(value: impl IntoSamplingConfig) -> Result<Self, AUTDDriverError> {
        value.into_sampling_config()
    }

    /// Creates a new [`SamplingConfig`] with the nearest frequency or period value of the possible values.
    pub fn new_nearest(value: impl IntoSamplingConfigNearest) -> Self {
        value.into_sampling_config_nearest()
    }

    /// Gets the sampling frequency.
    pub fn freq(&self) -> Freq<f32> {
        ULTRASOUND_FREQ.hz() as f32 / self.division() as f32 * Hz
    }

    /// Gets the sampling period.
    pub fn period(&self) -> Duration {
        ULTRASOUND_PERIOD * self.division() as u32
    }
}

// GRCOV_EXCL_START
impl TryInto<SamplingConfig> for Freq<u32> {
    type Error = AUTDDriverError;

    fn try_into(self) -> Result<SamplingConfig, Self::Error> {
        SamplingConfig::new(self)
    }
}

impl TryInto<SamplingConfig> for Freq<f32> {
    type Error = AUTDDriverError;

    fn try_into(self) -> Result<SamplingConfig, Self::Error> {
        SamplingConfig::new(self)
    }
}

impl TryInto<SamplingConfig> for Duration {
    type Error = AUTDDriverError;

    fn try_into(self) -> Result<SamplingConfig, Self::Error> {
        SamplingConfig::new(self)
    }
}
// GRCOV_EXCL_STOP

#[cfg(test)]
mod tests {
    use crate::defined::Hz;

    use super::*;

    #[rstest::rstest]
    #[test]
    #[case(Ok(1), 1)]
    #[case(Ok(u16::MAX), u16::MAX)]
    #[case(Ok(1), 40000 * Hz)]
    #[case(Ok(10), 4000 * Hz)]
    #[case(Ok(1), 40000. * Hz)]
    #[case(Ok(10), 4000. * Hz)]
    #[case(Ok(1), Duration::from_micros(25))]
    #[case(Ok(10), Duration::from_micros(250))]
    #[case(Err(AUTDDriverError::SamplingDivisionInvalid(0)), 0)]
    #[case(Err(AUTDDriverError::SamplingFreqInvalid(ULTRASOUND_FREQ - 1 * Hz)), ULTRASOUND_FREQ - 1 * Hz)]
    #[case(Err(AUTDDriverError::SamplingFreqOutOfRange(0 * Hz, FREQ_MIN, FREQ_MAX)), 0 * Hz)]
    #[case(Err(AUTDDriverError::SamplingFreqOutOfRange(ULTRASOUND_FREQ + 1 * Hz, FREQ_MIN, FREQ_MAX)), ULTRASOUND_FREQ + 1 * Hz)]
    #[case(Err(AUTDDriverError::SamplingFreqInvalidF((ULTRASOUND_FREQ.hz() as f32 - 1.) * Hz)), (ULTRASOUND_FREQ.hz() as f32 - 1.) * Hz)]
    #[case(Err(AUTDDriverError::SamplingFreqOutOfRangeF(0. * Hz, FREQ_MIN_F, FREQ_MAX_F)), 0. * Hz)]
    #[case(Err(AUTDDriverError::SamplingFreqOutOfRangeF(40000. * Hz + 1. * Hz, FREQ_MIN_F, FREQ_MAX_F)), 40000. * Hz + 1. * Hz)]
    #[case(Err(AUTDDriverError::SamplingPeriodInvalid(PERIOD_MAX - Duration::from_nanos(1))), PERIOD_MAX - Duration::from_nanos(1))]
    #[case(Err(AUTDDriverError::SamplingPeriodOutOfRange(PERIOD_MIN / 2, PERIOD_MIN, PERIOD_MAX)), PERIOD_MIN / 2)]
    #[case(Err(AUTDDriverError::SamplingPeriodOutOfRange(PERIOD_MAX * 2, PERIOD_MIN, PERIOD_MAX)), PERIOD_MAX * 2)]
    fn division(
        #[case] expect: Result<u16, AUTDDriverError>,
        #[case] value: impl IntoSamplingConfig,
    ) {
        assert_eq!(expect, SamplingConfig::new(value).map(|c| c.division()));
    }

    #[rstest::rstest]
    #[test]
    #[case(Ok(40000. * Hz), 1)]
    #[case(Ok(0.61036086 * Hz), u16::MAX)]
    #[case(Ok(40000. * Hz), 40000 * Hz)]
    #[case(Ok(4000. * Hz), 4000 * Hz)]
    #[case(Ok(40000. * Hz), 40000. * Hz)]
    #[case(Ok(4000. * Hz), 4000. * Hz)]
    #[case(Ok(40000. * Hz), Duration::from_micros(25))]
    #[case(Ok(4000. * Hz), Duration::from_micros(250))]
    fn freq(
        #[case] expect: Result<Freq<f32>, AUTDDriverError>,
        #[case] value: impl IntoSamplingConfig,
    ) {
        assert_eq!(expect, SamplingConfig::new(value).map(|c| c.freq()));
    }

    #[rstest::rstest]
    #[test]
    #[case(Ok(Duration::from_micros(25)), 1)]
    #[case(Ok(Duration::from_micros(1638375)), u16::MAX)]
    #[case(Ok(Duration::from_micros(25)), 40000 * Hz)]
    #[case(Ok(Duration::from_micros(250)), 4000 * Hz)]
    #[case(Ok(Duration::from_micros(25)), 40000. * Hz)]
    #[case(Ok(Duration::from_micros(250)), 4000. * Hz)]
    #[case(Ok(Duration::from_micros(25)), Duration::from_micros(25))]
    #[case(Ok(Duration::from_micros(250)), Duration::from_micros(250))]
    fn period(
        #[case] expect: Result<Duration, AUTDDriverError>,
        #[case] value: impl IntoSamplingConfig,
    ) {
        assert_eq!(expect, SamplingConfig::new(value).map(|c| c.period()));
    }

    #[rstest::rstest]
    #[test]
    #[case::min(u16::MAX, (40000. / u16::MAX as f32) * Hz)]
    #[case::max(1, 40000. * Hz)]
    #[case::not_supported_max(1, (ULTRASOUND_FREQ.hz() as f32 - 1.) * Hz)]
    #[case::out_of_range_min(u16::MAX, 0. * Hz)]
    #[case::out_of_range_max(1, 40000. * Hz + 1. * Hz)]
    fn from_freq_f32_nearest(#[case] expected: u16, #[case] freq: Freq<f32>) {
        assert_eq!(expected, SamplingConfig::new_nearest(freq).division());
    }

    #[rstest::rstest]
    #[test]
    #[case::min(40000, 1 * Hz)]
    #[case::max(1, 40000 * Hz)]
    #[case::not_supported_max(1, ULTRASOUND_FREQ - 1 * Hz)]
    #[case::out_of_range_min(0xFFFF, 0 * Hz)]
    #[case::out_of_range_max(1, ULTRASOUND_FREQ + 1 * Hz)]
    fn from_freq_u32_nearest(#[case] expected: u16, #[case] freq: Freq<u32>) {
        assert_eq!(expected, SamplingConfig::new_nearest(freq).division());
    }

    #[rstest::rstest]
    #[test]
    #[case::min(1, PERIOD_MIN)]
    #[case::max(u16::MAX, PERIOD_MAX)]
    #[case::not_supported_max(u16::MAX, PERIOD_MAX - Duration::from_nanos(1))]
    #[case::out_of_range_min(1, PERIOD_MIN / 2)]
    #[case::out_of_range_max(u16::MAX, PERIOD_MAX * 2)]
    fn from_period_nearest(#[case] expected: u16, #[case] p: Duration) {
        assert_eq!(expected, SamplingConfig::new_nearest(p).division());
    }
}