RateLimiter.hpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // ======================================================================
  2. // \title RateLimiter.hpp
  3. // \author vwong
  4. // \brief hpp file for a rate limiter utility class
  5. //
  6. // \copyright
  7. // Copyright (C) 2009-2020 California Institute of Technology.
  8. //
  9. // ALL RIGHTS RESERVED. United States Government Sponsorship
  10. // acknowledged.
  11. // ======================================================================
  12. #ifndef RateLimiter_HPP
  13. #define RateLimiter_HPP
  14. #include <FpConfig.hpp>
  15. #include <Fw/Time/Time.hpp>
  16. namespace Utils {
  17. class RateLimiter
  18. {
  19. public:
  20. // Construct with defined cycles
  21. RateLimiter(U32 counterCycle, U32 timeCycle);
  22. // Construct with cycles set to 0
  23. RateLimiter();
  24. public:
  25. // Adjust cycles at run-time
  26. void setCounterCycle(U32 counterCycle);
  27. void setTimeCycle(U32 timeCycle);
  28. // Main point of entry
  29. //
  30. // It will only factor in counter or time, whichever one has a cycle defined
  31. //
  32. // If both are defined, then satisfying _either_ one will work
  33. // e.g. I want to trigger only once every X times or once every Y
  34. // seconds, whichever comes first
  35. //
  36. // The argument-less version is a shorthand for counter-only RateLimiters
  37. // If a time cycle is defined but the argument-less version is called,
  38. // RateLimiter assumes the client forgot to supply a time, and asserts
  39. //
  40. bool trigger(Fw::Time time);
  41. bool trigger();
  42. // Manual state adjustments, if necessary
  43. void reset();
  44. void resetCounter();
  45. void resetTime();
  46. void setCounter(U32);
  47. void setTime(Fw::Time time);
  48. private:
  49. // Helper functions to update each independently
  50. bool shouldCounterTrigger();
  51. bool shouldTimeTrigger(Fw::Time time);
  52. void updateCounter(bool triggered);
  53. void updateTime(bool triggered, Fw::Time time);
  54. private:
  55. // parameters
  56. U32 m_counterCycle;
  57. U32 m_timeCycle;
  58. // state
  59. U32 m_counter;
  60. Fw::Time m_time;
  61. bool m_timeAtNegativeInfinity;
  62. };
  63. } // end namespace Utils
  64. #endif