timer.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. #include <time.h>
  2. #include <signal.h>
  3. #include <stdlib.h>
  4. #include <rtthread.h>
  5. #include "timer.h"
  6. typedef struct {
  7. rt_timer_t timer;
  8. int times;
  9. int times_max;
  10. timer_fn_t fn;
  11. void *arg;
  12. int inited;
  13. }timer_handle_t;
  14. static void timer_callback(void *arg)
  15. {
  16. timer_handle_t *h=(timer_handle_t*)arg;
  17. if(h->fn) {
  18. if(h->times_max>0 && h->times<h->times_max) {
  19. int last=0;
  20. h->times++;
  21. if(h->times==h->times_max) {
  22. last = 1;
  23. }
  24. h->fn(h->arg, last);
  25. }
  26. else {
  27. h->fn(h->arg, 0);
  28. }
  29. }
  30. }
  31. static int set_time(timer_handle_t *h, int t)
  32. {
  33. rt_timer_delete(h->timer);
  34. h->timer = rt_timer_create("timer", timer_callback, h, rt_tick_from_millisecond(t), RT_TIMER_FLAG_PERIODIC);
  35. return 0;
  36. }
  37. int timer_init(void)
  38. {
  39. int r;
  40. timer_handle_t *h=(timer_handle_t*)malloc(sizeof(timer_handle_t));
  41. if(!h) {
  42. return -1;
  43. }
  44. h->timer = NULL;
  45. h->times = 0;
  46. h->times_max = 0;
  47. h->fn = NULL;
  48. h->arg = NULL;
  49. h->inited = 1;
  50. return (int)h;
  51. }
  52. int timer_deinit(int h)
  53. {
  54. int r;
  55. timer_handle_t *th=(timer_handle_t*)h;
  56. if(h==-1 || !th->inited) {
  57. return -1;
  58. }
  59. rt_timer_delete(th->timer);
  60. th->inited = 0;
  61. free(th);
  62. return r;
  63. }
  64. int timer_start(int h, int t, int times, timer_fn_t fn, void *arg)
  65. {
  66. int r;
  67. timer_handle_t *th=(timer_handle_t*)h;
  68. if(h==-1 || !th->inited) {
  69. return -1;
  70. }
  71. rt_timer_stop(th->timer);
  72. th->times = 0;
  73. th->times_max = times;
  74. th->fn = fn;
  75. th->arg = arg;
  76. r = set_time(th, t);
  77. return rt_timer_start(th->timer);
  78. }
  79. int timer_stop(int h)
  80. {
  81. int r;
  82. timer_handle_t *th=(timer_handle_t*)h;
  83. if(h==-1 || !th->inited) {
  84. return -1;
  85. }
  86. return rt_timer_stop(th->timer);
  87. }