Adding needed function to get some time handle on request
authorRomain Forlot <romain.forlot@iot.bzh>
Fri, 10 Mar 2017 01:02:00 +0000 (02:02 +0100)
committerRomain Forlot <romain.forlot@iot.bzh>
Thu, 16 Mar 2017 16:10:40 +0000 (17:10 +0100)
for diagnostic at first.

Change-Id: I3ab966d6386bad52f68ebdbea723bb7507cfaf2a
Signed-off-by: Romain Forlot <romain.forlot@iot.bzh>
src/utils/timer.cpp
src/utils/timer.hpp

index 433fcb2..966178b 100644 (file)
  * limitations under the License.
  */
 
+#include <stdlib.h> 
+
 #include "timer.hpp"
 
-long long int systemTimeMs()
+#define MS_PER_SECOND 1000
+
+long long int system_time_ms()
 {
        struct timeb t_msec;
        long long int timestamp_msec;
@@ -30,7 +34,40 @@ long long int systemTimeMs()
        return timestamp_msec;
 }
 
-
 frequency_clock_t::frequency_clock_t()
        : frequency_{0.0}, last_tick_{0}, time_function_{nullptr}
-{}
\ No newline at end of file
+{}
+
+
+frequency_clock_t::frequency_clock_t(float frequency)
+       : frequency_{frequency}, last_tick_{0}, time_function_{nullptr}
+{}
+
+/// @brief Return the period in ms given the frequency in hertz.
+float frequency_clock_t::frequency_to_period(float frequency)
+{
+       return 1 / frequency * MS_PER_SECOND;
+}
+
+bool frequency_clock_t::started()
+{
+       return last_tick_ != 0;
+}
+
+time_function_t frequency_clock_t::get_time_function()
+{
+       return time_function_ != nullptr ? time_function_ : system_time_ms;
+}
+
+bool frequency_clock_t::elapsed(bool stagger)
+{
+       float period = frequency_to_period(frequency_);
+       float elapsed_time = 0;
+       if(!started() && stagger)
+               last_tick_ = get_time_function()() - (rand() % int(period));
+       else
+               // Make sure it ticks the the first call to conditionalTick(...)
+               elapsed_time = !started() ? period : get_time_function()() - last_tick_;
+
+       return frequency_ == 0 || elapsed_time >= period;
+}
index a3cbecd..8037b85 100644 (file)
  *
  * @return long long int epoch in milliseconds
  */
-typedef long long int (*TimeFunction)();
+typedef long long int (*time_function_t)();
+
+
+long long int system_time_ms();
 
 /**
  * @class frequency_clock_t 
@@ -43,8 +46,14 @@ class frequency_clock_t
 private:
        float frequency_;
        unsigned long last_tick_;
-       TimeFunction time_function_;
+       time_function_t time_function_;
 
 public:
        frequency_clock_t();
+       frequency_clock_t(float frequency);
+
+       static float frequency_to_period(float frequency);
+       bool started();
+       time_function_t get_time_function();
+       bool elapsed(bool stagger);
 };
\ No newline at end of file