luat_timer_cmsis_os2.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #include "luat_base.h"
  2. #include "luat_malloc.h"
  3. #include "luat_timer.h"
  4. #include "luat_msgbus.h"
  5. #include "cmsis_os2.h"
  6. #include "FreeRTOS.h"
  7. #include "task.h"
  8. #define LUAT_LOG_TAG "timer"
  9. #include "luat_log.h"
  10. #define FREERTOS_TIMER_COUNT 32
  11. static luat_timer_t* timers[FREERTOS_TIMER_COUNT] = {0};
  12. static void luat_timer_callback(void* param) {
  13. //LLOGD("timer callback");
  14. rtos_msg_t msg;
  15. luat_timer_t *timer = (luat_timer_t*)param;
  16. msg.handler = timer->func;
  17. msg.ptr = param;
  18. msg.arg1 = 0;
  19. msg.arg2 = 0;
  20. int re = 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. osTimerId_t os_timer;
  34. int timerIndex;
  35. //LLOGD(">>luat_timer_start timeout=%ld", timer->timeout);
  36. timerIndex = nextTimerSlot();
  37. //LLOGD("timer id=%ld", timerIndex);
  38. if (timerIndex < 0) {
  39. return 1; // too many timer!!
  40. }
  41. os_timer = osTimerNew(luat_timer_callback, timer->repeat ? osTimerPeriodic : osTimerOnce, timer, NULL);
  42. //LLOGD("timer id=%ld, osTimerNew=%08X", timerIndex, (int)timer);
  43. if (!os_timer) {
  44. return NULL;
  45. }
  46. timers[timerIndex] = timer;
  47. timer->os_timer = os_timer;
  48. int re = osTimerStart(os_timer, timer->timeout);
  49. //LLOGD("timer id=%ld timeout=%ld start=%ld", timerIndex, timer->timeout, re);
  50. if (re != 0) {
  51. osTimerDelete(os_timer);
  52. timers[timerIndex] = 0;
  53. }
  54. return re;
  55. }
  56. int luat_timer_stop(luat_timer_t* timer) {
  57. if (!timer)
  58. return 1;
  59. for (size_t i = 0; i < FREERTOS_TIMER_COUNT; i++)
  60. {
  61. if (timers[i] == timer) {
  62. timers[i] = NULL;
  63. break;
  64. }
  65. }
  66. osTimerStop(timer->os_timer);
  67. osTimerDelete(timer->os_timer);
  68. return 0;
  69. };
  70. luat_timer_t* luat_timer_get(size_t timer_id) {
  71. for (size_t i = 0; i < FREERTOS_TIMER_COUNT; i++)
  72. {
  73. if (timers[i] && timers[i]->id == timer_id) {
  74. return timers[i];
  75. }
  76. }
  77. return NULL;
  78. }
  79. int luat_timer_mdelay(size_t ms) {
  80. if (ms > 0) {
  81. vTaskDelay(ms);
  82. }
  83. return 0;
  84. }