0
|
1 |
#include <stdlib.h>
|
|
2 |
|
|
3 |
#include <sys/time.h>
|
|
4 |
#include <signal.h>
|
|
5 |
#include <pthread.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 |
TIMEVAL last_time_set = TIMEVAL_MAX;
|
|
14 |
|
|
15 |
struct timeval last_sig;
|
|
16 |
|
|
17 |
char stop_timer=0;
|
|
18 |
|
|
19 |
void sig(int val)
|
|
20 |
{
|
|
21 |
signal( SIGALRM, sig);
|
|
22 |
gettimeofday(&last_sig,NULL);
|
|
23 |
// printf("getCurrentTime() return=%u\n", p.tv_usec);
|
|
24 |
}
|
|
25 |
|
|
26 |
void initTimer(void)
|
|
27 |
{
|
|
28 |
gettimeofday(&last_sig,NULL);
|
|
29 |
signal( SIGALRM, sig);
|
|
30 |
stop_timer = 0;
|
|
31 |
}
|
|
32 |
|
|
33 |
void stopTimer(void)
|
|
34 |
{
|
|
35 |
stop_timer = 1;
|
|
36 |
kill(0, SIGALRM);
|
|
37 |
}
|
|
38 |
|
|
39 |
void EnterMutex(void)
|
|
40 |
{
|
|
41 |
pthread_mutex_lock(&CanFestival_mutex);
|
|
42 |
}
|
|
43 |
|
|
44 |
void LeaveMutex(void)
|
|
45 |
{
|
|
46 |
pthread_mutex_unlock(&CanFestival_mutex);
|
|
47 |
}
|
|
48 |
|
|
49 |
void TimerLoop(TimerCallback_t init_callback)
|
|
50 |
{
|
|
51 |
initTimer();
|
|
52 |
// At first, TimeDispatch will call init_callback.
|
|
53 |
SetAlarm(NULL, 0, init_callback, 0, 0);
|
|
54 |
while (!stop_timer) {
|
|
55 |
EnterMutex();
|
|
56 |
TimeDispatch();
|
|
57 |
LeaveMutex();
|
|
58 |
pause();
|
|
59 |
}
|
|
60 |
}
|
|
61 |
|
|
62 |
void ReceiveLoop(void* arg)
|
|
63 |
{
|
|
64 |
canReceiveLoop((CAN_HANDLE)arg);
|
|
65 |
}
|
|
66 |
|
|
67 |
void CreateReceiveTask(CAN_HANDLE fd0, TASK_HANDLE* Thread)
|
|
68 |
{
|
|
69 |
pthread_create(Thread, NULL, (void *)&ReceiveLoop, (void*)fd0);
|
|
70 |
}
|
|
71 |
|
|
72 |
void WaitReceiveTaskEnd(TASK_HANDLE Thread)
|
|
73 |
{
|
|
74 |
pthread_join(Thread, NULL);
|
|
75 |
}
|
|
76 |
|
|
77 |
#define max(a,b) a>b?a:b
|
|
78 |
void setTimer(TIMEVAL value)
|
|
79 |
{
|
|
80 |
// printf("setTimer(TIMEVAL value=%d)\n", value);
|
|
81 |
struct itimerval timerValues;
|
|
82 |
struct itimerval timerV = {{0,0},{0,0}};
|
|
83 |
timerValues.it_value.tv_sec = 0;
|
|
84 |
timerValues.it_value.tv_usec = max(value,1);
|
|
85 |
timerValues.it_interval.tv_sec = 0;
|
|
86 |
timerValues.it_interval.tv_usec = 0;
|
|
87 |
setitimer(ITIMER_REAL, &timerValues, &timerV);
|
|
88 |
}
|
|
89 |
|
|
90 |
TIMEVAL getElapsedTime(void)
|
|
91 |
{
|
|
92 |
struct timeval p;
|
|
93 |
gettimeofday(&p,NULL);
|
|
94 |
// printf("getCurrentTime() return=%u\n", p.tv_usec);
|
|
95 |
return (p.tv_sec - last_sig.tv_sec)* 1000000 + p.tv_usec - last_sig.tv_usec;
|
|
96 |
}
|