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