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