blob: b9725b84abc08151c480db3a68530b30542cbb0e [file] [log] [blame]
Adam Snaider43516782023-06-26 15:14:18 -07001use aos_configuration as config;
2use aos_events_event_loop_runtime::{EventLoopRuntime, Sender, Watcher};
3use aos_events_shm_event_loop::ShmEventLoop;
4use core::cell::Cell;
5use core::future::Future;
6use core::time::Duration;
7use futures::never::Never;
8use std::path::Path;
9
10use ping_rust_fbs::aos::examples as ping;
11use pong_rust_fbs::aos::examples as pong;
12
13fn main() {
14 aos_init::init();
15 let config = config::read_config_from(Path::new("pingpong_config.json")).unwrap();
16 let ping = PingTask::new();
17 ShmEventLoop::new(&config).run_with(|runtime| {
18 let task = ping.tasks(runtime);
19 runtime.spawn(task);
20 });
21}
22
23#[derive(Debug)]
24struct PingTask {
25 counter: Cell<i32>,
26}
27
28impl PingTask {
29 pub fn new() -> Self {
30 Self {
31 counter: Cell::new(0),
32 }
33 }
34
35 /// Returns a future with all the tasks for the ping process
36 pub fn tasks(&self, event_loop: &mut EventLoopRuntime) -> impl Future<Output = Never> + '_ {
37 let ping = self.ping(event_loop);
38 let handle_pong = self.handle_pong(event_loop);
39
40 async move {
41 futures::join!(ping, handle_pong);
42 unreachable!("Let's hope `never_type` gets stabilized soon :)");
43 }
44 }
45
46 fn ping(&self, event_loop: &mut EventLoopRuntime) -> impl Future<Output = Never> + '_ {
47 // The sender is used to send messages back to the pong channel.
48 let mut ping_sender: Sender<ping::Ping> = event_loop.make_sender("/test").unwrap();
49 let startup = event_loop.on_run();
50
51 let mut interval = event_loop.add_interval(Duration::from_secs(1));
52
53 async move {
54 // Wait for startup.
55 startup.await;
56 loop {
57 interval.tick().await;
58 self.counter.set(self.counter.get() + 1);
59 let mut builder = ping_sender.make_builder();
60 let mut ping = ping::PingBuilder::new(builder.fbb());
61 let iter = self.counter.get();
62 ping.add_value(iter);
63 let ping = ping.finish();
64 builder.send(ping).expect("Can't send ping");
65 }
66 }
67 }
68
69 fn handle_pong(&self, event_loop: &mut EventLoopRuntime) -> impl Future<Output = Never> + '_ {
70 // The watcher gives us incoming ping messages.
71 let mut pong_watcher: Watcher<pong::Pong> = event_loop.make_watcher("/test").unwrap();
72 let startup = event_loop.on_run();
73
74 async move {
75 // Wait for startup.
76 startup.await;
77 loop {
78 let pong = dbg!(pong_watcher.next().await);
79 assert_eq!(
80 pong.message().unwrap().value(),
81 self.counter.get(),
82 "Missed a reply"
83 );
84 }
85 }
86 }
87}