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