Mail.h 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /* Copyright (c) 2012 mbed.org */
  2. #ifndef MAIL_H
  3. #define MAIL_H
  4. #include <stdint.h>
  5. #include <string.h>
  6. #include "cmsis_os.h"
  7. namespace rtos {
  8. /*! The Mail class allow to control, send, receive, or wait for mail.
  9. A mail is a memory block that is send to a thread or interrupt service routine.
  10. \tparam T data type of a single message element.
  11. \tparam queue_sz maximum number of messages in queue.
  12. */
  13. template<typename T, uint32_t queue_sz>
  14. class Mail {
  15. public:
  16. /*! Create and Initialise Mail queue. */
  17. Mail() {
  18. #ifdef CMSIS_OS_RTX
  19. memset(_mail_q, 0, sizeof(_mail_q));
  20. _mail_p[0] = _mail_q;
  21. memset(_mail_m, 0, sizeof(_mail_m));
  22. _mail_p[1] = _mail_m;
  23. _mail_def.pool = _mail_p;
  24. _mail_def.queue_sz = queue_sz;
  25. _mail_def.item_sz = sizeof(T);
  26. #endif
  27. _mail_id = osMailCreate(&_mail_def, NULL);
  28. }
  29. /*! Allocate a memory block of type T
  30. \param millisec timeout value or 0 in case of no time-out. (default: 0).
  31. \return pointer to memory block that can be filled with mail or NULL in case error.
  32. */
  33. T* alloc(uint32_t millisec=0) {
  34. return (T*)osMailAlloc(_mail_id, millisec);
  35. }
  36. /*! Allocate a memory block of type T and set memory block to zero.
  37. \param millisec timeout value or 0 in case of no time-out. (default: 0).
  38. \return pointer to memory block that can be filled with mail or NULL in case error.
  39. */
  40. T* calloc(uint32_t millisec=0) {
  41. return (T*)osMailCAlloc(_mail_id, millisec);
  42. }
  43. /*! Put a mail in the queue.
  44. \param mptr memory block previously allocated with Mail::alloc or Mail::calloc.
  45. \return status code that indicates the execution status of the function.
  46. */
  47. osStatus put(T *mptr) {
  48. return osMailPut(_mail_id, (void*)mptr);
  49. }
  50. /*! Get a mail from a queue.
  51. \param millisec timeout value or 0 in case of no time-out. (default: osWaitForever).
  52. \return event that contains mail information or error code.
  53. */
  54. osEvent get(uint32_t millisec=osWaitForever) {
  55. return osMailGet(_mail_id, millisec);
  56. }
  57. /*! Free a memory block from a mail.
  58. \param mptr pointer to the memory block that was obtained with Mail::get.
  59. \return status code that indicates the execution status of the function.
  60. */
  61. osStatus free(T *mptr) {
  62. return osMailFree(_mail_id, (void*)mptr);
  63. }
  64. private:
  65. osMailQId _mail_id;
  66. osMailQDef_t _mail_def;
  67. #ifdef CMSIS_OS_RTX
  68. uint32_t _mail_q[4+(queue_sz)];
  69. uint32_t _mail_m[3+((sizeof(T)+3)/4)*(queue_sz)];
  70. void *_mail_p[2];
  71. #endif
  72. };
  73. }
  74. #endif