xref: /btstack/platform/freertos/btstack_run_loop_freertos.c (revision bdc352b16da8ddb06e0abca313290fcc1e06a43b)
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_linked_list.h"
51 #include "btstack_debug.h"
52 #include "btstack_run_loop_freertos.h"
53 #include "hal_time_ms.h"
54 
55 // some SDKs, e.g. esp-idf, place FreeRTOS headers into an 'freertos' folder to avoid name collisions (e.g. list.h, queue.h, ..)
56 // wih this flag, the headers are properly found
57 
58 #ifdef HAVE_FREERTOS_INCLUDE_PREFIX
59 #include "freertos/FreeRTOS.h"
60 #include "freertos/task.h"
61 #include "freertos/queue.h"
62 #include "freertos/event_groups.h"
63 #else
64 #include "FreeRTOS.h"
65 #include "task.h"
66 #include "queue.h"
67 #include "event_groups.h"
68 #endif
69 
70 typedef struct function_call {
71     void (*fn)(void * arg);
72     void * arg;
73 } function_call_t;
74 
75 static const btstack_run_loop_t btstack_run_loop_freertos;
76 
77 static QueueHandle_t        btstack_run_loop_queue;
78 static TaskHandle_t         btstack_run_loop_task;
79 
80 #ifndef HAVE_FREERTOS_TASK_NOTIFICATIONS
81 static EventGroupHandle_t   btstack_run_loop_event_group;
82 #endif
83 
84 // bit 0 event group reserved to wakeup run loop
85 #define EVENT_GROUP_FLAG_RUN_LOOP 1
86 
87 // the run loop
88 static btstack_linked_list_t timers;
89 static btstack_linked_list_t data_sources;
90 
91 static uint32_t btstack_run_loop_freertos_get_time_ms(void){
92     return hal_time_ms();
93 }
94 
95 // set timer
96 static void btstack_run_loop_freertos_set_timer(btstack_timer_source_t *ts, uint32_t timeout_in_ms){
97     ts->timeout = btstack_run_loop_freertos_get_time_ms() + timeout_in_ms + 1;
98 }
99 
100 /**
101  * Add timer to run_loop (keep list sorted)
102  */
103 static void btstack_run_loop_freertos_add_timer(btstack_timer_source_t *ts){
104     btstack_linked_item_t *it;
105     for (it = (btstack_linked_item_t *) &timers; it->next ; it = it->next){
106         // don't add timer that's already in there
107         if ((btstack_timer_source_t *) it->next == ts){
108             log_error( "btstack_run_loop_timer_add error: timer to add already in list!");
109             return;
110         }
111         if (ts->timeout < ((btstack_timer_source_t *) it->next)->timeout) {
112             break;
113         }
114     }
115     ts->item.next = it->next;
116     it->next = (btstack_linked_item_t *) ts;
117 }
118 
119 /**
120  * Remove timer from run loop
121  */
122 static int btstack_run_loop_freertos_remove_timer(btstack_timer_source_t *ts){
123     return btstack_linked_list_remove(&timers, (btstack_linked_item_t *) ts);
124 }
125 
126 static void btstack_run_loop_freertos_dump_timer(void){
127 #ifdef ENABLE_LOG_INFO
128     btstack_linked_item_t *it;
129     int i = 0;
130     for (it = (btstack_linked_item_t *) timers; it ; it = it->next){
131         btstack_timer_source_t *ts = (btstack_timer_source_t*) it;
132         log_info("timer %u, timeout %u\n", i, (unsigned int) ts->timeout);
133     }
134 #endif
135 }
136 
137 // schedules execution from regular thread
138 void btstack_run_loop_freertos_trigger(void){
139 #ifdef HAVE_FREERTOS_TASK_NOTIFICATIONS
140     xTaskNotify(btstack_run_loop_task, EVENT_GROUP_FLAG_RUN_LOOP, eSetBits);
141 #else
142     xEventGroupSetBits(btstack_run_loop_event_group, EVENT_GROUP_FLAG_RUN_LOOP);
143 #endif
144 }
145 
146 void btstack_run_loop_freertos_execute_code_on_main_thread(void (*fn)(void *arg), void * arg){
147 
148     // directly call function if already on btstack task
149     if (xTaskGetCurrentTaskHandle() == btstack_run_loop_task){
150         (*fn)(arg);
151         return;
152     }
153 
154     function_call_t message;
155     message.fn  = fn;
156     message.arg = arg;
157     BaseType_t res = xQueueSendToBack(btstack_run_loop_queue, &message, 0); // portMAX_DELAY);
158     if (res != pdTRUE){
159         log_error("Failed to post fn %p", fn);
160     }
161     btstack_run_loop_freertos_trigger();
162 }
163 
164 #if defined(HAVE_FREERTOS_TASK_NOTIFICATIONS) || (INCLUDE_xEventGroupSetBitFromISR == 1)
165 void btstack_run_loop_freertos_trigger_from_isr(void){
166     BaseType_t xHigherPriorityTaskWoken;
167 #ifdef HAVE_FREERTOS_TASK_NOTIFICATIONS
168     xTaskNotifyFromISR(btstack_run_loop_task, EVENT_GROUP_FLAG_RUN_LOOP, eSetBits, &xHigherPriorityTaskWoken);
169     if (xHigherPriorityTaskWoken) {
170 #ifdef ESP_PLATFORM
171         portYIELD_FROM_ISR();
172 #else
173         portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
174 #endif
175     }
176 #else
177     xEventGroupSetBitsFromISR(btstack_run_loop_event_group, EVENT_GROUP_FLAG_RUN_LOOP, &xHigherPriorityTaskWoken);
178 #endif
179 }
180 
181 void btstack_run_loop_freertos_execute_code_on_main_thread_from_isr(void (*fn)(void *arg), void * arg){
182     function_call_t message;
183     message.fn  = fn;
184     message.arg = arg;
185     BaseType_t xHigherPriorityTaskWoken;
186     xQueueSendToBackFromISR(btstack_run_loop_queue, &message, &xHigherPriorityTaskWoken);
187     btstack_run_loop_freertos_trigger_from_isr();
188 }
189 #endif
190 
191 /**
192  * Execute run_loop
193  */
194 static void btstack_run_loop_freertos_execute(void) {
195     log_debug("RL: execute");
196 
197     while (1) {
198 
199         // process data sources
200         btstack_data_source_t *ds;
201         btstack_data_source_t *next;
202         for (ds = (btstack_data_source_t *) data_sources; ds != NULL ; ds = next){
203             next = (btstack_data_source_t *) ds->item.next; // cache pointer to next data_source to allow data source to remove itself
204             if (ds->flags & DATA_SOURCE_CALLBACK_POLL){
205                 ds->process(ds, DATA_SOURCE_CALLBACK_POLL);
206             }
207         }
208 
209         // process registered function calls on run loop thread
210         while (1){
211             function_call_t message = { NULL, NULL };
212             BaseType_t res = xQueueReceive( btstack_run_loop_queue, &message, 0);
213             if (res == pdFALSE) break;
214             if (message.fn){
215                 message.fn(message.arg);
216             }
217         }
218 
219         // process timers and get et next timeout
220         uint32_t timeout_ms = portMAX_DELAY;
221         log_debug("RL: portMAX_DELAY %u", portMAX_DELAY);
222         while (timers) {
223             btstack_timer_source_t * ts = (btstack_timer_source_t *) timers;
224             uint32_t now = btstack_run_loop_freertos_get_time_ms();
225             log_debug("RL: now %u, expires %u", now, ts->timeout);
226             if (ts->timeout > now){
227                 timeout_ms = ts->timeout - now;
228                 break;
229             }
230             // remove timer before processing it to allow handler to re-register with run loop
231             btstack_run_loop_freertos_remove_timer(ts);
232             log_debug("RL: first timer %p", ts->process);
233             ts->process(ts);
234         }
235 
236         // wait for timeout or event group/task notification
237         log_debug("RL: wait with timeout %u", (int) timeout_ms);
238 #ifdef HAVE_FREERTOS_TASK_NOTIFICATIONS
239         xTaskNotifyWait(pdFALSE, 0xffffffff, NULL, pdMS_TO_TICKS(timeout_ms));
240 #else
241         xEventGroupWaitBits(btstack_run_loop_event_group, EVENT_GROUP_FLAG_RUN_LOOP, 1, 0, pdMS_TO_TICKS(timeout_ms));
242 #endif
243     }
244 }
245 
246 static void btstack_run_loop_freertos_add_data_source(btstack_data_source_t *ds){
247     btstack_linked_list_add(&data_sources, (btstack_linked_item_t *) ds);
248 }
249 
250 static int btstack_run_loop_freertos_remove_data_source(btstack_data_source_t *ds){
251     return btstack_linked_list_remove(&data_sources, (btstack_linked_item_t *) ds);
252 }
253 
254 static void btstack_run_loop_freertos_enable_data_source_callbacks(btstack_data_source_t * ds, uint16_t callback_types){
255     ds->flags |= callback_types;
256 }
257 
258 static void btstack_run_loop_freertos_disable_data_source_callbacks(btstack_data_source_t * ds, uint16_t callback_types){
259     ds->flags &= ~callback_types;
260 }
261 
262 static void btstack_run_loop_freertos_init(void){
263     timers = NULL;
264 
265     // queue to receive events: up to 2 calls from transport, up to 3 for app
266     btstack_run_loop_queue = xQueueCreate(20, sizeof(function_call_t));
267 
268 #ifndef HAVE_FREERTOS_TASK_NOTIFICATIONS
269     // event group to wake run loop
270     btstack_run_loop_event_group = xEventGroupCreate();
271 #endif
272 
273     // task to handle to optimize 'run on main thread'
274     btstack_run_loop_task = xTaskGetCurrentTaskHandle();
275 
276     log_info("run loop init, task %p, queue item size %u", btstack_run_loop_task, (int) sizeof(function_call_t));
277 }
278 
279 /**
280  * @brief Provide btstack_run_loop_posix instance for use with btstack_run_loop_init
281  */
282 const btstack_run_loop_t * btstack_run_loop_freertos_get_instance(void){
283     return &btstack_run_loop_freertos;
284 }
285 
286 static const btstack_run_loop_t btstack_run_loop_freertos = {
287     &btstack_run_loop_freertos_init,
288     &btstack_run_loop_freertos_add_data_source,
289     &btstack_run_loop_freertos_remove_data_source,
290     &btstack_run_loop_freertos_enable_data_source_callbacks,
291     &btstack_run_loop_freertos_disable_data_source_callbacks,
292     &btstack_run_loop_freertos_set_timer,
293     &btstack_run_loop_freertos_add_timer,
294     &btstack_run_loop_freertos_remove_timer,
295     &btstack_run_loop_freertos_execute,
296     &btstack_run_loop_freertos_dump_timer,
297     &btstack_run_loop_freertos_get_time_ms,
298 };
299