autd3_core/link/
sync.rs

1use alloc::{boxed::Box, vec::Vec};
2
3use crate::geometry::Geometry;
4
5use super::{RxMessage, TxMessage, error::LinkError};
6
7/// A trait that provides the interface with the device.
8pub trait Link: Send {
9    /// Opens the link.
10    fn open(&mut self, geometry: &Geometry) -> Result<(), LinkError>;
11
12    /// Closes the link.
13    fn close(&mut self) -> Result<(), LinkError>;
14
15    #[doc(hidden)]
16    fn update(&mut self, _: &Geometry) -> Result<(), LinkError> {
17        Ok(())
18    }
19
20    /// Allocate a sending buffer for the link.
21    fn alloc_tx_buffer(&mut self) -> Result<Vec<TxMessage>, LinkError>;
22
23    /// Sends a message to the device.
24    fn send(&mut self, tx: Vec<TxMessage>) -> Result<(), LinkError>;
25
26    /// Receives a message from the device.
27    fn receive(&mut self, rx: &mut [RxMessage]) -> Result<(), LinkError>;
28
29    /// Checks if the link is open.
30    #[must_use]
31    fn is_open(&self) -> bool;
32
33    /// Ensures that the link is open, returning an error if it is not.
34    fn ensure_is_open(&self) -> Result<(), LinkError> {
35        if self.is_open() {
36            Ok(())
37        } else {
38            Err(LinkError::closed())
39        }
40    }
41}
42
43impl Link for Box<dyn Link> {
44    fn open(&mut self, geometry: &Geometry) -> Result<(), LinkError> {
45        self.as_mut().open(geometry)
46    }
47
48    fn close(&mut self) -> Result<(), LinkError> {
49        self.as_mut().close()
50    }
51
52    fn update(&mut self, geometry: &Geometry) -> Result<(), LinkError> {
53        self.as_mut().update(geometry)
54    }
55
56    fn alloc_tx_buffer(&mut self) -> Result<Vec<TxMessage>, LinkError> {
57        self.as_mut().alloc_tx_buffer()
58    }
59
60    fn send(&mut self, tx: Vec<TxMessage>) -> Result<(), LinkError> {
61        self.as_mut().send(tx)
62    }
63
64    fn receive(&mut self, rx: &mut [RxMessage]) -> Result<(), LinkError> {
65        self.as_mut().receive(rx)
66    }
67
68    fn is_open(&self) -> bool {
69        self.as_ref().is_open()
70    }
71}