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