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