blob: b904cb281b177a494467597a031005634b4b3f05 [file] [log] [blame]
Alex Perrycb7da4b2019-08-28 19:35:56 -07001#include <chrono>
2
3#include "aos/configuration.h"
4#include "aos/events/pingpong_generated.h"
5#include "aos/events/shm_event_loop.h"
6#include "aos/init.h"
7#include "aos/json_to_flatbuffer.h"
8#include "gflags/gflags.h"
9#include "glog/logging.h"
10
11DEFINE_int32(sleep_ms, 10, "Time to sleep between pings");
12
13namespace aos {
14
15namespace chrono = std::chrono;
16
17class Ping {
18 public:
19 Ping(EventLoop *event_loop)
20 : event_loop_(event_loop),
21 sender_(event_loop_->MakeSender<examples::Ping>("/test")) {
22 timer_handle_ = event_loop_->AddTimer([this]() { SendPing(); });
23
24 event_loop_->MakeWatcher(
25 "/test", [this](const examples::Pong &pong) { HandlePong(pong); });
26
27 event_loop_->OnRun([this]() {
28 timer_handle_->Setup(event_loop_->monotonic_now(),
29 chrono::milliseconds(FLAGS_sleep_ms));
30 });
31
32 event_loop_->SetRuntimeRealtimePriority(5);
33 }
34
35 void SendPing() {
36 ++count_;
37 aos::Sender<examples::Ping>::Builder msg = sender_.MakeBuilder();
38 examples::Ping::Builder builder = msg.MakeBuilder<examples::Ping>();
39 builder.add_value(count_);
40 builder.add_send_time(
41 event_loop_->monotonic_now().time_since_epoch().count());
42 CHECK(msg.Send(builder.Finish()));
43 VLOG(2) << "Sending ping";
44 }
45
46 void HandlePong(const examples::Pong &pong) {
47 const aos::monotonic_clock::time_point monotonic_send_time(
48 chrono::nanoseconds(pong.initial_send_time()));
49 const aos::monotonic_clock::time_point monotonic_now =
50 event_loop_->monotonic_now();
51
52 const chrono::nanoseconds round_trip_time =
53 monotonic_now - monotonic_send_time;
54
55 if (pong.value() == count_) {
56 VLOG(1) << "Elapsed time " << round_trip_time.count() << " ns "
57 << FlatbufferToJson(&pong);
58 } else {
59 VLOG(1) << "Missmatched pong message";
60 }
61 }
62
63 private:
64 EventLoop *event_loop_;
65 aos::Sender<examples::Ping> sender_;
66 TimerHandler *timer_handle_;
67 int count_ = 0;
68};
69
70} // namespace aos
71
72int main(int argc, char **argv) {
73 FLAGS_logtostderr = true;
74 google::InitGoogleLogging(argv[0]);
75 ::gflags::ParseCommandLineFlags(&argc, &argv, true);
76
77 aos::FlatbufferDetachedBuffer<aos::Configuration> config =
78 aos::configuration::ReadConfig("aos/events/config.fb.json");
79
80 ::aos::ShmEventLoop event_loop(&config.message());
81
82 aos::Ping ping(&event_loop);
83
84 event_loop.Run();
85
86 ::aos::Cleanup();
87 return 0;
88}