Skip to content

Commit

Permalink
build: parser & src:device : Allow device to accept any io stream type
Browse files Browse the repository at this point in the history
  • Loading branch information
RaulTrombin authored and patrickelectric committed May 7, 2024
1 parent 071bb88 commit 43a316b
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 15 deletions.
7 changes: 1 addition & 6 deletions build/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -584,6 +584,7 @@ pub fn generate<R: Read, W: Write>(input: &mut R, output_rust: &mut W) {
use crate::error::PingError;
use crate::message::ProtocolMessage;
use std::convert::TryInto;
use tokio::io::{AsyncRead, AsyncWrite};

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
Expand All @@ -593,12 +594,6 @@ pub fn generate<R: Read, W: Write>(input: &mut R, output_rust: &mut W) {
}

impl PingDevice for Device {
fn new(port: tokio_serial::SerialStream) -> Self {
Self {
common: Common::new(port),
}
}

fn get_common(&self) -> &Common {
&self.common
}
Expand Down
19 changes: 10 additions & 9 deletions src/device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ use futures::{
stream::{SplitSink, SplitStream},
SinkExt, StreamExt,
};
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::sync::{
broadcast::{self, Sender},
mpsc::{self, Receiver},
};
use tokio_serial::SerialStream;
use tokio_util::codec::{Decoder, Framed};
use tracing::error;

Expand All @@ -30,9 +30,12 @@ pub struct Common {
}

impl Common {
pub fn new(port: tokio_serial::SerialStream) -> Self {
pub fn new<T>(io: T) -> Self
where
T: AsyncRead + AsyncWrite + Unpin + Send + 'static,
{
// Prepare Serial sink and stream modules
let serial: Framed<tokio_serial::SerialStream, PingCodec> = PingCodec::new().framed(port);
let serial: Framed<T, PingCodec> = PingCodec::new().framed(io);
let (serial_sink, serial_stream) = serial.split();

// Prepare Serial receiver broadcast and sender
Expand All @@ -47,8 +50,8 @@ impl Common {
}
}

async fn sink(
mut sink: SplitSink<Framed<SerialStream, PingCodec>, ProtocolMessage>,
async fn sink<T: AsyncRead + AsyncWrite + Unpin + Send + 'static>(
mut sink: SplitSink<Framed<T, PingCodec>, ProtocolMessage>,
mut sender_rx: Receiver<ProtocolMessage>,
) {
while let Some(item) = sender_rx.recv().await {
Expand All @@ -58,8 +61,8 @@ impl Common {
}
}

async fn stream(
mut serial_stream: SplitStream<Framed<SerialStream, PingCodec>>,
async fn stream<T: AsyncRead + AsyncWrite + Unpin + Send + 'static>(
mut serial_stream: SplitStream<Framed<T, PingCodec>>,
broadcast_tx: Sender<ProtocolMessage>,
) {
'outside_loop: loop {
Expand Down Expand Up @@ -92,8 +95,6 @@ impl Common {
}

pub trait PingDevice {
fn new(port: tokio_serial::SerialStream) -> Self;

fn get_common(&self) -> &Common;

fn get_mut_common(&mut self) -> &mut Common;
Expand Down

0 comments on commit 43a316b

Please sign in to comment.