-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathraw.cpp
More file actions
984 lines (871 loc) · 29.2 KB
/
Copy pathraw.cpp
File metadata and controls
984 lines (871 loc) · 29.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
//#include "BluetoothCommon.h"
//#include "nsString.h"
#define BLUEZ_DBUS_BASE_PATH "/org/bluez"
#define BLUEZ_DBUS_BASE_IFC "org.bluez"
#define DBUS_ADAPTER_IFACE BLUEZ_DBUS_BASE_IFC ".Adapter"
#define DBUS_DEVICE_IFACE BLUEZ_DBUS_BASE_IFC ".Device"
#include <string.h>
#include <stdint.h>
#include <dbus/dbus.h>
#include <stdio.h>
#include <string>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/socket.h>
#include <poll.h>
// size of the dbus event loops pollfd structure, hopefully never to be grown
#define DEFAULT_INITIAL_POLLFD_COUNT 8
class RawDBusConnection
{
public:
RawDBusConnection();
~RawDBusConnection();
bool createDBusConnection();
DBusMessage * dbus_func_args_timeout_valist(
int timeout_ms,
DBusError *err,
const char *path,
const char *ifc,
const char *func,
int first_arg_type,
va_list args);
DBusMessage * dbus_func_args_timeout(
int timeout_ms,
const char *path,
const char *ifc,
const char *func,
int first_arg_type,
...);
DBusMessage * dbus_func_args(
const char *path,
const char *ifc,
const char *func,
int first_arg_type,
...);
DBusMessage * dbus_func_args_error(
DBusError *err,
const char *path,
const char *ifc,
const char *func,
int first_arg_type,
...);
int32_t dbus_returns_int32(DBusMessage *reply);
uint32_t dbus_returns_uint32(DBusMessage *reply);
// std::string dbus_returns_string(DBusMessage *reply);
bool dbus_returns_boolean(DBusMessage *reply);
template<typename T>
bool GetDBusDictValue(DBusMessageIter& iter, const char* name, int expected_type, T& val) {
DBusMessageIter dict_entry, dict;
int size = 0,array_index = 0;
int len = 0, prop_type = DBUS_TYPE_INVALID, prop_index = -1, type;
if(dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY) {
printf("This isn't a dictionary!\n");
return false;
}
dbus_message_iter_recurse(&iter, &dict);
do {
len = 0;
if (dbus_message_iter_get_arg_type(&dict) != DBUS_TYPE_DICT_ENTRY)
{
printf("Not a dict entry!\n");
return false;
}
dbus_message_iter_recurse(&dict, &dict_entry);
DBusMessageIter prop_val, array_val_iter;
char *property = NULL;
uint32_t array_type;
char *str_val;
int i, j, type, int_val;
if (dbus_message_iter_get_arg_type(&dict_entry) != DBUS_TYPE_STRING) {
printf("Iter not a string!\n");
return false;
}
dbus_message_iter_get_basic(&dict_entry, &property);
printf("Property: %s\n", property);
if(strcmp(property, name) != 0) continue;
if (!dbus_message_iter_next(&dict_entry))
{
printf("No next!\n");
return false;
}
if (dbus_message_iter_get_arg_type(&dict_entry) != DBUS_TYPE_VARIANT)
{
printf("Iter not a variant!\n");
return false;
}
dbus_message_iter_recurse(&dict_entry, &prop_val);
// type = properties[*prop_index].type;
if (dbus_message_iter_get_arg_type(&prop_val) != expected_type) {
// LOGE("Property type mismatch in get_property: %d, expected:%d, index:%d",
// dbus_message_dict_entry_get_arg_type(&prop_val), type, *prop_index);
printf("Not the type we expect!\n");
return false;
}
dbus_message_iter_get_basic(&prop_val, &val);
return true;
} while(dbus_message_iter_next(&dict));
return false;
}
virtual void EventFilter(DBusMessage* msg) = 0;
protected:
DBusConnection* mConnection;
};
RawDBusConnection::RawDBusConnection() {
}
RawDBusConnection::~RawDBusConnection() {
}
bool RawDBusConnection::createDBusConnection() {
DBusError err;
dbus_error_init(&err);
dbus_threads_init_default();
mConnection = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
if (dbus_error_is_set(&err)) {
dbus_error_free(&err);
return false;
}
dbus_connection_set_exit_on_disconnect(mConnection, FALSE);
return true;
}
// If err is NULL, then any errors will be LOGE'd, and free'd and the reply
// will be NULL.
// If err is not NULL, then it is assumed that dbus_error_init was already
// called, and error's will be returned to the caller without logging. The
// return value is NULL iff an error was set. The client must free the error if
// set.
DBusMessage * RawDBusConnection::dbus_func_args_timeout_valist(int timeout_ms,
DBusError *err,
const char *path,
const char *ifc,
const char *func,
int first_arg_type,
va_list args) {
DBusMessage *msg = NULL, *reply = NULL;
const char *name;
bool return_error = (err != NULL);
if (!return_error) {
err = (DBusError*)malloc(sizeof(DBusError));
dbus_error_init(err);
}
/* Compose the command */
msg = dbus_message_new_method_call(BLUEZ_DBUS_BASE_IFC, path, ifc, func);
if (msg == NULL) {
//LOGE("Could not allocate D-Bus message object!");
goto done;
}
/* append arguments */
if (!dbus_message_append_args_valist(msg, first_arg_type, args)) {
//LOGE("Could not append argument to method call!");
goto done;
}
/* Make the call. */
reply = dbus_connection_send_with_reply_and_block(mConnection, msg, timeout_ms, err);
if (!return_error && dbus_error_is_set(err)) {
//LOG_AND_FREE_DBUS_ERROR_WITH_MSG(err, msg);
}
done:
if (!return_error) {
free(err);
}
if (msg) dbus_message_unref(msg);
return reply;
}
DBusMessage * RawDBusConnection::dbus_func_args_timeout(int timeout_ms,
const char *path,
const char *ifc,
const char *func,
int first_arg_type,
...) {
DBusMessage *ret;
va_list lst;
va_start(lst, first_arg_type);
ret = dbus_func_args_timeout_valist(timeout_ms, NULL,
path, ifc, func,
first_arg_type, lst);
va_end(lst);
return ret;
}
DBusMessage * RawDBusConnection::dbus_func_args(
const char *path,
const char *ifc,
const char *func,
int first_arg_type,
...) {
DBusMessage *ret;
va_list lst;
va_start(lst, first_arg_type);
ret = dbus_func_args_timeout_valist(-1, NULL,
path, ifc, func,
first_arg_type, lst);
va_end(lst);
return ret;
}
DBusMessage * RawDBusConnection::dbus_func_args_error(DBusError *err,
const char *path,
const char *ifc,
const char *func,
int first_arg_type,
...) {
DBusMessage *ret;
va_list lst;
va_start(lst, first_arg_type);
ret = dbus_func_args_timeout_valist(-1, err,
path, ifc, func,
first_arg_type, lst);
va_end(lst);
return ret;
}
int32_t RawDBusConnection::dbus_returns_int32(DBusMessage *reply) {
DBusError err;
int ret = -1;
dbus_error_init(&err);
if (!dbus_message_get_args(reply, &err,
DBUS_TYPE_INT32, &ret,
DBUS_TYPE_INVALID)) {
//LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, reply);
}
dbus_message_unref(reply);
return ret;
}
uint32_t RawDBusConnection::dbus_returns_uint32(DBusMessage *reply) {
DBusError err;
int ret = -1;
dbus_error_init(&err);
if (!dbus_message_get_args(reply, &err,
DBUS_TYPE_UINT32, &ret,
DBUS_TYPE_INVALID)) {
//LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, reply);
}
dbus_message_unref(reply);
return ret;
}
// nsString RawDBusConnection::dbus_returns_string(DBusMessage *reply) {
// DBusError err;
// nsString ret = NS_LITERAL_STRING("test");
// const char *name;
// dbus_error_init(&err);
// if (dbus_message_get_args(reply, &err,
// DBUS_TYPE_STRING, &name,
// DBUS_TYPE_INVALID)) {
// //ret = env->NewStringUTF(name);
// } else {
// //LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, reply);
// }
// dbus_message_unref(reply);
// return ret;
// }
bool RawDBusConnection::dbus_returns_boolean(DBusMessage *reply) {
DBusError err;
bool ret = false;
dbus_bool_t val = false;
dbus_error_init(&err);
/* Check the return value. */
if (dbus_message_get_args(reply, &err,
DBUS_TYPE_BOOLEAN, &val,
DBUS_TYPE_INVALID)) {
ret = val == true ? true : false;
} else {
//LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, reply);
}
dbus_message_unref(reply);
return ret;
}
class BluetoothAdapter : public RawDBusConnection {
public:
BluetoothAdapter();
~BluetoothAdapter() {}
void get_adapter_path ();
void get_adapter_properties();
void start_discovery();
virtual void EventFilter(DBusMessage* msg);
const char* mAdapterPath;
bool mPowered;
bool mDiscoverable;
uint32_t mClass;
const char* mAddress;
const char* mName;
bool mPairable;
uint32_t mPairableTimeout;
uint32_t mDiscoverableTimeout;
bool mDiscovering;
};
BluetoothAdapter::BluetoothAdapter() {
}
void BluetoothAdapter::EventFilter(DBusMessage* msg) {
}
void BluetoothAdapter::get_adapter_path() {
DBusMessage *msg = NULL, *reply = NULL;
DBusError err;
const char *device_path = NULL;
int attempt = 0;
for (attempt = 0; attempt < 1000 && reply == NULL; attempt ++) {
msg = dbus_message_new_method_call("org.bluez", "/",
"org.bluez.Manager", "DefaultAdapter");
if (!msg) {
printf("%s: Can't allocate new method call for get_adapter_path!",
__FUNCTION__);
return;
}
dbus_message_append_args(msg, DBUS_TYPE_INVALID);
dbus_error_init(&err);
reply = dbus_connection_send_with_reply_and_block(mConnection, msg, -1, &err);
if (!reply) {
if (dbus_error_is_set(&err)) {
if (dbus_error_has_name(&err,
"org.freedesktop.DBus.Error.ServiceUnknown")) {
// bluetoothd is still down, retry
//LOG_AND_FREE_DBUS_ERROR(&err);
printf("Service unknown\n");
usleep(10000); // 10 ms
continue;
} else {
// Some other error we weren't expecting
printf("other error\n");
//LOG_AND_FREE_DBUS_ERROR(&err);
}
}
goto failed;
}
}
if (attempt == 1000) {
printf("timeout\n");
//LOGE("Time out while trying to get Adapter path, is bluetoothd up ?");
goto failed;
}
if (!dbus_message_get_args(reply, &err, DBUS_TYPE_OBJECT_PATH,
&device_path, DBUS_TYPE_INVALID)
|| !device_path){
if (dbus_error_is_set(&err)) {
//LOG_AND_FREE_DBUS_ERROR(&err);
}
goto failed;
}
dbus_message_unref(msg);
printf("Adapter path: %s\n", device_path);
mAdapterPath = device_path;
return;
failed:
dbus_message_unref(msg);
}
void BluetoothAdapter::get_adapter_properties() {
DBusMessage *msg, *reply;
DBusError err;
dbus_error_init(&err);
reply = dbus_func_args(mAdapterPath,
DBUS_ADAPTER_IFACE, "GetProperties",
DBUS_TYPE_INVALID);
if (!reply) {
if (dbus_error_is_set(&err)) {
//LOG_AND_FREE_DBUS_ERROR(&err);
printf("Error!\n");
} else
printf("DBus reply is NULL in function %s\n", __FUNCTION__);
return ;
}
DBusMessageIter iter;
//jobjectArray str_array = NULL;
if (!dbus_message_iter_init(reply, &iter)) {
printf("Return value is wrong!\n");
dbus_message_unref(reply);
return;
}
//str_array = parse_adapter_properties(env, &iter);
GetDBusDictValue<const char*>(iter, "Name", DBUS_TYPE_STRING, mName);
printf("name! %s\n", mName);
dbus_message_unref(reply);
printf("Adapter properties got\n");
}
void BluetoothAdapter::start_discovery() {
DBusMessage *msg, *reply;
DBusError err;
dbus_error_init(&err);
reply = dbus_func_args(mAdapterPath,
DBUS_ADAPTER_IFACE, "StartDiscovery",
DBUS_TYPE_INVALID);
if (!reply) {
if (dbus_error_is_set(&err)) {
//LOG_AND_FREE_DBUS_ERROR(&err);
printf("Error!\n");
} else
printf("DBus reply is NULL in function %s\n", __FUNCTION__);
return ;
}
}
#define EVENT_LOOP_EXIT 1
#define EVENT_LOOP_ADD 2
#define EVENT_LOOP_REMOVE 3
static unsigned int unix_events_to_dbus_flags(short events) {
return (events & DBUS_WATCH_READABLE ? POLLIN : 0) |
(events & DBUS_WATCH_WRITABLE ? POLLOUT : 0) |
(events & DBUS_WATCH_ERROR ? POLLERR : 0) |
(events & DBUS_WATCH_HANGUP ? POLLHUP : 0);
}
static short dbus_flags_to_unix_events(unsigned int flags) {
return (flags & POLLIN ? DBUS_WATCH_READABLE : 0) |
(flags & POLLOUT ? DBUS_WATCH_WRITABLE : 0) |
(flags & POLLERR ? DBUS_WATCH_ERROR : 0) |
(flags & POLLHUP ? DBUS_WATCH_HANGUP : 0);
}
class DBusThread : protected RawDBusConnection {
public:
DBusThread();
~DBusThread();
bool setUpEventLoop();
bool startEventLoop();
void stopEventLoop();
bool isEventLoopRunning();
static dbus_bool_t addWatch(DBusWatch* w, void* ptr);
static void removeWatch(DBusWatch* w, void* ptr);
static void toggleWatch(DBusWatch* w, void* ptr);
static void* eventLoop(void* ptr);
static DBusHandlerResult event_filter(DBusConnection *conn, DBusMessage *msg,
void *data);
static void handleWatchAdd(DBusThread* dbt);
void EventFilter(DBusMessage* msg);
/* protects the thread */
pthread_mutex_t thread_mutex;
pthread_t thread;
/* our comms socket */
/* mem for the list of sockets to listen to */
struct pollfd *pollData;
int pollMemberCount;
int pollDataSize;
/* mem for matching set of dbus watch ptrs */
DBusWatch **watchData;
/* pair of sockets for event loop control, Reader and Writer */
int controlFdR;
int controlFdW;
bool running;
};
void DBusThread::EventFilter(DBusMessage* msg) {
printf("I SHOULD NOT BE BEING CALLED\n");
}
DBusThread::DBusThread()
{
createDBusConnection();
pthread_mutex_init(&(thread_mutex), NULL);
pollData = NULL;
}
DBusThread::~DBusThread()
{
}
dbus_bool_t DBusThread::addWatch(DBusWatch *watch, void *data) {
printf("add Watch!\n");
DBusThread *dbt = (DBusThread *)data;
if (dbus_watch_get_enabled(watch)) {
printf("enabled Watch!\n");
// note that we can't just send the watch and inspect it later
// because we may get a removeWatch call before this data is reacted
// to by our eventloop and remove this watch.. reading the add first
// and then inspecting the recently deceased watch would be bad.
char control = EVENT_LOOP_ADD;
write(dbt->controlFdW, &control, sizeof(char));
int fd = dbus_watch_get_fd(watch);
write(dbt->controlFdW, &fd, sizeof(int));
unsigned int flags = dbus_watch_get_flags(watch);
write(dbt->controlFdW, &flags, sizeof(unsigned int));
write(dbt->controlFdW, &watch, sizeof(DBusWatch*));
}
return true;
}
void DBusThread::removeWatch(DBusWatch *watch, void *data) {
printf("remove Watch!\n");
DBusThread *dbt = (DBusThread *)data;
char control = EVENT_LOOP_REMOVE;
write(dbt->controlFdW, &control, sizeof(char));
int fd = dbus_watch_get_fd(watch);
write(dbt->controlFdW, &fd, sizeof(int));
unsigned int flags = dbus_watch_get_flags(watch);
write(dbt->controlFdW, &flags, sizeof(unsigned int));
}
void DBusThread::toggleWatch(DBusWatch *watch, void *data) {
printf("toggle Watch!\n");
if (dbus_watch_get_enabled(watch)) {
DBusThread::addWatch(watch, data);
} else {
DBusThread::removeWatch(watch, data);
}
}
void DBusThread::handleWatchAdd(DBusThread* dbt) {
DBusWatch *watch;
int newFD;
unsigned int flags;
printf("Handling watch addition!\n");
read(dbt->controlFdR, &newFD, sizeof(int));
read(dbt->controlFdR, &flags, sizeof(unsigned int));
read(dbt->controlFdR, &watch, sizeof(DBusWatch *));
short events = dbus_flags_to_unix_events(flags);
for (int y = 0; y<dbt->pollMemberCount; y++) {
if ((dbt->pollData[y].fd == newFD) &&
(dbt->pollData[y].events == events)) {
printf("DBusWatch duplicate add\n");
return;
}
}
if (dbt->pollMemberCount == dbt->pollDataSize) {
printf("Bluetooth EventLoop poll struct growing\n");
struct pollfd *temp = (struct pollfd *)malloc(
sizeof(struct pollfd) * (dbt->pollMemberCount+1));
if (!temp) {
return;
}
memcpy(temp, dbt->pollData, sizeof(struct pollfd) *
dbt->pollMemberCount);
free(dbt->pollData);
dbt->pollData = temp;
DBusWatch **temp2 = (DBusWatch **)malloc(sizeof(DBusWatch *) *
(dbt->pollMemberCount+1));
if (!temp2) {
return;
}
memcpy(temp2, dbt->watchData, sizeof(DBusWatch *) *
dbt->pollMemberCount);
free(dbt->watchData);
dbt->watchData = temp2;
dbt->pollDataSize++;
}
dbt->pollData[dbt->pollMemberCount].fd = newFD;
dbt->pollData[dbt->pollMemberCount].revents = 0;
dbt->pollData[dbt->pollMemberCount].events = events;
dbt->watchData[dbt->pollMemberCount] = watch;
dbt->pollMemberCount++;
}
bool
DBusThread::setUpEventLoop()
{
if(!mConnection) {
return false;
}
dbus_threads_init_default();
DBusError err;
dbus_error_init(&err);
// Add a filter for all incoming messages_base
if (!dbus_connection_add_filter(mConnection, DBusThread::event_filter, this, NULL)){
return false;
}
// Set which messages will be processed by this dbus connection
dbus_bus_add_match(mConnection,
"type='signal',interface='org.freedesktop.DBus'",
&err);
if (dbus_error_is_set(&err)) {
//LOG_AND_FREE_DBUS_ERROR(&err);
return false;
}
dbus_bus_add_match(mConnection,
"type='signal',interface='"BLUEZ_DBUS_BASE_IFC".Adapter'",
&err);
if (dbus_error_is_set(&err)) {
return false;
}
dbus_bus_add_match(mConnection,
"type='signal',interface='"BLUEZ_DBUS_BASE_IFC".Device'",
&err);
if (dbus_error_is_set(&err)) {
return false;
}
dbus_bus_add_match(mConnection,
"type='signal',interface='org.bluez.AudioSink'",
&err);
if (dbus_error_is_set(&err)) {
return false;
}
// const char *agent_path = "/android/bluetooth/agent";
// const char *capabilities = "DisplayYesNo";
// if (register_agent(nat, agent_path, capabilities) < 0) {
// dbus_connection_unregister_object_path (dbt->conn, agent_path);
// return JNI_FALSE;
// }
return true;
}
// Called by dbus during WaitForAndDispatchEventNative()
DBusHandlerResult DBusThread::event_filter(DBusConnection *conn, DBusMessage *msg,
void *data) {
// native_data_t *nat;
// JNIEnv *env;
DBusError err;
DBusHandlerResult ret;
dbus_error_init(&err);
// nat = (native_data_t *)data;
// dbt->vm->GetEnv((void**)&env, dbt->envVer);
if (dbus_message_get_type(msg) != DBUS_MESSAGE_TYPE_SIGNAL) {
printf("%s: not interested (not a signal).\n", __FUNCTION__);
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
printf("%s: Received signal %s:%s from %s\n", __FUNCTION__,
dbus_message_get_interface(msg), dbus_message_get_member(msg),
dbus_message_get_path(msg));
// env->PushLocalFrame(EVENT_LOOP_REFS);
// if (dbus_message_is_signal(msg,
// "org.bluez.Adapter",
// "DeviceFound")) {
// char *c_address;
// DBusMessageIter iter;
// jobjectArray str_array = NULL;
// if (dbus_message_iter_init(msg, &iter)) {
// dbus_message_iter_get_basic(&iter, &c_address);
// if (dbus_message_iter_next(&iter))
// str_array =
// parse_remote_device_properties(env, &iter);
// }
// if (str_array != NULL) {
// env->CallVoidMethod(dbt->me,
// method_onDeviceFound,
// env->NewStringUTF(c_address),
// str_array);
// } else
// LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg);
// goto success;
// } else if (dbus_message_is_signal(msg,
// "org.bluez.Adapter",
// "DeviceDisappeared")) {
// char *c_address;
// if (dbus_message_get_args(msg, &err,
// DBUS_TYPE_STRING, &c_address,
// DBUS_TYPE_INVALID)) {
// LOGV("... address = %s", c_address);
// env->CallVoidMethod(dbt->me, method_onDeviceDisappeared,
// env->NewStringUTF(c_address));
// } else LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg);
// goto success;
// } else if (dbus_message_is_signal(msg,
// "org.bluez.Adapter",
// "DeviceCreated")) {
// char *c_object_path;
// if (dbus_message_get_args(msg, &err,
// DBUS_TYPE_OBJECT_PATH, &c_object_path,
// DBUS_TYPE_INVALID)) {
// LOGV("... address = %s", c_object_path);
// env->CallVoidMethod(dbt->me,
// method_onDeviceCreated,
// env->NewStringUTF(c_object_path));
// } else LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg);
// goto success;
// } else if (dbus_message_is_signal(msg,
// "org.bluez.Adapter",
// "DeviceRemoved")) {
// char *c_object_path;
// if (dbus_message_get_args(msg, &err,
// DBUS_TYPE_OBJECT_PATH, &c_object_path,
// DBUS_TYPE_INVALID)) {
// LOGV("... Object Path = %s", c_object_path);
// env->CallVoidMethod(dbt->me,
// method_onDeviceRemoved,
// env->NewStringUTF(c_object_path));
// } else LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg);
// goto success;
// } else if (dbus_message_is_signal(msg,
// "org.bluez.Adapter",
// "PropertyChanged")) {
// jobjectArray str_array = parse_adapter_property_change(env, msg);
// if (str_array != NULL) {
// /* Check if bluetoothd has (re)started, if so update the path. */
// jstring property =(jstring) env->GetObjectArrayElement(str_array, 0);
// const char *c_property = env->GetStringUTFChars(property, NULL);
// if (!strncmp(c_property, "Powered", strlen("Powered"))) {
// jstring value =
// (jstring) env->GetObjectArrayElement(str_array, 1);
// const char *c_value = env->GetStringUTFChars(value, NULL);
// if (!strncmp(c_value, "true", strlen("true")))
// dbt->adapter = get_adapter_path(dbt->conn);
// env->ReleaseStringUTFChars(value, c_value);
// }
// env->ReleaseStringUTFChars(property, c_property);
// env->CallVoidMethod(dbt->me,
// method_onPropertyChanged,
// str_array);
// } else LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg);
// goto success;
// } else if (dbus_message_is_signal(msg,
// "org.bluez.Device",
// "PropertyChanged")) {
// jobjectArray str_array = parse_remote_device_property_change(env, msg);
// if (str_array != NULL) {
// const char *remote_device_path = dbus_message_get_path(msg);
// env->CallVoidMethod(dbt->me,
// method_onDevicePropertyChanged,
// env->NewStringUTF(remote_device_path),
// str_array);
// } else LOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg);
// goto success;
// } else if (dbus_message_is_signal(msg,
// "org.bluez.Device",
// "DisconnectRequested")) {
// const char *remote_device_path = dbus_message_get_path(msg);
// env->CallVoidMethod(dbt->me,
// method_onDeviceDisconnectRequested,
// env->NewStringUTF(remote_device_path));
// goto success;
// }
// ret = a2dp_event_filter(msg, env);
// env->PopLocalFrame(NULL);
// return ret;
// success:
// env->PopLocalFrame(NULL);
return DBUS_HANDLER_RESULT_HANDLED;
}
void* DBusThread::eventLoop(void *ptr) {
char name[] = "BT EventLoop";
DBusThread* dbt = (DBusThread*)ptr;
bool result;
dbus_connection_set_watch_functions(dbt->mConnection, DBusThread::addWatch,
DBusThread::removeWatch, DBusThread::toggleWatch, ptr, NULL);
dbt->running = true;
while (1) {
for (int i = 0; i < dbt->pollMemberCount; i++) {
if (!dbt->pollData[i].revents) {
continue;
}
if (dbt->pollData[i].fd == dbt->controlFdR) {
printf("Got a watch request!\n");
char data;
while (recv(dbt->controlFdR, &data, sizeof(char), MSG_DONTWAIT)
!= -1) {
switch (data) {
case EVENT_LOOP_EXIT:
{
dbus_connection_set_watch_functions(dbt->mConnection,
NULL, NULL, NULL, NULL, NULL);
// tearDownEventLoop(nat);
int fd = dbt->controlFdR;
dbt->controlFdR = 0;
close(fd);
return NULL;
}
case EVENT_LOOP_ADD:
{
DBusThread::handleWatchAdd(dbt);
break;
}
case EVENT_LOOP_REMOVE:
{
// handleWatchRemove(nat);
break;
}
}
}
} else {
printf("Got an watch handle!\n");
short events = dbt->pollData[i].revents;
unsigned int flags = unix_events_to_dbus_flags(events);
dbus_watch_handle(dbt->watchData[i], flags);
dbt->pollData[i].revents = 0;
// can only do one - it may have caused a 'remove'
break;
}
}
while (dbus_connection_dispatch(dbt->mConnection) ==
DBUS_DISPATCH_DATA_REMAINS) {
printf("Got an event!\n");
}
poll(dbt->pollData, dbt->pollMemberCount, -1);
}
}
bool DBusThread::startEventLoop() {
pthread_mutex_lock(&(thread_mutex));
bool result = false;
running = false;
printf("Hey, what's controlFdR right now? %d\n", controlFdR);
if (pollData) {
printf("trying to start EventLoop a second time!\n");
pthread_mutex_unlock( &(thread_mutex) );
return false;
}
pollData = (struct pollfd *)malloc(sizeof(struct pollfd) *
DEFAULT_INITIAL_POLLFD_COUNT);
if (!pollData) {
printf("out of memory error starting EventLoop!\n");
goto done;
}
watchData = (DBusWatch **)malloc(sizeof(DBusWatch *) *
DEFAULT_INITIAL_POLLFD_COUNT);
if (!watchData) {
printf("out of memory error starting EventLoop!\n");
goto done;
}
memset(pollData, 0, sizeof(struct pollfd) *
DEFAULT_INITIAL_POLLFD_COUNT);
memset(watchData, 0, sizeof(DBusWatch *) *
DEFAULT_INITIAL_POLLFD_COUNT);
pollDataSize = DEFAULT_INITIAL_POLLFD_COUNT;
pollMemberCount = 1;
if (socketpair(AF_LOCAL, SOCK_STREAM, 0, &(controlFdR))) {
printf("Error getting BT control socket\n");
goto done;
}
pollData[0].fd = controlFdR;
pollData[0].events = POLLIN;
if (setUpEventLoop() != true) {
printf("failure setting up Event Loop!\n");
goto done;
}
printf("Control file descriptor: %d\n", controlFdR);
pthread_create(&(thread), NULL, DBusThread::eventLoop, this);
result = true;
done:
if (false == result) {
if (controlFdW) {
close(controlFdW);
controlFdW = 0;
}
if (controlFdR) {
close(controlFdR);
controlFdR = 0;
}
if (pollData) free(pollData);
pollData = NULL;
if (watchData) free(watchData);
watchData = NULL;
pollDataSize = 0;
pollMemberCount = 0;
}
pthread_mutex_unlock(&(thread_mutex));
return result;
}
void DBusThread::stopEventLoop() {
pthread_mutex_lock(&(thread_mutex));
if (pollData) {
char data = EVENT_LOOP_EXIT;
ssize_t t = write(controlFdW, &data, sizeof(char));
void *ret;
pthread_join(thread, &ret);
free(pollData);
pollData = NULL;
free(watchData);
watchData = NULL;
pollDataSize = 0;
pollMemberCount = 0;
int fd = controlFdW;
controlFdW = 0;
close(fd);
}
running = false;
pthread_mutex_unlock(&(thread_mutex));
printf("Event loop stopped!\n");
}
bool DBusThread::isEventLoopRunning() {
bool result = false;
pthread_mutex_lock(&(thread_mutex));
if (running) {
result = true;
}
pthread_mutex_unlock(&(thread_mutex));
return result;
}
int main(int argc, char** argv) {
DBusThread t;
BluetoothAdapter b;
b.createDBusConnection();
b.get_adapter_path();
b.get_adapter_properties();
if(!t.startEventLoop()) {
printf("Cannot start loop!\n");
return 1;
}
b.start_discovery();
sleep(100);
t.stopEventLoop();
// b.start_dbus_thread();
// b.start_device_discovery();
// b.stop_device_discovery();
return 0;
}