luat_timer_freertos.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #include "luat_base.h"
  2. #include "luat_malloc.h"
  3. #include "luat_timer.h"
  4. #include "luat_msgbus.h"
  5. #include "luat_log.h"
  6. #include "cmsis_os2.h"
  7. #include "FreeRTOS.h"
  8. #include "task.h"
  9. #define FREERTOS_TIMER_COUNT 32
  10. static luat_timer_t* timers[FREERTOS_TIMER_COUNT];
  11. static void luat_timer_callback(void* param) {
  12. //luat_log_debug("luat.timer", "timer callback");
  13. rtos_msg_t msg;
  14. luat_timer_t *timer = (luat_timer_t*)param;
  15. msg.handler = timer->func;
  16. msg.ptr = param;
  17. msg.arg1 = 0;
  18. msg.arg2 = 0;
  19. int re = luat_msgbus_put(&msg, 1);
  20. //luat_log_debug("luat.timer", "timer msgbus re=%ld", re);
  21. }
  22. static int nextTimerSlot() {
  23. for (size_t i = 0; i < FREERTOS_TIMER_COUNT; i++)
  24. {
  25. if (timers[i] == NULL) {
  26. return i;
  27. }
  28. }
  29. return -1;
  30. }
  31. int luat_timer_start(luat_timer_t* timer) {
  32. osTimerId_t os_timer;
  33. int timerIndex;
  34. //luat_log_debug("luat.timer", ">>luat_timer_start timeout=%ld", timer->timeout);
  35. timerIndex = nextTimerSlot();
  36. //luat_log_debug("luat.timer", "timer id=%ld", timerIndex);
  37. if (timerIndex < 0) {
  38. return 1; // too many timer!!
  39. }
  40. os_timer = osTimerNew(luat_timer_callback, timer->repeat ? osTimerPeriodic : osTimerOnce, timer, NULL);
  41. //luat_log_debug("luat.timer", "timer id=%ld, osTimerNew=%08X", timerIndex, (int)timer);
  42. if (!os_timer) {
  43. return NULL;
  44. }
  45. timers[timerIndex] = timer;
  46. timer->os_timer = os_timer;
  47. int re = osTimerStart(os_timer, timer->timeout);
  48. //luat_log_debug("luat.timer", "timer id=%ld timeout=%ld start=%ld", timerIndex, timer->timeout, re);
  49. if (re != 0) {
  50. osTimerDelete(timer);
  51. timers[timerIndex] = 0;
  52. }
  53. return re;
  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. osTimerStop(timer->os_timer);
  66. osTimerDelete(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 > 0) {
  80. vTaskDelay(ms);
  81. }
  82. return 0;
  83. }