luat_timer_rtt.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #include "luat_base.h"
  2. #include "luat_malloc.h"
  3. #include "luat_msgbus.h"
  4. #include "luat_timer.h"
  5. #include "rtthread.h"
  6. #include "rthw.h"
  7. #define DBG_TAG "rtt.timer"
  8. #define DBG_LVL DBG_INFO
  9. #include <rtdbg.h>
  10. #define LUATOS_TIMER_COUNT 64
  11. static luat_timer_t* timers[LUATOS_TIMER_COUNT] = {0};
  12. static char timer_name[32];
  13. static void rt_timer_callback(void *param) {
  14. rtos_msg_t msg;
  15. size_t timer_id = (size_t)param;
  16. luat_timer_t *timer = luat_timer_get(timer_id);
  17. if (timer == NULL) return;
  18. msg.handler = timer->func;
  19. msg.ptr = timer;
  20. msg.arg1 = timer_id;
  21. msg.arg2 = 0;
  22. luat_msgbus_put(&msg, 1);
  23. }
  24. static int nextTimerSlot() {
  25. for (size_t i = 0; i < LUATOS_TIMER_COUNT; i++)
  26. {
  27. if (timers[i] == NULL) {
  28. return i;
  29. }
  30. }
  31. return -1;
  32. }
  33. int luat_timer_start(luat_timer_t* timer) {
  34. int timerIndex = nextTimerSlot();
  35. rt_sprintf(timer_name, "t%06X", timer->id);
  36. LOG_D("rtt timer name=%s", timer_name);
  37. rt_tick_t tick = rt_tick_from_millisecond(timer->timeout);
  38. rt_uint8_t flag = timer->repeat ? RT_TIMER_FLAG_PERIODIC : RT_TIMER_FLAG_ONE_SHOT ;
  39. rt_timer_t r_timer = rt_timer_create(timer_name, rt_timer_callback, (void*)timer->id, tick, flag|RT_TIMER_FLAG_SOFT_TIMER);
  40. if (r_timer == RT_NULL) {
  41. LOG_E("rt_timer_create FAIL!!!");
  42. return 1;
  43. }
  44. if (rt_timer_start(r_timer) != RT_EOK) {
  45. LOG_E("rt_timer_start FAIL!!!");
  46. rt_timer_delete(r_timer);
  47. return 1;
  48. };
  49. timers[timerIndex] = timer;
  50. timer->os_timer = r_timer;
  51. LOG_D("rt_timer_start complete");
  52. return 0;
  53. }
  54. int luat_timer_stop(luat_timer_t* timer) {
  55. if (!timer)
  56. return 0;
  57. for (size_t i = 0; i < LUATOS_TIMER_COUNT; i++)
  58. {
  59. if (timers[i] == timer) {
  60. timers[i] = NULL;
  61. break;
  62. }
  63. }
  64. rt_timer_stop((rt_timer_t)timer->os_timer);
  65. rt_timer_delete((rt_timer_t)timer->os_timer);
  66. return 0;
  67. }
  68. luat_timer_t* luat_timer_get(size_t timer_id) {
  69. for (size_t i = 0; i < LUATOS_TIMER_COUNT; i++)
  70. {
  71. if (timers[i] && timers[i]->id == timer_id) {
  72. return timers[i];
  73. }
  74. }
  75. return RT_NULL;
  76. }
  77. int luat_timer_mdelay(size_t ms) {
  78. if (ms > 0)
  79. rt_thread_mdelay(ms);
  80. return 0;
  81. }