use anyhow::{Result, bail};
pub use serialport;
use serialport::{SerialPort, SerialPortType};
#[derive(Clone, clap::Args)]
pub struct ConnectionOptions {
#[arg(long)]
serial: Option<String>,
#[arg(long, default_value = "1s")]
timeout: humantime::Duration,
}
impl ConnectionOptions {
pub fn connect(&self) -> Result<Box<dyn SerialPort>> {
let ConnectionOptions { serial, timeout } = self;
for info in serialport::available_ports()? {
let path = info.port_name;
let SerialPortType::UsbPort(info) = info.port_type else { continue };
if info.vid != 0x18d1 || info.pid != 0x0239 {
continue;
}
match (serial, &info.serial_number) {
(None, _) => (),
(Some(expected), Some(actual)) if actual == expected => (),
_ => continue,
}
return Ok(serialport::new(path, 19200).timeout(**timeout).open()?);
}
bail!("no available port");
}
}