Skip to main content

mavlink_core/connection/direct_serial/
config.rs

1use core::fmt::Display;
2use core::time::Duration;
3
4/// MAVLink address for a serial connection
5///
6/// # Example
7///
8/// ```ignore
9/// use mavlink::{Connectable, SerialConfig};
10///
11/// let config = SerialConfig::new("/dev/ttyTHS1".to_owned(), 115200);
12/// config.connect::<mavlink::ardupilotmega::MavMessage>();
13/// ```
14#[derive(Debug, Clone)]
15pub struct SerialConfig {
16    pub(crate) port_name: String,
17    pub(crate) baud_rate: u32,
18    pub(crate) timeout: Option<Duration>,
19    read_buffer_capacity: usize,
20}
21
22impl SerialConfig {
23    /// Creates a serial connection address with port name and baud rate.
24    pub fn new(port_name: String, baud_rate: u32) -> Self {
25        // Calculate a sane default buffer capacity based on the baud rate.
26        let default_capacity = (baud_rate / 100).clamp(1024, 1024 * 8) as usize;
27
28        Self {
29            port_name,
30            baud_rate,
31            timeout: None,
32            read_buffer_capacity: default_capacity,
33        }
34    }
35
36    /// Sets the serial port timeout.
37    ///
38    /// When set, serial reads will return an error after the specified duration.
39    ///
40    /// By default, this is 1 millisecond.
41    ///
42    /// Only applies to sync connections and is a no-op for async ones.
43    pub fn timeout(mut self, timeout: Duration) -> Self {
44        self.timeout = Some(timeout);
45        self
46    }
47
48    /// Updates the read buffer capacity.
49    pub fn with_read_buffer_capacity(mut self, capacity: usize) -> Self {
50        self.read_buffer_capacity = capacity;
51        self
52    }
53
54    /// Returns the configured read buffer capacity.
55    pub fn buffer_capacity(&self) -> usize {
56        self.read_buffer_capacity
57    }
58}
59
60impl Display for SerialConfig {
61    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
62        write!(f, "serial:{}:{}", self.port_name, self.baud_rate)
63    }
64}