blob: c4b3679766dabc4dead0c0f1be60ada30aa0cc38 [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
23 pub async fn tasks(&self, event_loop: EventLoopRuntime<'_>, sleep: u64) -> Never {
24 futures::join!(self.ping(&event_loop, sleep), self.handle_pong(&event_loop));
25 unreachable!("Let's hope `never_type` gets stabilized soon :)");
26 }
27
28 pub async fn ping(&self, event_loop: &EventLoopRuntime<'_>, sleep: u64) -> Never {
29 // The sender is used to send messages back to the pong channel.
30 let mut ping_sender: Sender<ping::Ping> = event_loop.make_sender("/test").unwrap();
31 let mut interval = event_loop.add_interval(Duration::from_micros(sleep));
32
33 let on_run = event_loop.on_run();
34 on_run.borrow().await;
35
36 loop {
37 interval.tick().await;
38 self.counter.set(self.counter.get() + 1);
39 let mut builder = ping_sender.make_builder();
40 let mut ping = ping::PingBuilder::new(builder.fbb());
41 let iter = self.counter.get();
42 ping.add_value(iter);
43 ping.add_send_time(event_loop.monotonic_now().into());
44 let ping = ping.finish();
45 builder.send(ping).expect("Can't send ping");
46 }
47 }
48
49 pub async fn handle_pong(&self, event_loop: &EventLoopRuntime<'_>) -> Never {
50 // The watcher gives us incoming ping messages.
51 let mut pong_watcher: Watcher<pong::Pong> = event_loop.make_watcher("/test").unwrap();
52
53 let on_run = event_loop.on_run();
54 on_run.borrow().await;
55 loop {
56 let pong = pong_watcher.next().await;
57 assert_eq!(
58 pong.message().unwrap().value(),
59 self.counter.get(),
60 "Missed a reply"
61 );
62 }
63 }
64}