xref: /btstack/platform/windows/btstack_run_loop_windows.c (revision 46d6c6044a82d8cc98f35a2ca93e895adb50ca82)
1 /*
2  * Copyright (C) 2014 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 BLUEKITCHEN
24  * GMBH 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 #define BTSTACK_FILE__ "btstack_run_loop_windows.c"
39 
40 /*
41  *  btstack_run_loop_windows.c
42  */
43 
44 #include "btstack_run_loop.h"
45 #include "btstack_run_loop_windows.h"
46 #include "btstack_linked_list.h"
47 #include "btstack_debug.h"
48 #include "btstack_util.h"
49 
50 #include <Windows.h>
51 
52 #include <stdio.h>
53 #include <stdlib.h>
54 
55 // start time.
56 static ULARGE_INTEGER start_time;
57 
58 static bool run_loop_exit_requested;
59 
60 // to trigger run loop from other thread
61 static HANDLE btstack_run_loop_windows_callbacks_mutex;
62 static btstack_data_source_t btstack_run_loop_windows_process_callbacks_ds;
63 static btstack_data_source_t btstack_run_loop_windows_poll_data_sources_ds;
64 
65 /**
66  * @brief Queries the current time in ms since start
67  */
68 static uint32_t btstack_run_loop_windows_get_time_ms(void){
69 
70     FILETIME    file_time;
71     SYSTEMTIME  system_time;
72     ULARGE_INTEGER now_time;
73     GetSystemTime(&system_time);
74     SystemTimeToFileTime(&system_time, &file_time);
75     now_time.LowPart =  file_time.dwLowDateTime;
76     now_time.HighPart = file_time.dwHighDateTime;
77     uint32_t time_ms = (uint32_t)((now_time.QuadPart - start_time.QuadPart) / 10000);
78     log_debug("btstack_run_loop_windows_get_time_ms: %u", time_ms);
79     return time_ms;
80 }
81 
82 /**
83  * Execute run_loop
84  */
85 static void btstack_run_loop_windows_execute(void) {
86 
87     btstack_linked_list_iterator_t it;
88 
89     while (true) {
90 
91         // process timers
92         uint32_t now_ms = btstack_run_loop_windows_get_time_ms();
93         btstack_run_loop_base_process_timers(now_ms);
94 
95         // get next timeout
96         int32_t timeout_ms = btstack_run_loop_base_get_time_until_timeout(now_ms);
97         if (timeout_ms < 0){
98             timeout_ms = INFINITE;
99         }
100 
101         // collect handles to wait for
102         HANDLE handles[100];
103         memset(handles, 0, sizeof(handles));
104         int num_handles = 0;
105         btstack_linked_list_iterator_init(&it, &btstack_run_loop_base_data_sources);
106         while (btstack_linked_list_iterator_has_next(&it)){
107             btstack_data_source_t *ds = (btstack_data_source_t*) btstack_linked_list_iterator_next(&it);
108             if (ds->source.handle == 0) continue;
109             if (ds->flags & (DATA_SOURCE_CALLBACK_READ | DATA_SOURCE_CALLBACK_WRITE)){
110                 handles[num_handles++] = ds->source.handle;
111                 log_debug("btstack_run_loop_execute adding handle %p", ds->source.handle);
112             }
113         }
114 
115         // wait for timeout or data source to become ready
116         DWORD res;
117         if (num_handles){
118             // wait for ready Events or timeout
119             res = WaitForMultipleObjects(num_handles, &handles[0], 0, timeout_ms);
120         } else {
121             // just wait for timeout
122             Sleep(timeout_ms);
123             res = WAIT_TIMEOUT;
124         }
125 
126         // process data source
127         if (WAIT_OBJECT_0 <= res && res < (WAIT_OBJECT_0 + num_handles)){
128             void * triggered_handle = handles[res - WAIT_OBJECT_0];
129             btstack_linked_list_iterator_init(&it, &btstack_run_loop_base_data_sources);
130             while (btstack_linked_list_iterator_has_next(&it)){
131                 btstack_data_source_t *ds = (btstack_data_source_t*) btstack_linked_list_iterator_next(&it);
132                 log_debug("btstack_run_loop_windows_execute: check ds %p with handle %p\n", ds, ds->source.handle);
133                 if (triggered_handle == ds->source.handle){
134                     if (ds->flags & DATA_SOURCE_CALLBACK_READ){
135                         log_debug("btstack_run_loop_windows_execute: process read ds %p with handle %p\n", ds, ds->source.handle);
136                         ds->process(ds, DATA_SOURCE_CALLBACK_READ);
137                     } else if (ds->flags & DATA_SOURCE_CALLBACK_WRITE){
138                         log_debug("btstack_run_loop_windows_execute: process write ds %p with handle %p\n", ds, ds->source.handle);
139                         ds->process(ds, DATA_SOURCE_CALLBACK_WRITE);
140                     }
141                     break;
142                 }
143             }
144         }
145     }
146 }
147 
148 static void btstack_run_loop_windows_trigger_exit(void){
149     run_loop_exit_requested = true;
150 }
151 
152 // set timer
153 static void btstack_run_loop_windows_set_timer(btstack_timer_source_t *a, uint32_t timeout_in_ms){
154     uint32_t time_ms = btstack_run_loop_windows_get_time_ms();
155     a->timeout = time_ms + timeout_in_ms;
156     log_debug("btstack_run_loop_windows_set_timer to %u ms (now %u, timeout %u)", a->timeout, time_ms, timeout_in_ms);
157 }
158 
159 static void btstack_run_loop_windows_process_callbacks_handler(btstack_data_source_t * ds, btstack_data_source_callback_type_t callback_type){
160     UNUSED(callback_type);
161 
162     // execute callbacks
163     while (1){
164         // protect list with mutex (Win32 style)
165         DWORD dwWaitResult = WaitForSingleObject( btstack_run_loop_windows_callbacks_mutex, INFINITE);
166         if (dwWaitResult != WAIT_OBJECT_0) return;
167 
168         btstack_context_callback_registration_t * callback_registration = (btstack_context_callback_registration_t *) btstack_linked_list_pop(&btstack_run_loop_base_callbacks);
169         ReleaseMutex(btstack_run_loop_windows_callbacks_mutex);
170 
171         if (callback_registration == NULL){
172             break;
173         }
174         (*callback_registration->callback)(callback_registration->context);
175     }
176 }
177 
178 static void btstack_run_loop_windows_execute_on_main_thread(btstack_context_callback_registration_t * callback_registration){
179     if (btstack_run_loop_windows_process_callbacks_ds.source.handle == NULL) return;
180 
181     // protect list with mutex (Win32 style)
182     DWORD dwWaitResult = WaitForSingleObject( btstack_run_loop_windows_callbacks_mutex, INFINITE);
183     if (dwWaitResult != WAIT_OBJECT_0) return;
184 
185     // We own mutex now, add callback to list
186     btstack_run_loop_base_add_callback(callback_registration);
187     ReleaseMutex(btstack_run_loop_windows_callbacks_mutex);
188     // trigger run loop
189     SetEvent(btstack_run_loop_windows_process_callbacks_ds.source.handle);
190 }
191 
192 
193 static void btstack_run_loop_windows_poll_data_sources_handler(btstack_data_source_t * ds, btstack_data_source_callback_type_t callback_type){
194     UNUSED(callback_type);
195     btstack_run_loop_base_poll_data_sources();
196 }
197 
198 static void btstack_run_loop_windows_poll_data_sources_from_irq(void){
199     SetEvent(btstack_run_loop_windows_poll_data_sources_ds.source.handle);
200 }
201 
202 static void btstack_run_loop_windows_init(void){
203     btstack_run_loop_base_init();
204 
205     // store start time
206     FILETIME    file_time;
207     SYSTEMTIME  system_time;
208     GetSystemTime(&system_time);
209     SystemTimeToFileTime(&system_time, &file_time);
210     start_time.LowPart =  file_time.dwLowDateTime;
211     start_time.HighPart = file_time.dwHighDateTime;
212 
213     // Create mutex with no initial owner
214     btstack_run_loop_windows_callbacks_mutex = CreateMutex(
215         NULL,              // default security attributes
216         FALSE,             // initially not owned
217         NULL);             // unnamed mutex
218     if (btstack_run_loop_windows_callbacks_mutex == NULL){
219         log_info("CreateMutex error: %ld\n", GetLastError());
220         return;
221     }
222 
223     // create Event that can be notified from other thread. bManualReset is fALSE => Object is auto-reset
224     btstack_run_loop_windows_process_callbacks_ds.source.handle  = CreateEvent(NULL, FALSE, FALSE, NULL);
225     btstack_run_loop_enable_data_source_callbacks(&btstack_run_loop_windows_process_callbacks_ds, DATA_SOURCE_CALLBACK_READ);
226     btstack_run_loop_set_data_source_handler(&btstack_run_loop_windows_process_callbacks_ds, &btstack_run_loop_windows_process_callbacks_handler);
227     btstack_run_loop_add_data_source(&btstack_run_loop_windows_process_callbacks_ds);
228 
229     btstack_run_loop_windows_poll_data_sources_ds.source.handle  = CreateEvent(NULL, FALSE, FALSE, NULL);
230     btstack_run_loop_enable_data_source_callbacks(&btstack_run_loop_windows_poll_data_sources_ds, DATA_SOURCE_CALLBACK_READ);
231     btstack_run_loop_set_data_source_handler(&btstack_run_loop_windows_poll_data_sources_ds, &btstack_run_loop_windows_poll_data_sources_handler);
232     btstack_run_loop_add_data_source(&btstack_run_loop_windows_poll_data_sources_ds);
233 }
234 
235 static const btstack_run_loop_t btstack_run_loop_windows = {
236     &btstack_run_loop_windows_init,
237     &btstack_run_loop_base_add_data_source,
238     &btstack_run_loop_base_remove_data_source,
239     &btstack_run_loop_base_enable_data_source_callbacks,
240     &btstack_run_loop_base_disable_data_source_callbacks,
241     &btstack_run_loop_windows_set_timer,
242     &btstack_run_loop_base_add_timer,
243     &btstack_run_loop_base_remove_timer,
244     &btstack_run_loop_windows_execute,
245     &btstack_run_loop_base_dump_timer,
246     &btstack_run_loop_windows_get_time_ms,
247     &btstack_run_loop_windows_poll_data_sources_from_irq,
248     &btstack_run_loop_windows_execute_on_main_thread,
249     &btstack_run_loop_windows_trigger_exit
250 };
251 
252 /**
253  * Provide btstack_run_loop_windows instance
254  */
255 const btstack_run_loop_t * btstack_run_loop_windows_get_instance(void){
256     return &btstack_run_loop_windows;
257 }
258 
259