53 lines
1.8 KiB
Rust
53 lines
1.8 KiB
Rust
use serialport::SerialPortInfo;
|
|
use std::time::Duration;
|
|
|
|
const BAUD: u32 = 9600;
|
|
const TIMEOUT: u64 = 1000;
|
|
|
|
fn get_port(ports: Vec<SerialPortInfo>) -> Option<SerialPortInfo> {
|
|
for p in ports {
|
|
if p.port_name.contains("ttyACM") {
|
|
return Some(p);
|
|
}
|
|
}
|
|
|
|
None
|
|
}
|
|
|
|
pub fn read_messages(mut request: curl::easy::Easy, data: String) {
|
|
let ports = serialport::available_ports().expect("No ports found!");
|
|
let r = get_port(ports)
|
|
.expect("[ERROR] Failed to get the port")
|
|
.port_name;
|
|
let mut connection = serialport::new(r, BAUD)
|
|
.timeout(Duration::from_millis(TIMEOUT))
|
|
.open()
|
|
.expect("Failed to open the port");
|
|
|
|
let mut serial_buf: Vec<u8> = vec![0; 1024];
|
|
|
|
loop {
|
|
if let Ok(bytes) = connection.read(serial_buf.as_mut_slice()) {
|
|
if bytes < 1 { continue; }
|
|
let output = String::from_utf8_lossy(&serial_buf[..bytes]);
|
|
if output.contains("1") {
|
|
// send curl request
|
|
let res = crate::curl::request(&mut request, &data);
|
|
match res {
|
|
Ok((code, response)) => {
|
|
println!("Response code: {code}");
|
|
match crate::json::get_state(response) {
|
|
Ok(state) => {
|
|
if let Some(valid_state) = state {
|
|
println!("State: {}", valid_state);
|
|
}
|
|
}
|
|
Err(e) => eprintln!("[ERROR] Failed to acquire entity state:\n{e}"),
|
|
}
|
|
}
|
|
Err(e) => eprintln!("[ERROR] Something went wrong with the CURL request:\n{e}"),
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} |