summaryrefslogtreecommitdiff
path: root/btctl.c
blob: 0262abbd65ae30c0aa041b83e4916b3d9a2c0617 (plain)
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
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
/*
 *  Android Bluetooth Control tool
 *
 *  Copyright (C) 2013 João Paulo Rechi Vita
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#include <ctype.h>
#include <err.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <hardware/bluetooth.h>
#include <hardware/bt_gatt.h>
#include <hardware/bt_gatt_client.h>
#include <hardware/hardware.h>

#include "util.h"
#include "rl_helper.h"

#define MAX_LINE_SIZE 64
#define MAX_SVCS_SIZE 128

/* AD types */
#define AD_FLAGS              0x01
#define AD_UUID16_SOME        0x02
#define AD_UUID16_ALL         0x03
#define AD_UUID128_SOME       0x06
#define AD_UUID128_ALL        0x07
#define AD_NAME_SHORT         0x08
#define AD_NAME_COMPLETE      0x09
#define AD_TX_POWER           0x0a
#define AD_SLAVE_CONN_INT     0x12
#define AD_SOLICIT_UUID16     0x14
#define AD_SOLICIT_UUID128    0x15
#define AD_SERVICE_DATA       0x16
#define AD_PUBLIC_ADDRESS     0x17
#define AD_RANDOM_ADDRESS     0x18
#define AD_GAP_APPEARANCE     0x19
#define AD_ADV_INTERVAL       0x1a
#define AD_MANUFACTURER_DATA  0xff

typedef enum {
    NORMAL_PSTATE,
    SSP_CONSENT_PSTATE,
    SSP_ENTRY_PSTATE
} prompt_state_t;

/* Data that have to be acessable by the callbacks */
struct userdata {
    const bt_interface_t *btiface;
    uint8_t btiface_initialized;
    const btgatt_interface_t *gattiface;
    uint8_t gattiface_initialized;
    uint8_t quit;
    bt_state_t adapter_state; /* The adapter is always OFF in the beginning */
    bt_discovery_state_t discovery_state;
    uint8_t scan_state;
    bool client_registered;
    int client_if;
    bt_bdaddr_t remote_addr;
    int conn_id;

    prompt_state_t prompt_state;
    bt_bdaddr_t r_bd_addr; /* remote address when pairing */

    /* When searching for services, we receive at search_result_cb a pointer
     * for btgatt_srvc_id_t. But its value is replaced each time. So one option
     * is to store these values and show a simpler ID to user.
     *
     * This static list limits the number of services that we can store, but it
     * is simpler than using linked list.
     */
    btgatt_srvc_id_t svcs[MAX_SVCS_SIZE];
    int svcs_size;
} u;

/* Arbitrary UUID used to identify this application with the GATT library. The
 * Android JAVA framework
 * (frameworks/base/core/java/android/bluetooth/BluetoothAdapter.java,
 * frameworks/base/core/java/android/bluetooth/BluetoothGatt.java and
 * frameworks/base/core/java/android/bluetooth/BluetoothGattServer.java) uses
 * the method randomUUID()
 */
static bt_uuid_t app_uuid = {
    .uu = { 0x1b, 0x1c, 0xb9, 0x2e, 0x0d, 0x2e, 0x4c, 0x45, \
            0xbb, 0xb9, 0xf4, 0x1b, 0x46, 0x39, 0x23, 0x36 }
};

/* Struct that defines a user command */
typedef struct cmd {
    const char *name;
    const char *description;
    void (*handler)(char *args);
} cmd_t;


void change_prompt_state(prompt_state_t new_state) {
    static char prompt_line[64] = {0};
    char addr_str[BT_ADDRESS_STR_LEN];

    switch (new_state) {
        case NORMAL_PSTATE:
            strcpy(prompt_line, "> ");
            break;
        case SSP_CONSENT_PSTATE:
            sprintf(prompt_line, "Pair with %s (Y/N)? ",
                    ba2str(u.r_bd_addr.address, addr_str));
            break;
        case SSP_ENTRY_PSTATE:
            sprintf(prompt_line, "Entry PIN code of dev %s: ",
                    ba2str(u.r_bd_addr.address, addr_str));
            break;
    }
    rl_set_prompt(prompt_line);
    u.prompt_state = new_state;
}

/* clear any cache list of connected device */
static void clear_list_cache() {

    u.svcs_size = 0;
}

/* Clean blanks until a non-blank is found */
static void line_skip_blanks(char **line) {
    while (**line == ' ')
        (*line)++;
}

/* Parses a sub-string out of a string */
static void line_get_str(char **line, char *str) {
  line_skip_blanks(line);

  while (**line != 0 && **line != ' ') {
        *str = **line;
        (*line)++;
        str++;
  }

  *str = 0;
}

static void cmd_quit(char *args) {
    u.quit = 1;
}

/* Called every time the adapter state changes */
static void adapter_state_change_cb(bt_state_t state) {

    u.adapter_state = state;
    rl_printf("\nAdapter state changed: %i\n", state);

    if (state ==  BT_STATE_ON) {
       /* Register as a GATT client with the stack
        *
	* This has to be done here because it is the first available point we're
	* sure the GATT interface is initialized and ready to be used, since
	* there is callback for gattiface->init().
        */
        bt_status_t status = u.gattiface->client->register_client(&app_uuid);
        if (status != BT_STATUS_SUCCESS)
            rl_printf("Failed to register as a GATT client, status: %d\n",
                      status);
    }
}

/* Enables the Bluetooth adapter */
static void cmd_enable(char *args) {
    int status;

    if (u.adapter_state == BT_STATE_ON) {
        rl_printf("Bluetooth is already enabled\n");
        return;
    }

    status = u.btiface->enable();
    if (status != BT_STATUS_SUCCESS)
        rl_printf("Failed to enable Bluetooth\n");
}

/* Disables the Bluetooth adapter */
static void cmd_disable(char *args) {
    bt_status_t result;
    int status;

    if (u.adapter_state == BT_STATE_OFF) {
        rl_printf("Bluetooth is already disabled\n");
        return;
    }

    result = u.gattiface->client->unregister_client(u.client_if);
    if (result != BT_STATUS_SUCCESS)
        rl_printf("Failed to unregister client, error: %u\n", result);

    status = u.btiface->disable();
    if (status != BT_STATUS_SUCCESS)
        rl_printf("Failed to disable Bluetooth\n");
}

static void adapter_properties_cb(bt_status_t status, int num_properties,
                                  bt_property_t *properties) {
    char addr_str[BT_ADDRESS_STR_LEN];
    int i;

    if (status != BT_STATUS_SUCCESS) {
        rl_printf("Failed to get adapter properties, error: %i\n", status);
        return;
    }

    rl_printf("\nAdapter properties\n");

    while (num_properties--) {
        bt_property_t prop = properties[num_properties];

        switch (prop.type) {
            case BT_PROPERTY_BDNAME:
                rl_printf("  Name: %s\n", (const char *) prop.val);
                break;

            case BT_PROPERTY_BDADDR:
                rl_printf("  Address: %s\n", ba2str((uint8_t *) prop.val,
                          addr_str));
                break;

            case BT_PROPERTY_CLASS_OF_DEVICE:
                rl_printf("  Class of Device: 0x%x\n",
                          ((uint32_t *) prop.val)[0]);
                break;

            case BT_PROPERTY_TYPE_OF_DEVICE:
                switch (((bt_device_type_t *) prop.val)[0]) {
                    case BT_DEVICE_DEVTYPE_BREDR:
                        rl_printf("  Device Type: BR/EDR only\n");
                        break;
                    case BT_DEVICE_DEVTYPE_BLE:
                        rl_printf("  Device Type: LE only\n");
                        break;
                    case BT_DEVICE_DEVTYPE_DUAL:
                        rl_printf("  Device Type: DUAL MODE\n");
                        break;
                }
                break;

            case BT_PROPERTY_ADAPTER_BONDED_DEVICES:
                i = prop.len / sizeof(bt_bdaddr_t);
                rl_printf("  Bonded devices: %u\n", i);
                while (i-- > 0) {
                    uint8_t *addr = ((bt_bdaddr_t *) prop.val)[i].address;
                    rl_printf("    Address: %s\n", ba2str(addr, addr_str));
                }
                break;

            default:
                /* Other properties not handled */
                break;
        }
    }
}

static void device_found_cb(int num_properties, bt_property_t *properties) {
    char addr_str[BT_ADDRESS_STR_LEN];

    rl_printf("\nDevice found\n");

    while (num_properties--) {
        bt_property_t prop = properties[num_properties];

        switch (prop.type) {
            case BT_PROPERTY_BDNAME:
                rl_printf("  name: %s\n", (const char *) prop.val);
                break;

            case BT_PROPERTY_BDADDR:
                rl_printf("  addr: %s\n", ba2str((uint8_t *) prop.val,
                          addr_str));
                break;

            case BT_PROPERTY_CLASS_OF_DEVICE:
                rl_printf("  class: 0x%x\n", ((uint32_t *) prop.val)[0]);
                break;

            case BT_PROPERTY_TYPE_OF_DEVICE:
                switch ( ((bt_device_type_t *) prop.val)[0] ) {
                    case BT_DEVICE_DEVTYPE_BREDR:
                        rl_printf("  type: BR/EDR only\n");
                        break;
                    case BT_DEVICE_DEVTYPE_BLE:
                        rl_printf("  type: LE only\n");
                        break;
                    case BT_DEVICE_DEVTYPE_DUAL:
                        rl_printf("  type: DUAL MODE\n");
                        break;
                }
                break;

            case BT_PROPERTY_REMOTE_FRIENDLY_NAME:
                rl_printf("  alias: %s\n", (const char *) prop.val);
                break;

            case BT_PROPERTY_REMOTE_RSSI:
                rl_printf("  rssi: %i\n", ((uint8_t *) prop.val)[0]);
                break;

            case BT_PROPERTY_REMOTE_VERSION_INFO:
                rl_printf("  version info:\n");
                rl_printf("    version: %d\n",
                          ((bt_remote_version_t *) prop.val)->version);
                rl_printf("    subversion: %d\n",
                          ((bt_remote_version_t *) prop.val)->sub_ver);
                rl_printf("    manufacturer: %d\n",
                          ((bt_remote_version_t *) prop.val)->manufacturer);
                break;

            default:
                rl_printf("  Unknown property type:%i len:%i val:%p\n",
                          prop.type, prop.len, prop.val);
                break;
        }
    }
}

static void discovery_state_changed_cb(bt_discovery_state_t state) {
    u.discovery_state = state;
    rl_printf("\nDiscovery state changed: %i\n", state);
}

static void cmd_discovery(char *args) {
    bt_status_t status;
    char arg[MAX_LINE_SIZE];

    line_get_str(&args, arg);

    if (arg[0] == 0 || strcmp(arg, "help") == 0) {
        rl_printf("discovery -- Controls discovery of nearby devices\n");
        rl_printf("Arguments:\n");
        rl_printf("start   starts a new discovery session\n");
        rl_printf("stop    interrupts an ongoing discovery session\n");

    } else if (strcmp(arg, "start") == 0) {

        if (u.adapter_state != BT_STATE_ON) {
            rl_printf("Unable to start discovery: Adapter is down\n");
            return;
        }

        if (u.discovery_state == BT_DISCOVERY_STARTED) {
            rl_printf("Discovery is already running\n");
            return;
        }

        status = u.btiface->start_discovery();
        if (status != BT_STATUS_SUCCESS)
            rl_printf("Failed to start discovery\n");

    } else if (strcmp(arg, "stop") == 0) {

        if (u.discovery_state == BT_DISCOVERY_STOPPED) {
            rl_printf("Unable to stop discovery: Discovery is not running\n");
            return;
        }

        status = u.btiface->cancel_discovery();
        if (status != BT_STATUS_SUCCESS)
            rl_printf("Failed to stop discovery\n");

    } else
        rl_printf("Invalid argument \"%s\"\n", arg);
}

static void parse_ad_data(uint8_t *data, uint8_t length) {
    uint8_t i = 0;
    uint8_t ad_type = data[i++];

    switch (ad_type) {
        uint8_t j;

        case AD_FLAGS: {
            uint8_t mask = data[i];
            static const struct {
                uint8_t bit;
                const char *str;
            } eir_flags_table[] = {
                {0, "LE Limited Discoverable Mode"},
                {1, "LE General Discoverable Mode"},
                {2, "BR/EDR Not Supported"},
                {3, "Simultaneous LE and BR/EDR (Controller)"},
                {4, "Simultaneous LE and BR/EDR (Host)"},
                {0xFF, NULL}
            };

            rl_printf("    Flags\n");

            for (j = 0; eir_flags_table[j].str; j++) {
                if (data[i] & (1 << eir_flags_table[j].bit)) {
                    rl_printf("      %s\n", eir_flags_table[j].str);
                    mask &= ~(1 << eir_flags_table[j].bit);
                }
            }

            if (mask)
                rl_printf("      Unknown flags (0x%02X)\n", mask);

            break;
        }
        case AD_UUID16_ALL:
        case AD_UUID16_SOME:
        case AD_SOLICIT_UUID16: {
            uint8_t count = (length - 1) / sizeof(uint16_t);
            const char *msg = NULL;

            switch (ad_type) {
                case AD_UUID16_ALL:
                    msg = "    Complete list of 16-bit Service UUIDs: ";
                    break;
                case AD_UUID16_SOME:
                    msg = "    Incomplete list of 16-bit Service UUIDs: ";
                    break;
                case AD_SOLICIT_UUID16:
                    msg = "    List of 16-bit Service Solicitation UUIDs: ";
                    break;
            }

            rl_printf("%s%u entr%s\n", msg, count, count == 1 ? "y" : "ies");

            for (j = 0; j < count; j++)
                rl_printf("      0x%02X%02X\n", data[i+j*sizeof(uint16_t)+1],
                          data[i+j*sizeof(uint16_t)]);

            break;
        }
        case AD_UUID128_ALL:
        case AD_UUID128_SOME:
        case AD_SOLICIT_UUID128: {
            uint8_t count = (length - 1) / 16;
            const char *msg = NULL;

            switch (ad_type) {
                case AD_UUID128_ALL:
                    msg = "    Complete list of 128-bit Service UUIDs: ";
                    break;
                case AD_UUID128_SOME:
                    msg = "    Incomplete list of 128-bit Service UUIDs: ";
                    break;
                case AD_SOLICIT_UUID128:
                    msg = "    List of 128-bit Service Solicitation UUIDs: ";
                    break;
            }

            rl_printf("%s%u entr%s\n", msg, count, count == 1 ? "y" : "ies");

            for (j = 0; j < count; j++)
                rl_printf("      %02X %02X %02X %02X %02X %02X %02X %02X %02X "
                          "%02X %02X %02X %02X %02X %02X %02X\n",
                          data[i+j*16+15], data[i+j*16+14], data[i+j*16+13],
                          data[i+j*16+12], data[i+j*16+11], data[i+j*16+10],
                          data[i+j*16+9], data[i+j*16+8], data[i+j*16+7],
                          data[i+j*16+6], data[i+j*16+5], data[i+j*16+4],
                          data[i+j*16+3], data[i+j*16+2], data[i+j*16+1],
                          data[i+j*16]);

            break;
        }
        case AD_NAME_SHORT:
        case AD_NAME_COMPLETE: {
            char name[length];

            memset(name, 0, sizeof(name));
            memcpy(name, &data[i], length-1);

            if (ad_type == AD_NAME_SHORT)
                rl_printf("    Shortened Local Name\n");
            else
                rl_printf("    Complete Local Name\n");

            rl_printf("      %s\n", name);

            break;
        }
        case AD_TX_POWER:
            rl_printf("    TX Power Level\n");
            rl_printf("      %d\n", (int8_t) data[i]);
            break;
        case AD_SLAVE_CONN_INT: {
            uint16_t min, max;

            rl_printf("    Slave Connection Interval\n");

            min = data[i] + (data[i+1] << 4);
            if (min >= 0x0006 && min <= 0x0c80)
                rl_printf("      Minimum = %.2f\n", (float) min * 1.25);

            max = data[i+2] + (data[i+3] << 4);
            if (max >= 0x0006 && max <= 0x0c80)
                rl_printf("      Maximum = %.2f\n", (float) max * 1.25);

            break;
        }
        case AD_SERVICE_DATA:
            rl_printf("    Service Data\n");
            break;
        case AD_PUBLIC_ADDRESS:
        case AD_RANDOM_ADDRESS:
            if (ad_type == AD_PUBLIC_ADDRESS)
                rl_printf("    Public Target Address\n");
            else
                rl_printf("    Random Target Address\n");

            rl_printf("      %02X:%02X:%02X:%02X:%02X:%02X\n", data[i+5],
                      data[i+4], data[i+3], data[i+2], data[i+1], data[i]);
            break;
        case AD_GAP_APPEARANCE:
            rl_printf("    Appearance\n");
            rl_printf("      0x%02X%02X\n", data[i+1], data[i]);
            break;
        case AD_ADV_INTERVAL: {
            uint16_t adv_interval;

            rl_printf("    Advertising Interval\n");

            adv_interval = data[i] + (data[i+1] << 4);
            rl_printf("      %.2f\n", (float) adv_interval * 0.625);

            break;
        }
        case AD_MANUFACTURER_DATA:
            rl_printf("    Manufacturer-specific data\n");
            rl_printf("      Company ID: 0x%02X%02X\n", data[i+1], data[i]);
            rl_printf("      Data:");
            for (j = i+2; j < i+length; j++)
                rl_printf(" %02X", data[j]);
            rl_printf("\n");
            break;
        default:
            rl_printf("    Invalid data type 0x%02X\n", ad_type);
            break;
    }
}

static void scan_result_cb(bt_bdaddr_t *bda, int rssi, uint8_t *adv_data) {
    char addr_str[BT_ADDRESS_STR_LEN];
    uint8_t i = 0;

    rl_printf("\nBLE device found\n");
    rl_printf("  Address: %s\n", ba2str(bda->address, addr_str));
    rl_printf("  RSSI: %d\n", rssi);

    rl_printf("  Advertising Data:\n");
    while (i < 31 && adv_data[i] != 0) {
        uint8_t length, ad_type, j;

        length = adv_data[i++];
        parse_ad_data(&adv_data[i], length);

        i += length;
    }
}

static void cmd_scan(char *args) {
    bt_status_t status;
    char arg[MAX_LINE_SIZE];

    if (u.gattiface == NULL) {
        rl_printf("Unable to start/stop BLE scan: GATT interface not "
                  "available\n");
        return;
    }

    line_get_str(&args, arg);

    if (arg[0] == 0 || strcmp(arg, "help") == 0) {
        rl_printf("scan -- Controls BLE scan of nearby devices\n");
        rl_printf("Arguments:\n");
        rl_printf("start   starts a new scan session\n");
        rl_printf("stop    interrupts an ongoing scan session\n");

    } else if (strcmp(arg, "start") == 0) {

        if (u.adapter_state != BT_STATE_ON) {
            rl_printf("Unable to start discovery: Adapter is down\n");
            return;
        }

        if (u.scan_state == 1) {
            rl_printf("Scan is already running\n");
            return;
        }

        status = u.gattiface->client->scan(u.client_if, 1);
        if (status != BT_STATUS_SUCCESS) {
            rl_printf("Failed to start discovery\n");
            return;
        }

        u.scan_state = 1;

    } else if (strcmp(arg, "stop") == 0) {

        if (u.scan_state == 0) {
            rl_printf("Unable to stop scan: Scan is not running\n");
            return;
        }

        status = u.gattiface->client->scan(u.client_if, 0);
        if (status != BT_STATUS_SUCCESS) {
            rl_printf("Failed to stop scan\n");
            return;
        }

        u.scan_state = 0;

    } else
        rl_printf("Invalid argument \"%s\"\n", arg);
}

static void connect_cb(int conn_id, int status, int client_if,
                       bt_bdaddr_t *bda) {
    char addr_str[BT_ADDRESS_STR_LEN];

    clear_list_cache();

    if (status != 0) {
        rl_printf("Failed to connect to device %s, status: %i\n",
                  ba2str(bda->address, addr_str), status);
        return;
    }

    rl_printf("Connected to device %s, conn_id: %d, client_if: %d\n",
              ba2str(bda->address, addr_str), conn_id, client_if);
    u.conn_id = conn_id;
}

static void disconnect_cb(int conn_id, int status, int client_if,
                          bt_bdaddr_t *bda) {
    char addr_str[BT_ADDRESS_STR_LEN];

    rl_printf("Disconnected from device %s, conn_id: %d, client_if: %d, "
              "status: %d\n", ba2str(bda->address, addr_str), conn_id,
              client_if, status);

    u.conn_id = 0;
}

static void cmd_disconnect(char *args) {
    bt_status_t status;

    if (u.conn_id <= 0) {
        rl_printf("Device not connected\n");
        return;
    }

    status = u.gattiface->client->disconnect(u.client_if, &u.remote_addr,
                                             u.conn_id);
    if (status != BT_STATUS_SUCCESS) {
        rl_printf("Failed to disconnect, status: %d\n", status);
        return;
    }
}

void do_ssp_reply(const bt_bdaddr_t *bd_addr, bt_ssp_variant_t variant,
                  uint8_t accept, uint32_t passkey) {
    bt_status_t status = u.btiface->ssp_reply(bd_addr, variant, accept,
                                              passkey);

    if (status != BT_STATUS_SUCCESS) {
        rl_printf("SSP Reply error: %u\n", status);
        return;
    }
}

void pin_request_cb(bt_bdaddr_t *remote_bd_addr, bt_bdname_t *bd_name,
                    uint32_t cod) {

    /* ask user which PIN code is showed at remote device */
    memcpy(&u.r_bd_addr, remote_bd_addr, sizeof(u.r_bd_addr));
    change_prompt_state(SSP_ENTRY_PSTATE);
}

void ssp_request_cb(bt_bdaddr_t *remote_bd_addr, bt_bdname_t *bd_name,
                    uint32_t cod, bt_ssp_variant_t pairing_variant,
                    uint32_t pass_key) {

    if (pairing_variant == BT_SSP_VARIANT_CONSENT) {
        /* we need to ask to user if he wants to bond */
        memcpy(&u.r_bd_addr, remote_bd_addr, sizeof(u.r_bd_addr));
        change_prompt_state(SSP_CONSENT_PSTATE);
    } else {
        char addr_str[BT_ADDRESS_STR_LEN];
        const char *action = "Enter";

        if (pairing_variant == BT_SSP_VARIANT_PASSKEY_CONFIRMATION) {
            action = "Confirm";
            do_ssp_reply(remote_bd_addr, pairing_variant, true, pass_key);
        }

        rl_printf("Remote addr: %s\n",
                  ba2str(remote_bd_addr->address, addr_str));
        rl_printf("%s passkey on peer device: %d\n", action, pass_key);
    }
}

static void cmd_connect(char *args) {
    bt_status_t status;
    char arg[MAX_LINE_SIZE];
    int ret;

    if (u.gattiface == NULL) {
        rl_printf("Unable to BLE connect: GATT interface not available\n");
        return;
    }

    if (u.adapter_state != BT_STATE_ON) {
        rl_printf("Unable to connect: Adapter is down\n");
        return;
    }

    if (u.client_registered == false) {
        rl_printf("Unable to connect: We're not registered as GATT client\n");
        return;
    }

    line_get_str(&args, arg);

    ret = str2ba(arg, &u.remote_addr);
    if (ret != 0) {
        rl_printf("Unable to connect: Invalid bluetooth address: %s\n", arg);
        return;
    }

    rl_printf("Connecting to: %s\n", arg);

    status = u.gattiface->client->connect(u.client_if, &u.remote_addr, true);
    if (status != BT_STATUS_SUCCESS) {
        rl_printf("Failed to connect, status: %d\n", status);
        return;
    }
}

static void bond_state_changed_cb(bt_status_t status, bt_bdaddr_t *bda,
                                  bt_bond_state_t state) {
    char addr_str[BT_ADDRESS_STR_LEN];
    char state_str[32] = {0};

    if (status != BT_STATUS_SUCCESS) {
        rl_printf("Failed to change bond state, status: %d\n", status);
        return;
    }

    switch (state) {
        case BT_BOND_STATE_NONE:
            strcpy(state_str, "BT_BOND_STATE_NONE");
            change_prompt_state(NORMAL_PSTATE); /* no bonding process running */
            break;

        case BT_BOND_STATE_BONDING:
            strcpy(state_str, "BT_BOND_STATE_BONDING");
            break;

        case BT_BOND_STATE_BONDED:
            strcpy(state_str, "BT_BOND_STATE_BONDED");
            break;

        default:
            sprintf(state_str, "Unknown (%d)", state);
            break;
    }

    rl_printf("Bond state changed for device %s: %s\n",
              ba2str(bda->address, addr_str), state_str);
}

static void cmd_pair(char *args) {
    char arg[MAX_LINE_SIZE];
    unsigned arg_pos;
    bt_bdaddr_t addr;
    bt_status_t status;
    int ret;
    const char* valid_arguments[] = {
        "create",
        "cancel",
        "remove",
        NULL,
    };

    if (u.btiface == NULL) {
        rl_printf("Unable to BLE pair: Bluetooth interface not available\n");
        return;
    }

    if (u.adapter_state != BT_STATE_ON) {
        rl_printf("Unable to pair: Adapter is down\n");
        return;
    }

    line_get_str(&args, arg);

    if (arg[0] == 0 || strcmp(arg, "help") == 0) {
        rl_printf("bond -- Controls BLE bond process\n");
        rl_printf("Arguments:\n");
        rl_printf("create <address>   start bond process to address\n");
        rl_printf("cancel <address>   cancel bond process to address\n");
        rl_printf("remove <address>   remove bond to address\n");
        return;
    }

    arg_pos = str_in_list(valid_arguments, arg);
    if (str_in_list(valid_arguments, arg) < 0) {
        rl_printf("Invalid argument \"%s\"\n", arg);
        return;
    }

    line_get_str(&args, arg);
    ret = str2ba(arg, &addr);
    if (ret != 0) {
        rl_printf("Invalid bluetooth address: %s\n", arg);
        return;
    }

    switch (arg_pos) {
        case 0:
            status = u.btiface->create_bond(&addr);
            if (status != BT_STATUS_SUCCESS) {
                rl_printf("Failed to create bond, status: %d\n", status);
                return;
            }
            break;
        case 1:
            status = u.btiface->cancel_bond(&addr);
            if (status != BT_STATUS_SUCCESS) {
                rl_printf("Failed to cancel bond, status: %d\n", status);
                return;
            }
            break;
        case 2:
            status = u.btiface->remove_bond(&addr);
            if (status != BT_STATUS_SUCCESS) {
                rl_printf("Failed to remove bond, status: %d\n", status);
                return;
            }
            break;
    }
}

/* called when search has finished */
void search_complete_cb(int conn_id, int status) {

    rl_printf("Search complete, status: %u\n", status);
}

/* called for each search result */
void search_result_cb(int conn_id, btgatt_srvc_id_t *srvc_id) {
    char uuid_str[UUID128_STR_LEN] = {0};

    if (u.svcs_size < MAX_SVCS_SIZE) {
        /* srvc_id value is replaced each time, so we need to copy it */
        memcpy(&u.svcs[u.svcs_size], srvc_id, sizeof(btgatt_srvc_id_t));
        u.svcs_size++;
    }

    rl_printf("ID:%i %s UUID: %s instance:%i\n", u.svcs_size - 1,
              srvc_id->is_primary ? "Primary" : "Secondary",
              uuid2str(&srvc_id->id.uuid, uuid_str), srvc_id->id.inst_id);
}

static void cmd_search_svc(char *args) {
    char arg[MAX_LINE_SIZE];
    bt_status_t status;

    if (u.conn_id <= 0) {
        rl_printf("Not connected\n");
        return;
    }

    if (u.gattiface == NULL) {
        rl_printf("Unable to BLE search-svc: GATT interface not avaiable\n");
        return;
    }

    u.svcs_size = 0;

    line_get_str(&args, arg);
    if (strlen(arg) > 0) {
            bt_uuid_t uuid;
            if (!str2uuid(arg, &uuid)) {
                rl_printf("Invalid format of UUID: %s\n", arg);
                return;
            }

            status = u.gattiface->client->search_service(u.conn_id, &uuid);
    } else
            status = u.gattiface->client->search_service(u.conn_id, NULL);

    if (status != BT_STATUS_SUCCESS) {
        rl_printf("Failed to search services\n");
        return;
    }
}

void get_included_service_cb(int conn_id, int status, btgatt_srvc_id_t *srvc_id,
                             btgatt_srvc_id_t *incl_srvc_id) {

    if (status == 0) {
        bt_status_t ret;
        char uuid_str[UUID128_STR_LEN] = {0};

        rl_printf("Included UUID: %s\n",
                  uuid2str(&incl_srvc_id->id.uuid, uuid_str));

        /* this callback is called only one time, so to have next included
         * service we need to call get_included_service again using incl_srvc_id
         * as parameter
         */
        ret = u.gattiface->client->get_included_service(conn_id, srvc_id,
                                                        incl_srvc_id);
        if (ret != BT_STATUS_SUCCESS) {
            rl_printf("Failed to list included services\n");
            return;
        }
    } else
        rl_printf("Included finished, status: %i\n", status);
}

static void cmd_included(char *args) {
    char arg[MAX_LINE_SIZE];
    bt_status_t status;
    int id;

    if (u.conn_id <= 0) {
        rl_printf("Not connected\n");
        return;
    }

    if (u.gattiface == NULL) {
        rl_printf("Unable to BLE included: GATT interface not avaiable\n");
        return;
    }

    if (u.svcs_size <= 0) {
        rl_printf("Run search-svc first to get all services list\n");
        return;
    }

    line_get_str(&args, arg);
    if (strlen(arg) <= 0) {
        rl_printf("Usage: included ID\n");
        return;
    }

    id = atoi(arg);
    if (id < 0 || id >= u.svcs_size) {
        rl_printf("Invalid ID: %s need to be between 0 and %i\n", arg,
                  u.svcs_size - 1);
        return;
    }

    /* get first included service */
    status = u.gattiface->client->get_included_service(u.conn_id, &u.svcs[id],
                                                       NULL);
    if (status != BT_STATUS_SUCCESS) {
        rl_printf("Failed to list included services\n");
        return;
    }
}

/* List of available user commands */
static const cmd_t cmd_list[] = {
    { "quit", "        Exits", cmd_quit },
    { "enable", "      Enables the Bluetooth adapter", cmd_enable },
    { "disable", "     Disables the Bluetooth adapter", cmd_disable },
    { "discovery", "   Controls discovery of nearby devices", cmd_discovery },
    { "scan", "        Controls BLE scan of nearby devices", cmd_scan },
    { "connect", "     Create a connection to a remote device", cmd_connect },
    { "pair", "        Pair with remote device", cmd_pair },
    { "disconnect", "  Disconnect from remote device", cmd_disconnect },
    { "search-svc", "  Search services on remote device", cmd_search_svc },
    { "included", "    List included services of a service", cmd_included },
    { NULL, NULL, NULL }
};

/* Parses a command and calls the respective handler */
static void cmd_process(char *line) {
    char cmd[MAX_LINE_SIZE];
    int i;

    if (line[0] == 0)
        return;

    if (u.prompt_state == SSP_ENTRY_PSTATE) {
        bt_status_t status = u.btiface->pin_reply(&u.r_bd_addr, true,
                                                  strlen(line),
                                                  (bt_pin_code_t *) line);
        change_prompt_state(NORMAL_PSTATE);
        return;
    }

    line_get_str(&line, cmd);

    if (strcmp(cmd, "help") == 0) {
        for (i = 0; cmd_list[i].name != NULL; i++)
            rl_printf("%s %s\n", cmd_list[i].name, cmd_list[i].description);
        return;
    }

    for (i = 0; cmd_list[i].name != NULL; i++)
        if (strcmp(cmd, cmd_list[i].name) == 0) {
            cmd_list[i].handler(line);
            return;
        }

    rl_printf("%s: unknown command, use 'help' for a list of available "
              "commands\n", cmd);
}

static void register_client_cb(int status, int client_if,
                               bt_uuid_t *app_uuid) {

    if (status != BT_STATUS_SUCCESS) {
        rl_printf("Failed to register client, status: %d\n", status);
        return;
    }

    rl_printf("Registered!, client_if: %d\n", client_if);

    u.client_if = client_if;
    u.client_registered = true;
}

/* GATT client callbacks */
static const btgatt_client_callbacks_t gattccbs = {
    register_client_cb, /* Called after client is registered */
    scan_result_cb, /* called every time an advertising report is seen */
    connect_cb, /* called every time a connection attempt finishes */
    disconnect_cb, /* called every time a connection attempt finishes */
    search_complete_cb, /* search_complete_callback */
    search_result_cb, /* search_result_callback */
    NULL, /* get_characteristic_callback */
    NULL, /* get_descriptor_callback */
    get_included_service_cb, /* get_included_service_callback */
    NULL, /* register_for_notification_callback */
    NULL, /* notify_callback */
    NULL, /* read_characteristic_callback */
    NULL, /* write_characteristic_callback */
    NULL, /* read_descriptor_callback */
    NULL, /* write_descriptor_callback */
    NULL, /* execute_write_callback */
    NULL  /* read_remote_rssi_callback */
};

/* GATT interface callbacks */
static const btgatt_callbacks_t gattcbs = {
    sizeof(btgatt_callbacks_t),
    &gattccbs,
    NULL  /* btgatt_server_callbacks_t */
};

/* This callback is used by the thread that handles Bluetooth interface (btif)
 * to send events for its users. At the moment there are two events defined:
 *
 *     ASSOCIATE_JVM: sinalizes the btif handler thread is ready;
 *     DISASSOCIATE_JVM: sinalizes the btif handler thread is about to exit.
 *
 * This events are used by the JNI to know when the btif handler thread should
 * be associated or dessociated with the JVM
 */
static void thread_event_cb(bt_cb_thread_evt event) {
    rl_printf("\nBluetooth interface %s\n",
              event == ASSOCIATE_JVM ? "ready" : "finished");
    if (event == ASSOCIATE_JVM) {
        u.btiface_initialized = 1;

        u.gattiface = u.btiface->get_profile_interface(BT_PROFILE_GATT_ID);
        if (u.gattiface != NULL) {
            bt_status_t status = u.gattiface->init(&gattcbs);
            if (status != BT_STATUS_SUCCESS) {
                rl_printf("Failed to initialize Bluetooth GATT interface, "
                          "status: %d\n", status);
                u.gattiface = NULL;
            } else
                u.gattiface_initialized = 1;
        } else
            rl_printf("Failed to get Bluetooth GATT Interface\n");
    } else
        u.btiface_initialized = 0;
}

/* Bluetooth interface callbacks */
static bt_callbacks_t btcbs = {
    sizeof(bt_callbacks_t),
    adapter_state_change_cb, /* Called every time the adapter state changes */
    adapter_properties_cb, /* adapter_properties_callback */
    NULL, /* remote_device_properties_callback */
    device_found_cb, /* Called for every device found */
    discovery_state_changed_cb, /* Called every time the discovery state changes */
    pin_request_cb, /* pin_request_callback */
    ssp_request_cb, /* ssp_request_callback */
    bond_state_changed_cb, /* bond_state_changed_callback */
    NULL, /* acl_state_changed_callback */
    thread_event_cb, /* Called when the JVM is associated / dissociated */
    NULL, /* dut_mode_recv_callback */
    NULL, /* le_test_mode_callback */
};

/* Initialize the Bluetooth stack */
static void bt_init() {
    int status;
    hw_module_t *module;
    hw_device_t *hwdev;
    bluetooth_device_t *btdev;

    u.btiface_initialized = 0;
    u.quit = 0;
    u.adapter_state = BT_STATE_OFF; /* The adapter is OFF in the beginning */
    u.conn_id = 0;

    /* Get the Bluetooth module from libhardware */
    status = hw_get_module(BT_STACK_MODULE_ID, (hw_module_t const**) &module);
    if (status < 0) {
        errno = status;
        err(1, "Failed to get the Bluetooth module");
    }
    rl_printf("Bluetooth stack infomation:\n");
    rl_printf("    id = %s\n", module->id);
    rl_printf("    name = %s\n", module->name);
    rl_printf("    author = %s\n", module->author);
    rl_printf("    HAL API version = %d\n", module->hal_api_version);

    /* Get the Bluetooth hardware device */
    status = module->methods->open(module, BT_STACK_MODULE_ID, &hwdev);
    if (status < 0) {
        errno = status;
        err(2, "Failed to get the Bluetooth hardware device");
    }
    rl_printf("Bluetooth device infomation:\n");
    rl_printf("    API version = %d\n", hwdev->version);

    /* Get the Bluetooth interface */
    btdev = (bluetooth_device_t *) hwdev;
    u.btiface = btdev->get_bluetooth_interface();
    if (u.btiface == NULL)
        err(3, "Failed to get the Bluetooth interface");

    /* Init the Bluetooth interface, setting a callback for each operation */
    status = u.btiface->init(&btcbs);
    if (status != BT_STATUS_SUCCESS && status != BT_STATUS_DONE)
        err(4, "Failed to initialize the Bluetooth interface");
}

/* simple tab completer */
const char *tab_completer_cb(char *line, int pos) {
    int i = 0;
    const cmd_t *p = &(cmd_list[0]);

    while (p->name) {
        /* test only commands starting with it */
        if (strncmp(p->name, line, pos) == 0)
            return p->name + pos;

        p = &cmd_list[++i];
    }

    return NULL;
}

int main (int argc, char * argv[]) {
    rl_init(cmd_process);
    change_prompt_state(NORMAL_PSTATE);
    rl_set_tab_completer(tab_completer_cb);

    rl_printf("Android Bluetooth control tool version 0.1\n");

    bt_init();

    while (!u.quit) {
        int c = getchar();

        /* if we are in consent bonding process, we need only a char */
        if (u.prompt_state == SSP_CONSENT_PSTATE) {
            c = toupper(c);
            if (c == 'Y' || c == 'N') {
                bt_status_t status;
                printf("%c\n", c); /* user feedback */
                do_ssp_reply(&u.r_bd_addr, BT_SSP_VARIANT_CONSENT,
                             c == 'Y' ? true : false, 0);
            }
            change_prompt_state(NORMAL_PSTATE);
        } else
            rl_feed(c);
    }

    /* Disable adapter on exit */
    if (u.adapter_state == BT_STATE_ON)
        cmd_disable(NULL);

    /* Cleanup the Bluetooth interface */
    rl_printf("Processing Bluetooth interface cleanup\n");
    u.btiface->cleanup();
    while (u.btiface_initialized)
        usleep(10000);

    rl_quit();
    return 0;
}