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
use crate::{
    error::AUTDInternalError,
    firmware::{
        fpga::FPGA_MAIN_CLK_FREQ,
        operation::{write_to_tx, Operation, TypeTag},
    },
    geometry::Device,
};

#[repr(C, align(2))]
struct Sync {
    tag: TypeTag,
    __pad: [u8; 3],
    ecat_sync_base_cnt: u32,
}

#[derive(Default)]
pub struct SyncOp {
    is_done: bool,
}

impl Operation for SyncOp {
    fn pack(&mut self, _: &Device, tx: &mut [u8]) -> Result<usize, AUTDInternalError> {
        write_to_tx(
            Sync {
                tag: TypeTag::Sync,
                __pad: [0; 3],
                ecat_sync_base_cnt: FPGA_MAIN_CLK_FREQ.hz() / 2000,
            },
            tx,
        );

        self.is_done = true;
        Ok(std::mem::size_of::<Sync>())
    }

    fn required_size(&self, _: &Device) -> usize {
        std::mem::size_of::<Sync>()
    }

    fn is_done(&self) -> bool {
        self.is_done
    }
}

#[cfg(test)]
mod tests {

    use std::mem::size_of;

    use super::*;
    use crate::geometry::tests::create_device;

    const NUM_TRANS_IN_UNIT: usize = 249;

    #[test]
    fn test() {
        let device = create_device(0, NUM_TRANS_IN_UNIT);

        let mut tx = [0x00u8; size_of::<Sync>()];

        let mut op = SyncOp::default();

        assert_eq!(op.required_size(&device), size_of::<Sync>());

        assert!(!op.is_done());

        assert!(op.pack(&device, &mut tx).is_ok());

        assert!(op.is_done());

        let sync_base_cnt = FPGA_MAIN_CLK_FREQ.hz() / 2000;
        assert_eq!(tx[0], TypeTag::Sync as u8);
        assert_eq!(tx[4], (sync_base_cnt & 0xFF) as u8);
        assert_eq!(tx[5], ((sync_base_cnt >> 8) & 0xFF) as u8);
        assert_eq!(tx[6], ((sync_base_cnt >> 16) & 0xFF) as u8);
        assert_eq!(tx[7], ((sync_base_cnt >> 24) & 0xFF) as u8);
    }
}