xref: /btstack/platform/freertos/btstack_run_loop_freertos.c (revision a813c6af954b1ed10b5fd5b17b7990fa061f3fd8)
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 void btstack_run_loop_freertos_execute_code_on_main_thread_from_isr(void (*fn)(void *arg), void * arg){
145     function_call_t message;
146     message.fn  = fn;
147     message.arg = arg;
148     BaseType_t xHigherPriorityTaskWoken;
149     xQueueSendToBackFromISR(btstack_run_loop_queue, &message, &xHigherPriorityTaskWoken);
150     btstack_run_loop_freertos_trigger_from_isr();
151 }
152 #endif
153 
154 void btstack_run_loop_freertos_trigger_exit(void){
155     run_loop_exit_requested = true;
156 }
157 
158 /**
159  * Execute run_loop
160  */
161 static void btstack_run_loop_freertos_execute(void) {
162     log_debug("RL: execute");
163 
164     run_loop_exit_requested = false;
165 
166     while (true) {
167 
168         // process data sources
169         btstack_run_loop_base_poll_data_sources();
170 
171         // process registered function calls on run loop thread
172         while (true){
173             function_call_t message = { NULL, NULL };
174             BaseType_t res = xQueueReceive( btstack_run_loop_queue, &message, 0);
175             if (res == pdFALSE) break;
176             if (message.fn){
177                 message.fn(message.arg);
178             }
179         }
180 
181         // process timers
182         uint32_t now = btstack_run_loop_freertos_get_time_ms();
183         btstack_run_loop_base_process_timers(now);
184 
185         // exit triggered by btstack_run_loop_freertos_trigger_exit (from data source, timer, run on main thread)
186         if (run_loop_exit_requested) break;
187 
188         // wait for timeout or event group/task notification
189         int32_t timeout_next_timer_ms = btstack_run_loop_base_get_time_until_timeout(now);
190 
191         uint32_t timeout_ms = portMAX_DELAY;
192         if (timeout_next_timer_ms >= 0){
193             timeout_ms = (uint32_t) timeout_next_timer_ms;
194         }
195 
196         log_debug("RL: wait with timeout %u", (int) timeout_ms);
197 #ifdef HAVE_FREERTOS_TASK_NOTIFICATIONS
198         xTaskNotifyWait(pdFALSE, 0xffffffff, NULL, pdMS_TO_TICKS(timeout_ms));
199 #else
200         xEventGroupWaitBits(btstack_run_loop_event_group, EVENT_GROUP_FLAG_RUN_LOOP, 1, 0, pdMS_TO_TICKS(timeout_ms));
201 #endif
202     }
203 }
204 
205 static void btstack_run_loop_freertos_init(void){
206     btstack_run_loop_base_init();
207 
208 #ifdef USE_STATIC_ALLOC
209     btstack_run_loop_queue = xQueueCreateStatic(RUN_LOOP_QUEUE_LENGTH, RUN_LOOP_QUEUE_ITEM_SIZE, btstack_run_loop_queue_storage, &btstack_run_loop_queue_object);
210 #else
211     btstack_run_loop_queue = xQueueCreate(RUN_LOOP_QUEUE_LENGTH, RUN_LOOP_QUEUE_ITEM_SIZE);
212 #endif
213 
214 #ifndef HAVE_FREERTOS_TASK_NOTIFICATIONS
215     // event group to wake run loop
216     btstack_run_loop_event_group = xEventGroupCreate();
217 #endif
218 
219     // task to handle to optimize 'run on main thread'
220     btstack_run_loop_task = xTaskGetCurrentTaskHandle();
221 
222     log_info("run loop init, task %p, queue item size %u", btstack_run_loop_task, (int) sizeof(function_call_t));
223 }
224 
225 /**
226  * @brief Provide btstack_run_loop_posix instance for use with btstack_run_loop_init
227  */
228 
229 static const btstack_run_loop_t btstack_run_loop_freertos = {
230     &btstack_run_loop_freertos_init,
231     &btstack_run_loop_base_add_data_source,
232     &btstack_run_loop_base_remove_data_source,
233     &btstack_run_loop_base_enable_data_source_callbacks,
234     &btstack_run_loop_base_disable_data_source_callbacks,
235     &btstack_run_loop_freertos_set_timer,
236     &btstack_run_loop_base_add_timer,
237     &btstack_run_loop_base_remove_timer,
238     &btstack_run_loop_freertos_execute,
239     &btstack_run_loop_base_dump_timer,
240     &btstack_run_loop_freertos_get_time_ms,
241 };
242 
243 const btstack_run_loop_t * btstack_run_loop_freertos_get_instance(void){
244     return &btstack_run_loop_freertos;
245 }
246