blob: ce4d8441f65fc21a4b95313136418aa59f4dca5d [file] [log] [blame]
Adam Snaidercc622812023-11-07 17:59:27 -08001use aos::events::event_loop_runtime::{EventLoopRuntime, Sender, Watcher};
Adam Snaiderc5bdbd32023-10-19 18:20:56 -06002use 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();
Adam Snaider9121b302023-12-14 15:30:54 -080043 log::trace!("Ping: {iter}");
Adam Snaiderc5bdbd32023-10-19 18:20:56 -060044 ping.add_value(iter);
45 ping.add_send_time(event_loop.monotonic_now().into());
46 let ping = ping.finish();
47 builder.send(ping).expect("Can't send ping");
48 }
49 }
50
51 pub async fn handle_pong(&self, event_loop: &EventLoopRuntime<'_>) -> Never {
52 // The watcher gives us incoming ping messages.
53 let mut pong_watcher: Watcher<pong::Pong> = event_loop.make_watcher("/test").unwrap();
54
55 let on_run = event_loop.on_run();
56 on_run.borrow().await;
57 loop {
58 let pong = pong_watcher.next().await;
Adam Snaider9121b302023-12-14 15:30:54 -080059 let pong = pong.message().unwrap();
60 log::trace!("Got pong: {}", pong.value());
61 assert_eq!(pong.value(), self.counter.get(), "Missed a reply");
Adam Snaiderc5bdbd32023-10-19 18:20:56 -060062 }
63 }
64}