Vanetza
Loading...
Searching...
No Matches
asio_event_port.cpp
1#include "vanetza/rpc/asio_event_port.hpp"
2
3#include <boost/asio/post.hpp>
4#include <chrono>
5
6namespace vanetza
7{
8namespace rpc
9{
10
11AsioEventPort::AsioEventPort(boost::asio::io_context& io) :
12 io_(io),
13 steady_timer_(io_),
14 clock_(kj::systemPreciseMonotonicClock()),
15 timer_(clock_.now())
16{
17}
18
19bool AsioEventPort::wait()
20{
21 io_.run_one();
22 advanceTime();
23 armTimeout();
24 return false;
25}
26
27bool AsioEventPort::poll()
28{
29 io_.poll();
30 advanceTime();
31 return false;
32}
33
34void AsioEventPort::setRunnable(bool runnable)
35{
36 if (runnable && loop_) {
37 boost::asio::post(io_, [this]() {
38 if (loop_ && loop_->isRunnable()) {
39 loop_->run();
40 }
41 });
42 }
43}
44
45void AsioEventPort::advanceTime()
46{
47 timer_.advanceTo(clock_.now());
48}
49
50void AsioEventPort::armTimeout()
51{
52 std::chrono::nanoseconds dt {
53 timer_.timeoutToNextEvent(clock_.now(), kj::NANOSECONDS, kj::maxValue)
54 .map([](uint64_t ns) { return ns; })
55 .orDefault(0)
56 };
57 if (dt > std::chrono::nanoseconds::zero()) {
58 steady_timer_.expires_after(dt);
59 steady_timer_.async_wait([this](const boost::system::error_code& ec) {
60 if (!ec) {
61 advanceTime();
62 }
63 });
64 }
65}
66
67} // namespace rpc
68} // namespace vanetza