C++11 Timer API

This commit is contained in:
Pavel Kirienko
2014-03-27 13:52:41 +04:00
parent c4e0404d02
commit 5157f9182e
3 changed files with 87 additions and 4 deletions
+34 -1
View File
@@ -5,12 +5,21 @@
#pragma once
#include <uavcan/stdint.hpp>
#include <uavcan/impl_constants.hpp>
#include <uavcan/node/scheduler.hpp>
#include <uavcan/util/compile_time.hpp>
#include <uavcan/node/abstract_node.hpp>
#include <uavcan/util/compile_time.hpp>
#include <uavcan/linked_list.hpp>
#include <uavcan/fatal_error.hpp>
#if !defined(UAVCAN_CPP11) || !defined(UAVCAN_CPP_VERSION)
# error UAVCAN_CPP_VERSION
#endif
#if UAVCAN_CPP_VERSION >= UAVCAN_CPP11
# include <functional>
#endif
namespace uavcan
{
@@ -87,4 +96,28 @@ public:
void setCallback(const Callback& callback) { callback_ = callback; }
};
#if UAVCAN_CPP_VERSION >= UAVCAN_CPP11
class Timer : public TimerBase
{
void handleTimerEvent(const TimerEvent& event);
public:
typedef std::function<void (const TimerEvent& event)> Callback;
explicit Timer(INode& node)
: TimerBase(node)
{ }
Timer(INode& node, const Callback& callback)
: TimerBase(node)
, callback(callback)
{ }
Callback callback;
};
#endif
}
+22 -1
View File
@@ -7,7 +7,9 @@
namespace uavcan
{
/*
* TimerBase
*/
void TimerBase::handleDeadline(MonotonicTime current)
{
assert(!isRunning());
@@ -45,4 +47,23 @@ void TimerBase::startPeriodic(MonotonicDuration period)
DeadlineHandler::startWithDelay(period);
}
/*
* Timer
*/
#if UAVCAN_CPP_VERSION >= UAVCAN_CPP11
void Timer::handleTimerEvent(const TimerEvent& event)
{
if (callback)
{
callback(event);
}
else
{
assert(0);
}
}
#endif
}
+31 -2
View File
@@ -9,6 +9,10 @@
#include "../transport/can/can.hpp"
#include "test_node.hpp"
#if !defined(UAVCAN_CPP11) || !defined(UAVCAN_CPP_VERSION)
# error UAVCAN_CPP_VERSION
#endif
struct TimerCallCounter
{
std::vector<uavcan::TimerEvent> events_a;
@@ -82,6 +86,31 @@ TEST(Scheduler, Timers)
ASSERT_EQ(1000, b.getPeriod().toUSec());
}
ASSERT_EQ(0, node.getScheduler().getDeadlineScheduler().getNumHandlers()); // Both timers were destroyed now
ASSERT_EQ(0, node.spin(durMono(1000))); // Spin some more without timers
ASSERT_EQ(0, node.getScheduler().getDeadlineScheduler().getNumHandlers()); // Both timers were destroyed by now
ASSERT_EQ(0, node.spin(durMono(1000))); // Spin some more without timers
}
#if UAVCAN_CPP_VERSION >= UAVCAN_CPP11
TEST(Scheduler, TimerCpp11)
{
SystemClockDriver clock_driver;
CanDriverMock can_driver(2, clock_driver);
TestNode node(can_driver, clock_driver, 1);
int count = 0;
uavcan::Timer tm(node, [&count](const uavcan::TimerEvent&) { count++; });
ASSERT_EQ(0, node.getScheduler().getDeadlineScheduler().getNumHandlers());
tm.startPeriodic(uavcan::MonotonicDuration::fromMSec(10));
ASSERT_EQ(1, node.getScheduler().getDeadlineScheduler().getNumHandlers());
ASSERT_EQ(0, node.spin(uavcan::MonotonicDuration::fromMSec(100)));
std::cout << count << std::endl;
ASSERT_LE(5, count);
ASSERT_GE(15, count);
}
#endif