luat_timer_air101.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. size_t timer_id = (size_t)parg;
  16. luat_timer_t *timer = luat_timer_get(timer_id);
  17. if (timer == NULL)
  18. return;
  19. msg.handler = timer->func;
  20. msg.ptr = timer;
  21. msg.arg1 = timer_id;
  22. msg.arg2 = 0;
  23. luat_msgbus_put(&msg, 1);
  24. // LLOGD("timer msgbus re=%ld", re);
  25. }
  26. static int nextTimerSlot() {
  27. for (size_t i = 0; i < FREERTOS_TIMER_COUNT; i++)
  28. {
  29. if (timers[i] == NULL) {
  30. return i;
  31. }
  32. }
  33. return -1;
  34. }
  35. int luat_timer_start(luat_timer_t* timer) {
  36. tls_os_timer_t *os_timer = NULL;
  37. int timerIndex;
  38. int ret;
  39. // LLOGD(">>luat_timer_start timeout=%ld", timer->timeout);
  40. timerIndex = nextTimerSlot();
  41. // LLOGD("timer id=%ld", timerIndex);
  42. if (timerIndex < 0) {
  43. return 1; // too many timer!!
  44. }
  45. if (timer->timeout < (1000 / configTICK_RATE_HZ))
  46. timer->timeout = 1000 / configTICK_RATE_HZ;
  47. ret = tls_os_timer_create(&os_timer, luat_timer_callback, (void*)timer->id,(timer->timeout)/(1000 / configTICK_RATE_HZ), timer->repeat ? 1 : 0, NULL);
  48. // LLOGD("timer id=%ld, osTimerNew=%08X", timerIndex, (int)timer);
  49. if (TLS_OS_SUCCESS != ret)
  50. {
  51. return 1;
  52. }
  53. timers[timerIndex] = timer;
  54. timer->os_timer = os_timer;
  55. tls_os_timer_start(os_timer);
  56. return 0;
  57. }
  58. int luat_timer_stop(luat_timer_t* timer) {
  59. if (!timer)
  60. return 1;
  61. for (size_t i = 0; i < FREERTOS_TIMER_COUNT; i++)
  62. {
  63. if (timers[i] == timer) {
  64. timers[i] = NULL;
  65. break;
  66. }
  67. }
  68. tls_os_timer_stop(timer->os_timer);
  69. tls_os_timer_delete(timer->os_timer);
  70. return 0;
  71. }
  72. luat_timer_t* luat_timer_get(size_t timer_id) {
  73. for (size_t i = 0; i < FREERTOS_TIMER_COUNT; i++)
  74. {
  75. if (timers[i] && timers[i]->id == timer_id) {
  76. return timers[i];
  77. }
  78. }
  79. return NULL;
  80. }
  81. int luat_timer_mdelay(size_t ms) {
  82. if (ms >= (1000 / configTICK_RATE_HZ)) {
  83. vTaskDelay(ms / (1000 / configTICK_RATE_HZ));
  84. }
  85. return 0;
  86. }