pt-timer.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. #include "pt-timer.h"
  2. #ifdef __USE_WT_TIMER_
  3. static volatile uint32_t baseTick=0;
  4. #endif
  5. void
  6. PTTimerTick(pt_timer_t *pool)
  7. {
  8. #ifdef __USE_WT_TIMER_
  9. baseTick++;
  10. #else
  11. pt_timer_t *timer = pool->next;
  12. if ( timer )
  13. {
  14. if ( timer->ticks )
  15. {
  16. timer->ticks--;
  17. }
  18. if (0 == timer->ticks)
  19. {
  20. timer->ms = 0;
  21. while( timer ) // 将后续超时的定时器都移除
  22. {
  23. timer = timer->next;
  24. if (timer && (0 == timer->ticks))
  25. {
  26. timer->ms = 0;
  27. }
  28. else
  29. {
  30. break;
  31. }
  32. }
  33. pool->next = timer;
  34. }
  35. }
  36. #endif
  37. }
  38. void
  39. PTTimerInitPool(pt_timer_t *pool)
  40. {
  41. #ifndef __USE_WT_TIMER_
  42. pool->ticks = 0;
  43. pool->next = NULL;
  44. #endif
  45. }
  46. extern unsigned long sysTimeCounter;
  47. void
  48. PTTimerStart(pt_timer_t *pool, pt_timer_t *timer, uint16_t ms)
  49. {
  50. #ifdef __USE_WT_TIMER_
  51. timer->ms=baseTick+ms;
  52. #else
  53. pt_timer_t *p = pool;
  54. PTTimerStop(pool, timer);
  55. timer->next = NULL;
  56. timer->ms = ms;
  57. timer->ticks = ms;//_ms(ms);
  58. if (0 == ms) return;
  59. while( p->next )
  60. {
  61. if (timer->ticks < p->next->ticks)
  62. {
  63. p->next->ticks -= timer->ticks;
  64. timer->next = p->next;
  65. p->next = timer;
  66. break;
  67. }
  68. else
  69. {
  70. timer->ticks -= p->next->ticks; // timer->ticks 有可能为 0
  71. }
  72. p = p->next;
  73. }
  74. if (NULL == p->next)
  75. {
  76. p->next = timer;
  77. }
  78. #endif
  79. }
  80. boolean
  81. PTTimerIsExpired(pt_timer_t *timer)
  82. {
  83. #ifdef __USE_WT_TIMER_
  84. return (baseTick>=timer->ms);
  85. #else
  86. return (0 == timer->ms);
  87. #endif
  88. }
  89. void
  90. PTTimerStop(pt_timer_t *pool, pt_timer_t *timer)
  91. {
  92. #ifndef __USE_WT_TIMER_
  93. pt_timer_t *p = pool;
  94. if (timer && timer->ms)
  95. {
  96. while( p->next )
  97. {
  98. if (p->next == timer)
  99. {
  100. if ( timer->next )
  101. {
  102. timer->next->ticks += timer->ticks;
  103. }
  104. p->next = timer->next;
  105. timer->ms = 0;
  106. timer->next = NULL;
  107. break;
  108. }
  109. p = p->next;
  110. }
  111. }
  112. #endif
  113. }