xref: /btstack/platform/freertos/btstack_run_loop_freertos.c (revision c8dfe071e5be306bdac290dfbe6cbf2b9a446e88)
1 /*
2  * Copyright (C) 2017 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 /*
39  *  btstack_run_loop_freertos.c
40  *
41  *  Run loop on dedicated thread on FreeRTOS
42  *  The run loop is triggered from other task/ISRs either via Event Groups
43  *  or Task Notifications if HAVE_FREERTOS_TASK_NOTIFICATIONS is defined
44  */
45 
46 #define BTSTACK_FILE__ "btstack_run_loop_freertos.c"
47 
48 #include <stddef.h> // NULL
49 
50 #include "btstack_run_loop_freertos.h"
51 
52 #include "btstack_linked_list.h"
53 #include "btstack_debug.h"
54 #include "btstack_util.h"
55 #include "hal_time_ms.h"
56 
57 // some SDKs, e.g. esp-idf, place FreeRTOS headers into an 'freertos' folder to avoid name collisions (e.g. list.h, queue.h, ..)
58 // wih this flag, the headers are properly found
59 
60 #ifdef HAVE_FREERTOS_INCLUDE_PREFIX
61 #include "freertos/FreeRTOS.h"
62 #include "freertos/task.h"
63 #include "freertos/queue.h"
64 #include "freertos/event_groups.h"
65 #else
66 #include "FreeRTOS.h"
67 #include "task.h"
68 #include "queue.h"
69 #include "event_groups.h"
70 #endif
71 
72 typedef struct function_call {
73     void (*fn)(void * arg);
74     void * arg;
75 } function_call_t;
76 
77 // pick allocation style, prefer static
78 #if( configSUPPORT_STATIC_ALLOCATION == 1 )
79 #define USE_STATIC_ALLOC
80 #elif( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
81 // ok, nothing to do
82 #else
83 #error "Either configSUPPORT_STATIC_ALLOCATION or configSUPPORT_DYNAMIC_ALLOCATION in FreeRTOSConfig.h must be 1"
84 #endif
85 
86 // queue to receive events: up to 2 calls from transport, rest for app
87 #define RUN_LOOP_QUEUE_LENGTH 20
88 #define RUN_LOOP_QUEUE_ITEM_SIZE sizeof(function_call_t)
89 
90 #ifdef USE_STATIC_ALLOC
91 static StaticQueue_t btstack_run_loop_queue_object;
92 static uint8_t btstack_run_loop_queue_storage[ RUN_LOOP_QUEUE_LENGTH * RUN_LOOP_QUEUE_ITEM_SIZE ];
93 #endif
94 
95 static QueueHandle_t        btstack_run_loop_queue;
96 static TaskHandle_t         btstack_run_loop_task;
97 
98 #ifndef HAVE_FREERTOS_TASK_NOTIFICATIONS
99 static EventGroupHandle_t   btstack_run_loop_event_group;
100 #endif
101 
102 // bit 0 event group reserved to wakeup run loop
103 #define EVENT_GROUP_FLAG_RUN_LOOP 1
104 
105 // the run loop
106 static bool run_loop_exit_requested;
107 
108 static uint32_t btstack_run_loop_freertos_get_time_ms(void){
109     return hal_time_ms();
110 }
111 
112 // set timer
113 static void btstack_run_loop_freertos_set_timer(btstack_timer_source_t *ts, uint32_t timeout_in_ms){
114     ts->timeout = btstack_run_loop_freertos_get_time_ms() + timeout_in_ms + 1;
115 }
116 
117 // schedules execution from regular thread
118 void btstack_run_loop_freertos_trigger(void){
119 #ifdef HAVE_FREERTOS_TASK_NOTIFICATIONS
120     xTaskNotify(btstack_run_loop_task, EVENT_GROUP_FLAG_RUN_LOOP, eSetBits);
121 #else
122     xEventGroupSetBits(btstack_run_loop_event_group, EVENT_GROUP_FLAG_RUN_LOOP);
123 #endif
124 }
125 
126 void btstack_run_loop_freertos_execute_code_on_main_thread(void (*fn)(void *arg), void * arg){
127 
128     // directly call function if already on btstack task
129     if (xTaskGetCurrentTaskHandle() == btstack_run_loop_task){
130         (*fn)(arg);
131         return;
132     }
133 
134     function_call_t message;
135     message.fn  = fn;
136     message.arg = arg;
137     BaseType_t res = xQueueSendToBack(btstack_run_loop_queue, &message, 0); // portMAX_DELAY);
138     if (res != pdTRUE){
139         log_error("Failed to post fn %p", fn);
140     }
141     btstack_run_loop_freertos_trigger();
142 }
143 
144 #if defined(HAVE_FREERTOS_TASK_NOTIFICATIONS) || (INCLUDE_xEventGroupSetBitFromISR == 1)
145 void btstack_run_loop_freertos_trigger_from_isr(void){
146     BaseType_t xHigherPriorityTaskWoken;
147 #ifdef HAVE_FREERTOS_TASK_NOTIFICATIONS
148     xTaskNotifyFromISR(btstack_run_loop_task, EVENT_GROUP_FLAG_RUN_LOOP, eSetBits, &xHigherPriorityTaskWoken);
149     if (xHigherPriorityTaskWoken) {
150 #ifdef ESP_PLATFORM
151         portYIELD_FROM_ISR();
152 #else
153         portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
154 #endif
155     }
156 #else
157     xEventGroupSetBitsFromISR(btstack_run_loop_event_group, EVENT_GROUP_FLAG_RUN_LOOP, &xHigherPriorityTaskWoken);
158 #endif
159 }
160 #endif
161 
162 void btstack_run_loop_freertos_trigger_exit(void){
163     run_loop_exit_requested = true;
164 }
165 
166 /**
167  * Execute run_loop
168  */
169 static void btstack_run_loop_freertos_execute(void) {
170     log_debug("RL: execute");
171 
172     run_loop_exit_requested = false;
173 
174     while (true) {
175 
176         // process data sources
177         btstack_run_loop_base_poll_data_sources();
178 
179         // process registered function calls on run loop thread
180         while (true){
181             function_call_t message = { NULL, NULL };
182             BaseType_t res = xQueueReceive( btstack_run_loop_queue, &message, 0);
183             if (res == pdFALSE) break;
184             if (message.fn){
185                 message.fn(message.arg);
186             }
187         }
188 
189         // process timers
190         uint32_t now = btstack_run_loop_freertos_get_time_ms();
191         btstack_run_loop_base_process_timers(now);
192 
193         // exit triggered by btstack_run_loop_freertos_trigger_exit (from data source, timer, run on main thread)
194         if (run_loop_exit_requested) break;
195 
196         // wait for timeout or event group/task notification
197         int32_t timeout_next_timer_ms = btstack_run_loop_base_get_time_until_timeout(now);
198 
199         uint32_t timeout_ms = portMAX_DELAY;
200         if (timeout_next_timer_ms >= 0){
201             timeout_ms = (uint32_t) timeout_next_timer_ms;
202         }
203 
204         log_debug("RL: wait with timeout %u", (int) timeout_ms);
205 #ifdef HAVE_FREERTOS_TASK_NOTIFICATIONS
206         xTaskNotifyWait(pdFALSE, 0xffffffff, NULL, pdMS_TO_TICKS(timeout_ms));
207 #else
208         xEventGroupWaitBits(btstack_run_loop_event_group, EVENT_GROUP_FLAG_RUN_LOOP, 1, 0, pdMS_TO_TICKS(timeout_ms));
209 #endif
210     }
211 }
212 
213 static void btstack_run_loop_freertos_init(void){
214     btstack_run_loop_base_init();
215 
216 #ifdef USE_STATIC_ALLOC
217     btstack_run_loop_queue = xQueueCreateStatic(RUN_LOOP_QUEUE_LENGTH, RUN_LOOP_QUEUE_ITEM_SIZE, btstack_run_loop_queue_storage, &btstack_run_loop_queue_object);
218 #else
219     btstack_run_loop_queue = xQueueCreate(RUN_LOOP_QUEUE_LENGTH, RUN_LOOP_QUEUE_ITEM_SIZE);
220 #endif
221 
222 #ifndef HAVE_FREERTOS_TASK_NOTIFICATIONS
223     // event group to wake run loop
224     btstack_run_loop_event_group = xEventGroupCreate();
225 #endif
226 
227     // task to handle to optimize 'run on main thread'
228     btstack_run_loop_task = xTaskGetCurrentTaskHandle();
229 
230     log_info("run loop init, task %p, queue item size %u", btstack_run_loop_task, (int) sizeof(function_call_t));
231 }
232 
233 /**
234  * @brief Provide btstack_run_loop_posix instance for use with btstack_run_loop_init
235  */
236 
237 static const btstack_run_loop_t btstack_run_loop_freertos = {
238     &btstack_run_loop_freertos_init,
239     &btstack_run_loop_base_add_data_source,
240     &btstack_run_loop_base_remove_data_source,
241     &btstack_run_loop_base_enable_data_source_callbacks,
242     &btstack_run_loop_base_disable_data_source_callbacks,
243     &btstack_run_loop_freertos_set_timer,
244     &btstack_run_loop_base_add_timer,
245     &btstack_run_loop_base_remove_timer,
246     &btstack_run_loop_freertos_execute,
247     &btstack_run_loop_base_dump_timer,
248     &btstack_run_loop_freertos_get_time_ms,
249 };
250 
251 const btstack_run_loop_t * btstack_run_loop_freertos_get_instance(void){
252     return &btstack_run_loop_freertos;
253 }
254