Mail.h 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /*
  2. * File : Mail.h
  3. * This file is part of RT-Thread RTOS
  4. * COPYRIGHT (C) 2016, RT-Thread Development Team
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License along
  17. * with this program; if not, write to the Free Software Foundation, Inc.,
  18. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  19. *
  20. * Change Logs:
  21. * Date Author Notes
  22. * 2016/10/1 Bernard The first version
  23. */
  24. #pragma once
  25. #include <stdint.h>
  26. #include <string.h>
  27. #include <rtthread.h>
  28. namespace rtthread {
  29. /**
  30. * The Mail class allow to control, send, receive, or wait for mail.
  31. * A mail is a memory block that is send to a thread or interrupt service routine.
  32. * @param T data type of a single message element.
  33. * @param queue_sz maximum number of messages in queue.
  34. */
  35. template<typename T, uint32_t queue_sz>
  36. class Mail {
  37. public:
  38. /** Create and Initialise Mail queue. */
  39. Mail(const char* name = "")
  40. {
  41. rt_mb_init(&mID, name, mPool, queue_sz, RT_IPC_FLAG_FIFO);
  42. }
  43. ~Mail()
  44. {
  45. rt_mb_detach(&mID);
  46. }
  47. /** Put a mail in the queue.
  48. @param mptr memory block previously allocated with Mail::alloc or Mail::calloc.
  49. @return status code that indicates the execution status of the function.
  50. */
  51. bool put(T *mptr, int32_t millisec = 0)
  52. {
  53. rt_int32_t tick;
  54. if (millisec < 0)
  55. tick = -1;
  56. else
  57. tick = rt_tick_from_millisecond(millisec);
  58. return rt_mb_send_wait(&mID, (rt_uint32_t)mptr, tick) == RT_EOK;
  59. }
  60. /** Get a mail from a queue.
  61. @param millisec timeout value or 0 in case of no time-out. (default: osWaitForever).
  62. @return event that contains mail information or error code.
  63. */
  64. T* get(int32_t millisec = -1)
  65. {
  66. T *t = NULL;
  67. rt_int32_t tick;
  68. if (millisec < 0)
  69. tick = -1;
  70. else
  71. tick = rt_tick_from_millisecond(millisec);
  72. rt_mb_recv(&mID, &t, tick);
  73. return t;
  74. }
  75. private:
  76. struct rt_mailbox mID;
  77. T* mPool[queue_sz];
  78. };
  79. }