timer.c 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. #include <time.h>
  2. #include <stdlib.h>
  3. #include "timer.h"
  4. #include "cfg.h"
  5. #if (CHIP_TYPE == CHIP_T113s)
  6. #include "asm-generic/siginfo.h"
  7. #else
  8. #include <signal.h>
  9. #endif
  10. typedef struct {
  11. timer_t tid;
  12. int times;
  13. int times_max;
  14. timer_fn_t fn;
  15. void *arg;
  16. int inited;
  17. }timer_handle_t;
  18. static void timer_callback(sigval_t sv)
  19. {
  20. timer_handle_t *h=(timer_handle_t*)sv.sival_ptr;
  21. if(h->fn) {
  22. if(h->times_max>0 && h->times<h->times_max) {
  23. int last=0;
  24. h->times++;
  25. if(h->times==h->times_max) {
  26. last = 1;
  27. }
  28. h->fn(h->arg, last);
  29. }
  30. else {
  31. h->fn(h->arg, 0);
  32. }
  33. }
  34. }
  35. static int set_time(timer_handle_t *h, int t1, int t2)
  36. {
  37. int r;
  38. struct itimerspec it;
  39. it.it_value.tv_sec = t1/1000; //��ʱ����ʼ����ʱ��
  40. it.it_value.tv_nsec = (t1%1000)*1000000;
  41. it.it_interval.tv_sec = t2/1000; //��ʱ�����Ϊ0�룬��ʾֻ����һ��
  42. it.it_interval.tv_nsec = (t2%1000)*1000000;
  43. r = timer_settime(h->tid, 0, &it, NULL);
  44. if(r<0) {
  45. return -1;
  46. }
  47. return 0;
  48. }
  49. int timer_init(void)
  50. {
  51. int r;
  52. struct sigevent sev;
  53. timer_handle_t *h=(timer_handle_t*)malloc(sizeof(timer_handle_t));
  54. if(!h) {
  55. return -1;
  56. }
  57. sev.sigev_notify = SIGEV_THREAD; // ֪ͨ����Ϊ�߳�
  58. sev.sigev_notify_function = timer_callback; // �ص�����
  59. sev.sigev_notify_attributes = NULL;
  60. sev.sigev_value.sival_ptr = h; // ���ݸ��ص�����������
  61. r = timer_create(CLOCK_REALTIME, &sev, &h->tid);
  62. if(r<0) {
  63. free(h); return -1;
  64. }
  65. h->times = 0;
  66. h->times_max = 0;
  67. h->fn = NULL;
  68. h->arg = NULL;
  69. h->inited = 1;
  70. return (int)h;
  71. }
  72. int timer_deinit(int h)
  73. {
  74. int r;
  75. timer_handle_t *th=(timer_handle_t*)h;
  76. if((h==0)||(h==-1) || !th->inited) {
  77. return -1;
  78. }
  79. r = timer_delete(th->tid);
  80. th->inited = 0;
  81. free(th);
  82. return r;
  83. }
  84. int timer_start(int h, int t, int times, timer_fn_t fn, void *arg)
  85. {
  86. int r;
  87. timer_handle_t *th=(timer_handle_t*)h;
  88. if((h==0)||(h==-1) || !th->inited) {
  89. return -1;
  90. }
  91. set_time(th, 0, 0);
  92. th->times = 0;
  93. th->times_max = times;
  94. th->fn = fn;
  95. th->arg = arg;
  96. return set_time(th, 1000, t);
  97. }
  98. int timer_stop(int h)
  99. {
  100. int r;
  101. timer_handle_t *th=(timer_handle_t*)h;
  102. if((h==0)||(h==-1) || !th->inited) {
  103. return -1;
  104. }
  105. r = set_time(th, 0, 0);
  106. return r;
  107. }