Hey,
I'm new to Rust/Dioxus and stucked somehow. I would like to write a desktop application to communicate with an external microcontroller via serial port. I can create a serial port and communicate with the microcontroller but don't know how to use it in Dioxus.
The serial port is an object stored on the heap and I'm trying to use its pointer in the prop struct to access it when an event happens. The pointer must be a mutable borrow reference.
I get this error warning
error[E0596]: cannot borrow
cx.props.port
as mutable, as it is behind a&
reference
send_command( &output, &mut cx.props.port);
^^^^^^^^^^^^^^^^^^ cannot borrow as mutable
Is this the correct way to use objects that need to be created only once for the app lifetime?
I'm grateful for any support.
use serialport::SerialPort;
use std::time::Duration;
use std::str;
use std::collections::HashMap;
use dioxus_desktop::Config;
#[allow(non_snake_case)]
use dioxus::prelude::*;
const COM_PORT: &str = "COM3";
const BAUD_RATE: u32 = 115200;
fn main() {
let app_props = AppProps {
port: open_serial_port(COM_PORT, BAUD_RATE)
};
dioxus_desktop::launch_with_props(
app,
app_props,
Config::default(),
)
}
struct AppProps {
port: Box<dyn SerialPort>,
}
fn open_serial_port(com_port : &str, baud_rate: u32) -> Box<dyn SerialPort> {
let sport: serialport::SerialPortBuilder = serialport::new(com_port, baud_rate);
let sport: serialport::SerialPortBuilder = sport.timeout(Duration::new(2, 0));
match sport.open() {
Ok(port) =>
{
print!("serial port open {:?}", port);
port
},
Err(e) =>
{
eprintln!("{:?}", e);
std::process::exit(1);
}
}
}
fn app(cx: Scope<AppProps>) -> Element {
let led0_state: &UseState<bool> = use_state(cx, || false);
let led_state: HashMap<bool, &str> = HashMap::from([
(false, "off"),
(true, "on"),
]);
cx.render(rsx! {
h1 { "LED 0 state: {led_state[led0_state]}"}
button { onclick: move |_|
{
led0_state.set(!led0_state);
let led = "led 1 ".to_owned();
let output = led + led_state[led0_state];
send_command( &output, &mut cx.props.port);
}, "LED 0" }
})
}
fn send_command(cmd: &str, port: &mut Box<dyn SerialPort>)
{
let _no_of_send_bytes: usize = match port.write(cmd.as_bytes())
{
Ok(s) => s,
Err(e) => {
println!("error writing to port: {:?}", e);
let o: usize = 0;
o
}
};
}