]> rtime.felk.cvut.cz Git - CanFestival-3.git/blob - drivers/timers_unix/timers_unix.c
Win32 Native support and dynamicaly loaded CAN drivers for Linux, Cygwin and Win32.
[CanFestival-3.git] / drivers / timers_unix / timers_unix.c
1 #include <stdlib.h>
2
3 #include <sys/time.h>
4 #include <pthread.h> 
5 #include <signal.h>
6
7 #include "applicfg.h"
8 #include "timer.h"
9
10 pthread_mutex_t CanFestival_mutex = PTHREAD_MUTEX_INITIALIZER;
11
12 TASK_HANDLE TimerLoopThread;
13
14 TIMEVAL last_time_set = TIMEVAL_MAX;
15
16 struct timeval last_sig;
17
18 timer_t timer;
19
20 void EnterMutex(void)
21 {
22         pthread_mutex_lock(&CanFestival_mutex); 
23 }
24
25 void LeaveMutex(void)
26 {
27         pthread_mutex_unlock(&CanFestival_mutex);
28 }
29
30 void timer_notify(sigval_t val)
31 {
32         gettimeofday(&last_sig,NULL);
33         EnterMutex();
34         TimeDispatch();
35         LeaveMutex();
36 //      printf("getCurrentTime() return=%u\n", p.tv_usec);
37 }
38
39 void initTimer(void)
40 {
41         struct sigevent sigev;
42
43         // Take first absolute time ref.
44         gettimeofday(&last_sig,NULL);
45
46         memset (&sigev, 0, sizeof (struct sigevent));
47         sigev.sigev_value.sival_int = 0;
48         sigev.sigev_notify = SIGEV_THREAD;
49         sigev.sigev_notify_attributes = NULL;
50         sigev.sigev_notify_function = timer_notify;
51
52         timer_create (CLOCK_REALTIME, &sigev, &timer);
53 }
54
55 void StopTimerLoop(void)
56 {
57         timer_delete (timer);
58 }
59
60 void StartTimerLoop(TimerCallback_t init_callback)
61 {
62         initTimer();
63         // At first, TimeDispatch will call init_callback.
64         SetAlarm(NULL, 0, init_callback, 0, 0);
65 }
66
67 void CreateReceiveTask(CAN_PORT port, TASK_HANDLE* Thread, void* ReceiveLoopPtr)
68 {
69         pthread_create(Thread, NULL, ReceiveLoopPtr, (void*)port);
70 }
71
72 void WaitReceiveTaskEnd(TASK_HANDLE Thread)
73 {
74         pthread_kill(Thread, SIGTERM);
75         pthread_join(Thread, NULL);
76 }
77
78 #define maxval(a,b) ((a>b)?a:b)
79 void setTimer(TIMEVAL value)
80 {
81 //      printf("setTimer(TIMEVAL value=%d)\n", value);
82         // TIMEVAL is us whereas setitimer wants ns...
83         long tv_nsec = 1000 * (maxval(value,1)%1000000);
84         time_t tv_sec = value/1000000;
85         struct itimerspec timerValues;
86         timerValues.it_value.tv_sec = tv_sec;
87         timerValues.it_value.tv_nsec = tv_nsec;
88         timerValues.it_interval.tv_sec = 0;
89         timerValues.it_interval.tv_nsec = 0;
90
91         timer_settime (timer, 0, &timerValues, NULL);
92 }
93
94 TIMEVAL getElapsedTime(void)
95 {
96         struct timeval p;
97         gettimeofday(&p,NULL);
98 //      printf("getCurrentTime() return=%u\n", p.tv_usec);
99         return (p.tv_sec - last_sig.tv_sec)* 1000000 + p.tv_usec - last_sig.tv_usec;
100 }