Hello All,
I am a Rust Beginner and I am trying to write first programme, an application similar to Putty that writes and reads serial comms.
Below is my read/write serial functions:
pub fn connect_serial_port(
port_name: &str,
baud_rate: u32,
serial_output: Arc<Mutex<String>>,
) -> Option<Arc<Mutex<Box<dyn SerialPort>>>> {
let port_name = port_name.to_string();
let serial_output = Arc::clone(&serial_output);
let builder = serialport::new(&port_name, baud_rate).timeout(Duration::from_millis(10));
match builder.open() {
Ok(port) => {
let port = Arc::new(Mutex::new(port));
let port_clone = Arc::clone(&port);
thread::spawn(move || {
let mut buffer: Vec<u8> = vec![0; 1024];
loop {
let mut port = port_clone.lock().unwrap();
match port.read(buffer.as_mut_slice()) {
Ok(bytes_read) => {
let output = String::from_utf8_lossy(&buffer[..bytes_read]);{
let mut serial_output = serial_output.lock().unwrap();
serial_output.push_str(&output);
} // MutexGuard for serial_output is dropped here
}
Err(ref e) if e.kind() == std::io::ErrorKind::TimedOut => (),
Err(e) => {
let mut serial_output = serial_output.lock().unwrap();
serial_output.push_str(&format!("Error: {}\n", e));
break;
}
}
}
});
Some(port)
}
Err(e) => {
let mut serial_output = serial_output.lock().unwrap();
serial_output.push_str(&format!("Failed to connect: {}\n", e));
None
}
}
}
pub fn send_serial_data(port: Arc<Mutex<Box<dyn SerialPort>>>, data: &str, serial_output: Arc<Mutex<String>>) {
let mut port = port.lock().unwrap();
let result = port.write(data.as_bytes());
println!("Trying to send {}\n",data);
// Lock the serial_output mutex
{
**let mut serial_output = serial_output.lock().unwrap();**
match result {
Ok(_) => {
serial_output.push_str(&format!("Sent: {}\n", data));
println!("Sent {}\n",data);
}
Err(e) => {
serial_output.push_str(&format!("Failed to send: {}\n", e));
println!("Sent {}\n",data);
}
}
// MutexGuard is dropped here, unlocking the mutex
}
}
The bold line is where my applications crashes, so my first question is surely trying to lock something shouldn't just crash my program, surely it should give me an error and continue on? And I thought this was the whole point of Rust for it to be safe i.e no crashes?
Secondly is there a way to check that it is locked and if it is locked, where else is responsible?
Note that I kinda feel over my head and there might be a really obvious error that I've not spotted. But any tips are most appreciated.
Toml here for reference:
[package]
name = "Putty"
version = "0.1.0"
edition = "2024"
[dependencies]
sqlite = "0.36.0"
anyhow = "1.0.82"
eframe = { version = "0.31.1", features = ["wgpu"] }
env_logger = "0.11.3"
log = "0.4.21"
ehttp = { version = "0.5.0", features = ["json"] }
serde = { version = "1.0.203", features = ["derive"] }
egui_extras = { version = "0.31.1", features = ["all_loaders"] }
image = { version = "0.25", features = ["jpeg", "png"] }
serialport = "4.0"
rumqttc = "0.24.0"
Update 1: Formatted code as requested