Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/main'
Browse files Browse the repository at this point in the history
# Conflicts:
#	src/loco_controller.rs
  • Loading branch information
juhu1705 committed Sep 2, 2022
2 parents 736a704 + c343fa0 commit 76449ed
Showing 1 changed file with 21 additions and 9 deletions.
30 changes: 21 additions & 9 deletions src/loco_controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::fmt::Debug;
use crate::error::{LocoDriveSendingError, MessageParseError};
use crate::protocol::Message;
use std::sync::{Arc, Mutex};
use std::thread::{spawn};
use tokio::time::{sleep, Duration};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::runtime::Runtime;
Expand Down Expand Up @@ -237,13 +238,25 @@ impl LocoDriveController {
///
/// This function panics if the reading thread has panicked or the reading thread was killed,
/// by some external source.
async fn stop_reader(&mut self) {
fn stop_reader(&mut self) {
if let Some(reader) = self.reading_thread.take() {
// Note the thread to end reading
*self.stop.lock().unwrap() = true;
self.fire_stop.notify_waiters();
// Wait until the thread is stopped
reader.await.unwrap();
match spawn(move || {
let runtime = match Runtime::new() {
Ok(runtime) => runtime,
Err(_) => { return; }
};
match runtime.block_on(reader) {
Ok(_) => "",
Err(_) => "",
};
}).join() {
Ok(_) => "",
Err(_) => "",
};

// We allow new threads to spawn and read from the port
*self.stop.lock().unwrap() = false;
Expand Down Expand Up @@ -553,10 +566,13 @@ impl LocoDriveController {
_ = notify.notified() => false,
_ = sleep(Duration::from_millis(self.sending_timeout)) => true,
} {
return Err(LocoDriveSendingError::Timeout)
Err(LocoDriveSendingError::Timeout)
} else {
Ok(())
}
} else {
Ok(())
}
Ok(())
}
Err(_) => Err(LocoDriveSendingError::NotWritable),
}
Expand All @@ -573,10 +589,6 @@ impl Drop for LocoDriveController {
///
/// The drop panics if the reading thread has panicked.
fn drop(&mut self) {
let runtime = match Runtime::new() {
Ok(runtime) => runtime,
Err(_) => { return; }
};
runtime.block_on(self.stop_reader());
self.stop_reader()
}
}

0 comments on commit 76449ed

Please sign in to comment.