summaryrefslogtreecommitdiffstats
path: root/btif/src/btif_hh.c
blob: 8188942b58872a231d1e612c6b72060ec8234896 (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
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
/******************************************************************************
 *
 *  Copyright (C) 2009-2012 Broadcom Corporation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at:
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 ******************************************************************************/

/************************************************************************************
 *
 *  Filename:      btif_hh.c
 *
 *  Description:   HID Host Profile Bluetooth Interface
 *
 *
 ***********************************************************************************/
#include <hardware/bluetooth.h>
#include <hardware/bt_hh.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

#define LOG_TAG "bt_btif_hh"

#include "bta_api.h"
#include "bta_hh_api.h"
#include "btif_storage.h"

#include "btif_common.h"
#include "btif_util.h"
#include "btif_hh.h"
#include "gki.h"
#include "l2c_api.h"
#include "osi/include/log.h"

#define BTIF_HH_APP_ID_MI       0x01
#define BTIF_HH_APP_ID_KB       0x02

#define COD_HID_KEYBOARD        0x0540
#define COD_HID_POINTING        0x0580
#define COD_HID_COMBO           0x05C0
#define COD_HID_MAJOR           0x0500

#define KEYSTATE_FILEPATH "/data/misc/bluedroid/bt_hh_ks" //keep this in sync with HID host jni

#define HID_REPORT_CAPSLOCK   0x39
#define HID_REPORT_NUMLOCK    0x53
#define HID_REPORT_SCROLLLOCK 0x47

//For Apple Magic Mouse
#define MAGICMOUSE_VENDOR_ID 0x05ac
#define MAGICMOUSE_PRODUCT_ID 0x030d

#define LOGITECH_KB_MX5500_VENDOR_ID  0x046D
#define LOGITECH_KB_MX5500_PRODUCT_ID 0xB30B

extern const int BT_UID;
extern const int BT_GID;
static int btif_hh_keylockstates=0; //The current key state of each key

#define BTIF_HH_ID_1        0
#define BTIF_HH_DEV_DISCONNECTED 3

#define BTIF_TIMEOUT_VUP_SECS   3


#ifndef BTUI_HH_SECURITY
#define BTUI_HH_SECURITY (BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT)
#endif

#ifndef BTUI_HH_MOUSE_SECURITY
#define BTUI_HH_MOUSE_SECURITY (BTA_SEC_NONE)
#endif

/* HH request events */
typedef enum
{
    BTIF_HH_CONNECT_REQ_EVT = 0,
    BTIF_HH_DISCONNECT_REQ_EVT,
    BTIF_HH_VUP_REQ_EVT
} btif_hh_req_evt_t;


/************************************************************************************
**  Constants & Macros
************************************************************************************/
#define BTIF_HH_SERVICES    (BTA_HID_SERVICE_MASK)



/************************************************************************************
**  Local type definitions
************************************************************************************/

typedef struct hid_kb_list
{
    UINT16 product_id;
    UINT16 version_id;
    char*  kb_name;
} tHID_KB_LIST;

/************************************************************************************
**  Static variables
************************************************************************************/
btif_hh_cb_t btif_hh_cb;

static bthh_callbacks_t *bt_hh_callbacks = NULL;

/* List of HID keyboards for which the NUMLOCK state needs to be
 * turned ON by default. Add devices to this list to apply the
 * NUMLOCK state toggle on fpr first connect.*/
static tHID_KB_LIST hid_kb_numlock_on_list[] =
{
    {LOGITECH_KB_MX5500_PRODUCT_ID,
    LOGITECH_KB_MX5500_VENDOR_ID,
    "Logitech MX5500 Keyboard"}
};


#define CHECK_BTHH_INIT() if (bt_hh_callbacks == NULL)\
    {\
        BTIF_TRACE_WARNING("BTHH: %s: BTHH not initialized", __FUNCTION__);\
        return BT_STATUS_NOT_READY;\
    }\
    else\
    {\
        BTIF_TRACE_EVENT("BTHH: %s", __FUNCTION__);\
    }



/************************************************************************************
**  Static functions
************************************************************************************/

/************************************************************************************
**  Externs
************************************************************************************/
extern void bta_hh_co_destroy(int fd);
extern void bta_hh_co_write(int fd, UINT8* rpt, UINT16 len);
extern bt_status_t btif_dm_remove_bond(const bt_bdaddr_t *bd_addr);
extern void bta_hh_co_send_hid_info(btif_hh_device_t *p_dev, char *dev_name, UINT16 vendor_id,
                                    UINT16 product_id, UINT16 version, UINT8 ctry_code,
                                    int dscp_len, UINT8 *p_dscp);
extern BOOLEAN check_cod(const bt_bdaddr_t *remote_bdaddr, uint32_t cod);
extern void btif_dm_cb_remove_bond(bt_bdaddr_t *bd_addr);
extern BOOLEAN check_cod_hid(const bt_bdaddr_t *remote_bdaddr, uint32_t cod);
extern int  scru_ascii_2_hex(char *p_ascii, int len, UINT8 *p_hex);
extern void btif_dm_hh_open_success(bt_bdaddr_t *bdaddr);
extern void btif_dm_hh_open_failed(bt_bdaddr_t *bdaddr);
extern void btif_hd_service_registration();

/*****************************************************************************
**  Local Function prototypes
*****************************************************************************/
static void set_keylockstate(int keymask, BOOLEAN isSet);
static void toggle_os_keylockstates(int fd, int changedkeystates);
static void sync_lockstate_on_connect(btif_hh_device_t *p_dev);
//static void hh_update_keyboard_lockstates(btif_hh_device_t *p_dev);
void btif_hh_tmr_hdlr(TIMER_LIST_ENT *tle);
void bte_hh_evt(tBTA_HH_EVT event, tBTA_HH *p_data);


/************************************************************************************
**  Functions
************************************************************************************/

static int get_keylockstates()
{
    return btif_hh_keylockstates;
}

static void set_keylockstate(int keymask, BOOLEAN isSet)
{
    if(isSet)
        btif_hh_keylockstates |= keymask;
}

/*******************************************************************************
**
** Function         toggle_os_keylockstates
**
** Description      Function to toggle the keyboard lock states managed by the linux.
**                  This function is used in by two call paths
**                  (1) if the lock state change occurred from an onscreen keyboard,
**                  this function is called to update the lock state maintained
                    for the HID keyboard(s)
**                  (2) if a HID keyboard is disconnected and reconnected,
**                  this function is called to update the lock state maintained
                    for the HID keyboard(s)
** Returns          void
*******************************************************************************/

static void toggle_os_keylockstates(int fd, int changedlockstates)
{
    BTIF_TRACE_EVENT("%s: fd = %d, changedlockstates = 0x%x",
        __FUNCTION__, fd, changedlockstates);
    UINT8 hidreport[9];
    int reportIndex;
    memset(hidreport,0,9);
    hidreport[0]=1;
    reportIndex=4;

    if (changedlockstates & BTIF_HH_KEYSTATE_MASK_CAPSLOCK) {
        BTIF_TRACE_DEBUG("%s Setting CAPSLOCK", __FUNCTION__);
        hidreport[reportIndex++] = (UINT8)HID_REPORT_CAPSLOCK;
    }

    if (changedlockstates & BTIF_HH_KEYSTATE_MASK_NUMLOCK)  {
        BTIF_TRACE_DEBUG("%s Setting NUMLOCK", __FUNCTION__);
        hidreport[reportIndex++] = (UINT8)HID_REPORT_NUMLOCK;
    }

    if (changedlockstates & BTIF_HH_KEYSTATE_MASK_SCROLLLOCK) {
        BTIF_TRACE_DEBUG("%s Setting SCROLLLOCK", __FUNCTION__);
        hidreport[reportIndex++] = (UINT8) HID_REPORT_SCROLLLOCK;
    }

     BTIF_TRACE_DEBUG("Writing hidreport #1 to os: "\
        "%s:  %x %x %x", __FUNCTION__,
         hidreport[0], hidreport[1], hidreport[2]);
    BTIF_TRACE_DEBUG("%s:  %x %x %x", __FUNCTION__,
         hidreport[3], hidreport[4], hidreport[5]);
    BTIF_TRACE_DEBUG("%s:  %x %x %x", __FUNCTION__,
         hidreport[6], hidreport[7], hidreport[8]);
    bta_hh_co_write(fd , hidreport, sizeof(hidreport));
    usleep(200000);
    memset(hidreport,0,9);
    hidreport[0]=1;
    BTIF_TRACE_DEBUG("Writing hidreport #2 to os: "\
       "%s:  %x %x %x", __FUNCTION__,
         hidreport[0], hidreport[1], hidreport[2]);
    BTIF_TRACE_DEBUG("%s:  %x %x %x", __FUNCTION__,
         hidreport[3], hidreport[4], hidreport[5]);
    BTIF_TRACE_DEBUG("%s:  %x %x %x ", __FUNCTION__,
         hidreport[6], hidreport[7], hidreport[8]);
    bta_hh_co_write(fd , hidreport, sizeof(hidreport));
}

/*******************************************************************************
**
** Function         create_pbuf
**
** Description      Helper function to create p_buf for send_data or set_report
**
*******************************************************************************/
static BT_HDR *create_pbuf(UINT16 len, UINT8 *data)
{
    BT_HDR* p_buf = GKI_getbuf((UINT16) (len + BTA_HH_MIN_OFFSET + sizeof(BT_HDR)));

    if (p_buf) {
        UINT8* pbuf_data;

        p_buf->len = len;
        p_buf->offset = BTA_HH_MIN_OFFSET;

        pbuf_data = (UINT8*) (p_buf + 1) + p_buf->offset;
        memcpy(pbuf_data, data, len);
    }
    return p_buf;
}

/*******************************************************************************
**
** Function         update_keyboard_lockstates
**
** Description      Sends a report to the keyboard to set the lock states of keys
**
*******************************************************************************/
static void update_keyboard_lockstates(btif_hh_device_t *p_dev)
{
    UINT8 len = 2;  /* reportid + 1 byte report*/
    BD_ADDR* bda;
    BT_HDR* p_buf;
    UINT8 data[] = {0x01, /* report id */
                    btif_hh_keylockstates}; /* keystate */

    /* Set report for other keyboards */
    BTIF_TRACE_EVENT("%s: setting report on dev_handle %d to 0x%x",
         __FUNCTION__, p_dev->dev_handle, btif_hh_keylockstates);

    /* Get SetReport buffer */
    p_buf = create_pbuf(len, data);
    if (p_buf != NULL) {
        p_buf->layer_specific = BTA_HH_RPTT_OUTPUT;
        bda = (BD_ADDR*) (&p_dev->bd_addr);
        BTA_HhSendData(p_dev->dev_handle, *bda, p_buf);
    }
}

/*******************************************************************************
**
** Function         sync_lockstate_on_connect
**
** Description      Function to update the keyboard lock states managed by the OS
**                  when a HID keyboard is connected or disconnected and reconnected
** Returns          void
*******************************************************************************/
static void sync_lockstate_on_connect(btif_hh_device_t *p_dev)
{
    int keylockstates;

    BTIF_TRACE_EVENT("%s: Syncing keyboard lock states after "\
        "reconnect...",__FUNCTION__);
    /*If the device is connected, update keyboard state */
    update_keyboard_lockstates(p_dev);

    /*Check if the lockstate of caps,scroll,num is set.
     If so, send a report to the kernel
    so the lockstate is in sync */
    keylockstates = get_keylockstates();
    if (keylockstates)
    {
        BTIF_TRACE_DEBUG("%s: Sending hid report to kernel "\
            "indicating lock key state 0x%x",__FUNCTION__,
            keylockstates);
        usleep(200000);
        toggle_os_keylockstates(p_dev->fd, keylockstates);
    }
    else
    {
        BTIF_TRACE_DEBUG("%s: NOT sending hid report to kernel "\
            "indicating lock key state 0x%x",__FUNCTION__,
            keylockstates);
    }
}

/*******************************************************************************
**
** Function         btif_hh_find_connected_dev_by_handle
**
** Description      Return the connected device pointer of the specified device handle
**
** Returns          Device entry pointer in the device table
*******************************************************************************/
btif_hh_device_t *btif_hh_find_connected_dev_by_handle(UINT8 handle)
{
    UINT32 i;
    for (i = 0; i < BTIF_HH_MAX_HID; i++) {
        if (btif_hh_cb.devices[i].dev_status == BTHH_CONN_STATE_CONNECTED &&
            btif_hh_cb.devices[i].dev_handle == handle)
        {
            return &btif_hh_cb.devices[i];
        }
    }
    return NULL;
}

/*******************************************************************************
**
** Function         btif_hh_find_dev_by_bda
**
** Description      Return the device pointer of the specified bt_bdaddr_t.
**
** Returns          Device entry pointer in the device table
*******************************************************************************/
static btif_hh_device_t *btif_hh_find_dev_by_bda(bt_bdaddr_t *bd_addr)
{
    UINT32 i;
    for (i = 0; i < BTIF_HH_MAX_HID; i++) {
        if (btif_hh_cb.devices[i].dev_status != BTHH_CONN_STATE_UNKNOWN &&
            memcmp(&(btif_hh_cb.devices[i].bd_addr), bd_addr, BD_ADDR_LEN) == 0)
        {
            return &btif_hh_cb.devices[i];
        }
    }
    return NULL;
}

/*******************************************************************************
**
** Function         btif_hh_find_connected_dev_by_bda
**
** Description      Return the connected device pointer of the specified bt_bdaddr_t.
**
** Returns          Device entry pointer in the device table
*******************************************************************************/
static btif_hh_device_t *btif_hh_find_connected_dev_by_bda(bt_bdaddr_t *bd_addr)
{
    UINT32 i;
    for (i = 0; i < BTIF_HH_MAX_HID; i++) {
        if (btif_hh_cb.devices[i].dev_status == BTHH_CONN_STATE_CONNECTED &&
            memcmp(&(btif_hh_cb.devices[i].bd_addr), bd_addr, BD_ADDR_LEN) == 0)
        {
            return &btif_hh_cb.devices[i];
        }
    }
    return NULL;
}

/*******************************************************************************
**
** Function      btif_hh_stop_vup_timer
**
** Description  stop vitual unplug timer
**
** Returns      void
*******************************************************************************/
void btif_hh_stop_vup_timer(bt_bdaddr_t *bd_addr)
{
    btif_hh_device_t *p_dev  = btif_hh_find_connected_dev_by_bda(bd_addr);
    if(p_dev != NULL)
    {
        if (p_dev->vup_timer_active)
        {
            BTIF_TRACE_DEBUG("stop VUP timer ");
            btu_stop_timer(&p_dev->vup_timer);
        }
        p_dev->vup_timer_active = FALSE;
    }
}
/*******************************************************************************
**
** Function      btif_hh_start_vup_timer
**
** Description  start virtual unplug timer
**
** Returns      void
*******************************************************************************/
void btif_hh_start_vup_timer(bt_bdaddr_t *bd_addr)
{
    btif_hh_device_t *p_dev  = btif_hh_find_connected_dev_by_bda(bd_addr);

    if (p_dev == NULL)
        return;

    if (p_dev->vup_timer_active == FALSE)
    {
        BTIF_TRACE_DEBUG("Start VUP timer ");
        memset(&p_dev->vup_timer, 0, sizeof(TIMER_LIST_ENT));
        p_dev->vup_timer.param = (UINT32)btif_hh_tmr_hdlr;
        btu_start_timer(&p_dev->vup_timer, BTU_TTYPE_USER_FUNC,
                        BTIF_TIMEOUT_VUP_SECS);
    }
    else
    {
        BTIF_TRACE_DEBUG("Restart VUP timer ");
        btu_stop_timer(&p_dev->vup_timer);
        btu_start_timer(&p_dev->vup_timer, BTU_TTYPE_USER_FUNC,
                        BTIF_TIMEOUT_VUP_SECS);
    }
    p_dev->vup_timer_active = TRUE;

}

/*******************************************************************************
**
** Function         btif_hh_add_added_dev
**
** Description      Add a new device to the added device list.
**
** Returns          TRUE if add successfully, otherwise FALSE.
*******************************************************************************/
BOOLEAN btif_hh_add_added_dev(bt_bdaddr_t bda, tBTA_HH_ATTR_MASK attr_mask)
{
    int i;
    for (i = 0; i < BTIF_HH_MAX_ADDED_DEV; i++) {
        if (memcmp(&(btif_hh_cb.added_devices[i].bd_addr), &bda, BD_ADDR_LEN) == 0) {
            BTIF_TRACE_WARNING(" Device %02X:%02X:%02X:%02X:%02X:%02X already added",
                  bda.address[0], bda.address[1], bda.address[2], bda.address[3], bda.address[4], bda.address[5]);
            return FALSE;
        }
    }
    for (i = 0; i < BTIF_HH_MAX_ADDED_DEV; i++) {
        if (btif_hh_cb.added_devices[i].bd_addr.address[0] == 0 &&
            btif_hh_cb.added_devices[i].bd_addr.address[1] == 0 &&
            btif_hh_cb.added_devices[i].bd_addr.address[2] == 0 &&
            btif_hh_cb.added_devices[i].bd_addr.address[3] == 0 &&
            btif_hh_cb.added_devices[i].bd_addr.address[4] == 0 &&
            btif_hh_cb.added_devices[i].bd_addr.address[5] == 0)
        {
            BTIF_TRACE_WARNING(" Added device %02X:%02X:%02X:%02X:%02X:%02X",
                  bda.address[0], bda.address[1], bda.address[2], bda.address[3], bda.address[4], bda.address[5]);
            memcpy(&(btif_hh_cb.added_devices[i].bd_addr), &bda, BD_ADDR_LEN);
            btif_hh_cb.added_devices[i].dev_handle = BTA_HH_INVALID_HANDLE;
            btif_hh_cb.added_devices[i].attr_mask  = attr_mask;
            return TRUE;
        }
    }

    BTIF_TRACE_WARNING("%s: Error, out of space to add device",__FUNCTION__);
    return FALSE;
}

/*******************************************************************************
 **
 ** Function         btif_hh_remove_device
 **
 ** Description      Remove an added device from the stack.
 **
 ** Returns          void
 *******************************************************************************/
void btif_hh_remove_device(bt_bdaddr_t bd_addr)
{
    int                    i;
    btif_hh_device_t       *p_dev;
    btif_hh_added_device_t *p_added_dev;

    LOG_INFO("%s: bda = %02x:%02x:%02x:%02x:%02x:%02x", __FUNCTION__,
         bd_addr.address[0], bd_addr.address[1], bd_addr.address[2], bd_addr.address[3], bd_addr.address[4], bd_addr.address[5]);

    for (i = 0; i < BTIF_HH_MAX_ADDED_DEV; i++) {
        p_added_dev = &btif_hh_cb.added_devices[i];
        if (memcmp(&(p_added_dev->bd_addr),&bd_addr, 6) == 0) {
            BTA_HhRemoveDev(p_added_dev->dev_handle);
            btif_storage_remove_hid_info(&(p_added_dev->bd_addr));
            memset(&(p_added_dev->bd_addr), 0, 6);
            p_added_dev->dev_handle = BTA_HH_INVALID_HANDLE;
            break;
        }
    }

    p_dev = btif_hh_find_dev_by_bda(&bd_addr);
    if (p_dev == NULL) {
        BTIF_TRACE_WARNING(" Oops, can't find device [%02x:%02x:%02x:%02x:%02x:%02x]",
             bd_addr.address[0], bd_addr.address[1], bd_addr.address[2], bd_addr.address[3], bd_addr.address[4], bd_addr.address[5]);
        return;
    }

    /* need to notify up-layer device is disconnected to avoid state out of sync with up-layer */
    HAL_CBACK(bt_hh_callbacks, connection_state_cb, &(p_dev->bd_addr), BTHH_CONN_STATE_DISCONNECTED);

    p_dev->dev_status = BTHH_CONN_STATE_UNKNOWN;
    p_dev->dev_handle = BTA_HH_INVALID_HANDLE;
    p_dev->ready_for_data = FALSE;

    if (btif_hh_cb.device_num > 0) {
        btif_hh_cb.device_num--;
    }
    else {
        BTIF_TRACE_WARNING("%s: device_num = 0", __FUNCTION__);
    }

    p_dev->hh_keep_polling = 0;
    p_dev->hh_poll_thread_id = -1;
    BTIF_TRACE_DEBUG("%s: uhid fd = %d", __FUNCTION__, p_dev->fd);
    if (p_dev->fd >= 0) {
        bta_hh_co_destroy(p_dev->fd);
        p_dev->fd = -1;
    }
}


BOOLEAN btif_hh_copy_hid_info(tBTA_HH_DEV_DSCP_INFO* dest , tBTA_HH_DEV_DSCP_INFO* src)
{
    dest->descriptor.dl_len = 0;
    if (src->descriptor.dl_len >0)
    {
        dest->descriptor.dsc_list = (UINT8 *) GKI_getbuf(src->descriptor.dl_len);
        if (dest->descriptor.dsc_list == NULL)
        {
            BTIF_TRACE_WARNING("%s: Failed to allocate DSCP for CB", __FUNCTION__);
            return FALSE;
        }
    }
    memcpy(dest->descriptor.dsc_list, src->descriptor.dsc_list, src->descriptor.dl_len);
    dest->descriptor.dl_len = src->descriptor.dl_len;
    dest->vendor_id  = src->vendor_id;
    dest->product_id = src->product_id;
    dest->version    = src->version;
    dest->ctry_code  = src->ctry_code;
    dest->ssr_max_latency = src->ssr_max_latency;
    dest->ssr_min_tout = src->ssr_min_tout;
    return TRUE;
}


/*******************************************************************************
**
** Function         btif_hh_virtual_unplug
**
** Description      Virtual unplug initiated from the BTIF thread context
**                  Special handling for HID mouse-
**
** Returns          void
**
*******************************************************************************/

bt_status_t btif_hh_virtual_unplug(bt_bdaddr_t *bd_addr)
{
    BTIF_TRACE_DEBUG("%s", __FUNCTION__);
    btif_hh_device_t *p_dev;
    char bd_str[18];
    sprintf(bd_str, "%02X:%02X:%02X:%02X:%02X:%02X",
            bd_addr->address[0],  bd_addr->address[1],  bd_addr->address[2],  bd_addr->address[3],
            bd_addr->address[4], bd_addr->address[5]);
    p_dev = btif_hh_find_dev_by_bda(bd_addr);
    if ((p_dev != NULL) && (p_dev->dev_status == BTHH_CONN_STATE_CONNECTED)
        && (p_dev->attr_mask & HID_VIRTUAL_CABLE))
    {
        BTIF_TRACE_DEBUG("%s Sending BTA_HH_CTRL_VIRTUAL_CABLE_UNPLUG", __FUNCTION__);
        /* start the timer */
        btif_hh_start_vup_timer(bd_addr);
        p_dev->local_vup = TRUE;
        BTA_HhSendCtrl(p_dev->dev_handle, BTA_HH_CTRL_VIRTUAL_CABLE_UNPLUG);
        return BT_STATUS_SUCCESS;
    }
    else
    {
        BTIF_TRACE_ERROR("%s: Error, device %s not opened.", __FUNCTION__, bd_str);
        return BT_STATUS_FAIL;
    }
}

/*******************************************************************************
**
** Function         btif_hh_connect
**
** Description      connection initiated from the BTIF thread context
**
** Returns          int status
**
*******************************************************************************/

bt_status_t btif_hh_connect(bt_bdaddr_t *bd_addr)
{
    btif_hh_device_t *dev;
    btif_hh_added_device_t *added_dev = NULL;
    char bda_str[20];
    int i;
    BD_ADDR *bda = (BD_ADDR*)bd_addr;
    CHECK_BTHH_INIT();
    dev = btif_hh_find_dev_by_bda(bd_addr);
    BTIF_TRACE_DEBUG("Connect _hh");
    sprintf(bda_str, "%02X:%02X:%02X:%02X:%02X:%02X",
            (*bda)[0], (*bda)[1], (*bda)[2], (*bda)[3], (*bda)[4], (*bda)[5]);
    if (dev == NULL && btif_hh_cb.device_num >= BTIF_HH_MAX_HID) {
        // No space for more HID device now.
         BTIF_TRACE_WARNING("%s: Error, exceeded the maximum supported HID device number %d",
             __FUNCTION__, BTIF_HH_MAX_HID);
        return BT_STATUS_FAIL;
    }

    for (i = 0; i < BTIF_HH_MAX_ADDED_DEV; i++) {
        if (memcmp(&(btif_hh_cb.added_devices[i].bd_addr), bd_addr, BD_ADDR_LEN) == 0) {
            added_dev = &btif_hh_cb.added_devices[i];
             BTIF_TRACE_WARNING("%s: Device %s already added, attr_mask = 0x%x",
                 __FUNCTION__, bda_str, added_dev->attr_mask);
        }
    }

    if (added_dev != NULL) {
        if (added_dev->dev_handle == BTA_HH_INVALID_HANDLE) {
            // No space for more HID device now.
            BTIF_TRACE_ERROR("%s: Error, device %s added but addition failed", __FUNCTION__, bda_str);
            memset(&(added_dev->bd_addr), 0, 6);
            added_dev->dev_handle = BTA_HH_INVALID_HANDLE;
            return BT_STATUS_FAIL;
        }
    }

    /* Not checking the NORMALLY_Connectible flags from sdp record, and anyways sending this
     request from host, for subsequent user initiated connection. If the remote is not in
     pagescan mode, we will do 2 retries to connect before giving up */
    tBTA_SEC sec_mask = BTUI_HH_SECURITY;
    btif_hh_cb.status = BTIF_HH_DEV_CONNECTING;
    BTA_HhOpen(*bda, BTA_HH_PROTO_RPT_MODE, sec_mask);

    HAL_CBACK(bt_hh_callbacks, connection_state_cb, bd_addr, BTHH_CONN_STATE_CONNECTING);
    return BT_STATUS_SUCCESS;
}

/*******************************************************************************
**
** Function         btif_hh_disconnect
**
** Description      disconnection initiated from the BTIF thread context
**
** Returns          void
**
*******************************************************************************/

void btif_hh_disconnect(bt_bdaddr_t *bd_addr)
{
    btif_hh_device_t *p_dev;
    p_dev = btif_hh_find_connected_dev_by_bda(bd_addr);
    if (p_dev != NULL)
    {
        BTA_HhClose(p_dev->dev_handle);
    }
    else
        BTIF_TRACE_DEBUG("%s-- Error: device not connected:",__FUNCTION__);
}

/*******************************************************************************
**
** Function         btif_btif_hh_setreport
**
** Description      setreport initiated from the BTIF thread context
**
** Returns          void
**
*******************************************************************************/
void btif_hh_setreport(btif_hh_device_t *p_dev, bthh_report_type_t r_type, UINT16 size,
                            UINT8* report)
{
    BT_HDR* p_buf = create_pbuf(size, report);
    if (p_buf == NULL) {
        APPL_TRACE_ERROR("%s: Error, failed to allocate RPT buffer, size = %d", __FUNCTION__, size);
        return;
    }
    BTA_HhSetReport(p_dev->dev_handle, r_type, p_buf);
}

/*******************************************************************************
**
** Function         btif_btif_hh_setreport
**
** Description      setreport initiated from the BTIF thread context
**
** Returns          void
**
*******************************************************************************/
void btif_hh_getreport(btif_hh_device_t *p_dev, bthh_report_type_t r_type,
                        UINT8 reportId, UINT16 bufferSize)

{
    BTA_HhGetReport(p_dev->dev_handle, r_type, reportId, bufferSize);
}

/*******************************************************************************
**
** Function         btif_hh_service_registration
**
** Description      Registers or derigisters the hid host service
**
** Returns          none
**
*******************************************************************************/
void btif_hh_service_registration(BOOLEAN enable)
{
    BTIF_TRACE_API("%s", __FUNCTION__);

    BTIF_TRACE_API("enable = %d", enable);
    if (enable)
    {
        BTA_HhEnable(BTA_SEC_ENCRYPT, bte_hh_evt);
    }
    else
    {
        btif_hh_cb.service_dereg_active = TRUE;
        BTA_HhDisable();
    }
}

/*****************************************************************************
**   Section name (Group of functions)
*****************************************************************************/

/*****************************************************************************
**
**   btif hh api functions (no context switch)
**
*****************************************************************************/


/*******************************************************************************
**
** Function         btif_hh_upstreams_evt
**
** Description      Executes HH UPSTREAMS events in btif context
**
** Returns          void
**
*******************************************************************************/
static void btif_hh_upstreams_evt(UINT16 event, char* p_param)
{
    tBTA_HH *p_data = (tBTA_HH *)p_param;
    btif_hh_device_t *p_dev = NULL;
    int i;
    int len, tmplen;

    BTIF_TRACE_DEBUG("%s: event=%s dereg = %d", __FUNCTION__, dump_hh_event(event),
        btif_hh_cb.service_dereg_active);

    switch (event)
    {
        case BTA_HH_ENABLE_EVT:
            BTIF_TRACE_DEBUG("%s: BTA_HH_ENABLE_EVT: status =%d",__FUNCTION__, p_data->status);
            if (p_data->status == BTA_HH_OK) {
                btif_hh_cb.status = BTIF_HH_ENABLED;
                BTIF_TRACE_DEBUG("%s--Loading added devices",__FUNCTION__);
                /* Add hid descriptors for already bonded hid devices*/
                btif_storage_load_bonded_hid_info();
            }
            else {
                btif_hh_cb.status = BTIF_HH_DISABLED;
                BTIF_TRACE_WARNING("BTA_HH_ENABLE_EVT: Error, HH enabling failed, status = %d", p_data->status);
            }
            break;

        case BTA_HH_DISABLE_EVT:
            btif_hh_cb.status = BTIF_HH_DISABLED;
            if (btif_hh_cb.service_dereg_active)
            {
                BTIF_TRACE_WARNING("BTA_HH_DISABLE_EVT: enabling HID Device service");
                btif_hd_service_registration();
                btif_hh_cb.service_dereg_active = FALSE;
            }
            if (p_data->status == BTA_HH_OK) {
                int i;
                //Clear the control block
                memset(&btif_hh_cb, 0, sizeof(btif_hh_cb));
                for (i = 0; i < BTIF_HH_MAX_HID; i++){
                    btif_hh_cb.devices[i].dev_status = BTHH_CONN_STATE_UNKNOWN;
                }
            }
            else
                BTIF_TRACE_WARNING("BTA_HH_DISABLE_EVT: Error, HH disabling failed, status = %d", p_data->status);
            break;

        case BTA_HH_OPEN_EVT:
            BTIF_TRACE_WARNING("%s: BTA_HH_OPN_EVT: handle=%d, status =%d",__FUNCTION__, p_data->conn.handle, p_data->conn.status);
            if (p_data->conn.status == BTA_HH_OK) {
                p_dev = btif_hh_find_connected_dev_by_handle(p_data->conn.handle);
                if (p_dev == NULL) {
                    BTIF_TRACE_WARNING("BTA_HH_OPEN_EVT: Error, cannot find device with handle %d", p_data->conn.handle);
                    btif_hh_cb.status = BTIF_HH_DEV_DISCONNECTED;
                    // The connect request must come from device side and exceeded the connected
                                   // HID device number.
                    BTA_HhClose(p_data->conn.handle);
                    HAL_CBACK(bt_hh_callbacks, connection_state_cb, (bt_bdaddr_t*) &p_data->conn.bda,BTHH_CONN_STATE_DISCONNECTED);
                }
                else if (p_dev->fd < 0) {
                    BTIF_TRACE_WARNING("BTA_HH_OPEN_EVT: Error, failed to find the uhid driver...");
                    memcpy(&(p_dev->bd_addr), p_data->conn.bda, BD_ADDR_LEN);
                    //remove the connection  and then try again to reconnect from the mouse side to recover
                    btif_hh_cb.status = BTIF_HH_DEV_DISCONNECTED;
                    BTA_HhClose(p_data->conn.handle);
                }
                else {
                    bt_bdaddr_t *bdaddr = (bt_bdaddr_t*)p_data->conn.bda;
                    btif_dm_hh_open_success(bdaddr);
                    BTIF_TRACE_WARNING("BTA_HH_OPEN_EVT: Found device...Getting dscp info for handle ... %d",p_data->conn.handle);
                    memcpy(&(p_dev->bd_addr), p_data->conn.bda, BD_ADDR_LEN);
                    btif_hh_cb.status = BTIF_HH_DEV_CONNECTED;
                    // Send set_idle if the peer_device is a keyboard
                    if (check_cod((bt_bdaddr_t*)p_data->conn.bda, COD_HID_KEYBOARD )||
                                check_cod((bt_bdaddr_t*)p_data->conn.bda, COD_HID_COMBO))
                        BTA_HhSetIdle(p_data->conn.handle, 0);
                    btif_hh_cb.p_curr_dev = btif_hh_find_connected_dev_by_handle(p_data->conn.handle);
                    BTA_HhGetDscpInfo(p_data->conn.handle);
                    p_dev->dev_status = BTHH_CONN_STATE_CONNECTED;
                    HAL_CBACK(bt_hh_callbacks, connection_state_cb,&(p_dev->bd_addr), p_dev->dev_status);
                }
            }
            else {
                bt_bdaddr_t *bdaddr = (bt_bdaddr_t*)p_data->conn.bda;
                btif_dm_hh_open_failed(bdaddr);
                p_dev = btif_hh_find_dev_by_bda(bdaddr);
                if (p_dev != NULL) {
                    if(p_dev->vup_timer_active)
                        btif_hh_stop_vup_timer(&(p_dev->bd_addr));
                    if (p_dev->fd >= 0) {
                        bta_hh_co_destroy(p_dev->fd);
                        p_dev->fd = -1;
                    }
                    p_dev->dev_status = BTHH_CONN_STATE_DISCONNECTED;
                }
                HAL_CBACK(bt_hh_callbacks, connection_state_cb, (bt_bdaddr_t*) &p_data->conn.bda,BTHH_CONN_STATE_DISCONNECTED);
                btif_hh_cb.status = BTIF_HH_DEV_DISCONNECTED;
            }
            break;

        case BTA_HH_CLOSE_EVT:
            BTIF_TRACE_DEBUG("BTA_HH_CLOSE_EVT: status = %d, handle = %d",
            p_data->dev_status.status, p_data->dev_status.handle);
            p_dev = btif_hh_find_connected_dev_by_handle(p_data->dev_status.handle);
            if (p_dev != NULL) {
                BTIF_TRACE_DEBUG("%s: uhid fd = %d", __FUNCTION__, p_dev->fd);
                if(p_dev->vup_timer_active)
                    btif_hh_stop_vup_timer(&(p_dev->bd_addr));
                if (p_dev->fd >= 0) {
                    bta_hh_co_destroy(p_dev->fd);
                    p_dev->fd = -1;
                }
                btif_hh_cb.status = BTIF_HH_DEV_DISCONNECTED;
                p_dev->dev_status = BTHH_CONN_STATE_DISCONNECTED;
                HAL_CBACK(bt_hh_callbacks, connection_state_cb,&(p_dev->bd_addr), p_dev->dev_status);
            }
            else {
                BTIF_TRACE_WARNING("Error: cannot find device with handle %d", p_data->dev_status.handle);
            }
            break;

        case BTA_HH_GET_RPT_EVT: {
            BT_HDR *hdr = p_data->hs_data.rsp_data.p_rpt_data;
            UINT8 *data = NULL;
            UINT16 len = 0;

            BTIF_TRACE_DEBUG("BTA_HH_GET_RPT_EVT: status = %d, handle = %d",
                 p_data->hs_data.status, p_data->hs_data.handle);
            p_dev = btif_hh_find_connected_dev_by_handle(p_data->hs_data.handle);
            if (p_dev) {
                /* p_rpt_data is NULL in HANDSHAKE response case */
                if (hdr) {
                    data = (UINT8 *)(hdr + 1) + hdr->offset;
                    len = hdr->len;
                    HAL_CBACK(bt_hh_callbacks, get_report_cb,
                              (bt_bdaddr_t*) &(p_dev->bd_addr),
                              (bthh_status_t) p_data->hs_data.status, data, len);
                } else {
                    HAL_CBACK(bt_hh_callbacks, handshake_cb,
                              (bt_bdaddr_t*) &(p_dev->bd_addr),
                              (bthh_status_t) p_data->hs_data.status);
                }
            } else {
                BTIF_TRACE_WARNING("Error: cannot find device with handle %d", p_data->hs_data.handle);
            }
            break;
        }

        case BTA_HH_SET_RPT_EVT:
            BTIF_TRACE_DEBUG("BTA_HH_SET_RPT_EVT: status = %d, handle = %d",
            p_data->dev_status.status, p_data->dev_status.handle);
            p_dev = btif_hh_find_connected_dev_by_handle(p_data->dev_status.handle);
            if (p_dev != NULL) {
                HAL_CBACK(bt_hh_callbacks, handshake_cb,
                          (bt_bdaddr_t*) &(p_dev->bd_addr),
                          (bthh_status_t) p_data->hs_data.status);
            }
            break;

        case BTA_HH_GET_PROTO_EVT:
            p_dev = btif_hh_find_connected_dev_by_handle(p_data->hs_data.handle);
            BTIF_TRACE_WARNING("BTA_HH_GET_PROTO_EVT: status = %d, handle = %d, proto = [%d], %s",
                 p_data->hs_data.status, p_data->hs_data.handle,
                 p_data->hs_data.rsp_data.proto_mode,
                 (p_data->hs_data.rsp_data.proto_mode == BTA_HH_PROTO_RPT_MODE) ? "Report Mode" :
                 (p_data->hs_data.rsp_data.proto_mode == BTA_HH_PROTO_BOOT_MODE) ? "Boot Mode" : "Unsupported");
            if (p_data->hs_data.rsp_data.proto_mode != BTA_HH_PROTO_UNKNOWN) {
                HAL_CBACK(bt_hh_callbacks, protocol_mode_cb,
                          (bt_bdaddr_t*) &(p_dev->bd_addr),
                          (bthh_status_t)p_data->hs_data.status,
                          (bthh_protocol_mode_t) p_data->hs_data.rsp_data.proto_mode);
            } else {
                HAL_CBACK(bt_hh_callbacks, handshake_cb,
                          (bt_bdaddr_t*) &(p_dev->bd_addr),
                          (bthh_status_t)p_data->hs_data.status);
            }
            break;

        case BTA_HH_SET_PROTO_EVT:
            BTIF_TRACE_DEBUG("BTA_HH_SET_PROTO_EVT: status = %d, handle = %d",
                 p_data->dev_status.status, p_data->dev_status.handle);
            p_dev = btif_hh_find_connected_dev_by_handle(p_data->dev_status.handle);
            if (p_dev) {
                HAL_CBACK(bt_hh_callbacks, handshake_cb,
                          (bt_bdaddr_t*)&(p_dev->bd_addr),
                          (bthh_status_t)p_data->hs_data.status);
            }
            break;

        case BTA_HH_GET_IDLE_EVT:
            BTIF_TRACE_DEBUG("BTA_HH_GET_IDLE_EVT: handle = %d, status = %d, rate = %d",
                 p_data->hs_data.handle, p_data->hs_data.status,
                 p_data->hs_data.rsp_data.idle_rate);
            p_dev = btif_hh_find_connected_dev_by_handle(p_data->hs_data.handle);
            HAL_CBACK(bt_hh_callbacks, idle_time_cb,(bt_bdaddr_t*) &(p_dev->bd_addr),
                (bthh_status_t) p_data->hs_data.status, p_data->hs_data.rsp_data.idle_rate);
            break;

        case BTA_HH_SET_IDLE_EVT:
            BTIF_TRACE_DEBUG("BTA_HH_SET_IDLE_EVT: status = %d, handle = %d",
            p_data->dev_status.status, p_data->dev_status.handle);
            break;

        case BTA_HH_GET_DSCP_EVT:
            len = p_data->dscp_info.descriptor.dl_len;
            BTIF_TRACE_DEBUG("BTA_HH_GET_DSCP_EVT: len = %d", len);
            p_dev = btif_hh_cb.p_curr_dev;
            if (p_dev == NULL) {
                BTIF_TRACE_ERROR("BTA_HH_GET_DSCP_EVT: No HID device is currently connected");
                return;
            }
            if (p_dev->fd < 0) {
                LOG_ERROR("BTA_HH_GET_DSCP_EVT: Error, failed to find the uhid driver...");
                return;
            }
            {
                char *cached_name = NULL;
                bt_bdname_t bdname;
                bt_property_t prop_name;
                BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_BDNAME,
                                           sizeof(bt_bdname_t), &bdname);
                if (btif_storage_get_remote_device_property(
                    &p_dev->bd_addr, &prop_name) == BT_STATUS_SUCCESS)
                {
                    cached_name = (char *)bdname.name;
                }
                else
                {
                    cached_name = "Bluetooth HID";
                }

                BTIF_TRACE_WARNING("%s: name = %s", __FUNCTION__, cached_name);
                bta_hh_co_send_hid_info(p_dev, cached_name,
                    p_data->dscp_info.vendor_id, p_data->dscp_info.product_id,
                    p_data->dscp_info.version,   p_data->dscp_info.ctry_code,
                    len, p_data->dscp_info.descriptor.dsc_list);
                if (btif_hh_add_added_dev(p_dev->bd_addr, p_dev->attr_mask)) {
                    BD_ADDR bda;
                    bdcpy(bda, p_dev->bd_addr.address);
                    tBTA_HH_DEV_DSCP_INFO dscp_info;
                    bt_status_t ret;
                    bdcpy(bda, p_dev->bd_addr.address);
                    btif_hh_copy_hid_info(&dscp_info, &p_data->dscp_info);
                    BTIF_TRACE_DEBUG("BTA_HH_GET_DSCP_EVT:bda = %02x:%02x:%02x:%02x:%02x:%02x",
                              p_dev->bd_addr.address[0], p_dev->bd_addr.address[1],
                              p_dev->bd_addr.address[2],p_dev->bd_addr.address[3],
                              p_dev->bd_addr.address[4], p_dev->bd_addr.address[5]);
                    BTA_HhAddDev(bda, p_dev->attr_mask,p_dev->sub_class,p_dev->app_id, dscp_info);
                    // write hid info to nvram
                    ret = btif_storage_add_hid_device_info(&(p_dev->bd_addr), p_dev->attr_mask,p_dev->sub_class,p_dev->app_id,
                                                        p_data->dscp_info.vendor_id, p_data->dscp_info.product_id,
                                                        p_data->dscp_info.version,   p_data->dscp_info.ctry_code,
                                                        p_data->dscp_info.ssr_max_latency, p_data->dscp_info.ssr_min_tout,
                                                        len, p_data->dscp_info.descriptor.dsc_list);

                    ASSERTC(ret == BT_STATUS_SUCCESS, "storing hid info failed", ret);
                    BTIF_TRACE_WARNING("BTA_HH_GET_DSCP_EVT: Called add device");

                    //Free buffer created for dscp_info;
                    if (dscp_info.descriptor.dl_len >0 && dscp_info.descriptor.dsc_list != NULL)
                    {
                      GKI_freebuf(dscp_info.descriptor.dsc_list);
                      dscp_info.descriptor.dsc_list = NULL;
                      dscp_info.descriptor.dl_len=0;
                    }
                }
                else {
                    //Device already added.
                    BTIF_TRACE_WARNING("%s: Device already added ",__FUNCTION__);
                }
                /*Sync HID Keyboard lockstates */
                tmplen = sizeof(hid_kb_numlock_on_list)
                            / sizeof(tHID_KB_LIST);
                for(i = 0; i< tmplen; i++)
                {
                    if(p_data->dscp_info.vendor_id
                        == hid_kb_numlock_on_list[i].version_id &&
                        p_data->dscp_info.product_id
                        == hid_kb_numlock_on_list[i].product_id)
                    {
                        BTIF_TRACE_DEBUG("%s() idx[%d] Enabling "\
                            "NUMLOCK for device :: %s", __FUNCTION__,
                            i, hid_kb_numlock_on_list[i].kb_name);
                        /* Enable NUMLOCK by default so that numeric
                            keys work from first keyboard connect */
                        set_keylockstate(BTIF_HH_KEYSTATE_MASK_NUMLOCK,
                                        TRUE);
                        sync_lockstate_on_connect(p_dev);
                        /* End Sync HID Keyboard lockstates */
                        break;
                    }
                }
            }
            break;

        case BTA_HH_ADD_DEV_EVT:
            BTIF_TRACE_WARNING("BTA_HH_ADD_DEV_EVT: status = %d, handle = %d",p_data->dev_info.status, p_data->dev_info.handle);
            int i;
            for (i = 0; i < BTIF_HH_MAX_ADDED_DEV; i++) {
                if (memcmp(btif_hh_cb.added_devices[i].bd_addr.address, p_data->dev_info.bda, 6) == 0) {
                    if (p_data->dev_info.status == BTA_HH_OK) {
                        btif_hh_cb.added_devices[i].dev_handle = p_data->dev_info.handle;
                    }
                    else {
                        memset(btif_hh_cb.added_devices[i].bd_addr.address, 0, 6);
                        btif_hh_cb.added_devices[i].dev_handle = BTA_HH_INVALID_HANDLE;
                    }
                    break;
                }
            }
            break;
        case BTA_HH_RMV_DEV_EVT:
                BTIF_TRACE_DEBUG("BTA_HH_RMV_DEV_EVT: status = %d, handle = %d",
                     p_data->dev_info.status, p_data->dev_info.handle);
                BTIF_TRACE_DEBUG("BTA_HH_RMV_DEV_EVT:bda = %02x:%02x:%02x:%02x:%02x:%02x",
                     p_data->dev_info.bda[0], p_data->dev_info.bda[1], p_data->dev_info.bda[2],
                     p_data->dev_info.bda[3], p_data->dev_info.bda[4], p_data->dev_info.bda[5]);
                break;


        case BTA_HH_VC_UNPLUG_EVT:
                BTIF_TRACE_DEBUG("BTA_HH_VC_UNPLUG_EVT: status = %d, handle = %d",
                     p_data->dev_status.status, p_data->dev_status.handle);
                p_dev = btif_hh_find_connected_dev_by_handle(p_data->dev_status.handle);
                btif_hh_cb.status = BTIF_HH_DEV_DISCONNECTED;
                if (p_dev != NULL) {
                    BTIF_TRACE_DEBUG("BTA_HH_VC_UNPLUG_EVT:bda = %02x:%02x:%02x:%02x:%02x:%02x",
                         p_dev->bd_addr.address[0], p_dev->bd_addr.address[1],
                         p_dev->bd_addr.address[2],p_dev->bd_addr.address[3],
                         p_dev->bd_addr.address[4], p_dev->bd_addr.address[5]);
                    /* Stop the VUP timer */
                    if(p_dev->vup_timer_active)
                    {
                        btif_hh_stop_vup_timer(&(p_dev->bd_addr));
                    }
                    p_dev->dev_status = BTHH_CONN_STATE_DISCONNECTED;
                    BTIF_TRACE_DEBUG("%s---Sending connection state change", __FUNCTION__);
                    HAL_CBACK(bt_hh_callbacks, connection_state_cb,&(p_dev->bd_addr), p_dev->dev_status);
                    BTIF_TRACE_DEBUG("%s---Removing HID bond", __FUNCTION__);
                    /* If it is locally initiated VUP or remote device has its major COD as
                    Peripheral removed the bond.*/
                    if (p_dev->local_vup  || check_cod_hid(&(p_dev->bd_addr), COD_HID_MAJOR))
                    {
                        p_dev->local_vup = FALSE;
                        BTA_DmRemoveDevice((UINT8 *)p_dev->bd_addr.address);
                    }
                    else
                        btif_hh_remove_device(p_dev->bd_addr);
                    HAL_CBACK(bt_hh_callbacks, virtual_unplug_cb,&(p_dev->bd_addr),
                                    p_data->dev_status.status);
                }
                break;

        case BTA_HH_API_ERR_EVT  :
                LOG_INFO("BTA_HH API_ERR");
                break;

        default:
            BTIF_TRACE_WARNING("%s: Unhandled event: %d", __FUNCTION__, event);
            break;
    }
}

/*******************************************************************************
**
** Function         bte_hh_evt
**
** Description      Switches context from BTE to BTIF for all HH events
**
** Returns          void
**
*******************************************************************************/

void bte_hh_evt(tBTA_HH_EVT event, tBTA_HH *p_data)
{
    bt_status_t status;
    int param_len = 0;

    if (BTA_HH_ENABLE_EVT == event)
        param_len = sizeof(tBTA_HH_STATUS);
    else if (BTA_HH_OPEN_EVT == event)
        param_len = sizeof(tBTA_HH_CONN);
    else if (BTA_HH_DISABLE_EVT == event)
        param_len = sizeof(tBTA_HH_STATUS);
    else if (BTA_HH_CLOSE_EVT == event)
        param_len = sizeof(tBTA_HH_CBDATA);
    else if (BTA_HH_GET_DSCP_EVT == event)
        param_len = sizeof(tBTA_HH_DEV_DSCP_INFO);
    else if ((BTA_HH_GET_PROTO_EVT == event) || (BTA_HH_GET_RPT_EVT == event)|| (BTA_HH_GET_IDLE_EVT == event))
        param_len = sizeof(tBTA_HH_HSDATA);
    else if ((BTA_HH_SET_PROTO_EVT == event) || (BTA_HH_SET_RPT_EVT == event) || (BTA_HH_VC_UNPLUG_EVT == event) || (BTA_HH_SET_IDLE_EVT == event))
        param_len = sizeof(tBTA_HH_CBDATA);
    else if ((BTA_HH_ADD_DEV_EVT == event) || (BTA_HH_RMV_DEV_EVT == event) )
        param_len = sizeof(tBTA_HH_DEV_INFO);
    else if (BTA_HH_API_ERR_EVT == event)
        param_len = 0;
    /* switch context to btif task context (copy full union size for convenience) */
    status = btif_transfer_context(btif_hh_upstreams_evt, (uint16_t)event, (void*)p_data, param_len, NULL);

    /* catch any failed context transfers */
    ASSERTC(status == BT_STATUS_SUCCESS, "context transfer failed", status);
}

/*******************************************************************************
**
** Function         btif_hh_handle_evt
**
** Description      Switches context for immediate callback
**
** Returns          void
**
*******************************************************************************/

static void btif_hh_handle_evt(UINT16 event, char *p_param)
{
    bt_bdaddr_t *bd_addr = (bt_bdaddr_t*)p_param;
    BTIF_TRACE_EVENT("%s: event=%d", __FUNCTION__, event);
    int ret;
    switch(event)
    {
        case BTIF_HH_CONNECT_REQ_EVT:
        {
            ret = btif_hh_connect(bd_addr);
            if(ret == BT_STATUS_SUCCESS)
            {
                HAL_CBACK(bt_hh_callbacks, connection_state_cb,bd_addr,BTHH_CONN_STATE_CONNECTING);
            }
            else
                HAL_CBACK(bt_hh_callbacks, connection_state_cb,bd_addr,BTHH_CONN_STATE_DISCONNECTED);
        }
        break;

        case BTIF_HH_DISCONNECT_REQ_EVT:
        {
            BTIF_TRACE_EVENT("%s: event=%d", __FUNCTION__, event);
            btif_hh_disconnect(bd_addr);
            HAL_CBACK(bt_hh_callbacks, connection_state_cb,bd_addr,BTHH_CONN_STATE_DISCONNECTING);
        }
        break;

        case BTIF_HH_VUP_REQ_EVT:
        {
            BTIF_TRACE_EVENT("%s: event=%d", __FUNCTION__, event);
            ret = btif_hh_virtual_unplug(bd_addr);
        }
        break;

        default:
        {
            BTIF_TRACE_WARNING("%s : Unknown event 0x%x", __FUNCTION__, event);
        }
        break;
    }
}

/*******************************************************************************
**
** Function      btif_hh_tmr_hdlr
**
** Description   Process timer timeout
**
** Returns      void
*******************************************************************************/
void btif_hh_tmr_hdlr(TIMER_LIST_ENT *tle)
{
    btif_hh_device_t *p_dev;
    UINT8               i;
    tBTA_HH_EVT event;
    tBTA_HH p_data;
    int param_len = 0;
    memset(&p_data, 0, sizeof(tBTA_HH));

    BTIF_TRACE_DEBUG("%s timer_in_use=%d",  __FUNCTION__, tle->in_use );

    for (i = 0; i < BTIF_HH_MAX_HID; i++) {
        if (btif_hh_cb.devices[i].dev_status == BTHH_CONN_STATE_CONNECTED)
        {

            p_dev = &btif_hh_cb.devices[i];

            if (p_dev->vup_timer_active)
            {
                p_dev->vup_timer_active = FALSE;
                event = BTA_HH_VC_UNPLUG_EVT;
                p_data.dev_status.status = BTHH_ERR;
                p_data.dev_status.handle = p_dev->dev_handle;
                param_len = sizeof(tBTA_HH_CBDATA);

                /* switch context to btif task context */
                btif_transfer_context(btif_hh_upstreams_evt, (uint16_t)event, (void*)&p_data,
                            param_len, NULL);
            }
        }
    }
}

/*******************************************************************************
**
** Function         btif_hh_init
**
** Description     initializes the hh interface
**
** Returns         bt_status_t
**
*******************************************************************************/
static bt_status_t init( bthh_callbacks_t* callbacks )
{
    UINT32 i;
    BTIF_TRACE_EVENT("%s", __FUNCTION__);

    bt_hh_callbacks = callbacks;
    memset(&btif_hh_cb, 0, sizeof(btif_hh_cb));
    for (i = 0; i < BTIF_HH_MAX_HID; i++){
        btif_hh_cb.devices[i].dev_status = BTHH_CONN_STATE_UNKNOWN;
    }
    /* Invoke the enable service API to the core to set the appropriate service_id */
    btif_enable_service(BTA_HID_SERVICE_ID);
    return BT_STATUS_SUCCESS;
}

/*******************************************************************************
**
** Function        connect
**
** Description     connect to hid device
**
** Returns         bt_status_t
**
*******************************************************************************/
static bt_status_t connect( bt_bdaddr_t *bd_addr)
{
    if(btif_hh_cb.status != BTIF_HH_DEV_CONNECTING)
    {
        btif_transfer_context(btif_hh_handle_evt, BTIF_HH_CONNECT_REQ_EVT,
                                 (char*)bd_addr, sizeof(bt_bdaddr_t), NULL);
        return BT_STATUS_SUCCESS;
    }
    else
        return BT_STATUS_BUSY;
}

/*******************************************************************************
**
** Function         disconnect
**
** Description      disconnect from hid device
**
** Returns         bt_status_t
**
*******************************************************************************/
static bt_status_t disconnect( bt_bdaddr_t *bd_addr )
{
    CHECK_BTHH_INIT();
    btif_hh_device_t *p_dev;

    if (btif_hh_cb.status == BTIF_HH_DISABLED)
    {
        BTIF_TRACE_WARNING("%s: Error, HH status = %d", __FUNCTION__, btif_hh_cb.status);
        return BT_STATUS_FAIL;
    }
    p_dev = btif_hh_find_connected_dev_by_bda(bd_addr);
    if (p_dev != NULL)
    {
        return btif_transfer_context(btif_hh_handle_evt, BTIF_HH_DISCONNECT_REQ_EVT,
                     (char*)bd_addr, sizeof(bt_bdaddr_t), NULL);
    }
    else
    {
        BTIF_TRACE_WARNING("%s: Error, device  not opened.", __FUNCTION__);
        return BT_STATUS_FAIL;
    }
}

/*******************************************************************************
**
** Function         virtual_unplug
**
** Description      Virtual UnPlug (VUP) the specified HID device.
**
** Returns         bt_status_t
**
*******************************************************************************/
static bt_status_t virtual_unplug (bt_bdaddr_t *bd_addr)
{
    CHECK_BTHH_INIT();
    btif_hh_device_t *p_dev;
    char bd_str[18];
    sprintf(bd_str, "%02X:%02X:%02X:%02X:%02X:%02X",
            bd_addr->address[0],  bd_addr->address[1],  bd_addr->address[2],  bd_addr->address[3],
            bd_addr->address[4], bd_addr->address[5]);
    if (btif_hh_cb.status == BTIF_HH_DISABLED)
    {
        BTIF_TRACE_ERROR("%s: Error, HH status = %d", __FUNCTION__, btif_hh_cb.status);
        return BT_STATUS_FAIL;
    }
    p_dev = btif_hh_find_dev_by_bda(bd_addr);
    if (!p_dev)
    {
        BTIF_TRACE_ERROR("%s: Error, device %s not opened.", __FUNCTION__, bd_str);
        return BT_STATUS_FAIL;
    }
    btif_transfer_context(btif_hh_handle_evt, BTIF_HH_VUP_REQ_EVT,
                                 (char*)bd_addr, sizeof(bt_bdaddr_t), NULL);
    return BT_STATUS_SUCCESS;
}


/*******************************************************************************
**
** Function         set_info
**
** Description      Set the HID device descriptor for the specified HID device.
**
** Returns         bt_status_t
**
*******************************************************************************/
static bt_status_t set_info (bt_bdaddr_t *bd_addr, bthh_hid_info_t hid_info )
{
    CHECK_BTHH_INIT();
    tBTA_HH_DEV_DSCP_INFO dscp_info;
    BD_ADDR* bda = (BD_ADDR*) bd_addr;

    BTIF_TRACE_DEBUG("addr = %02X:%02X:%02X:%02X:%02X:%02X",
         (*bda)[0], (*bda)[1], (*bda)[2], (*bda)[3], (*bda)[4], (*bda)[5]);
    BTIF_TRACE_DEBUG("%s: sub_class = 0x%02x, app_id = %d, vendor_id = 0x%04x, "
         "product_id = 0x%04x, version= 0x%04x",
         __FUNCTION__, hid_info.sub_class,
         hid_info.app_id, hid_info.vendor_id, hid_info.product_id,
         hid_info.version);

    if (btif_hh_cb.status == BTIF_HH_DISABLED)
    {
        BTIF_TRACE_ERROR("%s: Error, HH status = %d", __FUNCTION__, btif_hh_cb.status);
        return BT_STATUS_FAIL;
    }

    dscp_info.vendor_id  = hid_info.vendor_id;
    dscp_info.product_id = hid_info.product_id;
    dscp_info.version    = hid_info.version;
    dscp_info.ctry_code  = hid_info.ctry_code;

    dscp_info.descriptor.dl_len = hid_info.dl_len;
    dscp_info.descriptor.dsc_list = (UINT8 *) GKI_getbuf(dscp_info.descriptor.dl_len);
    if (dscp_info.descriptor.dsc_list == NULL)
    {
        LOG_ERROR("%s: Failed to allocate DSCP for CB", __FUNCTION__);
        return BT_STATUS_FAIL;
    }
    memcpy(dscp_info.descriptor.dsc_list, &(hid_info.dsc_list), hid_info.dl_len);

    if (btif_hh_add_added_dev(*bd_addr, hid_info.attr_mask))
    {
        BTA_HhAddDev(*bda, hid_info.attr_mask, hid_info.sub_class,
                     hid_info.app_id, dscp_info);
    }

    GKI_freebuf(dscp_info.descriptor.dsc_list);

    return BT_STATUS_SUCCESS;
}

/*******************************************************************************
**
** Function         get_idle_time
**
** Description      Get the HID idle time
**
** Returns         bt_status_t
**
*******************************************************************************/
static bt_status_t get_idle_time(bt_bdaddr_t *bd_addr)
{
    CHECK_BTHH_INIT();
    btif_hh_device_t *p_dev;
    BD_ADDR* bda = (BD_ADDR*) bd_addr;

    BTIF_TRACE_DEBUG(" addr = %02X:%02X:%02X:%02X:%02X:%02X",
         (*bda)[0], (*bda)[1], (*bda)[2], (*bda)[3], (*bda)[4], (*bda)[5]);

    if (btif_hh_cb.status == BTIF_HH_DISABLED) {
        BTIF_TRACE_ERROR("%s: Error, HH status = %d", __FUNCTION__, btif_hh_cb.status);
        return BT_STATUS_FAIL;
    }

    p_dev = btif_hh_find_connected_dev_by_bda(bd_addr);
    if (p_dev != NULL) {
        BTA_HhGetIdle(p_dev->dev_handle);
    }
    else {
        return BT_STATUS_FAIL;
    }
    return BT_STATUS_SUCCESS;
}

/*******************************************************************************
**
** Function         set_idle_time
**
** Description      Set the HID idle time
**
** Returns         bt_status_t
**
*******************************************************************************/
static bt_status_t set_idle_time (bt_bdaddr_t *bd_addr, uint8_t idle_time)
{
    CHECK_BTHH_INIT();
    btif_hh_device_t *p_dev;
    BD_ADDR* bda = (BD_ADDR*) bd_addr;

    BTIF_TRACE_DEBUG("addr = %02X:%02X:%02X:%02X:%02X:%02X",
         (*bda)[0], (*bda)[1], (*bda)[2], (*bda)[3], (*bda)[4], (*bda)[5]);

    if (btif_hh_cb.status == BTIF_HH_DISABLED) {
        BTIF_TRACE_ERROR("%s: Error, HH status = %d", __FUNCTION__, btif_hh_cb.status);
        return BT_STATUS_FAIL;
    }

    p_dev = btif_hh_find_connected_dev_by_bda(bd_addr);
    if (p_dev == NULL) {
        BTIF_TRACE_WARNING(" Error, device %02X:%02X:%02X:%02X:%02X:%02X not opened.",
             (*bda)[0], (*bda)[1], (*bda)[2], (*bda)[3], (*bda)[4], (*bda)[5]);
        return BT_STATUS_FAIL;
    }
    else {
        BTA_HhSetIdle(p_dev->dev_handle, idle_time);
    }
    return BT_STATUS_SUCCESS;
}

/*******************************************************************************
**
** Function         get_protocol
**
** Description      Get the HID proto mode.
**
** Returns         bt_status_t
**
*******************************************************************************/
static bt_status_t get_protocol (bt_bdaddr_t *bd_addr, bthh_protocol_mode_t protocolMode)
{
    CHECK_BTHH_INIT();
    btif_hh_device_t *p_dev;
    BD_ADDR* bda = (BD_ADDR*) bd_addr;
    UNUSED(protocolMode);

    BTIF_TRACE_DEBUG(" addr = %02X:%02X:%02X:%02X:%02X:%02X",
         (*bda)[0], (*bda)[1], (*bda)[2], (*bda)[3], (*bda)[4], (*bda)[5]);

    if (btif_hh_cb.status == BTIF_HH_DISABLED) {
        BTIF_TRACE_ERROR("%s: Error, HH status = %d", __FUNCTION__, btif_hh_cb.status);
        return BT_STATUS_FAIL;
    }

    p_dev = btif_hh_find_connected_dev_by_bda(bd_addr);
    if (p_dev != NULL) {

        BTA_HhGetProtoMode(p_dev->dev_handle);
    }
    else {
        return BT_STATUS_FAIL;
    }
    return BT_STATUS_SUCCESS;
}

/*******************************************************************************
**
** Function         set_protocol
**
** Description      Set the HID proto mode.
**
** Returns         bt_status_t
**
*******************************************************************************/
static bt_status_t set_protocol (bt_bdaddr_t *bd_addr, bthh_protocol_mode_t protocolMode)
{
    CHECK_BTHH_INIT();
    btif_hh_device_t *p_dev;
    UINT8 proto_mode = protocolMode;
    BD_ADDR* bda = (BD_ADDR*) bd_addr;

    BTIF_TRACE_DEBUG("%s:proto_mode = %d", __FUNCTION__,protocolMode);

    BTIF_TRACE_DEBUG("addr = %02X:%02X:%02X:%02X:%02X:%02X",
         (*bda)[0], (*bda)[1], (*bda)[2], (*bda)[3], (*bda)[4], (*bda)[5]);

    if (btif_hh_cb.status == BTIF_HH_DISABLED) {
        BTIF_TRACE_ERROR("%s: Error, HH status = %d", __FUNCTION__, btif_hh_cb.status);
        return BT_STATUS_FAIL;
    }

    p_dev = btif_hh_find_connected_dev_by_bda(bd_addr);
    if (p_dev == NULL) {
        BTIF_TRACE_WARNING(" Error, device %02X:%02X:%02X:%02X:%02X:%02X not opened.",
             (*bda)[0], (*bda)[1], (*bda)[2], (*bda)[3], (*bda)[4], (*bda)[5]);
        return BT_STATUS_FAIL;
    }
    else if (protocolMode != BTA_HH_PROTO_RPT_MODE && protocolMode != BTA_HH_PROTO_BOOT_MODE) {
        BTIF_TRACE_WARNING("s: Error, device proto_mode = %d.", __FUNCTION__, proto_mode);
        return BT_STATUS_FAIL;
    }
    else {
        BTA_HhSetProtoMode(p_dev->dev_handle, protocolMode);
    }


    return BT_STATUS_SUCCESS;
}

/*******************************************************************************
**
** Function         get_report
**
** Description      Send a GET_REPORT to HID device.
**
** Returns         bt_status_t
**
*******************************************************************************/
static bt_status_t get_report (bt_bdaddr_t *bd_addr, bthh_report_type_t reportType, uint8_t reportId, int bufferSize)
{
    CHECK_BTHH_INIT();
    btif_hh_device_t *p_dev;
    BD_ADDR* bda = (BD_ADDR*) bd_addr;

    BTIF_TRACE_DEBUG("%s:proto_mode = %dr_type = %d, rpt_id = %d, buf_size = %d", __FUNCTION__,
          reportType, reportId, bufferSize);

    BTIF_TRACE_DEBUG("addr = %02X:%02X:%02X:%02X:%02X:%02X",
         (*bda)[0], (*bda)[1], (*bda)[2], (*bda)[3], (*bda)[4], (*bda)[5]);

    if (btif_hh_cb.status == BTIF_HH_DISABLED) {
        BTIF_TRACE_ERROR("%s: Error, HH status = %d", __FUNCTION__, btif_hh_cb.status);
        return BT_STATUS_FAIL;
    }


    p_dev = btif_hh_find_connected_dev_by_bda(bd_addr);
    if (p_dev == NULL) {
        BTIF_TRACE_ERROR("%s: Error, device %02X:%02X:%02X:%02X:%02X:%02X not opened.",
             (*bda)[0], (*bda)[1], (*bda)[2], (*bda)[3], (*bda)[4], (*bda)[5]);
        return BT_STATUS_FAIL;
    }
    else if ( ((int) reportType) <= BTA_HH_RPTT_RESRV || ((int) reportType) > BTA_HH_RPTT_FEATURE) {
        BTIF_TRACE_ERROR(" Error, device %02X:%02X:%02X:%02X:%02X:%02X not opened.",
             (*bda)[0], (*bda)[1], (*bda)[2], (*bda)[3], (*bda)[4], (*bda)[5]);
        return BT_STATUS_FAIL;
    }
    else {
        BTA_HhGetReport(p_dev->dev_handle, reportType,
                        reportId, bufferSize);
    }

    return BT_STATUS_SUCCESS;
}

/*******************************************************************************
**
** Function         set_report
**
** Description      Send a SET_REPORT to HID device.
**
** Returns         bt_status_t
**
*******************************************************************************/
static bt_status_t set_report (bt_bdaddr_t *bd_addr, bthh_report_type_t reportType, char* report)
{
    CHECK_BTHH_INIT();
    btif_hh_device_t *p_dev;
    BD_ADDR* bda = (BD_ADDR*) bd_addr;

    BTIF_TRACE_DEBUG("%s:reportType = %d", __FUNCTION__,reportType);

    BTIF_TRACE_DEBUG("addr = %02X:%02X:%02X:%02X:%02X:%02X",
         (*bda)[0], (*bda)[1], (*bda)[2], (*bda)[3], (*bda)[4], (*bda)[5]);


    if (btif_hh_cb.status == BTIF_HH_DISABLED) {
        BTIF_TRACE_ERROR("%s: Error, HH status = %d", __FUNCTION__, btif_hh_cb.status);
        return BT_STATUS_FAIL;
    }

    p_dev = btif_hh_find_connected_dev_by_bda(bd_addr);
    if (p_dev == NULL) {
        BTIF_TRACE_ERROR("%s: Error, device %02X:%02X:%02X:%02X:%02X:%02X not opened.",
             (*bda)[0], (*bda)[1], (*bda)[2], (*bda)[3], (*bda)[4], (*bda)[5]);
        return BT_STATUS_FAIL;
    }
    else if ( ( (int) reportType) <= BTA_HH_RPTT_RESRV || ( (int) reportType) > BTA_HH_RPTT_FEATURE) {
        BTIF_TRACE_ERROR(" Error, device %02X:%02X:%02X:%02X:%02X:%02X not opened.",
             (*bda)[0], (*bda)[1], (*bda)[2], (*bda)[3], (*bda)[4], (*bda)[5]);
        return BT_STATUS_FAIL;
    }
    else {
        int    hex_bytes_filled;
        UINT8  *hexbuf;
        UINT16 len = (strlen(report) + 1) / 2;

        hexbuf = GKI_getbuf(len);
        if (hexbuf == NULL) {
            BTIF_TRACE_ERROR("%s: Error, failed to allocate RPT buffer, len = %d",
                __FUNCTION__, len);
            return BT_STATUS_FAIL;
        }

        /* Build a SetReport data buffer */
        memset(hexbuf, 0, len);
        //TODO
        hex_bytes_filled = ascii_2_hex(report, len, hexbuf);
        LOG_INFO("Hex bytes filled, hex value: %d", hex_bytes_filled);
        if (hex_bytes_filled) {
            BT_HDR* p_buf = create_pbuf(hex_bytes_filled, hexbuf);
            if (p_buf == NULL) {
                BTIF_TRACE_ERROR("%s: Error, failed to allocate RPT buffer, len = %d",
                                  __FUNCTION__, hex_bytes_filled);
                GKI_freebuf(hexbuf);
                return BT_STATUS_FAIL;
            }
            BTA_HhSetReport(p_dev->dev_handle, reportType, p_buf);
            GKI_freebuf(hexbuf);
            return BT_STATUS_SUCCESS;
        }
        GKI_freebuf(hexbuf);
        return BT_STATUS_FAIL;
    }
}

/*******************************************************************************
**
** Function         send_data
**
** Description      Send a SEND_DATA to HID device.
**
** Returns         bt_status_t
**
*******************************************************************************/
static bt_status_t send_data (bt_bdaddr_t *bd_addr, char* data)
{
    CHECK_BTHH_INIT();
    btif_hh_device_t *p_dev;
    BD_ADDR* bda = (BD_ADDR*) bd_addr;

    BTIF_TRACE_DEBUG("%s", __FUNCTION__);

    BTIF_TRACE_DEBUG("addr = %02X:%02X:%02X:%02X:%02X:%02X",
         (*bda)[0], (*bda)[1], (*bda)[2], (*bda)[3], (*bda)[4], (*bda)[5]);

    if (btif_hh_cb.status == BTIF_HH_DISABLED) {
        BTIF_TRACE_ERROR("%s: Error, HH status = %d", __FUNCTION__, btif_hh_cb.status);
        return BT_STATUS_FAIL;
    }

    p_dev = btif_hh_find_connected_dev_by_bda(bd_addr);
    if (p_dev == NULL) {
        BTIF_TRACE_ERROR("%s: Error, device %02X:%02X:%02X:%02X:%02X:%02X not opened.",
             (*bda)[0], (*bda)[1], (*bda)[2], (*bda)[3], (*bda)[4], (*bda)[5]);
        return BT_STATUS_FAIL;
    }

    else {
        int    hex_bytes_filled;
        UINT8  *hexbuf;
        UINT16 len = (strlen(data) + 1) / 2;

        hexbuf = GKI_getbuf(len);
        if (hexbuf == NULL) {
            BTIF_TRACE_ERROR("%s: Error, failed to allocate RPT buffer, len = %d",
                __FUNCTION__, len);
            return BT_STATUS_FAIL;
        }

        /* Build a SendData data buffer */
        memset(hexbuf, 0, len);
        hex_bytes_filled = ascii_2_hex(data, len, hexbuf);
        BTIF_TRACE_ERROR("Hex bytes filled, hex value: %d, %d", hex_bytes_filled, len);

        if (hex_bytes_filled) {
            BT_HDR* p_buf = create_pbuf(hex_bytes_filled, hexbuf);
            if (p_buf == NULL) {
                BTIF_TRACE_ERROR("%s: Error, failed to allocate RPT buffer, len = %d",
                                  __FUNCTION__, hex_bytes_filled);
                GKI_freebuf(hexbuf);
                return BT_STATUS_FAIL;
            }
            p_buf->layer_specific = BTA_HH_RPTT_OUTPUT;
            BTA_HhSendData(p_dev->dev_handle, *bda, p_buf);
            GKI_freebuf(hexbuf);
            return BT_STATUS_SUCCESS;
        }
        GKI_freebuf(hexbuf);
        return BT_STATUS_FAIL;
    }
}


/*******************************************************************************
**
** Function         cleanup
**
** Description      Closes the HH interface
**
** Returns          bt_status_t
**
*******************************************************************************/
static void  cleanup( void )
{
    btif_hh_device_t *p_dev;
    int i;

    BTIF_TRACE_EVENT("hh:%s: ", __FUNCTION__);
    if (btif_hh_cb.status == BTIF_HH_DISABLED) {
        BTIF_TRACE_WARNING("%s: HH disabling or disabled already, status = %d", __FUNCTION__, btif_hh_cb.status);
        return;
    }
    if (bt_hh_callbacks)
    {
        btif_hh_cb.status = BTIF_HH_DISABLING;
        /* update flag, not to enable hid device service now as BT is switching off */
        btif_hh_cb.service_dereg_active = FALSE;
        btif_disable_service(BTA_HID_SERVICE_ID);
        bt_hh_callbacks = NULL;
    }

    for (i = 0; i < BTIF_HH_MAX_HID; i++) {
         p_dev = &btif_hh_cb.devices[i];
         if (p_dev->dev_status != BTHH_CONN_STATE_UNKNOWN && p_dev->fd >= 0) {
             BTIF_TRACE_DEBUG("%s: Closing uhid fd = %d", __FUNCTION__, p_dev->fd);
             if (p_dev->fd >= 0) {
                 bta_hh_co_destroy(p_dev->fd);
                 p_dev->fd = -1;
             }
             p_dev->hh_keep_polling = 0;
             p_dev->hh_poll_thread_id = -1;
         }
     }
}

static const bthh_interface_t bthhInterface = {
    sizeof(bthhInterface),
    init,
    connect,
    disconnect,
    virtual_unplug,
    set_info,
    get_protocol,
    set_protocol,
    get_idle_time,
    set_idle_time,
    get_report,
    set_report,
    send_data,
    cleanup,
};

/*******************************************************************************
**
** Function         btif_hh_execute_service
**
** Description      Initializes/Shuts down the service
**
** Returns          BT_STATUS_SUCCESS on success, BT_STATUS_FAIL otherwise
**
*******************************************************************************/
bt_status_t btif_hh_execute_service(BOOLEAN b_enable)
{
     if (b_enable)
     {
          /* Enable and register with BTA-HH */
          BTA_HhEnable(BTUI_HH_SECURITY, bte_hh_evt);
     }
     else {
         /* Disable HH */
         BTA_HhDisable();
     }
     return BT_STATUS_SUCCESS;
}

/*******************************************************************************
**
** Function         btif_hh_get_interface
**
** Description      Get the hh callback interface
**
** Returns          bthh_interface_t
**
*******************************************************************************/
const bthh_interface_t *btif_hh_get_interface()
{
    BTIF_TRACE_EVENT("%s", __FUNCTION__);
    return &bthhInterface;
}