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