Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 26 additions & 4 deletions src/device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,16 @@ use futures::{
stream::{SplitSink, SplitStream},
SinkExt, StreamExt,
};
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::sync::{
broadcast::{self, Sender},
mpsc::{self, Receiver},
};
use tokio::{
io::{AsyncRead, AsyncWrite},
task::JoinHandle,
};
use tokio_util::codec::{Decoder, Framed};
use tracing::error;
use tracing::{error, info};

use crate::{
codec::PingCodec,
Expand All @@ -28,6 +31,13 @@ pub use crate::ping360::Device as Ping360;
pub struct Common {
tx: mpsc::Sender<ProtocolMessage>,
rx: broadcast::Receiver<ProtocolMessage>,
task_handles: TaskHandles,
}
#[derive(Debug)]

struct TaskHandles {
stream_handle: JoinHandle<()>,
sink_handle: JoinHandle<()>,
}

impl Common {
Expand All @@ -41,13 +51,17 @@ impl Common {

// Prepare Serial receiver broadcast and sender
let (broadcast_tx, broadcast_rx) = broadcast::channel::<ProtocolMessage>(100);
tokio::spawn(Self::stream(serial_stream, broadcast_tx));
let stream_handle = tokio::spawn(Self::stream(serial_stream, broadcast_tx));
let (sender, sender_rx) = mpsc::channel::<ProtocolMessage>(100);
tokio::spawn(Self::sink(serial_sink, sender_rx));
let sink_handle = tokio::spawn(Self::sink(serial_sink, sender_rx));

Common {
tx: sender,
rx: broadcast_rx,
task_handles: TaskHandles {
stream_handle,
sink_handle,
},
}
}

Expand Down Expand Up @@ -92,6 +106,14 @@ impl Common {
}
}

impl Drop for Common {
fn drop(&mut self) {
self.task_handles.stream_handle.abort();
self.task_handles.sink_handle.abort();
Comment on lines +111 to +112
Copy link
Member

@joaoantoniocardoso joaoantoniocardoso Oct 21, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are we sure they are cancel-safe?

edit: they are, I just checked.

info!("TaskHandles sink and stream dropped, tasks aborted");
}
}

pub trait PingDevice {
fn get_common(&self) -> &Common;

Expand Down
Loading