I'm trying to translate a javascript device controller into Rust. The Rust code is able to initialize, change display colors, and read buttons on the RazerStreamControllerX. It fails to deinitialize the device properly. The javascript code, on the other hand, successfully deinitializes the device onj shutdown. Both implementations will be posted below, take a look and provide suggestions to fix the Rust code.
// RUST CODE (main.rs) //
mod graphics;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use tokio::sync::mpsc::Sender;
use tokio::sync::oneshot;
use std::io::Result;
use tokio::sync::broadcast;
use tokio::sync::mpsc;
use tokio::time;
use tokio_serial::SerialPortBuilderExt;
#[tokio::main]
async fn main() -> Result<()> {
let (tx_event, _) = broadcast::channel(10);
// TODO: Use "tx_pending_send" to write things to the device
let (tx_pending_send, rx_pending_send): (Sender<Vec>, _) = mpsc::channel(100);
let mut serial = tokio_serial::new(PORT, BAUD_RATE)
.open_native_async()
.expect("Failed to open port");
code
// Perform WebSocket upgrade
serial.writable().await.unwrap();
serial.try_write(WS_UPGRADE_HEADER.as_bytes())
.expect("Failed to write to port");
serial.readable().await.unwrap();
let mut buf = vec![0; 1024];
serial.try_read(buf.as_mut_slice())
.expect("Failed to read from port");
let res = String::from_utf8_lossy(&buf);
if !res.contains(WS_UPGRADE_RESPONSE) {
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!("Failed to upgrade to websocket: {res:x?}"),
));
}
// Start the main communication loop
let comms = tokio::spawn(communication_loop(serial, tx_event.clone(), rx_pending_send));
// Handle events
let (r1,) = tokio::join!
(
event_handler(tx_event, tx_pending_send)
);
comms.abort();
r1.unwrap();
Ok(())
}
async fn communication_loop(
mut serial: tokio_serial::SerialStream,
tx_event: broadcast::Sender,
mut rx_pending_send: mpsc::Receiver<Vec>,
) {
loop
{
let mut single_byte = [0; 1];
tokio::select!
{
Some(message) = rx_pending_send.recv() =>
{
// Try to write everything we can from the port
time::sleep(time::Duration::from_millis(2)).await;
serial.write_all(&message).await.unwrap();
},
Ok(_) = serial.read_exact(&mut single_byte) =>
{
println!("Got: {single_byte:?}");
if single_byte[0] == 0x82 {
// Found delimiter
serial.read_exact(&mut single_byte).await.unwrap();
let length = single_byte[0] as usize;
let mut data = vec![0; length];
serial.read_exact(&mut data).await.unwrap();
if let Ok(Some(event)) = parse_serial_message(&data) {
tx_event.send(event).unwrap();
}
}
},
};
}
}
if buff_res.is_err() {
return Err(buff_res.unwrap_err());
}
// TODO: Expect event is TRUE after this is sent
construct_basic_message(Vec::from(MessageHeader::WriteFrameBuffer), buff_res.unwrap())
export class RazerStreamController extends LoupedeckLive {
static productId = 0x0d06
static vendorId = 0x1532
type = 'Razer Stream Controller'
}
export class RazerStreamControllerX extends LoupedeckDevice {
static productId = 0x0d09
static vendorId = 0x1532
type = 'Razer Stream Controller X'
buttons = []
columns = 5
displays = {
center: { id: Buffer.from('\x00M'), width: 480, height: 288 },
}
rows = 3
visibleX = [0, 480]
keySize = 96
// Emit an extra touchstart event since we are touching keys
onButton(buff) {
super.onButton(buff)
const event = buff[1] === 0x00 ? 'touchstart' : 'touchend'
const key = BUTTONS[buff[0]]
const row = Math.floor(key / this.columns)
const col = key % this.columns
const touch = {
id: 0,
// Add half so touch is in the center of the key
x: (col + 0.5) * this.keySize,
y: (row + 0.5) * this.keySize,
target: { key }
}
this.emit(event, {
touches: event === 'touchstart' ? [touch] : [],
changedTouches: [touch],
})
}
// eslint-disable-next-line class-methods-use-this
setButtonColor() {
throw new Error('Setting key color not available on this device!')
}
// eslint-disable-next-line class-methods-use-this
vibrate() {
throw new Error('Vibration not available on this device!')
}
}
It appears that the issue with your Rust code not properly deinitializing the device stems from the abrupt termination of the communication task using comms.abort(). This method forcefully aborts the task, potentially leaving the serial port in an undefined state and not allowing any necessary cleanup operations to occur.
In contrast, the JavaScript code seems to handle the closure of the connection more gracefully, calling the close() method on the connection, which likely ensures that all pending operations are completed and the device is properly notified of the disconnection.
To fix your Rust code, you should modify it to allow the communication_loop to exit gracefully, ensuring that the serial port is properly closed and any necessary deinitialization messages are sent to the device. Here's how you can do it:
Introduce a Shutdown Mechanism: Use a tokio::sync::watch::Receiver<bool> (or a similar mechanism) to signal the communication_loop to exit. This allows the loop to check periodically if it should terminate.
Avoid Abrupt Abortion: Replace the comms.abort() call with a signal to the communication_loop to exit and then await its completion.
Properly Close the Serial Port: Ensure that after the communication_loop exits, you properly close the serial port. This might involve dropping the serial object or explicitly calling a close method if available.
Graceful Shutdown in communication_loop: Modify the loop to check for the shutdown signal and perform any necessary cleanup before exiting.
Here is the modified Rust code incorporating these suggestions:
rust
use tokio::sync::watch;
use std::sync::Arc;
use tokio::sync::Mutex;
#[tokio::main]
async fn main() -> Result<()> {
let (tx_event, _) = broadcast::channel(10);
let (shutdown_tx, shutdown_rx) = watch::channel(false);
let (tx_pending_send, rx_pending_send): (Sender<Vec<u8>>, _) = mpsc::channel(100);
let serial = Arc::new(Mutex::new(tokio_serial::new(PORT, BAUD_RATE)
.open_native_async()
.expect("Failed to open port")));
// Rest of your initialization code...
// Start the main communication loop
let comms = tokio::spawn(communication_loop(serial.clone(), tx_event.clone(), rx_pending_send, shutdown_rx));
// Handle events
let (r1,) = tokio::join!(
event_handler(tx_event, tx_pending_send)
);
// Signal the communication loop to shutdown
shutdown_tx.send(true).unwrap();
// Wait for the communication loop to finish
comms.await.unwrap();
// Ensure serial port is properly closed
drop(serial);
r1.unwrap();
Ok(())
}
async fn communication_loop(
serial: Arc<Mutex<tokio_serial::SerialStream>>,
tx_event: broadcast::Sender<Event>,
mut rx_pending_send: mpsc::Receiver<Vec<u8>>,
mut shutdown_rx: watch::Receiver<bool>,
) {
loop {
let mut single_byte = [0; 1];
tokio::select! {
Some(message) = rx_pending_send.recv() => {
// Write to the serial port
let mut serial = serial.lock().await;
serial.write_all(&message).await.unwrap();
},
Ok(_) = serial.lock().await.read_exact(&mut single_byte) => {
// Handle incoming data
// Your existing code...
},
changed = shutdown_rx.changed() => {
if *shutdown_rx.borrow() {
// Perform any necessary cleanup here
break;
}
},
};
}
}
By introducing a shutdown signal and modifying the communication_loop to check for it, you ensure that the loop exits gracefully. The serial port is properly closed after the loop exits, which should allow the device to deinitialize correctly.
Explanation:
Graceful Shutdown: The shutdown_rx receiver allows the communication_loop to monitor for a shutdown signal. When the signal is received, the loop can perform any necessary cleanup and exit naturally.
Avoiding comms.abort(): Instead of forcibly aborting the task with comms.abort(), we send a shutdown signal and wait for the task to complete using await.
Proper Serial Port Closure: Dropping the serial object after ensuring that all tasks have completed allows the port to close properly. This is important for releasing the device and letting the operating system know that the connection is no longer needed.
Additional Suggestions:
Error Handling: Ensure that any errors during shutdown are properly handled to prevent panics or undefined behavior.
Device-Specific Deinitialization: If the device requires specific commands to be sent before disconnection, make sure to send those commands before signaling the communication loop to shutdown.
By making these changes, your Rust code should deinitialize the device properly, matching the behavior of the JavaScript implementation.