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