From 69a31c8f7fd16ae62eb73912c67e0303efbbe18e Mon Sep 17 00:00:00 2001 From: Raul Victor Trombin Date: Tue, 9 Apr 2024 15:52:11 -0300 Subject: [PATCH] tests: Add async codec test --- tests/async_codec.rs | 79 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 tests/async_codec.rs diff --git a/tests/async_codec.rs b/tests/async_codec.rs new file mode 100644 index 000000000..315095e89 --- /dev/null +++ b/tests/async_codec.rs @@ -0,0 +1,79 @@ +use futures::{SinkExt, StreamExt}; +use ping_rs::codec::PingCodec; +use ping_rs::{common, message::ProtocolMessage, ping1d, Messages}; +use std::convert::TryFrom; +use tokio::time::{sleep, Duration}; +use tokio_serial::SerialPortBuilderExt; +use tokio_util::codec::{Decoder, Framed}; + +async fn run_ping_test() -> Result<(), Box> { + let mut port = tokio_serial::new("/dev/ttyUSB0", 115_200).open_native_async()?; + #[cfg(unix)] + port.set_exclusive(false)?; + + let stream: Framed = PingCodec::new().framed(port); + let (mut tx, mut rx) = stream.split(); + + let request_id_list = [ + 1200, 1201, 1202, 1203, 1204, 1205, 1206, 1207, 1208, 1210, 1211, 1212, 1213, 1214, 1215, + 1300, + ]; + + tokio::spawn(async move { + for request_id in request_id_list { + let request = common::Messages::GeneralRequest(common::GeneralRequestStruct { + requested_id: request_id, + }); + let mut package = ProtocolMessage::new(); + package.set_message(&request); + + let write_result = tx.send(package).await; + match write_result { + Ok(_) => (), + Err(e) => { + eprintln!("Error on serial write: {:?}", e); + } + } + sleep(Duration::from_millis(200)).await; + } + }); + + for n in 0..request_id_list.len() { + let item = rx + .next() + .await + .expect("Error awaiting future in RX stream.") + .expect("Reading stream resulted in an error"); + + println!( + "Received: {} packages, actual package: {:?}", + { n + 1 }, + item + ); + + match Messages::try_from(&item) { + Ok(Messages::Ping1D(ping1d::Messages::DeviceId(answer))) => { + println!("{:?}", answer) + } + Ok(_) => {} + Err(e) => { + eprintln!("Error on decoder: {:?}", e) + } + } + } + + Ok(()) +} + +#[tokio::test] +#[cfg_attr(not(feature = "local_runner"), ignore)] +async fn test_run_ping_test() { + let result = tokio::try_join!(run_ping_test()); + + match result { + Ok(_) => {} + Err(e) => { + assert!(false, "Test failed: {:?}", e); + } + } +}