luat_timer_air101.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #include "luat_base.h"
  2. #include "luat_malloc.h"
  3. #include "luat_timer.h"
  4. #include "luat_msgbus.h"
  5. #include "FreeRTOS.h"
  6. #include "task.h"
  7. #include "wm_osal.h"
  8. #define LUAT_LOG_TAG "luat.timer"
  9. #include "luat_log.h"
  10. #define FREERTOS_TIMER_COUNT 64
  11. static luat_timer_t* timers[FREERTOS_TIMER_COUNT] = {0};
  12. static void luat_timer_callback(void *ptmr, void *parg) {
  13. // LLOGD("timer callback");
  14. rtos_msg_t msg;
  15. luat_timer_t *timer = (luat_timer_t*)parg;
  16. msg.handler = timer->func;
  17. msg.ptr = timer;
  18. msg.arg1 = 0;
  19. msg.arg2 = 0;
  20. luat_msgbus_put(&msg, 1);
  21. // LLOGD("timer msgbus re=%ld", re);
  22. }
  23. static int nextTimerSlot() {
  24. for (size_t i = 0; i < FREERTOS_TIMER_COUNT; i++)
  25. {
  26. if (timers[i] == NULL) {
  27. return i;
  28. }
  29. }
  30. return -1;
  31. }
  32. int luat_timer_start(luat_timer_t* timer) {
  33. tls_os_timer_t *os_timer = NULL;
  34. int timerIndex;
  35. int ret;
  36. // LLOGD(">>luat_timer_start timeout=%ld", timer->timeout);
  37. timerIndex = nextTimerSlot();
  38. // LLOGD("timer id=%ld", timerIndex);
  39. if (timerIndex < 0) {
  40. return 1; // too many timer!!
  41. }
  42. if (timer->timeout < (1000 / configTICK_RATE_HZ))
  43. timer->timeout = 1000 / configTICK_RATE_HZ;
  44. ret = tls_os_timer_create(&os_timer, luat_timer_callback, timer,(timer->timeout)/(1000 / configTICK_RATE_HZ), timer->repeat ? 1 : 0, NULL);
  45. // LLOGD("timer id=%ld, osTimerNew=%08X", timerIndex, (int)timer);
  46. if (TLS_OS_SUCCESS != ret)
  47. {
  48. return 1;
  49. }
  50. timers[timerIndex] = timer;
  51. timer->os_timer = os_timer;
  52. tls_os_timer_start(os_timer);
  53. return 0;
  54. }
  55. int luat_timer_stop(luat_timer_t* timer) {
  56. if (!timer)
  57. return 1;
  58. for (size_t i = 0; i < FREERTOS_TIMER_COUNT; i++)
  59. {
  60. if (timers[i] == timer) {
  61. timers[i] = NULL;
  62. break;
  63. }
  64. }
  65. tls_os_timer_stop(timer->os_timer);
  66. tls_os_timer_delete(timer->os_timer);
  67. return 0;
  68. }
  69. luat_timer_t* luat_timer_get(size_t timer_id) {
  70. for (size_t i = 0; i < FREERTOS_TIMER_COUNT; i++)
  71. {
  72. if (timers[i] && timers[i]->id == timer_id) {
  73. return timers[i];
  74. }
  75. }
  76. return NULL;
  77. }
  78. int luat_timer_mdelay(size_t ms) {
  79. if (ms >= (1000 / configTICK_RATE_HZ)) {
  80. vTaskDelay(ms / (1000 / configTICK_RATE_HZ));
  81. }
  82. return 0;
  83. }