xref: /btstack/platform/qt/btstack_run_loop_qt.cpp (revision b3483efb036b1a4f207fd285183f7b62e39389cb)
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 
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 
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 
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 
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 
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  */
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  */
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  */
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  */
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  */
216 static void btstack_run_loop_qt_execute(void) {
217 }
218 
219 // set timer
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  */
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
240 BTstackRunLoopQt::BTstackRunLoopQt(void) : QObject() {
241     // allow to trigger processCallbacks both from main thread as well as other threads later
242     connect(this, &BTstackRunLoopQt::callbackAdded, this, &BTstackRunLoopQt::processCallbacks, Qt::QueuedConnection);
243 }
244 
245 void BTstackRunLoopQt::processTimers(){
246     uint32_t now = btstack_run_loop_qt_get_time_ms();
247     int32_t next_timeout_before = btstack_run_loop_base_get_time_until_timeout(now);
248     btstack_run_loop_base_process_timers(btstack_run_loop_qt_get_time_ms());
249     int32_t next_timeout_after = btstack_run_loop_base_get_time_until_timeout(now);
250     if (next_timeout_after >= 0 && (next_timeout_after != next_timeout_before)){
251         QTimer::singleShot((uint32_t)next_timeout_after, this, SLOT(processTimers()));
252     }
253 }
254 #ifdef Q_OS_WIN
255 void BTstackRunLoopQt::processDataSource(HANDLE handle){
256     log_debug("lookup data source for handle %p, sender %p", handle, QObject::sender());
257     // find ds
258     btstack_linked_list_iterator_t it;
259     btstack_linked_list_iterator_init(&it, &btstack_run_loop_base_data_sources);
260     while (btstack_linked_list_iterator_has_next(&it)){
261         btstack_data_source_t *ds = (btstack_data_source_t*) btstack_linked_list_iterator_next(&it);
262         if (handle == ds->source.handle){
263             if (ds->flags & DATA_SOURCE_CALLBACK_READ){
264                 log_debug("process read ds %p with handle %p", ds, ds->source.handle);
265                 ds->process(ds, DATA_SOURCE_CALLBACK_READ);
266             } else if (ds->flags & DATA_SOURCE_CALLBACK_WRITE){
267                 log_debug("process write ds %p with handle %p", ds, ds->source.handle);
268                 ds->process(ds, DATA_SOURCE_CALLBACK_WRITE);
269             }
270             break;
271         }
272     }
273 }
274 #else
275 
276 void BTstackRunLoopQt::processCallbacks(void) {
277     // execute callbacks - protect list with mutex
278     while (1){
279         run_loop_callback_mutex.lock();
280         btstack_context_callback_registration_t * callback_registration = (btstack_context_callback_registration_t *) btstack_linked_list_pop(&btstack_run_loop_base_callbacks);
281         run_loop_callback_mutex.unlock();
282         if (callback_registration == NULL){
283             break;
284         }
285         (*callback_registration->callback)(callback_registration->context);
286     }
287 }
288 
289 static void btstack_run_loop_qt_execute_on_main_thread(btstack_context_callback_registration_t * callback_registration){
290     // protect list with mutex
291     run_loop_callback_mutex.lock();
292     btstack_run_loop_base_add_callback(callback_registration);
293     run_loop_callback_mutex.unlock();
294     btstack_run_loop_object->emit callbackAdded();
295 }
296 
297 static void btstack_run_loop_qt_process_data_source(int fd, uint16_t callback_types){
298     // find ds
299     btstack_linked_list_iterator_t it;
300     btstack_linked_list_iterator_init(&it, &btstack_run_loop_base_data_sources);
301     while (btstack_linked_list_iterator_has_next(&it)){
302         btstack_data_source_t *ds = (btstack_data_source_t*) btstack_linked_list_iterator_next(&it);
303         if (fd == ds->source.fd){
304             if ((callback_types & DATA_SOURCE_CALLBACK_READ) != 0){
305                 if ((ds->flags & DATA_SOURCE_CALLBACK_READ)  != 0){
306                     ds->process(ds, DATA_SOURCE_CALLBACK_READ);
307                 }
308             }
309             if ((callback_types & DATA_SOURCE_CALLBACK_WRITE) != 0){
310                 if ((ds->flags & DATA_SOURCE_CALLBACK_WRITE)  != 0){
311                     ds->process(ds, DATA_SOURCE_CALLBACK_WRITE);
312                 }
313             }
314             break;
315         }
316     }
317 }
318 
319 void BTstackRunLoopQt::processDataSourceRead(int fd){
320     log_debug("read - lookup data source for handle %p, sender %p", fd, QObject::sender());
321     btstack_run_loop_qt_process_data_source(fd, DATA_SOURCE_CALLBACK_READ);
322 }
323 void BTstackRunLoopQt::processDataSourceWrite(int fd){
324     log_debug("write - lookup data source for handle %p, sender %p", fd, QObject::sender());
325     btstack_run_loop_qt_process_data_source(fd, DATA_SOURCE_CALLBACK_WRITE);
326 }
327 #endif
328 
329 static void btstack_run_loop_qt_init(void){
330 
331     btstack_run_loop_base_init();
332 
333     btstack_run_loop_object = new BTstackRunLoopQt();
334 
335 #ifdef _POSIX_MONOTONIC_CLOCK
336     clock_gettime(CLOCK_MONOTONIC, &init_ts);
337     init_ts.tv_nsec = 0;
338 #else
339     // just assume that we started at tv_usec == 0
340     gettimeofday(&init_tv, NULL);
341     init_tv.tv_usec = 0;
342 #endif
343 }
344 
345 static void btstack_run_loop_qt_dump_timer(void){
346     btstack_linked_item_t *it;
347     int i = 0;
348     for (it = (btstack_linked_item_t *) btstack_run_loop_base_timers; it ; it = it->next){
349         btstack_timer_source_t *ts = (btstack_timer_source_t*) it;
350         log_info("timer %u (%p): timeout %u\n", i, ts, ts->timeout);
351     }
352 }
353 
354 static const btstack_run_loop_t btstack_run_loop_qt = {
355     &btstack_run_loop_qt_init,
356     &btstack_run_loop_qt_add_data_source,
357     &btstack_run_loop_qt_remove_data_source,
358     &btstack_run_loop_qt_enable_data_source_callbacks,
359     &btstack_run_loop_qt_disable_data_source_callbacks,
360     &btstack_run_loop_qt_set_timer,
361     &btstack_run_loop_qt_add_timer,
362     &btstack_run_loop_base_remove_timer,
363     &btstack_run_loop_qt_execute,
364     &btstack_run_loop_qt_dump_timer,
365     &btstack_run_loop_qt_get_time_ms,
366     NULL, /* poll data sources from irq */
367     &btstack_run_loop_qt_execute_on_main_thread,
368     NULL
369 };
370 
371 /**
372  * Provide btstack_run_loop_posix instance
373  */
374 const btstack_run_loop_t * btstack_run_loop_qt_get_instance(void){
375     return &btstack_run_loop_qt;
376 }
377 
378