use anyhow::{Context, Result};
use std::path::Path;
use tokio_serial::{DataBits, FlowControl, Parity, SerialPortBuilderExt, SerialStream, StopBits};
use tracing::info;

pub async fn open_serial(path: &Path, baud: u32) -> Result<SerialStream> {
    let path = path
        .to_str()
        .with_context(|| format!("serial path is not valid UTF-8: {}", path.display()))?;

    let stream = tokio_serial::new(path, baud)
        .data_bits(DataBits::Eight)
        .parity(Parity::None)
        .stop_bits(StopBits::One)
        .flow_control(FlowControl::None)
        .open_native_async()
        .with_context(|| format!("failed to open serial port {path}"))?;

    info!(port = path, baud, "serial port opened");
    Ok(stream)
}
