fsfw/src/fsfw/timemanager/Countdown.h

98 lines
2.4 KiB
C++

#ifndef FSFW_TIMEMANAGER_COUNTDOWN_H_
#define FSFW_TIMEMANAGER_COUNTDOWN_H_
#include "Clock.h"
/**
*
* Countdown keeps track of a timespan.
* This class uses the system clock internally to achieve
* a high resolution. This means that the API is only partially
* resistant against time jumps. The user must take care to account
* for time jumps in some from if this relevant.
*
* Countdown::resetTimer restarts the timer.
* Countdown::setTimeout sets a new countdown duration and resets.
*
* Can be checked with Countdown::hasTimedOut or
* Countdown::isBusy.
*
* Countdown::timeOut will force the timer to time out.
*
*/
class Countdown {
public:
/**
* Constructor which sets the countdown duration in milliseconds
*
* It does not start the countdown!
* Call resetTimer or setTimeout before usage!
* Otherwise a call to hasTimedOut might return True.
*
* @param initialTimeout Countdown duration in milliseconds
* @param startImmediately Set to false if countdown should not be started immediately
*/
Countdown(uint32_t initialTimeout = 0, bool startImmediately = true);
~Countdown();
/**
* Call to set a new countdown duration.
*
* Resets the countdown!
*
* @param milliseconds new countdown duration in milliseconds
* @return Returnvalue from Clock::getUptime
*/
ReturnValue_t setTimeout(uint32_t milliseconds);
ReturnValue_t setTimeoutTv(timeval tv);
/**
* Returns true if the countdown duration has passed.
*
* @return True if the countdown has passed
* False if it is still running
*/
bool hasTimedOut() const;
/**
* Complementary to hasTimedOut.
*
* @return True if the countdown is till running
* False if it is still running
*/
bool isBusy() const;
/**
* Uses last set timeout value and restarts timer.
*/
ReturnValue_t resetTimer();
/**
* Returns the remaining milliseconds (0 if timeout)
*/
uint32_t getRemainingMillis() const;
uint32_t getTimeoutMs() const;
timeval getTimeout() const;
/**
* Makes hasTimedOut() return true
*/
void timeOut();
static inline uint32_t timevalToMs(timeval& tv);
private:
/**
* Start time of the countdown.
*/
timeval startTime{};
/**
* Timeout as timeval type. The countdown has timed out when the
* current time exceeds the start time plus the timeout.
*/
timeval timeout{};
timeval getCurrentTime() const;
};
#endif /* FSFW_TIMEMANAGER_COUNTDOWN_H_ */