1 /*
2 * Copyright (C) 2019 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_qt.c"
39
40 /*
41 * btstack_run_loop_qt.c
42 */
43
44 // enable POSIX functions (needed for -std=c99)
45 #define _POSIX_C_SOURCE 200809
46
47 #include "btstack_run_loop_qt.h"
48
49 #include "btstack_run_loop.h"
50 #include "btstack_util.h"
51 #include "btstack_linked_list.h"
52 #include "btstack_debug.h"
53
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <sys/time.h>
57 #include <time.h>
58 #include <unistd.h>
59
60 #include <QHash>
61 #include <QMutex>
62
63 // start time. tv_usec/tv_nsec = 0
64 #ifdef _POSIX_MONOTONIC_CLOCK
65 // use monotonic clock if available
66 static struct timespec init_ts;
67 #else
68 // fallback to gettimeofday
69 static struct timeval init_tv;
70 #endif
71
72 static BTstackRunLoopQt * btstack_run_loop_object;
73
74
75 #ifdef Q_OS_WIN
76 // associate each data source with QWinEventNotifier
77 static QHash<btstack_data_source_t *, QWinEventNotifier *> win_event_notifiers;
78 #else
79 static QHash<btstack_data_source_t *, QSocketNotifier *> read_notifiers;
80 static QHash<btstack_data_source_t *, QSocketNotifier *> write_notifiers;
81 #endif
82
83 static QMutex run_loop_callback_mutex;
84
85 static void btstack_run_loop_qt_dump_timer(void);
86
btstack_run_loop_qt_update_data_source(btstack_data_source_t * ds)87 static void btstack_run_loop_qt_update_data_source(btstack_data_source_t * ds){
88 #ifdef Q_OS_WIN
89 QWinEventNotifier * win_notifier = win_event_notifiers.value(ds, NULL);
90 if (win_notifier){
91 bool enabled = (ds->flags & (DATA_SOURCE_CALLBACK_READ | DATA_SOURCE_CALLBACK_WRITE)) != 0;
92 win_notifier->setEnabled(enabled);
93 }
94 #else
95 QSocketNotifier * read_notifier = read_notifiers.value(ds, NULL);
96 if (read_notifier){
97 bool read_enabled = (ds->flags & DATA_SOURCE_CALLBACK_READ) != 0;
98 read_notifier->setEnabled(read_enabled);
99 }
100 QSocketNotifier * write_notifier = write_notifiers.value(ds, NULL);
101 if (write_notifier){
102 bool write_enabled = (ds->flags & DATA_SOURCE_CALLBACK_WRITE) != 0;
103 write_notifier->setEnabled(write_enabled);
104 }
105 #endif
106 }
107
btstack_run_loop_qt_add_data_source(btstack_data_source_t * ds)108 void btstack_run_loop_qt_add_data_source(btstack_data_source_t *ds){
109 #ifdef Q_OS_WIN
110 QWinEventNotifier * win_notifier = new QWinEventNotifier(ds->source.handle);
111 win_event_notifiers.insert(ds, win_notifier);
112 btstack_run_loop_qt_update_data_source(ds);
113 QObject::connect(win_notifier, SIGNAL(activated(HANDLE)), btstack_run_loop_object, SLOT(processDataSource(HANDLE)));
114 log_debug("add data source %p with handle %p", ds, ds->source.handle);
115 #else
116 // POSIX Systems: macOS, Linux, ..
117 QSocketNotifier * read_notifier = new QSocketNotifier(ds->source.fd, QSocketNotifier::Read);
118 QSocketNotifier * write_notifier = new QSocketNotifier(ds->source.fd, QSocketNotifier::Write);
119 read_notifiers.insert(ds, read_notifier);
120 write_notifiers.insert(ds, write_notifier);
121 btstack_run_loop_qt_update_data_source(ds);
122 QObject::connect(read_notifier, SIGNAL(activated(int)), btstack_run_loop_object, SLOT(processDataSourceRead(int)));
123 QObject::connect(write_notifier, SIGNAL(activated(int)), btstack_run_loop_object, SLOT(processDataSourceWrite(int)));
124 #endif
125 btstack_run_loop_base_add_data_source(ds);
126 }
127
btstack_run_loop_qt_remove_data_source(btstack_data_source_t * ds)128 bool btstack_run_loop_qt_remove_data_source(btstack_data_source_t *ds){
129 #ifdef Q_OS_WIN
130 QWinEventNotifier * win_notifier = win_event_notifiers.value(ds, NULL);
131 if (win_notifier){
132 win_event_notifiers.remove(ds);
133 free(win_notifier);
134 }
135 #else
136 QSocketNotifier * read_notifier = read_notifiers.value(ds, NULL);
137 if (read_notifier){
138 read_notifiers.remove(ds);
139 free(read_notifier);
140 }
141 QSocketNotifier * write_notifier = write_notifiers.value(ds, NULL);
142 if (write_notifier){
143 write_notifiers.remove(ds);
144 free(write_notifier);
145 }
146 #endif
147 return btstack_run_loop_base_remove_data_source(ds);
148 }
149
btstack_run_loop_qt_enable_data_source_callbacks(btstack_data_source_t * ds,uint16_t callback_types)150 void btstack_run_loop_qt_enable_data_source_callbacks(btstack_data_source_t * ds, uint16_t callback_types){
151 btstack_run_loop_base_enable_data_source_callbacks(ds, callback_types);
152 btstack_run_loop_qt_update_data_source(ds);
153 }
154
btstack_run_loop_qt_disable_data_source_callbacks(btstack_data_source_t * ds,uint16_t callback_types)155 void btstack_run_loop_qt_disable_data_source_callbacks(btstack_data_source_t * ds, uint16_t callback_types){
156 btstack_run_loop_base_disable_data_source_callbacks(ds, callback_types);
157 btstack_run_loop_qt_update_data_source(ds);
158 }
159
160 #ifdef _POSIX_MONOTONIC_CLOCK
161 /**
162 * @brief Returns the timespec which represents the time(stop - start). It might be negative
163 */
timespec_diff(struct timespec * start,struct timespec * stop,struct timespec * result)164 static void timespec_diff(struct timespec *start, struct timespec *stop, struct timespec *result){
165 result->tv_sec = stop->tv_sec - start->tv_sec;
166 if ((stop->tv_nsec - start->tv_nsec) < 0) {
167 result->tv_sec = stop->tv_sec - start->tv_sec - 1;
168 result->tv_nsec = stop->tv_nsec - start->tv_nsec + 1000000000;
169 } else {
170 result->tv_sec = stop->tv_sec - start->tv_sec;
171 result->tv_nsec = stop->tv_nsec - start->tv_nsec;
172 }
173 }
174
175 /**
176 * @brief Convert timespec to miliseconds, might overflow
177 */
timespec_to_milliseconds(struct timespec * a)178 static uint64_t timespec_to_milliseconds(struct timespec *a){
179 uint64_t ret = 0;
180 uint64_t sec_val = (uint64_t)(a->tv_sec);
181 uint64_t nsec_val = (uint64_t)(a->tv_nsec);
182 ret = (sec_val*1000) + (nsec_val/1000000);
183 return ret;
184 }
185
186 /**
187 * @brief Returns the milisecond value of (stop - start). Might overflow
188 */
timespec_diff_milis(struct timespec * start,struct timespec * stop)189 static uint64_t timespec_diff_milis(struct timespec* start, struct timespec* stop){
190 struct timespec diff_ts;
191 timespec_diff(start, stop, &diff_ts);
192 return timespec_to_milliseconds(&diff_ts);
193 }
194 #endif
195
196 /**
197 * @brief Queries the current time in ms since start
198 */
btstack_run_loop_qt_get_time_ms(void)199 static uint32_t btstack_run_loop_qt_get_time_ms(void){
200 uint32_t time_ms;
201 #ifdef _POSIX_MONOTONIC_CLOCK
202 struct timespec now_ts;
203 clock_gettime(CLOCK_MONOTONIC, &now_ts);
204 time_ms = (uint32_t) timespec_diff_milis(&init_ts, &now_ts);
205 #else
206 struct timeval tv;
207 gettimeofday(&tv, NULL);
208 time_ms = (uint32_t) ((tv.tv_sec - init_tv.tv_sec) * 1000) + (tv.tv_usec / 1000);
209 #endif
210 return time_ms;
211 }
212
213 /**
214 * Execute run_loop
215 */
btstack_run_loop_qt_execute(void)216 static void btstack_run_loop_qt_execute(void) {
217 }
218
219 // set timer
btstack_run_loop_qt_set_timer(btstack_timer_source_t * a,uint32_t timeout_in_ms)220 static void btstack_run_loop_qt_set_timer(btstack_timer_source_t *a, uint32_t timeout_in_ms){
221 uint32_t time_ms = btstack_run_loop_qt_get_time_ms();
222 a->timeout = time_ms + timeout_in_ms;
223 log_debug("btstack_run_loop_qt_set_timer to %u ms (now %u, timeout %u)", a->timeout, time_ms, timeout_in_ms);
224 }
225
226 /**
227 * Add timer to run_loop (keep list sorted)
228 */
btstack_run_loop_qt_add_timer(btstack_timer_source_t * ts)229 static void btstack_run_loop_qt_add_timer(btstack_timer_source_t *ts){
230 uint32_t now = btstack_run_loop_qt_get_time_ms();
231 int32_t next_timeout_before = btstack_run_loop_base_get_time_until_timeout(now);
232 btstack_run_loop_base_add_timer(ts);
233 int32_t next_timeout_after = btstack_run_loop_base_get_time_until_timeout(now);
234 if (next_timeout_after >= 0 && (next_timeout_after != next_timeout_before)){
235 QTimer::singleShot((uint32_t)next_timeout_after, btstack_run_loop_object, SLOT(processTimers()));
236 }
237 }
238
239 // BTstackRunLoopQt class implementation
BTstackRunLoopQt(void)240 BTstackRunLoopQt::BTstackRunLoopQt(void) : QObject() {
241 // enforce slot callback on receiver (main thread) via Qt::QueuedConnection
242 connect(this, &BTstackRunLoopQt::callbackAdded, this, &BTstackRunLoopQt::processCallbacks, Qt::QueuedConnection);
243 connect(this, &BTstackRunLoopQt::dataSourcesPollRequested, this, &BTstackRunLoopQt::pollDataSources, Qt::QueuedConnection);
244 }
245
processTimers()246 void BTstackRunLoopQt::processTimers(){
247 uint32_t now = btstack_run_loop_qt_get_time_ms();
248 int32_t next_timeout_before = btstack_run_loop_base_get_time_until_timeout(now);
249 btstack_run_loop_base_process_timers(btstack_run_loop_qt_get_time_ms());
250 int32_t next_timeout_after = btstack_run_loop_base_get_time_until_timeout(now);
251 if (next_timeout_after >= 0 && (next_timeout_after != next_timeout_before)){
252 QTimer::singleShot((uint32_t)next_timeout_after, this, SLOT(processTimers()));
253 }
254 }
255 #ifdef Q_OS_WIN
processDataSource(HANDLE handle)256 void BTstackRunLoopQt::processDataSource(HANDLE handle){
257 log_debug("lookup data source for handle %p, sender %p", handle, QObject::sender());
258 // find ds
259 btstack_linked_list_iterator_t it;
260 btstack_linked_list_iterator_init(&it, &btstack_run_loop_base_data_sources);
261 while (btstack_linked_list_iterator_has_next(&it)){
262 btstack_data_source_t *ds = (btstack_data_source_t*) btstack_linked_list_iterator_next(&it);
263 if (handle == ds->source.handle){
264 if (ds->flags & DATA_SOURCE_CALLBACK_READ){
265 log_debug("process read ds %p with handle %p", ds, ds->source.handle);
266 ds->process(ds, DATA_SOURCE_CALLBACK_READ);
267 } else if (ds->flags & DATA_SOURCE_CALLBACK_WRITE){
268 log_debug("process write ds %p with handle %p", ds, ds->source.handle);
269 ds->process(ds, DATA_SOURCE_CALLBACK_WRITE);
270 }
271 break;
272 }
273 }
274 }
275 #else
276
processCallbacks(void)277 void BTstackRunLoopQt::processCallbacks(void) {
278 // execute callbacks - protect list with mutex
279 while (1){
280 run_loop_callback_mutex.lock();
281 btstack_context_callback_registration_t * callback_registration = (btstack_context_callback_registration_t *) btstack_linked_list_pop(&btstack_run_loop_base_callbacks);
282 run_loop_callback_mutex.unlock();
283 if (callback_registration == NULL){
284 break;
285 }
286 (*callback_registration->callback)(callback_registration->context);
287 }
288 }
289
pollDataSources(void)290 void BTstackRunLoopQt::pollDataSources(void) {
291 btstack_run_loop_base_poll_data_sources();
292 }
293
btstack_run_loop_qt_execute_on_main_thread(btstack_context_callback_registration_t * callback_registration)294 static void btstack_run_loop_qt_execute_on_main_thread(btstack_context_callback_registration_t * callback_registration){
295 // protect list with mutex
296 run_loop_callback_mutex.lock();
297 btstack_run_loop_base_add_callback(callback_registration);
298 run_loop_callback_mutex.unlock();
299 btstack_run_loop_object->emit callbackAdded();
300 }
301
btstack_run_loop_qt_poll_data_sources_from_irq(void)302 static void btstack_run_loop_qt_poll_data_sources_from_irq(void){
303 btstack_run_loop_object->emit dataSourcesPollRequested();
304 }
305
btstack_run_loop_qt_process_data_source(int fd,uint16_t callback_types)306 static void btstack_run_loop_qt_process_data_source(int fd, uint16_t callback_types){
307 // find ds
308 btstack_linked_list_iterator_t it;
309 btstack_linked_list_iterator_init(&it, &btstack_run_loop_base_data_sources);
310 while (btstack_linked_list_iterator_has_next(&it)){
311 btstack_data_source_t *ds = (btstack_data_source_t*) btstack_linked_list_iterator_next(&it);
312 if (fd == ds->source.fd){
313 if ((callback_types & DATA_SOURCE_CALLBACK_READ) != 0){
314 if ((ds->flags & DATA_SOURCE_CALLBACK_READ) != 0){
315 ds->process(ds, DATA_SOURCE_CALLBACK_READ);
316 }
317 }
318 if ((callback_types & DATA_SOURCE_CALLBACK_WRITE) != 0){
319 if ((ds->flags & DATA_SOURCE_CALLBACK_WRITE) != 0){
320 ds->process(ds, DATA_SOURCE_CALLBACK_WRITE);
321 }
322 }
323 break;
324 }
325 }
326 }
327
processDataSourceRead(int fd)328 void BTstackRunLoopQt::processDataSourceRead(int fd){
329 log_debug("read - lookup data source for handle %p, sender %p", fd, QObject::sender());
330 btstack_run_loop_qt_process_data_source(fd, DATA_SOURCE_CALLBACK_READ);
331 }
processDataSourceWrite(int fd)332 void BTstackRunLoopQt::processDataSourceWrite(int fd){
333 log_debug("write - lookup data source for handle %p, sender %p", fd, QObject::sender());
334 btstack_run_loop_qt_process_data_source(fd, DATA_SOURCE_CALLBACK_WRITE);
335 }
336 #endif
337
btstack_run_loop_qt_init(void)338 static void btstack_run_loop_qt_init(void){
339
340 btstack_run_loop_base_init();
341
342 btstack_run_loop_object = new BTstackRunLoopQt();
343
344 #ifdef _POSIX_MONOTONIC_CLOCK
345 clock_gettime(CLOCK_MONOTONIC, &init_ts);
346 init_ts.tv_nsec = 0;
347 #else
348 // just assume that we started at tv_usec == 0
349 gettimeofday(&init_tv, NULL);
350 init_tv.tv_usec = 0;
351 #endif
352 }
353
btstack_run_loop_qt_dump_timer(void)354 static void btstack_run_loop_qt_dump_timer(void){
355 btstack_linked_item_t *it;
356 int i = 0;
357 for (it = (btstack_linked_item_t *) btstack_run_loop_base_timers; it ; it = it->next){
358 btstack_timer_source_t *ts = (btstack_timer_source_t*) it;
359 log_info("timer %u (%p): timeout %u\n", i, ts, ts->timeout);
360 }
361 }
362
363 static const btstack_run_loop_t btstack_run_loop_qt = {
364 &btstack_run_loop_qt_init,
365 &btstack_run_loop_qt_add_data_source,
366 &btstack_run_loop_qt_remove_data_source,
367 &btstack_run_loop_qt_enable_data_source_callbacks,
368 &btstack_run_loop_qt_disable_data_source_callbacks,
369 &btstack_run_loop_qt_set_timer,
370 &btstack_run_loop_qt_add_timer,
371 &btstack_run_loop_base_remove_timer,
372 &btstack_run_loop_qt_execute,
373 &btstack_run_loop_qt_dump_timer,
374 &btstack_run_loop_qt_get_time_ms,
375 &btstack_run_loop_qt_poll_data_sources_from_irq,
376 &btstack_run_loop_qt_execute_on_main_thread,
377 NULL
378 };
379
380 /**
381 * Provide btstack_run_loop_posix instance
382 */
btstack_run_loop_qt_get_instance(void)383 const btstack_run_loop_t * btstack_run_loop_qt_get_instance(void){
384 return &btstack_run_loop_qt;
385 }
386
387