use std::time::Duration;
use rppal::uart::Parity;
use rppal::uart::Uart;
use crate::errors::Error;
use crate::maestro::constants::Baudrate;
use crate::maestro::internals;
use crate::maestro::Maestro;
#[derive(Default)]
pub struct Builder {
pub baudrate: Option<Baudrate>,
pub block_duration: Option<Duration>,
}
impl Builder {
pub fn baudrate(self, baudrate: Baudrate) -> Self {
let baudrate = Some(baudrate);
Self { baudrate, ..self }
}
pub fn block_duration(self, block_duration: Duration) -> Self {
let block_duration = Some(block_duration);
Self {
block_duration,
..self
}
}
}
impl TryFrom<Builder> for Maestro {
type Error = crate::errors::Error;
fn try_from(
Builder {
baudrate,
block_duration,
}: Builder,
) -> Result<Self, Self::Error> {
let baudrate = baudrate.ok_or_else(|| Error::Uninitialized)? as u32;
let mut uart = Uart::new(
baudrate,
Parity::None,
internals::DATA_BITS,
internals::STOP_BITS,
)?;
let block_duration = block_duration.unwrap_or_default();
uart.set_read_mode(0u8, block_duration)?;
let read_buf = [0u8; internals::BUFFER_SIZE];
let mut write_buf = [0u8; internals::BUFFER_SIZE];
write_buf[0usize] = internals::SYNC as u8;
write_buf[1usize] = internals::DEVICE_NUMBER as u8;
let maestro = Self {
uart,
read_buf,
write_buf,
};
Ok(maestro)
}
}