Instead of a global pointer, config is now a Singleton.
[apps/agl-service-can-low-level.git] / src / utils / timer.cpp
1 /*
2  * Copyright (C) 2015, 2016 "IoT.bzh"
3  * Author "Romain Forlot" <romain.forlot@iot.bzh>
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *       http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #include <stdlib.h> 
19
20 #include "timer.hpp"
21
22 #define MS_PER_SECOND 1000
23
24 long long int system_time_ms()
25 {
26         struct timeb t_msec;
27         long long int timestamp_msec;
28         
29         if(!::ftime(&t_msec))
30         {
31                 timestamp_msec = (t_msec.time) * 1000ll + 
32                         t_msec.millitm;
33         }
34         return timestamp_msec;
35 }
36
37 frequency_clock_t::frequency_clock_t()
38         : frequency_{0.0}, last_tick_{0}, time_function_{nullptr}
39 {}
40
41
42 frequency_clock_t::frequency_clock_t(float frequency)
43         : frequency_{frequency}, last_tick_{0}, time_function_{nullptr}
44 {}
45
46 /// @brief Return the period in ms given the frequency in hertz.
47 float frequency_clock_t::frequency_to_period(float frequency)
48 {
49         return 1 / frequency * MS_PER_SECOND;
50 }
51
52 bool frequency_clock_t::started()
53 {
54         return last_tick_ != 0;
55 }
56
57 time_function_t frequency_clock_t::get_time_function()
58 {
59         return time_function_ != nullptr ? time_function_ : system_time_ms;
60 }
61
62 bool frequency_clock_t::elapsed(bool stagger)
63 {
64         float period = frequency_to_period(frequency_);
65         float elapsed_time = 0;
66         if(!started() && stagger)
67                 last_tick_ = get_time_function()() - (rand() % int(period));
68         else
69                 // Make sure it ticks the the first call to conditionalTick(...)
70                 elapsed_time = !started() ? period : get_time_function()() - last_tick_;
71
72         return frequency_ == 0 || elapsed_time >= period;
73 }