TokenBucket.hpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // ======================================================================
  2. // \title TokenBucket.hpp
  3. // \author vwong
  4. // \brief hpp file for a rate limiter utility class
  5. //
  6. // \copyright
  7. //
  8. // Copyright (C) 2009-2020 California Institute of Technology.
  9. //
  10. // ALL RIGHTS RESERVED. United States Government Sponsorship
  11. // acknowledged.
  12. // ======================================================================
  13. #ifndef TokenBucket_HPP
  14. #define TokenBucket_HPP
  15. #include <FpConfig.hpp>
  16. #include <Fw/Time/Time.hpp>
  17. #define MAX_TOKEN_BUCKET_TOKENS 1000
  18. namespace Utils {
  19. class TokenBucket
  20. {
  21. public:
  22. // Full constructor
  23. //
  24. // replenishInterval is in microseconds
  25. //
  26. TokenBucket(U32 replenishInterval, U32 maxTokens, U32 replenishRate, U32 startTokens, Fw::Time startTime);
  27. // replenishRate=1, startTokens=maxTokens, startTime=0
  28. TokenBucket(U32 replenishInterval, U32 maxTokens);
  29. public:
  30. // Adjust settings at runtime
  31. void setMaxTokens(U32 maxTokens);
  32. void setReplenishInterval(U32 replenishInterval);
  33. void setReplenishRate(U32 replenishRate);
  34. U32 getMaxTokens() const;
  35. U32 getReplenishInterval() const;
  36. U32 getReplenishRate() const;
  37. U32 getTokens() const;
  38. // Manual replenish
  39. void replenish();
  40. // Main point of entry
  41. //
  42. // Evaluates time since last trigger to determine number of tokens to
  43. // replenish. If time moved backwards, always returns false.
  44. //
  45. // If number of tokens is not zero, consumes one and returns true.
  46. // Otherwise, returns false.
  47. //
  48. bool trigger(const Fw::Time time);
  49. private:
  50. // parameters
  51. U32 m_replenishInterval;
  52. U32 m_maxTokens;
  53. U32 m_replenishRate;
  54. // state
  55. U32 m_tokens;
  56. Fw::Time m_time;
  57. };
  58. } // end namespace Utils
  59. #endif