luat_rtos_freertos_semaphore.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #ifdef LUAT_FREERTOS_FULL_INCLUDE
  2. #include "freertos/FreeRTOS.h"
  3. #include "freertos/task.h"
  4. #include "freertos/queue.h"
  5. #include "freertos/semphr.h"
  6. #include "freertos/timers.h"
  7. #else
  8. #include "FreeRTOS.h"
  9. #include "task.h"
  10. #include "queue.h"
  11. #include "semphr.h"
  12. #include "timers.h"
  13. #endif
  14. #include "luat_base.h"
  15. #include "luat_rtos.h"
  16. int luat_rtos_semaphore_create(luat_rtos_semaphore_t *semaphore_handle, uint32_t init_count)
  17. {
  18. if (!semaphore_handle) return -1;
  19. SemaphoreHandle_t sem = NULL;
  20. if (init_count <= 1)
  21. {
  22. sem = xSemaphoreCreateBinary();
  23. if (!sem)
  24. return -1;
  25. if (!init_count)
  26. xSemaphoreGive(sem);
  27. }
  28. else
  29. {
  30. sem = xSemaphoreCreateCounting(init_count, init_count);
  31. if (!sem)
  32. return -1;
  33. }
  34. *semaphore_handle = (luat_rtos_semaphore_t)sem;
  35. return 0;
  36. }
  37. int luat_rtos_semaphore_delete(luat_rtos_semaphore_t semaphore_handle)
  38. {
  39. if (!semaphore_handle) return -1;
  40. vSemaphoreDelete(semaphore_handle);
  41. return 0;
  42. }
  43. int luat_rtos_semaphore_take(luat_rtos_semaphore_t semaphore_handle, uint32_t timeout)
  44. {
  45. if (!semaphore_handle) return -1;
  46. if (pdTRUE == xSemaphoreTake(semaphore_handle, luat_rtos_ms2tick(timeout)))
  47. return 0;
  48. return -1;
  49. }
  50. int luat_rtos_semaphore_release(luat_rtos_semaphore_t semaphore_handle)
  51. {
  52. if (!semaphore_handle) return -1;
  53. if (luat_rtos_get_ipsr())
  54. {
  55. BaseType_t yield = pdFALSE;
  56. if (pdTRUE == xSemaphoreGiveFromISR(semaphore_handle, &yield))
  57. {
  58. portYIELD_FROM_ISR(yield);
  59. return 0;
  60. }
  61. return -1;
  62. }
  63. else
  64. {
  65. if (pdTRUE == xSemaphoreGive(semaphore_handle))
  66. return 0;
  67. return -1;
  68. }
  69. }