Austin Schuh | 6b9c415 | 2019-11-29 12:45:24 -0800 | [diff] [blame^] | 1 | #include "aos/events/ping_lib.h" |
| 2 | |
| 3 | #include "aos/events/pong_generated.h" |
| 4 | #include "aos/events/ping_generated.h" |
| 5 | #include "aos/json_to_flatbuffer.h" |
| 6 | #include "gflags/gflags.h" |
| 7 | #include "glog/logging.h" |
| 8 | |
| 9 | DEFINE_int32(sleep_ms, 10, "Time to sleep between pings"); |
| 10 | |
| 11 | namespace aos { |
| 12 | |
| 13 | namespace chrono = std::chrono; |
| 14 | |
| 15 | Ping::Ping(EventLoop *event_loop) |
| 16 | : event_loop_(event_loop), |
| 17 | sender_(event_loop_->MakeSender<examples::Ping>("/test")) { |
| 18 | timer_handle_ = event_loop_->AddTimer([this]() { SendPing(); }); |
| 19 | |
| 20 | event_loop_->MakeWatcher( |
| 21 | "/test", [this](const examples::Pong &pong) { HandlePong(pong); }); |
| 22 | |
| 23 | event_loop_->OnRun([this]() { |
| 24 | timer_handle_->Setup(event_loop_->monotonic_now(), |
| 25 | chrono::milliseconds(FLAGS_sleep_ms)); |
| 26 | }); |
| 27 | |
| 28 | event_loop_->SetRuntimeRealtimePriority(5); |
| 29 | } |
| 30 | |
| 31 | void Ping::SendPing() { |
| 32 | ++count_; |
| 33 | aos::Sender<examples::Ping>::Builder msg = sender_.MakeBuilder(); |
| 34 | examples::Ping::Builder builder = msg.MakeBuilder<examples::Ping>(); |
| 35 | builder.add_value(count_); |
| 36 | builder.add_send_time( |
| 37 | event_loop_->monotonic_now().time_since_epoch().count()); |
| 38 | CHECK(msg.Send(builder.Finish())); |
| 39 | VLOG(2) << "Sending ping"; |
| 40 | } |
| 41 | |
| 42 | void Ping::HandlePong(const examples::Pong &pong) { |
| 43 | const aos::monotonic_clock::time_point monotonic_send_time( |
| 44 | chrono::nanoseconds(pong.initial_send_time())); |
| 45 | const aos::monotonic_clock::time_point monotonic_now = |
| 46 | event_loop_->monotonic_now(); |
| 47 | |
| 48 | const chrono::nanoseconds round_trip_time = |
| 49 | monotonic_now - monotonic_send_time; |
| 50 | |
| 51 | if (pong.value() == count_) { |
| 52 | VLOG(1) << "Elapsed time " << round_trip_time.count() << " ns " |
| 53 | << FlatbufferToJson(&pong); |
| 54 | } else { |
| 55 | VLOG(1) << "Missmatched pong message"; |
| 56 | } |
| 57 | } |
| 58 | } // namespace aos |