Arduino-Pedal-Effects/rust/serial_reader/src/main.rs

105 lines
3.4 KiB
Rust
Raw Normal View History

use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::SeqCst;
// use std::thread::JoinHandle;
use gtk::{prelude::*, TextView};
use gtk::{Application, ApplicationWindow};
use gtk::{Button, Entry, Orientation};
mod port;
use port::*;
static CONNECTED: AtomicBool = AtomicBool::new(false);
// static mut THREAD: Option<JoinHandle<()>> = None;
fn main() {
let app = Application::builder()
.application_id("org.example.HelloWorld")
.build();
app.connect_activate(|app| {
// We create the main window.
let window = ApplicationWindow::builder()
.application(app)
.default_width(320)
.default_height(200)
.title("Hello, World!")
.build();
let master_box = gtk::Box::new(Orientation::Vertical, 5);
let top_bar_box = gtk::Box::new(Orientation::Horizontal, 5);
let pid = Entry::builder().text("0x27dd").editable(true).build();
let vid = Entry::builder().text("0x16c0").editable(true).build();
let connect_button = Button::with_label("Connect");
top_bar_box.pack_end(&connect_button, true, true, 3);
top_bar_box.pack_end(&vid, true, true, 3);
top_bar_box.pack_end(&pid, true, true, 3);
let serial_info = TextView::new();
master_box.pack_end(&serial_info, true, true, 3);
master_box.pack_end(&top_bar_box, false, true, 3);
window.add(&master_box);
connect_button.connect_clicked(move |_| {
if !CONNECTED.load(SeqCst) {
let usb_id = UsbId {
vendor_id: u16::from_str_radix(
vid.buffer().text().trim_start_matches("0x"),
16,
)
.unwrap(),
product_id: u16::from_str_radix(
pid.buffer().text().trim_start_matches("0x"),
16,
)
.unwrap(),
};
let serialport_settings = SerialPortSettings {
baud_rate: 57600,
data_bits: DataBits::Eight,
parity: Parity::None,
stop_bits: StopBits::One,
flow_control: FlowControl::None,
timeout: Duration::from_millis(2500),
};
if let Ok(mut port) = Port::open(usb_id, serialport_settings) {
CONNECTED.store(true, SeqCst);
// unsafe {
// THREAD = Some(std::thread::spawn(move || {
// loop forever
loop {
// handle incoming message
match port.read().unwrap() {
SerialReadResult::Message(msg) => {
let buffer = serial_info.buffer().unwrap();
buffer.insert(&mut buffer.end_iter(), &msg);
}
SerialReadResult::UtfConversion(err) => println!("{:?}", err),
SerialReadResult::Timeout => (),
}
}
// }));
// }
}
}
});
// Don't forget to make all widgets visible.
window.show_all();
});
app.run();
}