#include "timer_adapter.hpp" namespace timerlab { TimerAdapter::TimerAdapter(ServicePort &port) : port_(port) { } TimerAdapter::~TimerAdapter() { stop(); } int TimerAdapter::start(int timeout, int gain, int route) { if (timeout < 1 || timeout > 1000 || gain < -100 || gain > 100 || route < 0 || route > 15) { return -2; } if (state_.running) { return -3; } state_ = AdapterView{}; journal_.clear(); current_ = Result{}; deadline_ = 0; timeout_ = static_cast(timeout); gain_ = gain; route_ = static_cast(route); state_.running = true; return 0; } int TimerAdapter::callback(std::int64_t payload, int delay, int failure) { if (payload < -1000000 || payload > 1000000 || delay < 0 || delay > 1000 || failure < 0 || failure > 1) { return -2; } ++state_.callbacks; collect(); if (!state_.running) { return 2; } if (state_.pending) { ++state_.skipped; return 1; } if (client_ == 0) { client_ = port_.create(); } if (client_ == 0) { ++state_.rejected; return -1; } current_ = Result{state_.next_sequence, payload, 0, 0}; const int sent = port_.send(client_, current_.sequence, payload, static_cast(delay), failure != 0, gain_, route_); if (sent != 0) { ++state_.rejected; return -1; } ++state_.launched; ++state_.next_sequence; state_.pending = true; deadline_ = port_.now() + timeout_; return 0; } void TimerAdapter::finish(int status, std::int64_t value) { current_.status = status; current_.value = value; journal_.push_back(current_); state_.pending = false; port_.destroy(client_); client_ = 0; } void TimerAdapter::collect() { if (!state_.pending) { return; } Reply reply; const int received = port_.receive(client_, reply); if (received == 0) { finish(reply.status, reply.value); } else if (received == 1 && port_.now() >= deadline_) { port_.cancel(client_); finish(2, 0); } } void TimerAdapter::stop() { if (state_.pending) { port_.cancel(client_); finish(3, 0); } if (client_ != 0) { port_.destroy(client_); client_ = 0; } state_.running = false; } AdapterView TimerAdapter::view() const { AdapterView computed = state_; computed.succeeded = computed.failed = computed.timed_out = computed.canceled = 0; for (const Result &record : journal_) { switch (record.status) { case 0: ++computed.succeeded; break; case 1: ++computed.failed; break; case 2: ++computed.timed_out; break; case 3: ++computed.canceled; break; } } return computed; } const std::vector &TimerAdapter::results() const { return journal_; } }