xref: /nrf52832-nimble/rt-thread/components/cplusplus/Mail.h (revision 104654410c56c573564690304ae786df310c91fc)
1 /*
2  * Copyright (c) 2006-2018, RT-Thread Development Team
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  *
6  * Change Logs:
7  * Date           Author       Notes
8  * 2016/10/1      Bernard      The first version
9  */
10 
11 #pragma once
12 
13 #include <stdint.h>
14 #include <string.h>
15 
16 #include <rtthread.h>
17 
18 namespace rtthread {
19 
20 /**
21  * The Mail class allow to control, send, receive, or wait for mail.
22  * A mail is a memory block that is send to a thread or interrupt service routine.
23  * @param  T         data type of a single message element.
24  * @param  queue_sz  maximum number of messages in queue.
25  */
26 
27 template<typename T, uint32_t queue_sz>
28 class Mail {
29 public:
30     /** Create and Initialise Mail queue. */
31     Mail(const char* name = "")
32     {
33         rt_mb_init(&mID, name, mPool, queue_sz, RT_IPC_FLAG_FIFO);
34     }
35 
~Mail()36     ~Mail()
37     {
38         rt_mb_detach(&mID);
39     }
40 
41     /** Put a mail in the queue.
42       @param   mptr  memory block previously allocated with Mail::alloc or Mail::calloc.
43       @return  status code that indicates the execution status of the function.
44     */
45     bool put(T *mptr, int32_t millisec = 0)
46     {
47         rt_int32_t tick;
48 
49         if (millisec < 0)
50             tick = -1;
51         else
52             tick = rt_tick_from_millisecond(millisec);
53 
54         return rt_mb_send_wait(&mID, (rt_uint32_t)mptr, tick) == RT_EOK;
55     }
56 
57     /** Get a mail from a queue.
58       @param   millisec  timeout value or 0 in case of no time-out. (default: osWaitForever).
59       @return  event that contains mail information or error code.
60     */
61     T* get(int32_t millisec = -1)
62     {
63         T *t = NULL;
64         rt_int32_t tick;
65 
66         if (millisec < 0)
67             tick = -1;
68         else
69             tick = rt_tick_from_millisecond(millisec);
70 
71         rt_mb_recv(&mID, &t, tick);
72 
73         return t;
74     }
75 
76 private:
77     struct rt_mailbox mID;
78     T* mPool[queue_sz];
79 };
80 
81 }
82