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