xref: /btstack/platform/qt/btstack_run_loop_qt.cpp (revision c9921182ab4b1f83e3e5c671446dca5ffdf45b90)
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_run_loop_base.h"
51 #include "btstack_util.h"
52 #include "btstack_linked_list.h"
53 #include "btstack_debug.h"
54 
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <sys/time.h>
58 #include <time.h>
59 #include <unistd.h>
60 
61 static void btstack_run_loop_qt_dump_timer(void);
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 #include <QHash>
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 void btstack_run_loop_qt_update_data_source(btstack_data_source_t * ds){
84 #ifdef Q_OS_WIN
85     QWinEventNotifier * win_notifier = win_event_notifiers.value(ds, NULL);
86     if (win_notifier){
87         bool enabled = (ds->flags & (DATA_SOURCE_CALLBACK_READ | DATA_SOURCE_CALLBACK_WRITE)) != 0;
88         win_notifier->setEnabled(enabled);
89     }
90 #else
91     QSocketNotifier * read_notifier = read_notifiers.value(ds, NULL);
92     if (read_notifier){
93         bool read_enabled = (ds->flags & DATA_SOURCE_CALLBACK_READ)   != 0;
94         read_notifier->setEnabled(read_enabled);
95     }
96     QSocketNotifier * write_notifier = write_notifiers.value(ds, NULL);
97     if (write_notifier){
98         bool write_enabled = (ds->flags & DATA_SOURCE_CALLBACK_WRITE) != 0;
99         write_notifier->setEnabled(write_enabled);
100     }
101 #endif
102 }
103 
104 void btstack_run_loop_qt_add_data_source(btstack_data_source_t *ds){
105 #ifdef Q_OS_WIN
106     QWinEventNotifier * win_notifier = new QWinEventNotifier(ds->source.handle);
107     win_event_notifiers.insert(ds, win_notifier);
108     btstack_run_loop_qt_update_data_source(ds);
109     QObject::connect(win_notifier, SIGNAL(activated(HANDLE)), btstack_run_loop_object, SLOT(processDataSource(HANDLE)));
110     log_debug("add data source %p with handle %p", ds, ds->source.handle);
111 #else
112     // POSIX Systems: macOS, Linux, ..
113     QSocketNotifier * read_notifier = new QSocketNotifier(ds->source.fd, QSocketNotifier::Read);
114     QSocketNotifier * write_notifier = new QSocketNotifier(ds->source.fd, QSocketNotifier::Write);
115     read_notifiers.insert(ds, read_notifier);
116     write_notifiers.insert(ds, write_notifier);
117     btstack_run_loop_qt_update_data_source(ds);
118     QObject::connect(read_notifier, SIGNAL(activated(int)),  btstack_run_loop_object, SLOT(processDataSourceRead(int)));
119     QObject::connect(write_notifier, SIGNAL(activated(int)), btstack_run_loop_object, SLOT(processDataSourceWrite(int)));
120 #endif
121     btstack_run_loop_base_add_data_source(ds);
122 }
123 
124 bool btstack_run_loop_qt_remove_data_source(btstack_data_source_t *ds){
125 #ifdef Q_OS_WIN
126     QWinEventNotifier * win_notifier = win_event_notifiers.value(ds, NULL);
127     if (win_notifier){
128         win_event_notifiers.remove(ds);
129         free(win_notifier);
130     }
131 #else
132     QSocketNotifier * read_notifier = read_notifiers.value(ds, NULL);
133     if (read_notifier){
134         read_notifiers.remove(ds);
135         free(read_notifier);
136     }
137     QSocketNotifier * write_notifier = write_notifiers.value(ds, NULL);
138     if (write_notifier){
139         write_notifiers.remove(ds);
140         free(write_notifier);
141     }
142 #endif
143     return btstack_run_loop_base_remove_data_source(ds);
144 }
145 
146 void btstack_run_loop_qt_enable_data_source_callbacks(btstack_data_source_t * ds, uint16_t callback_types){
147     btstack_run_loop_base_enable_data_source_callbacks(ds, callback_types);
148     btstack_run_loop_qt_update_data_source(ds);
149 }
150 
151 void btstack_run_loop_qt_disable_data_source_callbacks(btstack_data_source_t * ds, uint16_t callback_types){
152     btstack_run_loop_base_disable_data_source_callbacks(ds, callback_types);
153     btstack_run_loop_qt_update_data_source(ds);
154 }
155 
156 #ifdef _POSIX_MONOTONIC_CLOCK
157 /**
158  * @brief Returns the timespec which represents the time(stop - start). It might be negative
159  */
160 static void timespec_diff(struct timespec *start, struct timespec *stop, struct timespec *result){
161     result->tv_sec = stop->tv_sec - start->tv_sec;
162     if ((stop->tv_nsec - start->tv_nsec) < 0) {
163         result->tv_sec = stop->tv_sec - start->tv_sec - 1;
164         result->tv_nsec = stop->tv_nsec - start->tv_nsec + 1000000000;
165     } else {
166         result->tv_sec = stop->tv_sec - start->tv_sec;
167         result->tv_nsec = stop->tv_nsec - start->tv_nsec;
168     }
169 }
170 
171 /**
172  * @brief Convert timespec to miliseconds, might overflow
173  */
174 static uint64_t timespec_to_milliseconds(struct timespec *a){
175     uint64_t ret = 0;
176     uint64_t sec_val = (uint64_t)(a->tv_sec);
177     uint64_t nsec_val = (uint64_t)(a->tv_nsec);
178     ret = (sec_val*1000) + (nsec_val/1000000);
179     return ret;
180 }
181 
182 /**
183  * @brief Returns the milisecond value of (stop - start). Might overflow
184  */
185 static uint64_t timespec_diff_milis(struct timespec* start, struct timespec* stop){
186     struct timespec diff_ts;
187     timespec_diff(start, stop, &diff_ts);
188     return timespec_to_milliseconds(&diff_ts);
189 }
190 #endif
191 
192 /**
193  * @brief Queries the current time in ms since start
194  */
195 static uint32_t btstack_run_loop_qt_get_time_ms(void){
196     uint32_t time_ms;
197 #ifdef _POSIX_MONOTONIC_CLOCK
198     struct timespec now_ts;
199     clock_gettime(CLOCK_MONOTONIC, &now_ts);
200     time_ms = (uint32_t) timespec_diff_milis(&init_ts, &now_ts);
201 #else
202     struct timeval tv;
203     gettimeofday(&tv, NULL);
204     time_ms = (uint32_t) ((tv.tv_sec  - init_tv.tv_sec) * 1000) + (tv.tv_usec / 1000);
205 #endif
206     return time_ms;
207 }
208 
209 /**
210  * Execute run_loop
211  */
212 static void btstack_run_loop_qt_execute(void) {
213 }
214 
215 // set timer
216 static void btstack_run_loop_qt_set_timer(btstack_timer_source_t *a, uint32_t timeout_in_ms){
217     uint32_t time_ms = btstack_run_loop_qt_get_time_ms();
218     a->timeout = time_ms + timeout_in_ms;
219     log_debug("btstack_run_loop_qt_set_timer to %u ms (now %u, timeout %u)", a->timeout, time_ms, timeout_in_ms);
220 }
221 
222 /**
223  * Add timer to run_loop (keep list sorted)
224  */
225 static void btstack_run_loop_qt_add_timer(btstack_timer_source_t *ts){
226     uint32_t now = btstack_run_loop_qt_get_time_ms();
227     int32_t next_timeout_before = btstack_run_loop_base_get_time_until_timeout(now);
228     btstack_run_loop_base_add_timer(ts);
229     int32_t next_timeout_after = btstack_run_loop_base_get_time_until_timeout(now);
230     if (next_timeout_after >= 0 && (next_timeout_after != next_timeout_before)){
231         QTimer::singleShot((uint32_t)next_timeout_after, btstack_run_loop_object, SLOT(processTimers()));
232     }
233 }
234 
235 // BTstackRunLoopQt class implementation
236 void BTstackRunLoopQt::processTimers(){
237     uint32_t now = btstack_run_loop_qt_get_time_ms();
238     int32_t next_timeout_before = btstack_run_loop_base_get_time_until_timeout(now);
239     btstack_run_loop_base_process_timers(btstack_run_loop_qt_get_time_ms());
240     int32_t next_timeout_after = btstack_run_loop_base_get_time_until_timeout(now);
241     if (next_timeout_after >= 0 && (next_timeout_after != next_timeout_before)){
242         QTimer::singleShot((uint32_t)next_timeout_after, this, SLOT(processTimers()));
243     }
244 }
245 #ifdef Q_OS_WIN
246 void BTstackRunLoopQt::processDataSource(HANDLE handle){
247     log_debug("lookup data source for handle %p, sender %p", handle, QObject::sender());
248     // find ds
249     btstack_linked_list_iterator_t it;
250     btstack_linked_list_iterator_init(&it, &btstack_run_loop_base_data_sources);
251     while (btstack_linked_list_iterator_has_next(&it)){
252         btstack_data_source_t *ds = (btstack_data_source_t*) btstack_linked_list_iterator_next(&it);
253         if (handle == ds->source.handle){
254             if (ds->flags & DATA_SOURCE_CALLBACK_READ){
255                 log_debug("process read ds %p with handle %p", ds, ds->source.handle);
256                 ds->process(ds, DATA_SOURCE_CALLBACK_READ);
257             } else if (ds->flags & DATA_SOURCE_CALLBACK_WRITE){
258                 log_debug("process write ds %p with handle %p", ds, ds->source.handle);
259                 ds->process(ds, DATA_SOURCE_CALLBACK_WRITE);
260             }
261             break;
262         }
263     }
264 }
265 #else
266 
267 static void btstack_run_loop_qt_process_data_source(int fd, uint16_t callback_types){
268     // find ds
269     btstack_linked_list_iterator_t it;
270     btstack_linked_list_iterator_init(&it, &btstack_run_loop_base_data_sources);
271     while (btstack_linked_list_iterator_has_next(&it)){
272         btstack_data_source_t *ds = (btstack_data_source_t*) btstack_linked_list_iterator_next(&it);
273         if (fd == ds->source.fd){
274             if ((callback_types & DATA_SOURCE_CALLBACK_READ) != 0){
275                 if ((ds->flags & DATA_SOURCE_CALLBACK_READ)  != 0){
276                     ds->process(ds, DATA_SOURCE_CALLBACK_READ);
277                 }
278             }
279             if ((callback_types & DATA_SOURCE_CALLBACK_WRITE) != 0){
280                 if ((ds->flags & DATA_SOURCE_CALLBACK_WRITE)  != 0){
281                     ds->process(ds, DATA_SOURCE_CALLBACK_WRITE);
282                 }
283             }
284             break;
285         }
286     }
287 }
288 
289 void BTstackRunLoopQt::processDataSourceRead(int fd){
290     log_debug("read - lookup data source for handle %p, sender %p", fd, QObject::sender());
291     btstack_run_loop_qt_process_data_source(fd, DATA_SOURCE_CALLBACK_READ);
292 }
293 void BTstackRunLoopQt::processDataSourceWrite(int fd){
294     log_debug("write - lookup data source for handle %p, sender %p", fd, QObject::sender());
295     btstack_run_loop_qt_process_data_source(fd, DATA_SOURCE_CALLBACK_WRITE);
296 }
297 #endif
298 
299 static void btstack_run_loop_qt_init(void){
300 
301     btstack_run_loop_base_init();
302 
303     btstack_run_loop_object = new BTstackRunLoopQt();
304 
305 #ifdef _POSIX_MONOTONIC_CLOCK
306     clock_gettime(CLOCK_MONOTONIC, &init_ts);
307     init_ts.tv_nsec = 0;
308 #else
309     // just assume that we started at tv_usec == 0
310     gettimeofday(&init_tv, NULL);
311     init_tv.tv_usec = 0;
312 #endif
313 }
314 
315 static void btstack_run_loop_qt_dump_timer(void){
316     btstack_linked_item_t *it;
317     int i = 0;
318     for (it = (btstack_linked_item_t *) btstack_run_loop_base_timers; it ; it = it->next){
319         btstack_timer_source_t *ts = (btstack_timer_source_t*) it;
320         log_info("timer %u (%p): timeout %u\n", i, ts, ts->timeout);
321     }
322 }
323 
324 static const btstack_run_loop_t btstack_run_loop_qt = {
325     &btstack_run_loop_qt_init,
326     &btstack_run_loop_qt_add_data_source,
327     &btstack_run_loop_qt_remove_data_source,
328     &btstack_run_loop_qt_enable_data_source_callbacks,
329     &btstack_run_loop_qt_disable_data_source_callbacks,
330     &btstack_run_loop_qt_set_timer,
331     &btstack_run_loop_qt_add_timer,
332     &btstack_run_loop_base_remove_timer,
333     &btstack_run_loop_qt_execute,
334     &btstack_run_loop_qt_dump_timer,
335     &btstack_run_loop_qt_get_time_ms,
336 };
337 
338 /**
339  * Provide btstack_run_loop_posix instance
340  */
341 const btstack_run_loop_t * btstack_run_loop_qt_get_instance(void){
342     return &btstack_run_loop_qt;
343 }
344 
345