summaryrefslogtreecommitdiffstats
path: root/src/com/android/bluetooth/gatt/GattService.java
blob: fa05c984dcc9165b5c871728c45adfef90f1fdc4 (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
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * 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.
 */

package com.android.bluetooth.gatt;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothUuid;
import android.bluetooth.IBluetoothGatt;
import android.bluetooth.IBluetoothGattCallback;
import android.bluetooth.IBluetoothGattServerCallback;
import android.content.Intent;
import android.os.IBinder;
import android.os.ParcelUuid;
import android.os.RemoteException;
import android.util.Log;

import com.android.bluetooth.btservice.ProfileService;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import com.android.bluetooth.LeScanRequestArbitrator;

/**
 * Provides Bluetooth Gatt profile, as a service in
 * the Bluetooth application.
 * @hide
 */
public class GattService extends ProfileService {
    private static final boolean DBG = GattServiceConfig.DBG;
    private static final String TAG = GattServiceConfig.TAG_PREFIX + "GattService";
    private static final int DEFAULT_SCAN_INTERVAL_MILLIS = 200;

    /**
     * Max packet size for ble advertising, defined in Bluetooth Specification Version 4.0 [Vol 3].
     */
    private static final int ADVERTISING_PACKET_MAX_BYTES = 31;
    /**
     * Size overhead for advertising flag.
     */
    private static final int ADVERTISING_FLAGS_BYTES = 3;
    /**
     * Size overhead per field. Usually it's just one byte of field length and one byte of
     * field type.
     */
    private static final int FIELD_OVERHEAD_BYTES = 2;

    /**
     * Byte size of 16 bit service uuid.
     */
    private static final int SHORT_UUID_BYTES = 2;
    /**
     * Byte size of 128 bit service uuid.
     */
    private static final int FULL_UUID_BYTES = 16;

    /**
     * Search queue to serialize remote onbject inspection.
     */
    SearchQueue mSearchQueue = new SearchQueue();

    /**
     * List of our registered clients.
     */

    class ClientMap extends ContextMap<IBluetoothGattCallback> {}
    ClientMap mClientMap = new ClientMap();

    /**
     * List of our registered server apps.
     */
    class ServerMap extends ContextMap<IBluetoothGattServerCallback> {}
    ServerMap mServerMap = new ServerMap();

    /**
     * Server handle map.
     */
    HandleMap mHandleMap = new HandleMap();
    private List<UUID> mAdvertisingServiceUuids = new ArrayList<UUID>();

    private int mAdvertisingClientIf = 0;

    private byte[] mServiceData = new byte[0];
    private int mManufacturerCode = -1;
    private byte[] mManufacturerData = new byte[0];
    private Integer mAdvertisingState = BluetoothAdapter.STATE_ADVERTISE_STOPPED;
    private final Object mLock = new Object();

    /**
     * Pending service declaration queue
     */
    private List<ServiceDeclaration> mServiceDeclarations = new ArrayList<ServiceDeclaration>();

    private ServiceDeclaration addDeclaration() {
        synchronized (mServiceDeclarations) {
            mServiceDeclarations.add(new ServiceDeclaration());
        }
        return getActiveDeclaration();
    }

    private ServiceDeclaration getActiveDeclaration() {
        synchronized (mServiceDeclarations) {
            if (mServiceDeclarations.size() > 0)
                return mServiceDeclarations.get(mServiceDeclarations.size() - 1);
        }
        return null;
    }

    private ServiceDeclaration getPendingDeclaration() {
        synchronized (mServiceDeclarations) {
            if (mServiceDeclarations.size() > 0)
                return mServiceDeclarations.get(0);
        }
        return null;
    }

    private void removePendingDeclaration() {
        synchronized (mServiceDeclarations) {
            if (mServiceDeclarations.size() > 0)
                mServiceDeclarations.remove(0);
        }
    }

    /**
     * List of clients interested in scan results.
     */
    private List<ScanClient> mScanQueue = new ArrayList<ScanClient>();

    private ScanClient getScanClient(int appIf, boolean isServer) {
        for(ScanClient client : mScanQueue) {
            if (client.appIf == appIf && client.isServer == isServer) {
                return client;
            }
        }
        return null;
    }

    private void removeScanClient(int appIf, boolean isServer) {
        for(ScanClient client : mScanQueue) {
          if (client.appIf == appIf && client.isServer == isServer) {
                mScanQueue.remove(client);
                break;
            }
        }
    }

    /**
     * Reliable write queue
     */
    private Set<String> mReliableQueue = new HashSet<String>();

    static {
        classInitNative();
    }

    protected String getName() {
        return TAG;
    }

    protected IProfileServiceBinder initBinder() {
        return new BluetoothGattBinder(this);
    }

    protected boolean start() {
        if (DBG) Log.d(TAG, "start()");
        initializeNative();
        return true;
    }

    protected boolean stop() {
        if (DBG) Log.d(TAG, "stop()");
        mClientMap.clear();
        mServerMap.clear();
        mSearchQueue.clear();
        mScanQueue.clear();
        mHandleMap.clear();
        mServiceDeclarations.clear();
        mReliableQueue.clear();
        return true;
    }

    protected boolean cleanup() {
        if (DBG) Log.d(TAG, "cleanup()");
        cleanupNative();
        return true;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (GattDebugUtils.handleDebugAction(this, intent)) {
            return Service.START_NOT_STICKY;
        }
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * DeathReceipient handlers used to unregister applications that
     * disconnect ungracefully (ie. crash or forced close).
     */

    class ClientDeathRecipient implements IBinder.DeathRecipient {
        int mAppIf;

        public ClientDeathRecipient(int appIf) {
            mAppIf = appIf;
        }

        public void binderDied() {
            if (DBG) Log.d(TAG, "Binder is dead - unregistering client (" + mAppIf + ")!");
            if (mAdvertisingClientIf == mAppIf) {
                stopAdvertising(true);  // force stop advertising.
            } else {
                stopScan(mAppIf, false);
            }
            unregisterClient(mAppIf);
        }
    }

    class ServerDeathRecipient implements IBinder.DeathRecipient {
        int mAppIf;

        public ServerDeathRecipient(int appIf) {
            mAppIf = appIf;
        }

        public void binderDied() {
            if (DBG) Log.d(TAG, "Binder is dead - unregistering server (" + mAppIf + ")!");
            unregisterServer(mAppIf);
        }
    }

    /**
     * Handlers for incoming service calls
     */
    private static class BluetoothGattBinder extends IBluetoothGatt.Stub implements IProfileServiceBinder {
        private GattService mService;

        public BluetoothGattBinder(GattService svc) {
            mService = svc;
        }

        public boolean cleanup()  {
            mService = null;
            return true;
        }

        private GattService getService() {
            if (mService  != null && mService.isAvailable()) return mService;
            Log.e(TAG, "getService() - Service requested, but not available!");
            return null;
        }

        public List<BluetoothDevice> getDevicesMatchingConnectionStates(int[] states) {
            GattService service = getService();
            if (service == null) return new ArrayList<BluetoothDevice>();
            return service.getDevicesMatchingConnectionStates(states);
        }

        public void registerClient(ParcelUuid uuid, IBluetoothGattCallback callback) {
            GattService service = getService();
            if (service == null) return;
            service.registerClient(uuid.getUuid(), callback);
        }

        public void unregisterClient(int clientIf) {
            GattService service = getService();
            if (service == null) return;
            service.unregisterClient(clientIf);
        }

        public void startScan(int appIf, boolean isServer) {
            GattService service = getService();
            if (service == null) return;
            service.startScan(appIf, isServer);
        }

        public void startScanWithUuids(int appIf, boolean isServer, ParcelUuid[] ids) {
            GattService service = getService();
            if (service == null) return;
            UUID[] uuids = new UUID[ids.length];
            for(int i = 0; i != ids.length; ++i) {
                uuids[i] = ids[i].getUuid();
            }
            service.startScanWithUuids(appIf, isServer, uuids);
        }

        public void stopScan(int appIf, boolean isServer) {
            GattService service = getService();
            if (service == null) return;
            service.stopScan(appIf, isServer);
        }

        public void clientConnect(int clientIf, String address, boolean isDirect) {
            GattService service = getService();
            if (service == null) return;
            service.clientConnect(clientIf, address, isDirect);
        }

        public void clientDisconnect(int clientIf, String address) {
            GattService service = getService();
            if (service == null) return;
            service.clientDisconnect(clientIf, address);
        }

        public void refreshDevice(int clientIf, String address) {
            GattService service = getService();
            if (service == null) return;
            service.refreshDevice(clientIf, address);
        }

        public void discoverServices(int clientIf, String address) {
            GattService service = getService();
            if (service == null) return;
            service.discoverServices(clientIf, address);
        }

        public void readCharacteristic(int clientIf, String address, int srvcType,
                                       int srvcInstanceId, ParcelUuid srvcId,
                                       int charInstanceId, ParcelUuid charId,
                                       int authReq) {
            GattService service = getService();
            if (service == null) return;
            service.readCharacteristic(clientIf, address, srvcType, srvcInstanceId,
                                       srvcId.getUuid(), charInstanceId,
                                       charId.getUuid(), authReq);
        }

        public void writeCharacteristic(int clientIf, String address, int srvcType,
                             int srvcInstanceId, ParcelUuid srvcId,
                             int charInstanceId, ParcelUuid charId,
                             int writeType, int authReq, byte[] value) {
            GattService service = getService();
            if (service == null) return;
            service.writeCharacteristic(clientIf, address, srvcType, srvcInstanceId,
                                       srvcId.getUuid(), charInstanceId,
                                       charId.getUuid(), writeType, authReq,
                                       value);
        }

        public void readDescriptor(int clientIf, String address, int srvcType,
                            int srvcInstanceId, ParcelUuid srvcId,
                            int charInstanceId, ParcelUuid charId,
                            int descrInstanceId, ParcelUuid descrId,
                            int authReq) {
            GattService service = getService();
            if (service == null) return;
            service.readDescriptor(clientIf, address, srvcType,
                                   srvcInstanceId, srvcId.getUuid(),
                                   charInstanceId, charId.getUuid(),
                                   descrInstanceId, descrId.getUuid(),
                                   authReq);
        }

        public void writeDescriptor(int clientIf, String address, int srvcType,
                            int srvcInstanceId, ParcelUuid srvcId,
                            int charInstanceId, ParcelUuid charId,
                            int descrInstanceId, ParcelUuid descrId,
                            int writeType, int authReq, byte[] value) {
            GattService service = getService();
            if (service == null) return;
            service.writeDescriptor(clientIf, address, srvcType,
                                    srvcInstanceId, srvcId.getUuid(),
                                    charInstanceId, charId.getUuid(),
                                    descrInstanceId, descrId.getUuid(),
                                    writeType, authReq, value);
        }

        public void beginReliableWrite(int clientIf, String address) {
            GattService service = getService();
            if (service == null) return;
            service.beginReliableWrite(clientIf, address);
        }

        public void endReliableWrite(int clientIf, String address, boolean execute) {
            GattService service = getService();
            if (service == null) return;
            service.endReliableWrite(clientIf, address, execute);
        }

        public void registerForNotification(int clientIf, String address, int srvcType,
                            int srvcInstanceId, ParcelUuid srvcId,
                            int charInstanceId, ParcelUuid charId,
                            boolean enable) {
            GattService service = getService();
            if (service == null) return;
            service.registerForNotification(clientIf, address, srvcType, srvcInstanceId,
                                       srvcId.getUuid(), charInstanceId,
                                       charId.getUuid(), enable);
        }

        public void readRemoteRssi(int clientIf, String address) {
            GattService service = getService();
            if (service == null) return;
            service.readRemoteRssi(clientIf, address);
        }

        public void registerServer(ParcelUuid uuid, IBluetoothGattServerCallback callback) {
            GattService service = getService();
            if (service == null) return;
            service.registerServer(uuid.getUuid(), callback);
        }

        public void unregisterServer(int serverIf) {
            GattService service = getService();
            if (service == null) return;
            service.unregisterServer(serverIf);
        }

        public void serverConnect(int serverIf, String address, boolean isDirect) {
            GattService service = getService();
            if (service == null) return;
            service.serverConnect(serverIf, address, isDirect);
        }

        public void serverDisconnect(int serverIf, String address) {
            GattService service = getService();
            if (service == null) return;
            service.serverDisconnect(serverIf, address);
        }

        public void beginServiceDeclaration(int serverIf, int srvcType,
                                            int srvcInstanceId, int minHandles,
                                            ParcelUuid srvcId, boolean advertisePreferred) {
            GattService service = getService();
            if (service == null) return;
            service.beginServiceDeclaration(serverIf, srvcType, srvcInstanceId,
                               minHandles, srvcId.getUuid(), advertisePreferred);
        }

        public void addIncludedService(int serverIf, int srvcType,
                            int srvcInstanceId, ParcelUuid srvcId) {
            GattService service = getService();
            if (service == null) return;
            service.addIncludedService(serverIf, srvcType, srvcInstanceId,
                                            srvcId.getUuid());
        }

        public void addCharacteristic(int serverIf, ParcelUuid charId,
                            int properties, int permissions) {
            GattService service = getService();
            if (service == null) return;
            service.addCharacteristic(serverIf, charId.getUuid(), properties,
                                      permissions);
        }

        public void addDescriptor(int serverIf, ParcelUuid descId,
                           int permissions) {
            GattService service = getService();
            if (service == null) return;
            service.addDescriptor(serverIf, descId.getUuid(), permissions);
        }

        public void endServiceDeclaration(int serverIf) {
            GattService service = getService();
            if (service == null) return;
            service.endServiceDeclaration(serverIf);
        }

        public void removeService(int serverIf, int srvcType,
                           int srvcInstanceId, ParcelUuid srvcId) {
            GattService service = getService();
            if (service == null) return;
            service.removeService(serverIf, srvcType, srvcInstanceId,
                                  srvcId.getUuid());
        }

        public void clearServices(int serverIf) {
            GattService service = getService();
            if (service == null) return;
            service.clearServices(serverIf);
        }

        public void sendResponse(int serverIf, String address, int requestId,
                                 int status, int offset, byte[] value) {
            GattService service = getService();
            if (service == null) return;
            service.sendResponse(serverIf, address, requestId, status, offset, value);
        }

        public void sendNotification(int serverIf, String address, int srvcType,
                                              int srvcInstanceId, ParcelUuid srvcId,
                                              int charInstanceId, ParcelUuid charId,
                                              boolean confirm, byte[] value) {
            GattService service = getService();
            if (service == null) return;
            service.sendNotification(serverIf, address, srvcType, srvcInstanceId,
                srvcId.getUuid(), charInstanceId, charId.getUuid(), confirm, value);
        }

        @Override
        public void startAdvertising(int appIf) throws RemoteException {
            GattService service = getService();
            if (service == null) return;
            service.startAdvertising(appIf);
        }

        @Override
        public boolean isAdvertising() {
            GattService service = getService();
            if (service == null) return false;
            return service.isAdvertising();
        }

        @Override
        public void stopAdvertising() throws RemoteException {
            GattService service = getService();
            if (service == null) return;
            service.stopAdvertising();
        }

        @Override
        public boolean setAdvServiceData(byte[] serviceData) throws RemoteException {
            GattService service = getService();
            if (service == null) return false;
            return service.setAdvServiceData(serviceData);
        }

        @Override
        public byte[] getAdvServiceData() throws RemoteException {
            GattService service = getService();
            if (service == null) return null;
            return service.getAdvServiceData();
        }

        @Override
        public boolean setAdvManufacturerCodeAndData(int manufactureCode, byte[] manufacturerData)
            throws RemoteException {
            GattService service = getService();
            if (service == null) return false;
            return service.setAdvManufacturerCodeAndData(manufactureCode, manufacturerData);
        }

        @Override
        public byte[] getAdvManufacturerData() throws RemoteException {
            GattService service = getService();
            if (service == null) return null;
            return service.getAdvManufacturerData();
        }

        @Override
        public List<ParcelUuid> getAdvServiceUuids() throws RemoteException {
            GattService service = getService();
            if (service == null) return null;
            return service.getAdvServiceUuids();
        }

        @Override
        public void removeAdvManufacturerCodeAndData(int manufacturerCode) throws RemoteException {
            GattService service = getService();
            if (service == null) return;
            service.removeAdvManufacturerCodeAndData(manufacturerCode);
        }
    };

    /**************************************************************************
     * Callback functions - CLIENT
     *************************************************************************/

    void onScanResult(String address, int rssi, byte[] adv_data) {
        if (DBG) Log.d(TAG, "onScanResult() - address=" + address
                    + ", rssi=" + rssi);

        List<UUID> remoteUuids = parseUuids(adv_data);
        for (ScanClient client : mScanQueue) {
            if (client.uuids.length > 0) {
                int matches = 0;
                for (UUID search : client.uuids) {
                    for (UUID remote: remoteUuids) {
                        if (remote.equals(search)) {
                            ++matches;
                            break; // Only count 1st match in case of duplicates
                        }
                    }
                }

                if (matches < client.uuids.length) continue;
            }

            if (!client.isServer) {
                ClientMap.App app = mClientMap.getById(client.appIf);
                if (app != null) {
                    try {
                        app.callback.onScanResult(address, rssi, adv_data);
                    } catch (RemoteException e) {
                        Log.e(TAG, "Exception: " + e);
                        mClientMap.remove(client.appIf);
                        mScanQueue.remove(client);
                    }
                }
            } else {
                ServerMap.App app = mServerMap.getById(client.appIf);
                if (app != null) {
                    try {
                        app.callback.onScanResult(address, rssi, adv_data);
                    } catch (RemoteException e) {
                        Log.e(TAG, "Exception: " + e);
                        mServerMap.remove(client.appIf);
                        mScanQueue.remove(client);
                    }
                }
            }
        }
    }

    void onClientRegistered(int status, int clientIf, long uuidLsb, long uuidMsb)
            throws RemoteException {
        UUID uuid = new UUID(uuidMsb, uuidLsb);
        if (DBG) Log.d(TAG, "onClientRegistered() - UUID=" + uuid + ", clientIf=" + clientIf);
        ClientMap.App app = mClientMap.getByUuid(uuid);
        if (app != null) {
            app.id = clientIf;
            app.linkToDeath(new ClientDeathRecipient(clientIf));
            app.callback.onClientRegistered(status, clientIf);
        }
    }

    void onConnected(int clientIf, int connId, int status, String address)
            throws RemoteException  {
        if (DBG) Log.d(TAG, "onConnected() - clientIf=" + clientIf
            + ", connId=" + connId + ", address=" + address);

        if (status == 0) mClientMap.addConnection(clientIf, connId, address);
        ClientMap.App app = mClientMap.getById(clientIf);
        if (app != null) {
            app.callback.onClientConnectionState(status, clientIf, true, address);
        }
    }

    void onDisconnected(int clientIf, int connId, int status, String address)
            throws RemoteException {
        if (DBG) Log.d(TAG, "onDisconnected() - clientIf=" + clientIf
            + ", connId=" + connId + ", address=" + address);

        mClientMap.removeConnection(clientIf, connId);
        mSearchQueue.removeConnId(connId);
        ClientMap.App app = mClientMap.getById(clientIf);
        if (app != null) {
            app.callback.onClientConnectionState(status, clientIf, false, address);
        }
    }

    void onSearchCompleted(int connId, int status) throws RemoteException {
        if (DBG) Log.d(TAG, "onSearchCompleted() - connId=" + connId+ ", status=" + status);
        // We got all services, now let's explore characteristics...
        continueSearch(connId, status);
    }

    void onSearchResult(int connId, int srvcType,
            int srvcInstId, long srvcUuidLsb, long srvcUuidMsb)
            throws RemoteException {
        UUID uuid = new UUID(srvcUuidMsb, srvcUuidLsb);
        String address = mClientMap.addressByConnId(connId);

        if (DBG) Log.d(TAG, "onSearchResult() - address=" + address + ", uuid=" + uuid);

        mSearchQueue.add(connId, srvcType, srvcInstId, srvcUuidLsb, srvcUuidMsb);

        ClientMap.App app = mClientMap.getByConnId(connId);
        if (app != null) {
            app.callback.onGetService(address, srvcType, srvcInstId,
                                        new ParcelUuid(uuid));
        }
    }

    void onGetCharacteristic(int connId, int status, int srvcType,
            int srvcInstId, long srvcUuidLsb, long srvcUuidMsb,
            int charInstId, long charUuidLsb, long charUuidMsb,
            int charProp) throws RemoteException {

        UUID srvcUuid = new UUID(srvcUuidMsb, srvcUuidLsb);
        UUID charUuid = new UUID(charUuidMsb, charUuidLsb);
        String address = mClientMap.addressByConnId(connId);

        if (DBG) Log.d(TAG, "onGetCharacteristic() - address=" + address
            + ", status=" + status + ", charUuid=" + charUuid + ", prop=" + charProp);

        if (status == 0) {
            mSearchQueue.add(connId, srvcType,
                            srvcInstId, srvcUuidLsb, srvcUuidMsb,
                            charInstId, charUuidLsb, charUuidMsb);

            ClientMap.App app = mClientMap.getByConnId(connId);
            if (app != null) {
                app.callback.onGetCharacteristic(address, srvcType,
                            srvcInstId, new ParcelUuid(srvcUuid),
                            charInstId, new ParcelUuid(charUuid), charProp);
            }

            // Get next characteristic in the current service
            gattClientGetCharacteristicNative(connId, srvcType,
                                        srvcInstId, srvcUuidLsb, srvcUuidMsb,
                                        charInstId, charUuidLsb, charUuidMsb);
        } else {
            // Check for included services next
            gattClientGetIncludedServiceNative(connId,
                srvcType, srvcInstId, srvcUuidLsb, srvcUuidMsb,
                0,0,0,0);
        }
    }

    void onGetDescriptor(int connId, int status, int srvcType,
            int srvcInstId, long srvcUuidLsb, long srvcUuidMsb,
            int charInstId, long charUuidLsb, long charUuidMsb,
            int descrInstId, long descrUuidLsb, long descrUuidMsb) throws RemoteException {

        UUID srvcUuid = new UUID(srvcUuidMsb, srvcUuidLsb);
        UUID charUuid = new UUID(charUuidMsb, charUuidLsb);
        UUID descUuid = new UUID(descrUuidMsb, descrUuidLsb);
        String address = mClientMap.addressByConnId(connId);

        if (DBG) Log.d(TAG, "onGetDescriptor() - address=" + address
            + ", status=" + status + ", descUuid=" + descUuid);

        if (status == 0) {
            ClientMap.App app = mClientMap.getByConnId(connId);
            if (app != null) {
                app.callback.onGetDescriptor(address, srvcType,
                            srvcInstId, new ParcelUuid(srvcUuid),
                            charInstId, new ParcelUuid(charUuid),
                            descrInstId, new ParcelUuid(descUuid));
            }

            // Get next descriptor for the current characteristic
            gattClientGetDescriptorNative(connId, srvcType,
                                    srvcInstId, srvcUuidLsb, srvcUuidMsb,
                                    charInstId, charUuidLsb, charUuidMsb,
                                    descrInstId, descrUuidLsb, descrUuidMsb);
        } else {
            // Explore the next service
            continueSearch(connId, 0);
        }
    }

    void onGetIncludedService(int connId, int status, int srvcType,
            int srvcInstId, long srvcUuidLsb, long srvcUuidMsb, int inclSrvcType,
            int inclSrvcInstId, long inclSrvcUuidLsb, long inclSrvcUuidMsb)
            throws RemoteException {
        UUID srvcUuid = new UUID(srvcUuidMsb, srvcUuidLsb);
        UUID inclSrvcUuid = new UUID(inclSrvcUuidMsb, inclSrvcUuidLsb);
        String address = mClientMap.addressByConnId(connId);

        if (DBG) Log.d(TAG, "onGetIncludedService() - address=" + address
            + ", status=" + status + ", uuid=" + srvcUuid
            + ", inclUuid=" + inclSrvcUuid);

        if (status == 0) {
            ClientMap.App app = mClientMap.getByConnId(connId);
            if (app != null) {
                app.callback.onGetIncludedService(address,
                    srvcType, srvcInstId, new ParcelUuid(srvcUuid),
                    inclSrvcType, inclSrvcInstId, new ParcelUuid(inclSrvcUuid));
            }

            // Find additional included services
            gattClientGetIncludedServiceNative(connId,
                srvcType, srvcInstId, srvcUuidLsb, srvcUuidMsb,
                inclSrvcType, inclSrvcInstId, inclSrvcUuidLsb, inclSrvcUuidMsb);
        } else {
            // Discover descriptors now
            continueSearch(connId, 0);
        }
    }

    void onRegisterForNotifications(int connId, int status, int registered, int srvcType,
            int srvcInstId, long srvcUuidLsb, long srvcUuidMsb,
            int charInstId, long charUuidLsb, long charUuidMsb) {
        UUID srvcUuid = new UUID(srvcUuidMsb, srvcUuidLsb);
        UUID charUuid = new UUID(charUuidMsb, charUuidLsb);
        String address = mClientMap.addressByConnId(connId);

        if (DBG) Log.d(TAG, "onRegisterForNotifications() - address=" + address
            + ", status=" + status + ", registered=" + registered
            + ", charUuid=" + charUuid);
    }

    void onNotify(int connId, String address, int srvcType,
            int srvcInstId, long srvcUuidLsb, long srvcUuidMsb,
            int charInstId, long charUuidLsb, long charUuidMsb,
            boolean isNotify, byte[] data) throws RemoteException {
        UUID srvcUuid = new UUID(srvcUuidMsb, srvcUuidLsb);
        UUID charUuid = new UUID(charUuidMsb, charUuidLsb);

        if (DBG) Log.d(TAG, "onNotify() - address=" + address
            + ", charUuid=" + charUuid + ", length=" + data.length);

        ClientMap.App app = mClientMap.getByConnId(connId);
        if (app != null) {
            app.callback.onNotify(address, srvcType,
                        srvcInstId, new ParcelUuid(srvcUuid),
                        charInstId, new ParcelUuid(charUuid),
                        data);
        }
    }

    void onReadCharacteristic(int connId, int status, int srvcType,
            int srvcInstId, long srvcUuidLsb, long srvcUuidMsb,
            int charInstId, long charUuidLsb, long charUuidMsb,
            int charType, byte[] data) throws RemoteException {

        UUID srvcUuid = new UUID(srvcUuidMsb, srvcUuidLsb);
        UUID charUuid = new UUID(charUuidMsb, charUuidLsb);
        String address = mClientMap.addressByConnId(connId);

        if (DBG) Log.d(TAG, "onReadCharacteristic() - address=" + address
            + ", status=" + status + ", length=" + data.length);

        ClientMap.App app = mClientMap.getByConnId(connId);
        if (app != null) {
            app.callback.onCharacteristicRead(address, status, srvcType,
                        srvcInstId, new ParcelUuid(srvcUuid),
                        charInstId, new ParcelUuid(charUuid), data);
        }
    }

    void onWriteCharacteristic(int connId, int status, int srvcType,
            int srvcInstId, long srvcUuidLsb, long srvcUuidMsb,
            int charInstId, long charUuidLsb, long charUuidMsb)
            throws RemoteException {

        UUID srvcUuid = new UUID(srvcUuidMsb, srvcUuidLsb);
        UUID charUuid = new UUID(charUuidMsb, charUuidLsb);
        String address = mClientMap.addressByConnId(connId);

        if (DBG) Log.d(TAG, "onWriteCharacteristic() - address=" + address
            + ", status=" + status);

        ClientMap.App app = mClientMap.getByConnId(connId);
        if (app != null) {
            app.callback.onCharacteristicWrite(address, status, srvcType,
                        srvcInstId, new ParcelUuid(srvcUuid),
                        charInstId, new ParcelUuid(charUuid));
        }
    }

    void onExecuteCompleted(int connId, int status) throws RemoteException {
        String address = mClientMap.addressByConnId(connId);
        if (DBG) Log.d(TAG, "onExecuteCompleted() - address=" + address
            + ", status=" + status);

        ClientMap.App app = mClientMap.getByConnId(connId);
        if (app != null) {
            app.callback.onExecuteWrite(address, status);
        }
    }

    void onReadDescriptor(int connId, int status, int srvcType,
            int srvcInstId, long srvcUuidLsb, long srvcUuidMsb,
            int charInstId, long charUuidLsb, long charUuidMsb,
            int descrInstId, long descrUuidLsb, long descrUuidMsb,
            int charType, byte[] data) throws RemoteException {

        UUID srvcUuid = new UUID(srvcUuidMsb, srvcUuidLsb);
        UUID charUuid = new UUID(charUuidMsb, charUuidLsb);
        UUID descrUuid = new UUID(descrUuidMsb, descrUuidLsb);
        String address = mClientMap.addressByConnId(connId);

        if (DBG) Log.d(TAG, "onReadDescriptor() - address=" + address
            + ", status=" + status + ", length=" + data.length);

        ClientMap.App app = mClientMap.getByConnId(connId);
        if (app != null) {
            app.callback.onDescriptorRead(address, status, srvcType,
                        srvcInstId, new ParcelUuid(srvcUuid),
                        charInstId, new ParcelUuid(charUuid),
                        descrInstId, new ParcelUuid(descrUuid), data);
        }
    }

    void onWriteDescriptor(int connId, int status, int srvcType,
            int srvcInstId, long srvcUuidLsb, long srvcUuidMsb,
            int charInstId, long charUuidLsb, long charUuidMsb,
            int descrInstId, long descrUuidLsb, long descrUuidMsb) throws RemoteException {

        UUID srvcUuid = new UUID(srvcUuidMsb, srvcUuidLsb);
        UUID charUuid = new UUID(charUuidMsb, charUuidLsb);
        UUID descrUuid = new UUID(descrUuidMsb, descrUuidLsb);
        String address = mClientMap.addressByConnId(connId);

        if (DBG) Log.d(TAG, "onWriteDescriptor() - address=" + address
            + ", status=" + status);

        ClientMap.App app = mClientMap.getByConnId(connId);
        if (app != null) {
            app.callback.onDescriptorWrite(address, status, srvcType,
                        srvcInstId, new ParcelUuid(srvcUuid),
                        charInstId, new ParcelUuid(charUuid),
                        descrInstId, new ParcelUuid(descrUuid));
        }
    }

    void onReadRemoteRssi(int clientIf, String address,
                    int rssi, int status) throws RemoteException{
        if (DBG) Log.d(TAG, "onReadRemoteRssi() - clientIf=" + clientIf + " address=" +
                     address + ", rssi=" + rssi + ", status=" + status);

        ClientMap.App app = mClientMap.getById(clientIf);
        if (app != null) {
            app.callback.onReadRemoteRssi(address, rssi, status);
        }
    }

    void onAdvertiseCallback(int status, int clientIf) throws RemoteException {
        if (DBG) Log.d(TAG, "onClientListen() status=" + status);
        synchronized (mLock) {
            if (DBG) Log.d(TAG, "state" + mAdvertisingState);
            // Invalid advertising state
            if (mAdvertisingState == BluetoothAdapter.STATE_ADVERTISE_STARTED ||
                    mAdvertisingState == BluetoothAdapter.STATE_ADVERTISE_STOPPED) {
                Log.e(TAG, "invalid callback state " + mAdvertisingState);
                return;
            }

            // Force stop advertising, no callback.
            if (mAdvertisingState == BluetoothAdapter.STATE_ADVERTISE_FORCE_STOPPING) {
                mAdvertisingState = BluetoothAdapter.STATE_ADVERTISE_STOPPED;
                mAdvertisingClientIf = 0;
                sendBroadcast(new Intent(
                        BluetoothAdapter.ACTION_BLUETOOTH_ADVERTISING_STOPPED));
                return;
            }

            if (mAdvertisingState == BluetoothAdapter.STATE_ADVERTISE_STARTING) {
                if (status == 0) {
                    mAdvertisingClientIf = clientIf;
                    mAdvertisingState = BluetoothAdapter.STATE_ADVERTISE_STARTED;
                    sendBroadcast(new Intent(
                            BluetoothAdapter.ACTION_BLUETOOTH_ADVERTISING_STARTED));
                } else {
                    mAdvertisingState = BluetoothAdapter.STATE_ADVERTISE_STOPPED;
                }
            } else if (mAdvertisingState == BluetoothAdapter.STATE_ADVERTISE_STOPPING) {
                if (status == 0) {
                    mAdvertisingState = BluetoothAdapter.STATE_ADVERTISE_STOPPED;
                    sendBroadcast(new Intent(
                            BluetoothAdapter.ACTION_BLUETOOTH_ADVERTISING_STOPPED));
                    mAdvertisingClientIf = 0;
                } else {
                    mAdvertisingState = BluetoothAdapter.STATE_ADVERTISE_STARTED;
                }
            }
        }
        ClientMap.App app = mClientMap.getById(clientIf);
        if (app == null || app.callback == null) {
            Log.e(TAG, "app or callback is null");
            return;
        }
        app.callback.onAdvertiseStateChange(mAdvertisingState, status);
    }

    /**************************************************************************
     * GATT Service functions - Shared CLIENT/SERVER
     *************************************************************************/

    List<BluetoothDevice> getDevicesMatchingConnectionStates(int[] states) {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");

        final int DEVICE_TYPE_BREDR = 0x1;

        Map<BluetoothDevice, Integer> deviceStates = new HashMap<BluetoothDevice,
                                                                 Integer>();

        // Add paired LE devices

        Set<BluetoothDevice> bondedDevices = mAdapter.getBondedDevices();
        for (BluetoothDevice device : bondedDevices) {
            if (getDeviceType(device) != DEVICE_TYPE_BREDR) {
                deviceStates.put(device, BluetoothProfile.STATE_DISCONNECTED);
            }
        }

        // Add connected deviceStates

        Set<String> connectedDevices = new HashSet<String>();
        connectedDevices.addAll(mClientMap.getConnectedDevices());
        connectedDevices.addAll(mServerMap.getConnectedDevices());

        for (String address : connectedDevices ) {
            BluetoothDevice device = mAdapter.getRemoteDevice(address);
            if (device != null) {
                deviceStates.put(device, BluetoothProfile.STATE_CONNECTED);
            }
        }

        // Create matching device sub-set

        List<BluetoothDevice> deviceList = new ArrayList<BluetoothDevice>();

        for (Map.Entry<BluetoothDevice, Integer> entry : deviceStates.entrySet()) {
            for(int state : states) {
                if (entry.getValue() == state) {
                    deviceList.add(entry.getKey());
                }
            }
        }

        return deviceList;
    }

    void startScan(int appIf, boolean isServer) {
        enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, "Need BLUETOOTH_ADMIN permission");

        if (DBG) Log.d(TAG, "startScan() - queue=" + mScanQueue.size());

        if (getScanClient(appIf, isServer) == null &&
            LeScanRequestArbitrator.instance().RequestLeScan(LeScanRequestArbitrator.LE_NORMAL_SCAN_TYPE)) {
            if (DBG) Log.d(TAG, "startScan() - adding client=" + appIf);
            mScanQueue.add(new ScanClient(appIf, isServer));
            if(mScanQueue.size()==1)//start scan only if it is not already started
            {
                gattClientScanNative(appIf, true);
            }
            else
            {
                Log.d(TAG, "startScan scan already in progress for appifs-queue=" + mScanQueue.size());
            }
        }
    }

    void startScanWithUuids(int appIf, boolean isServer, UUID[] uuids) {
        enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, "Need BLUETOOTH_ADMIN permission");

        if (DBG) Log.d(TAG, "startScanWithUuids() - queue=" + mScanQueue.size());

        if (getScanClient(appIf, isServer) == null &&
            LeScanRequestArbitrator.instance().RequestLeScan(LeScanRequestArbitrator.LE_NORMAL_SCAN_TYPE)) {
            if (DBG) Log.d(TAG, "startScanWithUuids() - adding client=" + appIf);
            mScanQueue.add(new ScanClient(appIf, isServer, uuids));
            if(mScanQueue.size()==1)//start scan only if it is not already started
            {
                gattClientScanNative(appIf, true);
            }
            else
            {
                Log.d(TAG, "startScanWithUuids scan already in progress for appifs-queue=" + mScanQueue.size());
            }
        }
    }

    void stopScan(int appIf, boolean isServer) {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH_ADMIN permission");

        if (DBG) Log.d(TAG, "stopScan() - queue=" + mScanQueue.size());
        if (getScanClient(appIf, isServer) != null) {
            LeScanRequestArbitrator.instance().StopLeScan(LeScanRequestArbitrator.LE_NORMAL_SCAN_TYPE);
            removeScanClient(appIf, isServer);
        }

        if (mScanQueue.isEmpty()) {
            if (DBG) Log.d(TAG, "stopScan() - queue empty; stopping scan");
            gattClientScanNative(appIf, false);
        }
    }

    /**************************************************************************
     * GATT Service functions - CLIENT
     *************************************************************************/

    void registerClient(UUID uuid, IBluetoothGattCallback callback) {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");

        if (DBG) Log.d(TAG, "registerClient() - UUID=" + uuid);
        mClientMap.add(uuid, callback);
        gattClientRegisterAppNative(uuid.getLeastSignificantBits(),
                                    uuid.getMostSignificantBits());
    }

    void unregisterClient(int clientIf) {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");

        if (DBG) Log.d(TAG, "unregisterClient() - clientIf=" + clientIf);
        mClientMap.remove(clientIf);
        gattClientUnregisterAppNative(clientIf);
    }

    void clientConnect(int clientIf, String address, boolean isDirect) {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");

        if (DBG) Log.d(TAG, "clientConnect() - address=" + address + ", isDirect=" + isDirect);
        gattClientConnectNative(clientIf, address, isDirect);
    }

    void clientDisconnect(int clientIf, String address) {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");

        Integer connId = mClientMap.connIdByAddress(clientIf, address);
        if (DBG) Log.d(TAG, "clientDisconnect() - address=" + address + ", connId=" + connId);

        gattClientDisconnectNative(clientIf, address, connId != null ? connId : 0);
    }

    synchronized boolean setAdvServiceData(byte[] serviceData) {
        enforcePrivilegedPermission();
        if (serviceData == null) return false;
        // Calculate how many more bytes are needed for advertising service data field.
        int extraBytes = (mServiceData == null) ?
                FIELD_OVERHEAD_BYTES + serviceData.length :
                    serviceData.length - mServiceData.length;
        if (getAvailableSize() < extraBytes) {
            Log.e(TAG, "cannot set service data, available size " + getAvailableSize());
            return false;
        }
        mServiceData = serviceData;
        return true;
    }

    byte[] getAdvServiceData() {
        enforcePrivilegedPermission();
        return mServiceData;
    }

    synchronized boolean setAdvManufacturerCodeAndData(
        int manufacturerCode, byte[] manufacturerData) {
        enforcePrivilegedPermission();
        if (manufacturerCode <= 0 || manufacturerData == null) {
            return false;
        }
        if (mManufacturerCode > 0 && mManufacturerData != null) {
            Log.e(TAG, "manufacture data is already set");
            return false;
        }
        if (getAvailableSize() <
            FIELD_OVERHEAD_BYTES + manufacturerData.length) {
            Log.e(TAG, "cannot set manu data, available size " + getAvailableSize());
            return false;
        }
        this.mManufacturerCode = manufacturerCode;
        this.mManufacturerData = manufacturerData;
        return true;
    }

    void removeAdvManufacturerCodeAndData(int manufacturerCode) {
        enforcePrivilegedPermission();
        if (mManufacturerCode != manufacturerCode) {
            return;
        }
        mManufacturerCode = -1;
        mManufacturerData = new byte[0];
    }

    byte[] getAdvManufacturerData() {
        enforcePrivilegedPermission();
        return mManufacturerData;
    }

    synchronized List<ParcelUuid> getAdvServiceUuids() {
        enforcePrivilegedPermission();;
        boolean fullUuidFound = false;
        List<ParcelUuid> serviceUuids = new ArrayList<ParcelUuid>();
        for (HandleMap.Entry entry : mHandleMap.mEntries) {
            if (entry.advertisePreferred) {
                ParcelUuid parcelUuid = new ParcelUuid(entry.uuid);
                if (BluetoothUuid.isShortUuid(parcelUuid)) {
                    serviceUuids.add(parcelUuid);
                } else {
                    // Allow at most one 128 bit service uuid to be advertised.
                    if (!fullUuidFound) {
                      fullUuidFound = true;
                      serviceUuids.add(parcelUuid);
                    }
                }
            }
        }
        return serviceUuids;
    }

    boolean isAdvertising() {
        enforcePrivilegedPermission();
        return mAdvertisingState != BluetoothAdapter.STATE_ADVERTISE_STOPPED;
    }

    void startAdvertising(int clientIf) {
        enforcePrivilegedPermission();
        if (DBG) Log.d(TAG, "start advertising for app - " + clientIf);
        List<ParcelUuid> serviceUuids = getAdvServiceUuids();
        int advertisingServiceUuidLength = serviceUuids == null ? 0 : serviceUuids.size();

        // Note according to Bluetooth Spec Version 4.0, for advertising and scan response data
        // "all numerical multi-byte entities and values shall use little-endian byte order".
        ByteBuffer advertisingUuidBytes = ByteBuffer.allocate(advertisingServiceUuidLength * 16)
                .order(ByteOrder.LITTLE_ENDIAN);
        for (ParcelUuid parcelUuid : serviceUuids) {
            UUID uuid = parcelUuid.getUuid();
            // Least signifcant bits first as the advertising uuid should be in little-endian.
            advertisingUuidBytes.putLong(uuid.getLeastSignificantBits())
                    .putLong(uuid.getMostSignificantBits());
        }

        // Set advertising data.
        gattSetAdvDataNative(clientIf,
                false,  // not scan response data
                false,  // no device name
                false,  // no tx power included
                DEFAULT_SCAN_INTERVAL_MILLIS,
                DEFAULT_SCAN_INTERVAL_MILLIS,
                0,  // no appearance limit
                mManufacturerData,
                mServiceData,
                advertisingUuidBytes.array());

        // Start advertising if advertising is not already started.
        if (!isAdvertising()) {
            gattAdvertiseNative(clientIf, true);
            mAdvertisingClientIf = clientIf;
            mAdvertisingState = BluetoothAdapter.STATE_ADVERTISE_STARTING;
        }
    }

    void stopAdvertising() {
        stopAdvertising(false);
    }

    void stopAdvertising(boolean forceStop) {
        enforcePrivilegedPermission();
        gattAdvertiseNative(mAdvertisingClientIf, false);
        synchronized (mLock) {
            if (forceStop) {
                mAdvertisingState = BluetoothAdapter.STATE_ADVERTISE_FORCE_STOPPING;
            } else {
                mAdvertisingState = BluetoothAdapter.STATE_ADVERTISE_STOPPING;
            }
        }
    }

    List<String> getConnectedDevices() {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");

        Set<String> connectedDevAddress = new HashSet<String>();
        connectedDevAddress.addAll(mClientMap.getConnectedDevices());
        connectedDevAddress.addAll(mServerMap.getConnectedDevices());
        List<String> connectedDeviceList = new ArrayList<String>(connectedDevAddress);
        return connectedDeviceList;
    }

    void refreshDevice(int clientIf, String address) {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");

        if (DBG) Log.d(TAG, "refreshDevice() - address=" + address);
        gattClientRefreshNative(clientIf, address);
    }

    void discoverServices(int clientIf, String address) {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");

        Integer connId = mClientMap.connIdByAddress(clientIf, address);
        if (DBG) Log.d(TAG, "discoverServices() - address=" + address + ", connId=" + connId);

        if (connId != null)
            gattClientSearchServiceNative(connId, true, 0, 0);
        else
            Log.e(TAG, "discoverServices() - No connection for " + address + "...");
    }

    void readCharacteristic(int clientIf, String address, int srvcType,
                            int srvcInstanceId, UUID srvcUuid,
                            int charInstanceId, UUID charUuid, int authReq) {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");

        if (DBG) Log.d(TAG, "readCharacteristic() - address=" + address);

        Integer connId = mClientMap.connIdByAddress(clientIf, address);
        if (connId != null)
            gattClientReadCharacteristicNative(connId, srvcType,
                srvcInstanceId, srvcUuid.getLeastSignificantBits(),
                srvcUuid.getMostSignificantBits(), charInstanceId,
                charUuid.getLeastSignificantBits(), charUuid.getMostSignificantBits(),
                authReq);
        else
            Log.e(TAG, "readCharacteristic() - No connection for " + address + "...");
    }

    void writeCharacteristic(int clientIf, String address, int srvcType,
                             int srvcInstanceId, UUID srvcUuid,
                             int charInstanceId, UUID charUuid, int writeType,
                             int authReq, byte[] value) {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");

        if (DBG) Log.d(TAG, "writeCharacteristic() - address=" + address);

        if (mReliableQueue.contains(address)) writeType = 3; // Prepared write

        Integer connId = mClientMap.connIdByAddress(clientIf, address);
        if (connId != null)
            gattClientWriteCharacteristicNative(connId, srvcType,
                srvcInstanceId, srvcUuid.getLeastSignificantBits(),
                srvcUuid.getMostSignificantBits(), charInstanceId,
                charUuid.getLeastSignificantBits(), charUuid.getMostSignificantBits(),
                writeType, authReq, value);
        else
            Log.e(TAG, "writeCharacteristic() - No connection for " + address + "...");
    }

    void readDescriptor(int clientIf, String address, int srvcType,
                            int srvcInstanceId, UUID srvcUuid,
                            int charInstanceId, UUID charUuid,
                            int descrInstanceId, UUID descrUuid,
                            int authReq) {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");

        if (DBG) Log.d(TAG, "readDescriptor() - address=" + address);

        Integer connId = mClientMap.connIdByAddress(clientIf, address);
        if (connId != null)
            gattClientReadDescriptorNative(connId, srvcType,
                srvcInstanceId,
                srvcUuid.getLeastSignificantBits(), srvcUuid.getMostSignificantBits(),
                charInstanceId,
                charUuid.getLeastSignificantBits(), charUuid.getMostSignificantBits(),
                descrInstanceId,
                descrUuid.getLeastSignificantBits(), descrUuid.getMostSignificantBits(),
                authReq);
        else
            Log.e(TAG, "readDescriptor() - No connection for " + address + "...");
    };

    void writeDescriptor(int clientIf, String address, int srvcType,
                            int srvcInstanceId, UUID srvcUuid,
                            int charInstanceId, UUID charUuid,
                            int descrInstanceId, UUID descrUuid,
                            int writeType, int authReq, byte[] value) {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");

        if (DBG) Log.d(TAG, "writeDescriptor() - address=" + address);

        Integer connId = mClientMap.connIdByAddress(clientIf, address);
        if (connId != null)
            gattClientWriteDescriptorNative(connId, srvcType,
                srvcInstanceId,
                srvcUuid.getLeastSignificantBits(), srvcUuid.getMostSignificantBits(),
                charInstanceId,
                charUuid.getLeastSignificantBits(), charUuid.getMostSignificantBits(),
                descrInstanceId,
                descrUuid.getLeastSignificantBits(), descrUuid.getMostSignificantBits(),
                writeType, authReq, value);
        else
            Log.e(TAG, "writeDescriptor() - No connection for " + address + "...");
    }

    void beginReliableWrite(int clientIf, String address) {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");

        if (DBG) Log.d(TAG, "beginReliableWrite() - address=" + address);
        mReliableQueue.add(address);
    }

    void endReliableWrite(int clientIf, String address, boolean execute) {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");

        if (DBG) Log.d(TAG, "endReliableWrite() - address=" + address
                                + " execute: " + execute);
        mReliableQueue.remove(address);

        Integer connId = mClientMap.connIdByAddress(clientIf, address);
        if (connId != null) gattClientExecuteWriteNative(connId, execute);
    }

    void registerForNotification(int clientIf, String address, int srvcType,
                int srvcInstanceId, UUID srvcUuid,
                int charInstanceId, UUID charUuid,
                boolean enable) {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");

        if (DBG) Log.d(TAG, "registerForNotification() - address=" + address + " enable: " + enable);

        Integer connId = mClientMap.connIdByAddress(clientIf, address);
        if (connId != null) {
            gattClientRegisterForNotificationsNative(clientIf, address,
                srvcType, srvcInstanceId, srvcUuid.getLeastSignificantBits(),
                srvcUuid.getMostSignificantBits(), charInstanceId,
                charUuid.getLeastSignificantBits(), charUuid.getMostSignificantBits(),
                enable);
        } else {
            Log.e(TAG, "registerForNotification() - No connection for " + address + "...");
        }
    }

    void readRemoteRssi(int clientIf, String address) {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");

        if (DBG) Log.d(TAG, "readRemoteRssi() - address=" + address);
        gattClientReadRemoteRssiNative(clientIf, address);
    }

    /**************************************************************************
     * Callback functions - SERVER
     *************************************************************************/

    void onServerRegistered(int status, int serverIf, long uuidLsb, long uuidMsb)
            throws RemoteException {

        UUID uuid = new UUID(uuidMsb, uuidLsb);
        if (DBG) Log.d(TAG, "onServerRegistered() - UUID=" + uuid + ", serverIf=" + serverIf);
        ServerMap.App app = mServerMap.getByUuid(uuid);
        if (app != null) {
            app.id = serverIf;
            app.linkToDeath(new ServerDeathRecipient(serverIf));
            app.callback.onServerRegistered(status, serverIf);
        }
    }

    void onServiceAdded(int status, int serverIf, int srvcType, int srvcInstId,
                        long srvcUuidLsb, long srvcUuidMsb, int srvcHandle)
                        throws RemoteException {
        UUID uuid = new UUID(srvcUuidMsb, srvcUuidLsb);
        if (DBG) Log.d(TAG, "onServiceAdded() UUID=" + uuid + ", status=" + status
            + ", handle=" + srvcHandle);
        if (status == 0) {
            mHandleMap.addService(serverIf, srvcHandle, uuid, srvcType, srvcInstId,
                mAdvertisingServiceUuids.remove(uuid));
        }

        continueServiceDeclaration(serverIf, status, srvcHandle);
    }

    void onIncludedServiceAdded(int status, int serverIf, int srvcHandle,
                                int includedSrvcHandle) throws RemoteException {
        if (DBG) Log.d(TAG, "onIncludedServiceAdded() status=" + status
            + ", service=" + srvcHandle + ", included=" + includedSrvcHandle);
        continueServiceDeclaration(serverIf, status, srvcHandle);
    }

    void onCharacteristicAdded(int status, int serverIf,
                               long charUuidLsb, long charUuidMsb,
                               int srvcHandle, int charHandle)
                               throws RemoteException {
            UUID uuid = new UUID(charUuidMsb, charUuidLsb);
        if (DBG) Log.d(TAG, "onCharacteristicAdded() UUID=" + uuid + ", status=" + status
            + ", srvcHandle=" + srvcHandle + ", charHandle=" + charHandle);
        if (status == 0)
            mHandleMap.addCharacteristic(serverIf, charHandle, uuid, srvcHandle);
        continueServiceDeclaration(serverIf, status, srvcHandle);
    }

    void onDescriptorAdded(int status, int serverIf,
                           long descrUuidLsb, long descrUuidMsb,
                           int srvcHandle, int descrHandle)
                           throws RemoteException {
            UUID uuid = new UUID(descrUuidMsb, descrUuidLsb);
        if (DBG) Log.d(TAG, "onDescriptorAdded() UUID=" + uuid + ", status=" + status
            + ", srvcHandle=" + srvcHandle + ", descrHandle=" + descrHandle);
        if (status == 0)
            mHandleMap.addDescriptor(serverIf, descrHandle, uuid, srvcHandle);
        continueServiceDeclaration(serverIf, status, srvcHandle);
    }

    void onServiceStarted(int status, int serverIf, int srvcHandle)
            throws RemoteException {
        if (DBG) Log.d(TAG, "onServiceStarted() srvcHandle=" + srvcHandle
            + ", status=" + status);
        if (status == 0)
            mHandleMap.setStarted(serverIf, srvcHandle, true);
    }

    void onServiceStopped(int status, int serverIf, int srvcHandle)
            throws RemoteException {
        if (DBG) Log.d(TAG, "onServiceStopped() srvcHandle=" + srvcHandle
            + ", status=" + status);
        if (status == 0)
            mHandleMap.setStarted(serverIf, srvcHandle, false);
        stopNextService(serverIf, status);
    }

    void onServiceDeleted(int status, int serverIf, int srvcHandle) {
        if (DBG) Log.d(TAG, "onServiceDeleted() srvcHandle=" + srvcHandle
            + ", status=" + status);
        mHandleMap.deleteService(serverIf, srvcHandle);
    }

    void onClientConnected(String address, boolean connected, int connId, int serverIf)
            throws RemoteException {

        if (DBG) Log.d(TAG, "onConnected() connId=" + connId
            + ", address=" + address + ", connected=" + connected);

        ServerMap.App app = mServerMap.getById(serverIf);
        if (app == null) return;

        if (connected) {
            mServerMap.addConnection(serverIf, connId, address);
        } else {
            mServerMap.removeConnection(serverIf, connId);
        }

        app.callback.onServerConnectionState((byte)0, serverIf, connected, address);
    }

    void onAttributeRead(String address, int connId, int transId,
                            int attrHandle, int offset, boolean isLong)
                            throws RemoteException {
        if (DBG) Log.d(TAG, "onAttributeRead() connId=" + connId
            + ", address=" + address + ", handle=" + attrHandle
            + ", requestId=" + transId + ", offset=" + offset);

        HandleMap.Entry entry = mHandleMap.getByHandle(attrHandle);
        if (entry == null) return;

        if (DBG) Log.d(TAG, "onAttributeRead() UUID=" + entry.uuid
            + ", serverIf=" + entry.serverIf + ", type=" + entry.type);

        mHandleMap.addRequest(transId, attrHandle);

        ServerMap.App app = mServerMap.getById(entry.serverIf);
        if (app == null) return;

        switch(entry.type) {
            case HandleMap.TYPE_CHARACTERISTIC:
            {
                HandleMap.Entry serviceEntry = mHandleMap.getByHandle(entry.serviceHandle);
                app.callback.onCharacteristicReadRequest(address, transId, offset, isLong,
                    serviceEntry.serviceType, serviceEntry.instance,
                    new ParcelUuid(serviceEntry.uuid), entry.instance,
                    new ParcelUuid(entry.uuid));
                break;
            }

            case HandleMap.TYPE_DESCRIPTOR:
            {
                HandleMap.Entry serviceEntry = mHandleMap.getByHandle(entry.serviceHandle);
                HandleMap.Entry charEntry = mHandleMap.getByHandle(entry.charHandle);
                app.callback.onDescriptorReadRequest(address, transId, offset, isLong,
                    serviceEntry.serviceType, serviceEntry.instance,
                    new ParcelUuid(serviceEntry.uuid), charEntry.instance,
                    new ParcelUuid(charEntry.uuid),
                    new ParcelUuid(entry.uuid));
                break;
            }

            default:
                Log.e(TAG, "onAttributeRead() - Requested unknown attribute type.");
                break;
        }
    }

    void onAttributeWrite(String address, int connId, int transId,
                            int attrHandle, int offset, int length,
                            boolean needRsp, boolean isPrep,
                            byte[] data)
                            throws RemoteException {
        if (DBG) Log.d(TAG, "onAttributeWrite() connId=" + connId
            + ", address=" + address + ", handle=" + attrHandle
            + ", requestId=" + transId + ", isPrep=" + isPrep
            + ", offset=" + offset);

        HandleMap.Entry entry = mHandleMap.getByHandle(attrHandle);
        if (entry == null) return;

        if (DBG) Log.d(TAG, "onAttributeWrite() UUID=" + entry.uuid
            + ", serverIf=" + entry.serverIf + ", type=" + entry.type);

        mHandleMap.addRequest(transId, attrHandle);

        ServerMap.App app = mServerMap.getById(entry.serverIf);
        if (app == null) return;

        switch(entry.type) {
            case HandleMap.TYPE_CHARACTERISTIC:
            {
                HandleMap.Entry serviceEntry = mHandleMap.getByHandle(entry.serviceHandle);
                app.callback.onCharacteristicWriteRequest(address, transId,
                            offset, length, isPrep, needRsp,
                            serviceEntry.serviceType, serviceEntry.instance,
                            new ParcelUuid(serviceEntry.uuid), entry.instance,
                            new ParcelUuid(entry.uuid), data);
                break;
            }

            case HandleMap.TYPE_DESCRIPTOR:
            {
                HandleMap.Entry serviceEntry = mHandleMap.getByHandle(entry.serviceHandle);
                HandleMap.Entry charEntry = mHandleMap.getByHandle(entry.charHandle);
                app.callback.onDescriptorWriteRequest(address, transId,
                            offset, length, isPrep, needRsp,
                            serviceEntry.serviceType, serviceEntry.instance,
                            new ParcelUuid(serviceEntry.uuid), charEntry.instance,
                            new ParcelUuid(charEntry.uuid),
                            new ParcelUuid(entry.uuid), data);
                break;
            }

            default:
                Log.e(TAG, "onAttributeWrite() - Requested unknown attribute type.");
                break;
        }
    }

    void onExecuteWrite(String address, int connId, int transId, int execWrite)
            throws RemoteException {
        if (DBG) Log.d(TAG, "onExecuteWrite() connId=" + connId
            + ", address=" + address + ", transId=" + transId);

        ServerMap.App app = mServerMap.getByConnId(connId);
        if (app == null) return;

        app.callback.onExecuteWrite(address, transId, execWrite == 1);
    }

    void onResponseSendCompleted(int status, int attrHandle) {
        if (DBG) Log.d(TAG, "onResponseSendCompleted() handle=" + attrHandle);
    }

    /**************************************************************************
     * GATT Service functions - SERVER
     *************************************************************************/

    void registerServer(UUID uuid, IBluetoothGattServerCallback callback) {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");

        if (DBG) Log.d(TAG, "registerServer() - UUID=" + uuid);
        mServerMap.add(uuid, callback);
        gattServerRegisterAppNative(uuid.getLeastSignificantBits(),
                                    uuid.getMostSignificantBits());
    }

    void unregisterServer(int serverIf) {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");

        if (DBG) Log.d(TAG, "unregisterServer() - serverIf=" + serverIf);

        deleteServices(serverIf);

        mServerMap.remove(serverIf);
        gattServerUnregisterAppNative(serverIf);
    }

    void serverConnect(int serverIf, String address, boolean isDirect) {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");

        if (DBG) Log.d(TAG, "serverConnect() - address=" + address);
        gattServerConnectNative(serverIf, address, isDirect);
    }

    void serverDisconnect(int serverIf, String address) {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");

        Integer connId = mServerMap.connIdByAddress(serverIf, address);
        if (DBG) Log.d(TAG, "serverDisconnect() - address=" + address + ", connId=" + connId);

        gattServerDisconnectNative(serverIf, address, connId != null ? connId : 0);
    }

    void beginServiceDeclaration(int serverIf, int srvcType, int srvcInstanceId,
                                 int minHandles, UUID srvcUuid, boolean advertisePreferred) {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");

        if (DBG) Log.d(TAG, "beginServiceDeclaration() - uuid=" + srvcUuid);
        ServiceDeclaration serviceDeclaration = addDeclaration();
        serviceDeclaration.addService(srvcUuid, srvcType, srvcInstanceId, minHandles,
            advertisePreferred);
    }

    void addIncludedService(int serverIf, int srvcType, int srvcInstanceId,
                            UUID srvcUuid) {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");

        if (DBG) Log.d(TAG, "addIncludedService() - uuid=" + srvcUuid);
        getActiveDeclaration().addIncludedService(srvcUuid, srvcType, srvcInstanceId);
    }

    void addCharacteristic(int serverIf, UUID charUuid, int properties,
                           int permissions) {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");

        if (DBG) Log.d(TAG, "addCharacteristic() - uuid=" + charUuid);
        getActiveDeclaration().addCharacteristic(charUuid, properties, permissions);
    }

    void addDescriptor(int serverIf, UUID descUuid, int permissions) {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");

        if (DBG) Log.d(TAG, "addDescriptor() - uuid=" + descUuid);
        getActiveDeclaration().addDescriptor(descUuid, permissions);
    }

    void endServiceDeclaration(int serverIf) {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");

        if (DBG) Log.d(TAG, "endServiceDeclaration()");

        if (getActiveDeclaration() == getPendingDeclaration()) {
            try {
                continueServiceDeclaration(serverIf, (byte)0, 0);
            } catch (RemoteException e) {
                Log.e(TAG,""+e);
            }
        }
    }

    void removeService(int serverIf, int srvcType,
                  int srvcInstanceId, UUID srvcUuid) {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");

        if (DBG) Log.d(TAG, "removeService() - uuid=" + srvcUuid);

        int srvcHandle = mHandleMap.getServiceHandle(srvcUuid, srvcType, srvcInstanceId);
        if (srvcHandle == 0) return;
        gattServerDeleteServiceNative(serverIf, srvcHandle);
    }

    void clearServices(int serverIf) {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");

        if (DBG) Log.d(TAG, "clearServices()");
        deleteServices(serverIf);
    }

    void sendResponse(int serverIf, String address, int requestId,
                      int status, int offset, byte[] value) {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");

        if (DBG) Log.d(TAG, "sendResponse() - address=" + address);

        int handle = 0;
        HandleMap.Entry entry = mHandleMap.getByRequestId(requestId);
        if (entry != null) handle = entry.handle;

        int connId = mServerMap.connIdByAddress(serverIf, address);
        gattServerSendResponseNative(serverIf, connId, requestId, (byte)status,
                                     handle, offset, value, (byte)0);
        mHandleMap.deleteRequest(requestId);
    }

    void sendNotification(int serverIf, String address, int srvcType,
                                 int srvcInstanceId, UUID srvcUuid,
                                 int charInstanceId, UUID charUuid,
                                 boolean confirm, byte[] value) {
        enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");

        if (DBG) Log.d(TAG, "sendNotification() - address=" + address);

        int srvcHandle = mHandleMap.getServiceHandle(srvcUuid, srvcType, srvcInstanceId);
        if (srvcHandle == 0) return;

        int charHandle = mHandleMap.getCharacteristicHandle(srvcHandle, charUuid, charInstanceId);
        if (charHandle == 0) return;

        int connId = mServerMap.connIdByAddress(serverIf, address);
        if (connId == 0) return;

        if (confirm) {
            gattServerSendIndicationNative(serverIf, charHandle, connId, value);
        } else {
            gattServerSendNotificationNative(serverIf, charHandle, connId, value);
        }
    }

    /**************************************************************************
     * Private functions
     *************************************************************************/

    private int getDeviceType(BluetoothDevice device) {
        int type = gattClientGetDeviceTypeNative(device.getAddress());
        if (DBG) Log.d(TAG, "getDeviceType() - device=" + device
            + ", type=" + type);
        return type;
    }

    private synchronized int getAvailableSize() {
        enforcePrivilegedPermission();
        int availableSize = ADVERTISING_PACKET_MAX_BYTES - ADVERTISING_FLAGS_BYTES;

        for (ParcelUuid parcelUuid : getAdvServiceUuids()) {
            if (BluetoothUuid.isShortUuid(parcelUuid)) {
                availableSize -= FIELD_OVERHEAD_BYTES + SHORT_UUID_BYTES;
            } else {
                availableSize -= FIELD_OVERHEAD_BYTES + FULL_UUID_BYTES;
            }
        }
        if (mManufacturerCode > 0 && mManufacturerData != null) {
            availableSize -= (FIELD_OVERHEAD_BYTES + mManufacturerData.length);
        }
        if (mServiceData != null) {
            availableSize -= (FIELD_OVERHEAD_BYTES + mServiceData.length);
        }
        return availableSize;
    }

    // Enforce caller has BLUETOOTH_PRIVILEGED permission. A {@link SecurityException} will be
    // thrown if the caller app does not have BLUETOOTH_PRIVILEGED permission.
    private void enforcePrivilegedPermission() {
        enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED,
            "Need BLUETOOTH_PRIVILEGED permission");
    }

    private void continueSearch(int connId, int status) throws RemoteException {
        Log.d(TAG, "continueSearch() - connid=" + connId + ", status=" + status);

        if(mSearchQueue.isEmpty())
            Log.d(TAG,"Queue is completely empty");
        if(mSearchQueue.isEmpty(connId))
            Log.d(TAG,"continueSearch():Queue is empty for connid=" + connId);
        if (status == 0 && !mSearchQueue.isEmpty(connId)) {
            SearchQueue.Entry svc = mSearchQueue.pop(connId);

            //verify once that the popped value is correct
            if(svc.connId!=connId)
                Log.d(TAG,"continueSearch(): connid of popped value not matching: input=" + connId + "and popped="+svc.connId);

            if (svc.charUuidLsb == 0) {
                // Characteristic is up next
                gattClientGetCharacteristicNative(svc.connId, svc.srvcType,
                    svc.srvcInstId, svc.srvcUuidLsb, svc.srvcUuidMsb, 0, 0, 0);
            } else {
                // Descriptor is up next
                gattClientGetDescriptorNative(svc.connId, svc.srvcType,
                    svc.srvcInstId, svc.srvcUuidLsb, svc.srvcUuidMsb,
                    svc.charInstId, svc.charUuidLsb, svc.charUuidMsb, 0, 0, 0);
            }
        } else {
            ClientMap.App app = mClientMap.getByConnId(connId);
            if (app != null) {
                Log.d(TAG,"continueSearch(): calling searchcomplete in frameworks");
                app.callback.onSearchComplete(mClientMap.addressByConnId(connId), status);
            }
        }
    }

    private void continueServiceDeclaration(int serverIf, int status, int srvcHandle) throws RemoteException {
        if (mServiceDeclarations.size() == 0) return;
        if (DBG) Log.d(TAG, "continueServiceDeclaration() - srvcHandle=" + srvcHandle);

        boolean finished = false;

        ServiceDeclaration.Entry entry = null;
        if (status == 0)
            entry = getPendingDeclaration().getNext();

        if (entry != null) {
            if (DBG) Log.d(TAG, "continueServiceDeclaration() - next entry type="
                + entry.type);
            switch(entry.type) {
                case ServiceDeclaration.TYPE_SERVICE:
                    if (entry.advertisePreferred) {
                        mAdvertisingServiceUuids.add(entry.uuid);
                    }
                    gattServerAddServiceNative(serverIf, entry.serviceType,
                        entry.instance,
                        entry.uuid.getLeastSignificantBits(),
                        entry.uuid.getMostSignificantBits(),
                        getPendingDeclaration().getNumHandles());
                    break;

                case ServiceDeclaration.TYPE_CHARACTERISTIC:
                    gattServerAddCharacteristicNative(serverIf, srvcHandle,
                        entry.uuid.getLeastSignificantBits(),
                        entry.uuid.getMostSignificantBits(),
                        entry.properties, entry.permissions);
                    break;

                case ServiceDeclaration.TYPE_DESCRIPTOR:
                    gattServerAddDescriptorNative(serverIf, srvcHandle,
                        entry.uuid.getLeastSignificantBits(),
                        entry.uuid.getMostSignificantBits(),
                        entry.permissions);
                    break;

                case ServiceDeclaration.TYPE_INCLUDED_SERVICE:
                {
                    int inclSrvc = mHandleMap.getServiceHandle(entry.uuid,
                                            entry.serviceType, entry.instance);
                    if (inclSrvc != 0) {
                        gattServerAddIncludedServiceNative(serverIf, srvcHandle,
                                                           inclSrvc);
                    } else {
                        finished = true;
                    }
                    break;
                }
            }
        } else {
            gattServerStartServiceNative(serverIf, srvcHandle, (byte)2 /*BREDR/LE*/);
            finished = true;
        }

        if (finished) {
            if (DBG) Log.d(TAG, "continueServiceDeclaration() - completed.");
            ServerMap.App app = mServerMap.getById(serverIf);
            if (app != null) {
                HandleMap.Entry serviceEntry = mHandleMap.getByHandle(srvcHandle);

                if (serviceEntry != null) {
                    app.callback.onServiceAdded(status, serviceEntry.serviceType,
                        serviceEntry.instance, new ParcelUuid(serviceEntry.uuid));
                } else {
                    app.callback.onServiceAdded(status, 0, 0, null);
                }
            }
            removePendingDeclaration();

            if (getPendingDeclaration() != null) {
                continueServiceDeclaration(serverIf, (byte)0, 0);
            }
        }
    }

    private void stopNextService(int serverIf, int status) throws RemoteException {
        if (DBG) Log.d(TAG, "stopNextService() - serverIf=" + serverIf
            + ", status=" + status);

        if (status == 0) {
            List<HandleMap.Entry> entries = mHandleMap.getEntries();
            for(HandleMap.Entry entry : entries) {
                if (entry.type != HandleMap.TYPE_SERVICE ||
                    entry.serverIf != serverIf ||
                    entry.started == false)
                        continue;

                gattServerStopServiceNative(serverIf, entry.handle);
                return;
            }
        }
    }

    private void deleteServices(int serverIf) {
        if (DBG) Log.d(TAG, "deleteServices() - serverIf=" + serverIf);

        /*
         * Figure out which handles to delete.
         * The handles are copied into a new list to avoid race conditions.
         */
        List<Integer> handleList = new ArrayList<Integer>();
        List<HandleMap.Entry> entries = mHandleMap.getEntries();
        for(HandleMap.Entry entry : entries) {
            if (entry.type != HandleMap.TYPE_SERVICE ||
                entry.serverIf != serverIf)
                    continue;
            handleList.add(entry.handle);
        }

        /* Now actually delete the services.... */
        for(Integer handle : handleList) {
            gattServerDeleteServiceNative(serverIf, handle);
        }
    }

    private List<UUID> parseUuids(byte[] adv_data) {
        List<UUID> uuids = new ArrayList<UUID>();

        int offset = 0;
        while(offset < (adv_data.length-2)) {
            int len = adv_data[offset++];
            if (len == 0) break;

            int type = adv_data[offset++];
            switch (type) {
                case 0x02: // Partial list of 16-bit UUIDs
                case 0x03: // Complete list of 16-bit UUIDs
                    while (len > 1) {
                        int uuid16 = adv_data[offset++];
                        uuid16 += (adv_data[offset++] << 8);
                        len -= 2;
                        uuids.add(UUID.fromString(String.format(
                            "%08x-0000-1000-8000-00805f9b34fb", uuid16)));
                    }
                    break;

                default:
                    offset += (len - 1);
                    break;
            }
        }

        return uuids;
    }

    /**************************************************************************
     * GATT Test functions
     *************************************************************************/

    void gattTestCommand(int command, UUID uuid1, String bda1,
                         int p1, int p2, int p3, int p4, int p5) {
        if (bda1 == null) bda1 = "00:00:00:00:00:00";
        if (uuid1 != null)
            gattTestNative(command, uuid1.getLeastSignificantBits(),
                       uuid1.getMostSignificantBits(), bda1, p1, p2, p3, p4, p5);
        else
            gattTestNative(command, 0,0, bda1, p1, p2, p3, p4, p5);
    }

    private native void gattTestNative(int command,
                                    long uuid1_lsb, long uuid1_msb, String bda1,
                                    int p1, int p2, int p3, int p4, int p5);

    /**************************************************************************
     * Native functions prototypes
     *************************************************************************/

    private native static void classInitNative();
    private native void initializeNative();
    private native void cleanupNative();

    private native int gattClientGetDeviceTypeNative(String address);

    private native void gattClientRegisterAppNative(long app_uuid_lsb,
                                                    long app_uuid_msb);

    private native void gattClientUnregisterAppNative(int clientIf);

    private native void gattClientScanNative(int clientIf, boolean start);

    private native void gattClientConnectNative(int clientIf, String address,
            boolean isDirect);

    private native void gattClientDisconnectNative(int clientIf, String address,
            int conn_id);

    private native void gattClientRefreshNative(int clientIf, String address);

    private native void gattClientSearchServiceNative(int conn_id,
            boolean search_all, long service_uuid_lsb, long service_uuid_msb);

    private native void gattClientGetCharacteristicNative(int conn_id,
            int service_type, int service_id_inst_id, long service_id_uuid_lsb,
            long service_id_uuid_msb, int char_id_inst_id, long char_id_uuid_lsb,
            long char_id_uuid_msb);

    private native void gattClientGetDescriptorNative(int conn_id, int service_type,
            int service_id_inst_id, long service_id_uuid_lsb, long service_id_uuid_msb,
            int char_id_inst_id, long char_id_uuid_lsb, long char_id_uuid_msb,
            int descr_id_inst_id, long descr_id_uuid_lsb, long descr_id_uuid_msb);

    private native void gattClientGetIncludedServiceNative(int conn_id,
            int service_type, int service_id_inst_id,
            long service_id_uuid_lsb, long service_id_uuid_msb,
            int incl_service_id_inst_id, int incl_service_type,
            long incl_service_id_uuid_lsb, long incl_service_id_uuid_msb);

    private native void gattClientReadCharacteristicNative(int conn_id,
            int service_type, int service_id_inst_id, long service_id_uuid_lsb,
            long service_id_uuid_msb, int char_id_inst_id, long char_id_uuid_lsb,
            long char_id_uuid_msb, int authReq);

    private native void gattClientReadDescriptorNative(int conn_id, int service_type,
            int service_id_inst_id, long service_id_uuid_lsb, long service_id_uuid_msb,
            int char_id_inst_id, long char_id_uuid_lsb, long char_id_uuid_msb,
            int descr_id_inst_id, long descr_id_uuid_lsb, long descr_id_uuid_msb,
            int authReq);

    private native void gattClientWriteCharacteristicNative(int conn_id,
            int service_type, int service_id_inst_id, long service_id_uuid_lsb,
            long service_id_uuid_msb, int char_id_inst_id, long char_id_uuid_lsb,
            long char_id_uuid_msb, int write_type, int auth_req, byte[] value);

    private native void gattClientWriteDescriptorNative(int conn_id, int service_type,
            int service_id_inst_id, long service_id_uuid_lsb, long service_id_uuid_msb,
            int char_id_inst_id, long char_id_uuid_lsb, long char_id_uuid_msb,
            int descr_id_inst_id, long descr_id_uuid_lsb, long descr_id_uuid_msb,
            int write_type, int auth_req, byte[] value);

    private native void gattClientExecuteWriteNative(int conn_id, boolean execute);

    private native void gattClientRegisterForNotificationsNative(int clientIf,
            String address, int service_type, int service_id_inst_id,
            long service_id_uuid_lsb, long service_id_uuid_msb,
            int char_id_inst_id, long char_id_uuid_lsb, long char_id_uuid_msb,
            boolean enable);

    private native void gattClientReadRemoteRssiNative(int clientIf,
            String address);

    private native void gattAdvertiseNative(int client_if, boolean start);

    private native void gattSetAdvDataNative(int serverIf, boolean setScanRsp, boolean inclName,
            boolean inclTxPower, int minInterval, int maxInterval,
            int appearance, byte[] manufacturerData, byte[] serviceData, byte[] serviceUuid);

    private native void gattServerRegisterAppNative(long app_uuid_lsb,
                                                    long app_uuid_msb);

    private native void gattServerUnregisterAppNative(int serverIf);

    private native void gattServerConnectNative(int server_if, String address,
                                             boolean is_direct);

    private native void gattServerDisconnectNative(int serverIf, String address,
                                              int conn_id);

    private native void gattServerAddServiceNative (int server_if,
            int service_type, int service_id_inst_id,
            long service_id_uuid_lsb, long service_id_uuid_msb,
            int num_handles);

    private native void gattServerAddIncludedServiceNative (int server_if,
            int svc_handle, int included_svc_handle);

    private native void gattServerAddCharacteristicNative (int server_if,
            int svc_handle, long char_uuid_lsb, long char_uuid_msb,
            int properties, int permissions);

    private native void gattServerAddDescriptorNative (int server_if,
            int svc_handle, long desc_uuid_lsb, long desc_uuid_msb,
            int permissions);

    private native void gattServerStartServiceNative (int server_if,
            int svc_handle, int transport );

    private native void gattServerStopServiceNative (int server_if,
                                                     int svc_handle);

    private native void gattServerDeleteServiceNative (int server_if,
                                                       int svc_handle);

    private native void gattServerSendIndicationNative (int server_if,
            int attr_handle, int conn_id, byte[] val);

    private native void gattServerSendNotificationNative (int server_if,
            int attr_handle, int conn_id, byte[] val);

    private native void gattServerSendResponseNative (int server_if,
            int conn_id, int trans_id, int status, int handle, int offset,
            byte[] val, int auth_req);
}