blob: 96d7132653c1cb015fecd36123b7e712803d5822 [file] [log] [blame]
Adam Snaiderc5bdbd32023-10-19 18:20:56 -06001use aos_events_event_loop_runtime::{EventLoopRuntime, Sender, Watcher};
2use core::cell::Cell;
3use core::time::Duration;
4use futures::never::Never;
5use std::borrow::Borrow;
6
7use ping_rust_fbs::aos::examples as ping;
8use pong_rust_fbs::aos::examples as pong;
9
10#[derive(Debug)]
11pub struct PingTask {
12 counter: Cell<i32>,
13}
14
15impl PingTask {
16 pub fn new() -> Self {
17 Self {
18 counter: Cell::new(0),
19 }
20 }
21
22 /// Returns a future with all the tasks for the ping process
Adam Snaiderb40b72f2023-11-02 19:40:55 -070023 #[allow(unreachable_code)]
Adam Snaiderc5bdbd32023-10-19 18:20:56 -060024 pub async fn tasks(&self, event_loop: EventLoopRuntime<'_>, sleep: u64) -> Never {
25 futures::join!(self.ping(&event_loop, sleep), self.handle_pong(&event_loop));
26 unreachable!("Let's hope `never_type` gets stabilized soon :)");
27 }
28
29 pub async fn ping(&self, event_loop: &EventLoopRuntime<'_>, sleep: u64) -> Never {
30 // The sender is used to send messages back to the pong channel.
31 let mut ping_sender: Sender<ping::Ping> = event_loop.make_sender("/test").unwrap();
32 let mut interval = event_loop.add_interval(Duration::from_micros(sleep));
33
34 let on_run = event_loop.on_run();
35 on_run.borrow().await;
36
37 loop {
38 interval.tick().await;
39 self.counter.set(self.counter.get() + 1);
40 let mut builder = ping_sender.make_builder();
41 let mut ping = ping::PingBuilder::new(builder.fbb());
42 let iter = self.counter.get();
43 ping.add_value(iter);
44 ping.add_send_time(event_loop.monotonic_now().into());
45 let ping = ping.finish();
46 builder.send(ping).expect("Can't send ping");
47 }
48 }
49
50 pub async fn handle_pong(&self, event_loop: &EventLoopRuntime<'_>) -> Never {
51 // The watcher gives us incoming ping messages.
52 let mut pong_watcher: Watcher<pong::Pong> = event_loop.make_watcher("/test").unwrap();
53
54 let on_run = event_loop.on_run();
55 on_run.borrow().await;
56 loop {
57 let pong = pong_watcher.next().await;
58 assert_eq!(
59 pong.message().unwrap().value(),
60 self.counter.get(),
61 "Missed a reply"
62 );
63 }
64 }
65}