autd3/datagram/modulation/
custom.rs

1use std::fmt::Debug;
2
3use autd3_core::derive::*;
4
5///[`Modulation`] to use arbitrary modulation data
6#[derive(Modulation, Clone, Debug)]
7pub struct Custom<Config>
8where
9    Config: Into<SamplingConfig> + Debug + Copy,
10{
11    /// The modulation data.
12    pub buffer: Vec<u8>,
13    /// The sampling configuration of the modulation data.
14    pub sampling_config: Config,
15}
16
17impl<Config> Custom<Config>
18where
19    Config: Into<SamplingConfig> + Debug + Copy,
20{
21    /// Create a new [`Custom`].
22    #[must_use]
23    pub fn new(
24        buffer: impl IntoIterator<Item = impl std::borrow::Borrow<u8>>,
25        sampling_config: Config,
26    ) -> Self {
27        Self {
28            buffer: buffer.into_iter().map(|v| *v.borrow()).collect(),
29            sampling_config,
30        }
31    }
32}
33
34impl<Config> Modulation for Custom<Config>
35where
36    Config: Into<SamplingConfig> + Debug + Copy,
37{
38    fn calc(self) -> Result<Vec<u8>, ModulationError> {
39        Ok(self.buffer)
40    }
41
42    fn sampling_config(&self) -> SamplingConfig {
43        self.sampling_config.into()
44    }
45}
46
47#[cfg(test)]
48mod tests {
49    use autd3_driver::common::kHz;
50    use rand::Rng;
51
52    use super::*;
53
54    #[test]
55    fn new() -> Result<(), Box<dyn std::error::Error>> {
56        let mut rng = rand::rng();
57
58        let test_buf = (0..2).map(|_| rng.random()).collect::<Vec<u8>>();
59        let custom = Custom::new(test_buf.clone(), 4. * kHz);
60
61        let d = custom.calc()?;
62        assert_eq!(test_buf, *d);
63
64        Ok(())
65    }
66}