Use serialport crate to query serial connection

This commit is contained in:
hodasemi 2019-11-24 08:10:54 +01:00
parent a22670ad08
commit b673509380
3 changed files with 42 additions and 28 deletions

View file

@ -15,6 +15,6 @@ path = "src/gui.rs"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
serial = "*"
serialport = "*"
gtk = { version = "*", features = ["v3_24"] }
utilities = { git = "http://dimov.cloud:80/hodasemi/Context.git" }

View file

@ -1,39 +1,32 @@
use serial;
use serial::prelude::*;
pub use serial::PortSettings;
use serialport;
use serialport::prelude::*;
use utilities::prelude::*;
use std::cell::RefCell;
use std::ffi::OsStr;
use std::time::Duration;
pub use serialport::{DataBits, FlowControl, Parity, SerialPortSettings, StopBits};
pub use std::time::Duration;
pub struct Port {
serial_port: RefCell<Box<dyn SerialPort>>,
}
impl Port {
pub fn open<T: AsRef<OsStr> + ?Sized + std::fmt::Display>(
port: &T,
settings: PortSettings,
) -> VerboseResult<Self> {
let mut port = serial::open(port).map_err(|err| {
pub fn open(settings: SerialPortSettings) -> VerboseResult<Self> {
let port_path = Self::find_macroboard()?;
let port = serialport::open_with_settings(&port_path, &settings).map_err(|err| {
format!(
"could not open serial port ({:?}, {}, {})",
err.kind(),
err,
port
port_path
)
})?;
port.configure(&settings)
.map_err(|err| format!("failed configuring serial port ({})", err))?;
port.set_timeout(Duration::from_millis(2500))
.map_err(|err| format!("failed setting time out for serial port ({})", err))?;
Ok(Port {
serial_port: RefCell::new(Box::new(port)),
serial_port: RefCell::new(port),
})
}
@ -57,4 +50,25 @@ impl Port {
Ok(())
}
fn find_macroboard() -> VerboseResult<String> {
let available_ports = serialport::available_ports()
.map_err(|err| format!("error querying serial ports ( {})", err))?;
for available_port in available_ports.iter() {
if let serialport::SerialPortType::UsbPort(usb_info) = &available_port.port_type {
// check for the correct device
if let Some(product_name) = &usb_info.product {
if product_name == "FT232R_USB_UART"
&& usb_info.vid == 1027
&& usb_info.pid == 24577
{
return Ok(available_port.port_name.clone());
}
}
}
}
create_error!("macro board not found on usb bus")
}
}

View file

@ -1,20 +1,20 @@
mod port;
use serial;
use utilities::prelude::*;
use port::{Port, PortSettings};
use port::*;
fn main() -> VerboseResult<()> {
let settings = PortSettings {
baud_rate: serial::Baud9600,
char_size: serial::Bits8,
parity: serial::ParityNone,
stop_bits: serial::Stop1,
flow_control: serial::FlowNone,
let settings = SerialPortSettings {
baud_rate: 9600,
data_bits: DataBits::Eight,
parity: Parity::None,
stop_bits: StopBits::One,
flow_control: FlowControl::None,
timeout: Duration::from_millis(2500),
};
let port = Port::open("/dev/macroboard/tty00000000", settings)?;
let port = Port::open(settings)?;
loop {
if let Ok(msg) = port.read() {