summaryrefslogtreecommitdiffstats
path: root/services/java/com/trustedlogic/trustednfc/android/server/NfcService.java
blob: 431b798ee28ca75f432233c85a1dd320aa5cf0a8 (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
/*
 * Copyright (C) 2010 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.trustedlogic.trustednfc.android.server;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Set;

import com.trustedlogic.trustednfc.android.ILlcpConnectionlessSocket;
import com.trustedlogic.trustednfc.android.ILlcpServiceSocket;
import com.trustedlogic.trustednfc.android.INfcManager;
import com.trustedlogic.trustednfc.android.ILlcpSocket;
import com.trustedlogic.trustednfc.android.INfcTag;
import com.trustedlogic.trustednfc.android.IP2pInitiator;
import com.trustedlogic.trustednfc.android.IP2pTarget;
import com.trustedlogic.trustednfc.android.LlcpPacket;
import com.trustedlogic.trustednfc.android.NdefMessage;
import com.trustedlogic.trustednfc.android.NfcException;
import com.trustedlogic.trustednfc.android.NfcManager;
import com.trustedlogic.trustednfc.android.internal.NativeLlcpConnectionlessSocket;
import com.trustedlogic.trustednfc.android.internal.NativeLlcpServiceSocket;
import com.trustedlogic.trustednfc.android.internal.NativeLlcpSocket;
import com.trustedlogic.trustednfc.android.internal.NativeNfcManager;
import com.trustedlogic.trustednfc.android.internal.NativeNfcTag;
import com.trustedlogic.trustednfc.android.internal.NativeP2pDevice;
import com.trustedlogic.trustednfc.android.internal.ErrorCodes;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.os.RemoteException;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.util.Log;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

public class NfcService extends INfcManager.Stub implements Runnable {

    /**
     * NFC Service tag
     */
    private static final String TAG = "NfcService";

    /**
     * NFC features disabled state
     */
    private static final short NFC_STATE_DISABLED = 0x00;

    /**
     * NFC features enabled state
     */
    private static final short NFC_STATE_ENABLED = 0x01;

    /**
     * NFC Discovery for Reader mode
     */
    private static final int DISCOVERY_MODE_READER = 0;

    /**
     * NFC Discovery for Card Emulation Mode
     */
    private static final int DISCOVERY_MODE_CARD_EMULATION = 2;

    /**
     * LLCP Service Socket type
     */
    private static final int LLCP_SERVICE_SOCKET_TYPE = 0;

    /**
     * LLCP Socket type
     */
    private static final int LLCP_SOCKET_TYPE = 1;

    /**
     * LLCP Connectionless socket type
     */
    private static final int LLCP_CONNECTIONLESS_SOCKET_TYPE = 2;

    /**
     * Maximun number of sockets managed
     */
    private static final int LLCP_SOCKET_NB_MAX = 5;

    /**
     * Default value for the Maximum Information Unit parameter
     */
    private static final int LLCP_LTO_DEFAULT_VALUE = 150;

    /**
     * Default value for the Maximum Information Unit parameter
     */
    private static final int LLCP_LTO_MAX_VALUE = 255;

    /**
     * Maximun value for the Receive Window
     */
    private static final int LLCP_RW_MAX_VALUE = 15;

    /**
     * Default value for the Maximum Information Unit parameter
     */
    private static final int LLCP_MIU_DEFAULT_VALUE = 128;

    /**
     * Default value for the Maximum Information Unit parameter
     */
    private static final int LLCP_MIU_MAX_VALUE = 2176;

    /**
     * Default value for the Well Known Service List parameter
     */
    private static final int LLCP_WKS_DEFAULT_VALUE = 1;

    /**
     * Max value for the Well Known Service List parameter
     */
    private static final int LLCP_WKS_MAX_VALUE = 15;

    /**
     * Default value for the Option parameter
     */
    private static final int LLCP_OPT_DEFAULT_VALUE = 0;

    /**
     * Max value for the Option parameter
     */
    private static final int LLCP_OPT_MAX_VALUE = 3;

    /**
     * LLCP Properties
     */
    private static final int PROPERTY_LLCP_LTO = 0;

    private static final int PROPERTY_LLCP_MIU = 1;

    private static final int PROPERTY_LLCP_WKS = 2;

    private static final int PROPERTY_LLCP_OPT = 3;

    private static final String PROPERTY_LLCP_LTO_VALUE = "llcp.lto";

    private static final String PROPERTY_LLCP_MIU_VALUE = "llcp.miu";

    private static final String PROPERTY_LLCP_WKS_VALUE = "llcp.wks";

    private static final String PROPERTY_LLCP_OPT_VALUE = "llcp.opt";

    /**
     * NFC Reader Properties
     */
    private static final int PROPERTY_NFC_DISCOVERY_A = 4;

    private static final int PROPERTY_NFC_DISCOVERY_B = 5;

    private static final int PROPERTY_NFC_DISCOVERY_F = 6;

    private static final int PROPERTY_NFC_DISCOVERY_15693 = 7;

    private static final int PROPERTY_NFC_DISCOVERY_NFCIP = 8;

    private static final String PROPERTY_NFC_DISCOVERY_A_VALUE = "discovery.iso14443A";

    private static final String PROPERTY_NFC_DISCOVERY_B_VALUE = "discovery.iso14443B";

    private static final String PROPERTY_NFC_DISCOVERY_F_VALUE = "discovery.felica";

    private static final String PROPERTY_NFC_DISCOVERY_15693_VALUE = "discovery.iso15693";

    private static final String PROPERTY_NFC_DISCOVERY_NFCIP_VALUE = "discovery.nfcip";

    private Context mContext;

    private HashMap<Integer, Object> mObjectMap = new HashMap<Integer, Object>();

    private HashMap<Integer, Object> mSocketMap = new HashMap<Integer, Object>();

    private LinkedList<RegisteredSocket> mRegisteredSocketList = new LinkedList<RegisteredSocket>();

    private int mLlcpLinkState = NfcManager.LLCP_LINK_STATE_DEACTIVATED;

    private int mGeneratedSocketHandle = 0;

    private int mNbSocketCreated = 0;

    private boolean mIsNfcEnabled = false;

    private NfcHandler mNfcHandler;

    private int mSelectedSeId = 0;

    private int mTimeout = 0;

    private int mNfcState;

    private int mNfcSecureElementState;

    private boolean mOpenPending = false;

    private NativeNfcManager mManager;

    private ILlcpSocket mLlcpSocket = new ILlcpSocket.Stub() {

        public int close(int nativeHandle) throws RemoteException {
            NativeLlcpSocket socket = null;
            boolean isSuccess = false;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return ErrorCodes.ERROR_NOT_INITIALIZED;
            }

            /* find the socket in the hmap */
            socket = (NativeLlcpSocket) findSocket(nativeHandle);
            if (socket != null) {
                if (mLlcpLinkState == NfcManager.LLCP_LINK_STATE_ACTIVATED) {
                    isSuccess = socket.doClose();
                    if (isSuccess) {
                        /* Remove the socket closed from the hmap */
                        RemoveSocket(nativeHandle);
                        /* Update mNbSocketCreated */
                        mNbSocketCreated--;
                        return ErrorCodes.SUCCESS;
                    } else {
                        return ErrorCodes.ERROR_IO;
                    }
                } else {
                    /* Remove the socket closed from the hmap */
                    RemoveSocket(nativeHandle);

                    /* Remove registered socket from the list */
                    RemoveRegisteredSocket(nativeHandle);

                    /* Update mNbSocketCreated */
                    mNbSocketCreated--;

                    return ErrorCodes.SUCCESS;
                }
            } else {
                return ErrorCodes.ERROR_IO;
            }
        }

        public int connect(int nativeHandle, int sap) throws RemoteException {
            NativeLlcpSocket socket = null;
            boolean isSuccess = false;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return ErrorCodes.ERROR_NOT_INITIALIZED;
            }

            /* find the socket in the hmap */
            socket = (NativeLlcpSocket) findSocket(nativeHandle);
            if (socket != null) {
                isSuccess = socket.doConnect(sap, socket.getConnectTimeout());
                if (isSuccess) {
                    return ErrorCodes.SUCCESS;
                } else {
                    return ErrorCodes.ERROR_IO;
                }
            } else {
                return ErrorCodes.ERROR_IO;
            }

        }

        public int connectByName(int nativeHandle, String sn) throws RemoteException {
            NativeLlcpSocket socket = null;
            boolean isSuccess = false;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return ErrorCodes.ERROR_NOT_INITIALIZED;
            }

            /* find the socket in the hmap */
            socket = (NativeLlcpSocket) findSocket(nativeHandle);
            if (socket != null) {
                isSuccess = socket.doConnectBy(sn, socket.getConnectTimeout());
                if (isSuccess) {
                    return ErrorCodes.SUCCESS;
                } else {
                    return ErrorCodes.ERROR_IO;
                }
            } else {
                return ErrorCodes.ERROR_IO;
            }

        }

        public int getConnectTimeout(int nativeHandle) throws RemoteException {
            NativeLlcpSocket socket = null;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return ErrorCodes.ERROR_NOT_INITIALIZED;
            }

            /* find the socket in the hmap */
            socket = (NativeLlcpSocket) findSocket(nativeHandle);
            if (socket != null) {
                return socket.getConnectTimeout();
            } else {
                return 0;
            }
        }

        public int getLocalSap(int nativeHandle) throws RemoteException {
            NativeLlcpSocket socket = null;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return ErrorCodes.ERROR_NOT_INITIALIZED;
            }

            /* find the socket in the hmap */
            socket = (NativeLlcpSocket) findSocket(nativeHandle);
            if (socket != null) {
                return socket.getSap();
            } else {
                return 0;
            }
        }

        public int getLocalSocketMiu(int nativeHandle) throws RemoteException {
            NativeLlcpSocket socket = null;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return ErrorCodes.ERROR_NOT_INITIALIZED;
            }

            /* find the socket in the hmap */
            socket = (NativeLlcpSocket) findSocket(nativeHandle);
            if (socket != null) {
                return socket.getMiu();
            } else {
                return 0;
            }
        }

        public int getLocalSocketRw(int nativeHandle) throws RemoteException {
            NativeLlcpSocket socket = null;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return ErrorCodes.ERROR_NOT_INITIALIZED;
            }

            /* find the socket in the hmap */
            socket = (NativeLlcpSocket) findSocket(nativeHandle);
            if (socket != null) {
                return socket.getRw();
            } else {
                return 0;
            }
        }

        public int getRemoteSocketMiu(int nativeHandle) throws RemoteException {
            NativeLlcpSocket socket = null;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return ErrorCodes.ERROR_NOT_INITIALIZED;
            }

            /* find the socket in the hmap */
            socket = (NativeLlcpSocket) findSocket(nativeHandle);
            if (socket != null) {
                if (socket.doGetRemoteSocketMiu() != 0) {
                    return socket.doGetRemoteSocketMiu();
                } else {
                    return ErrorCodes.ERROR_SOCKET_NOT_CONNECTED;
                }
            } else {
                return ErrorCodes.ERROR_SOCKET_NOT_CONNECTED;
            }
        }

        public int getRemoteSocketRw(int nativeHandle) throws RemoteException {
            NativeLlcpSocket socket = null;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return ErrorCodes.ERROR_NOT_INITIALIZED;
            }

            /* find the socket in the hmap */
            socket = (NativeLlcpSocket) findSocket(nativeHandle);
            if (socket != null) {
                if (socket.doGetRemoteSocketRw() != 0) {
                    return socket.doGetRemoteSocketRw();
                } else {
                    return ErrorCodes.ERROR_SOCKET_NOT_CONNECTED;
                }
            } else {
                return ErrorCodes.ERROR_SOCKET_NOT_CONNECTED;
            }
        }

        public int receive(int nativeHandle, byte[] receiveBuffer) throws RemoteException {
            NativeLlcpSocket socket = null;
            int receiveLength = 0;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return ErrorCodes.ERROR_NOT_INITIALIZED;
            }

            /* find the socket in the hmap */
            socket = (NativeLlcpSocket) findSocket(nativeHandle);
            if (socket != null) {
                receiveLength = socket.doReceive(receiveBuffer);
                if (receiveLength != 0) {
                    return receiveLength;
                } else {
                    return ErrorCodes.ERROR_IO;
                }
            } else {
                return ErrorCodes.ERROR_IO;
            }
        }

        public int send(int nativeHandle, byte[] data) throws RemoteException {
            NativeLlcpSocket socket = null;
            boolean isSuccess = false;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return ErrorCodes.ERROR_NOT_INITIALIZED;
            }

            /* find the socket in the hmap */
            socket = (NativeLlcpSocket) findSocket(nativeHandle);
            if (socket != null) {
                isSuccess = socket.doSend(data);
                if (isSuccess) {
                    return ErrorCodes.SUCCESS;
                } else {
                    return ErrorCodes.ERROR_IO;
                }
            } else {
                return ErrorCodes.ERROR_IO;
            }
        }

        public void setConnectTimeout(int nativeHandle, int timeout) throws RemoteException {
            NativeLlcpSocket socket = null;

            /* find the socket in the hmap */
            socket = (NativeLlcpSocket) findSocket(nativeHandle);
            if (socket != null) {
                socket.setConnectTimeout(timeout);
            }
        }

    };

    private ILlcpServiceSocket mLlcpServerSocketService = new ILlcpServiceSocket.Stub() {

        public int accept(int nativeHandle) throws RemoteException {
            NativeLlcpServiceSocket socket = null;
            NativeLlcpSocket clientSocket = null;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return ErrorCodes.ERROR_NOT_INITIALIZED;
            }

            if (mNbSocketCreated < LLCP_SOCKET_NB_MAX) {
                /* find the socket in the hmap */
                socket = (NativeLlcpServiceSocket) findSocket(nativeHandle);
                if (socket != null) {
                    clientSocket = socket.doAccept(socket.getAcceptTimeout(), socket.getMiu(),
                            socket.getRw(), socket.getLinearBufferLength());
                    if (clientSocket != null) {
                        /* Add the socket into the socket map */
                        mSocketMap.put(clientSocket.getHandle(), clientSocket);
                        mNbSocketCreated++;
                        return clientSocket.getHandle();
                    } else {
                        return ErrorCodes.ERROR_IO;
                    }
                } else {
                    return ErrorCodes.ERROR_IO;
                }
            } else {
                return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES;
            }

        }

        public void close(int nativeHandle) throws RemoteException {
            NativeLlcpServiceSocket socket = null;
            boolean isSuccess = false;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return;
            }

            /* find the socket in the hmap */
            socket = (NativeLlcpServiceSocket) findSocket(nativeHandle);
            if (socket != null) {
                if (mLlcpLinkState == NfcManager.LLCP_LINK_STATE_ACTIVATED) {
                    isSuccess = socket.doClose();
                    if (isSuccess) {
                        /* Remove the socket closed from the hmap */
                        RemoveSocket(nativeHandle);
                        /* Update mNbSocketCreated */
                        mNbSocketCreated--;
                    }
                } else {
                    /* Remove the socket closed from the hmap */
                    RemoveSocket(nativeHandle);

                    /* Remove registered socket from the list */
                    RemoveRegisteredSocket(nativeHandle);

                    /* Update mNbSocketCreated */
                    mNbSocketCreated--;
                }
            }
        }

        public int getAcceptTimeout(int nativeHandle) throws RemoteException {
            NativeLlcpServiceSocket socket = null;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return ErrorCodes.ERROR_NOT_INITIALIZED;
            }

            /* find the socket in the hmap */
            socket = (NativeLlcpServiceSocket) findSocket(nativeHandle);
            if (socket != null) {
                return socket.getAcceptTimeout();
            } else {
                return 0;
            }
        }

        public void setAcceptTimeout(int nativeHandle, int timeout) throws RemoteException {
            NativeLlcpServiceSocket socket = null;

            /* find the socket in the hmap */
            socket = (NativeLlcpServiceSocket) findSocket(nativeHandle);
            if (socket != null) {
                socket.setAcceptTimeout(timeout);
            }
        }
    };

    private ILlcpConnectionlessSocket mLlcpConnectionlessSocketService = new ILlcpConnectionlessSocket.Stub() {

        public void close(int nativeHandle) throws RemoteException {
            NativeLlcpConnectionlessSocket socket = null;
            boolean isSuccess = false;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return;
            }

            /* find the socket in the hmap */
            socket = (NativeLlcpConnectionlessSocket) findSocket(nativeHandle);
            if (socket != null) {
                if (mLlcpLinkState == NfcManager.LLCP_LINK_STATE_ACTIVATED) {
                    isSuccess = socket.doClose();
                    if (isSuccess) {
                        /* Remove the socket closed from the hmap */
                        RemoveSocket(nativeHandle);
                        /* Update mNbSocketCreated */
                        mNbSocketCreated--;
                    }
                } else {
                    /* Remove the socket closed from the hmap */
                    RemoveSocket(nativeHandle);

                    /* Remove registered socket from the list */
                    RemoveRegisteredSocket(nativeHandle);

                    /* Update mNbSocketCreated */
                    mNbSocketCreated--;
                }
            }
        }

        public int getSap(int nativeHandle) throws RemoteException {
            NativeLlcpConnectionlessSocket socket = null;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return ErrorCodes.ERROR_NOT_INITIALIZED;
            }

            /* find the socket in the hmap */
            socket = (NativeLlcpConnectionlessSocket) findSocket(nativeHandle);
            if (socket != null) {
                return socket.getSap();
            } else {
                return 0;
            }
        }

        public LlcpPacket receiveFrom(int nativeHandle) throws RemoteException {
            NativeLlcpConnectionlessSocket socket = null;
            LlcpPacket packet;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return null;
            }

            /* find the socket in the hmap */
            socket = (NativeLlcpConnectionlessSocket) findSocket(nativeHandle);
            if (socket != null) {
                packet = socket.doReceiveFrom(socket.getLinkMiu());
                if (packet != null) {
                    return packet;
                }
                return null;
            } else {
                return null;
            }
        }

        public int sendTo(int nativeHandle, LlcpPacket packet) throws RemoteException {
            NativeLlcpConnectionlessSocket socket = null;
            boolean isSuccess = false;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return ErrorCodes.ERROR_NOT_INITIALIZED;
            }

            /* find the socket in the hmap */
            socket = (NativeLlcpConnectionlessSocket) findSocket(nativeHandle);
            if (socket != null) {
                isSuccess = socket.doSendTo(packet.getRemoteSap(), packet.getDataBuffer());
                if (isSuccess) {
                    return ErrorCodes.SUCCESS;
                } else {
                    return ErrorCodes.ERROR_IO;
                }
            } else {
                return ErrorCodes.ERROR_IO;
            }
        }
    };

    private INfcTag mNfcTagService = new INfcTag.Stub() {

        public int close(int nativeHandle) throws RemoteException {
            NativeNfcTag tag = null;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return ErrorCodes.ERROR_NOT_INITIALIZED;
            }

            /* find the tag in the hmap */
            tag = (NativeNfcTag) findObject(nativeHandle);
            if (tag != null) {
                if (tag.doDisconnect()) {
                    /* Remove the device from the hmap */
                    RemoveObject(nativeHandle);
                    /* Restart polling loop for notification */
                    mManager.enableDiscovery(DISCOVERY_MODE_READER);
                    mOpenPending = false;
                    return ErrorCodes.SUCCESS;
                }

            }
            /* Restart polling loop for notification */
            mManager.enableDiscovery(DISCOVERY_MODE_READER);
            mOpenPending = false;
            return ErrorCodes.ERROR_DISCONNECT;
        }

        public int connect(int nativeHandle) throws RemoteException {
            NativeNfcTag tag = null;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return ErrorCodes.ERROR_NOT_INITIALIZED;
            }

            /* find the tag in the hmap */
            tag = (NativeNfcTag) findObject(nativeHandle);
            if (tag != null) {
                if (tag.doConnect())
                    return ErrorCodes.SUCCESS;
            }
            /* Restart polling loop for notification */
            mManager.enableDiscovery(DISCOVERY_MODE_READER);
            mOpenPending = false;
            return ErrorCodes.ERROR_CONNECT;
        }

        public String getType(int nativeHandle) throws RemoteException {
            NativeNfcTag tag = null;
            String type;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return null;
            }

            /* find the tag in the hmap */
            tag = (NativeNfcTag) findObject(nativeHandle);
            if (tag != null) {
                type = tag.getType();
                return type;
            }
            return null;
        }

        public byte[] getUid(int nativeHandle) throws RemoteException {
            NativeNfcTag tag = null;
            byte[] uid;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return null;
            }

            /* find the tag in the hmap */
            tag = (NativeNfcTag) findObject(nativeHandle);
            if (tag != null) {
                uid = tag.getUid();
                return uid;
            }
            return null;
        }

        public boolean isNdef(int nativeHandle) throws RemoteException {
            NativeNfcTag tag = null;
            boolean isSuccess = false;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return isSuccess;
            }

            /* find the tag in the hmap */
            tag = (NativeNfcTag) findObject(nativeHandle);
            if (tag != null) {
                isSuccess = tag.checkNDEF();
            }
            return isSuccess;
        }

        public byte[] transceive(int nativeHandle, byte[] data) throws RemoteException {
            NativeNfcTag tag = null;
            byte[] response;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return null;
            }

            /* find the tag in the hmap */
            tag = (NativeNfcTag) findObject(nativeHandle);
            if (tag != null) {
                response = tag.doTransceive(data);
                return response;
            }
            return null;
        }

        public NdefMessage read(int nativeHandle) throws RemoteException {
            NativeNfcTag tag;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return null;
            }

            /* find the tag in the hmap */
            tag = (NativeNfcTag) findObject(nativeHandle);
            if (tag != null) {
                byte[] buf = tag.doRead();
                if (buf == null)
                    return null;

                /* Create an NdefMessage */
                try {
                    return new NdefMessage(buf);
                } catch (NfcException e) {
                    return null;
                }
            }
            return null;
        }

        public boolean write(int nativeHandle, NdefMessage msg) throws RemoteException {
            NativeNfcTag tag;
            boolean isSuccess = false;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return isSuccess;
            }

            /* find the tag in the hmap */
            tag = (NativeNfcTag) findObject(nativeHandle);
            if (tag != null) {
                isSuccess = tag.doWrite(msg.toByteArray());
            }
            return isSuccess;

        }

    };

    private IP2pInitiator mP2pInitiatorService = new IP2pInitiator.Stub() {

        public byte[] getGeneralBytes(int nativeHandle) throws RemoteException {
            NativeP2pDevice device;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return null;
            }

            /* find the device in the hmap */
            device = (NativeP2pDevice) findObject(nativeHandle);
            if (device != null) {
                byte[] buff = device.getGeneralBytes();
                if (buff == null)
                    return null;
                return buff;
            }
            return null;
        }

        public int getMode(int nativeHandle) throws RemoteException {
            NativeP2pDevice device;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return ErrorCodes.ERROR_NOT_INITIALIZED;
            }

            /* find the device in the hmap */
            device = (NativeP2pDevice) findObject(nativeHandle);
            if (device != null) {
                return device.getMode();
            }
            return ErrorCodes.ERROR_INVALID_PARAM;
        }

        public byte[] receive(int nativeHandle) throws RemoteException {
            NativeP2pDevice device;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return null;
            }

            /* find the device in the hmap */
            device = (NativeP2pDevice) findObject(nativeHandle);
            if (device != null) {
                byte[] buff = device.doReceive();
                if (buff == null)
                    return null;
                return buff;
            }
            /* Restart polling loop for notification */
            mManager.enableDiscovery(DISCOVERY_MODE_READER);
            mOpenPending = false;
            return null;
        }

        public boolean send(int nativeHandle, byte[] data) throws RemoteException {
            NativeP2pDevice device;
            boolean isSuccess = false;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return isSuccess;
            }

            /* find the device in the hmap */
            device = (NativeP2pDevice) findObject(nativeHandle);
            if (device != null) {
                isSuccess = device.doSend(data);
            }
            return isSuccess;
        }
    };

    private IP2pTarget mP2pTargetService = new IP2pTarget.Stub() {

        public int connect(int nativeHandle) throws RemoteException {
            NativeP2pDevice device;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return ErrorCodes.ERROR_NOT_INITIALIZED;
            }

            /* find the device in the hmap */
            device = (NativeP2pDevice) findObject(nativeHandle);
            if (device != null) {
                if (device.doConnect()) {
                    return ErrorCodes.SUCCESS;
                }
            }
            return ErrorCodes.ERROR_CONNECT;
        }

        public boolean disconnect(int nativeHandle) throws RemoteException {
            NativeP2pDevice device;
            boolean isSuccess = false;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return isSuccess;
            }

            /* find the device in the hmap */
            device = (NativeP2pDevice) findObject(nativeHandle);
            if (device != null) {
                if (isSuccess = device.doDisconnect()) {
                    mOpenPending = false;
                    /* remove the device from the hmap */
                    RemoveObject(nativeHandle);
                    /* Restart polling loop for notification */
                    mManager.enableDiscovery(DISCOVERY_MODE_READER);
                }
            }
            return isSuccess;

        }

        public byte[] getGeneralBytes(int nativeHandle) throws RemoteException {
            NativeP2pDevice device;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return null;
            }

            /* find the device in the hmap */
            device = (NativeP2pDevice) findObject(nativeHandle);
            if (device != null) {
                byte[] buff = device.getGeneralBytes();
                if (buff == null)
                    return null;
                return buff;
            }
            return null;
        }

        public int getMode(int nativeHandle) throws RemoteException {
            NativeP2pDevice device;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return ErrorCodes.ERROR_NOT_INITIALIZED;
            }

            /* find the device in the hmap */
            device = (NativeP2pDevice) findObject(nativeHandle);
            if (device != null) {
                return device.getMode();
            }
            return ErrorCodes.ERROR_INVALID_PARAM;
        }

        public byte[] transceive(int nativeHandle, byte[] data) throws RemoteException {
            NativeP2pDevice device;

            // Check if NFC is enabled
            if (!mIsNfcEnabled) {
                return null;
            }

            /* find the device in the hmap */
            device = (NativeP2pDevice) findObject(nativeHandle);
            if (device != null) {
                byte[] buff = device.doTransceive(data);
                if (buff == null)
                    return null;
                return buff;
            }
            return null;
        }
    };

    private class NfcHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            try {

            } catch (Exception e) {
                // Log, don't crash!
                Log.e(TAG, "Exception in NfcHandler.handleMessage:", e);
            }
        }

    };

    public NfcService(Context context) {
        super();
        mContext = context;
        mManager = new NativeNfcManager(mContext);

        mContext.registerReceiver(mNfcServiceReceiver, new IntentFilter(
                NativeNfcManager.INTERNAL_LLCP_LINK_STATE_CHANGED_ACTION));

        mContext.registerReceiver(mNfcServiceReceiver, new IntentFilter(
                NfcManager.LLCP_LINK_STATE_CHANGED_ACTION));
        
        mContext.registerReceiver(mNfcServiceReceiver, new IntentFilter(
                NativeNfcManager.INTERNAL_TARGET_DESELECTED_ACTION));

        Thread thread = new Thread(null, this, "NfcService");
        thread.start();

        mManager.initializeNativeStructure();

            int nfcState = Settings.System.getInt(mContext.getContentResolver(),
                Settings.System.NFC_ON, 0);

            if (nfcState == NFC_STATE_ENABLED) {
                if (this._enable()) {
                }
            }

    }

    public void run() {
        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
        Looper.prepare();
        mNfcHandler = new NfcHandler();
        Looper.loop();
    }

    public void cancel() throws RemoteException {
        mContext.enforceCallingPermission(android.Manifest.permission.NFC_RAW,
                "NFC_RAW permission required to cancel NFC opening");
        if (mOpenPending) {
            mOpenPending = false;
            mManager.doCancel();
            /* Restart polling loop for notification */
            mManager.enableDiscovery(DISCOVERY_MODE_READER);
        }
    }

    public int createLlcpConnectionlessSocket(int sap) throws RemoteException {

        // Check if NFC is enabled
        if (!mIsNfcEnabled) {
            return ErrorCodes.ERROR_NOT_INITIALIZED;
        }

        mContext.enforceCallingPermission(android.Manifest.permission.NFC_LLCP,
                "NFC_LLCP permission required for LLCP operations with NFC service");

        /* Check SAP is not already used */

        /* Check nb socket created */
        if (mNbSocketCreated < LLCP_SOCKET_NB_MAX) {
            /* Store the socket handle */
            int sockeHandle = mGeneratedSocketHandle;

            if (mLlcpLinkState == NfcManager.LLCP_LINK_STATE_ACTIVATED) {
                NativeLlcpConnectionlessSocket socket;

                socket = mManager.doCreateLlcpConnectionlessSocket(sap);
                if (socket != null) {
                    /* Update the number of socket created */
                    mNbSocketCreated++;

                    /* Add the socket into the socket map */
                    mSocketMap.put(sockeHandle, socket);

                    return sockeHandle;
                } else {
                    /*
                     * socket creation error - update the socket handle
                     * generation
                     */
                    mGeneratedSocketHandle -= 1;

                    /* Get Error Status */
                    int errorStatus = mManager.doGetLastError();

                    switch (errorStatus) {
                        case ErrorCodes.ERROR_BUFFER_TO_SMALL:
                            return ErrorCodes.ERROR_BUFFER_TO_SMALL;
                        case ErrorCodes.ERROR_INSUFFICIENT_RESOURCES:
                            return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES;
                        default:
                            return ErrorCodes.ERROR_SOCKET_CREATION;
                    }
                }
            } else {
                /* Check SAP is not already used */
                if (!CheckSocketSap(sap)) {
                    return ErrorCodes.ERROR_SAP_USED;
                }

                NativeLlcpConnectionlessSocket socket = new NativeLlcpConnectionlessSocket(sap);

                /* Add the socket into the socket map */
                mSocketMap.put(sockeHandle, socket);

                /* Update the number of socket created */
                mNbSocketCreated++;

                /* Create new registered socket */
                RegisteredSocket registeredSocket = new RegisteredSocket(
                        LLCP_CONNECTIONLESS_SOCKET_TYPE, sockeHandle, sap);

                /* Put this socket into a list of registered socket */
                mRegisteredSocketList.add(registeredSocket);
            }

            /* update socket handle generation */
            mGeneratedSocketHandle++;

            return sockeHandle;

        } else {
            /* No socket available */
            return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES;
        }

    }

    public int createLlcpServiceSocket(int sap, String sn, int miu, int rw, int linearBufferLength)
            throws RemoteException {

        // Check if NFC is enabled
        if (!mIsNfcEnabled) {
            return ErrorCodes.ERROR_NOT_INITIALIZED;
        }

        mContext.enforceCallingPermission(android.Manifest.permission.NFC_LLCP,
                "NFC_LLCP permission required for LLCP operations with NFC service");

        if (mNbSocketCreated < LLCP_SOCKET_NB_MAX) {
            int sockeHandle = mGeneratedSocketHandle;

            if (mLlcpLinkState == NfcManager.LLCP_LINK_STATE_ACTIVATED) {
                NativeLlcpServiceSocket socket;

                socket = mManager.doCreateLlcpServiceSocket(sap, sn, miu, rw, linearBufferLength);
                if (socket != null) {
                    /* Update the number of socket created */
                    mNbSocketCreated++;
                    /* Add the socket into the socket map */
                    mSocketMap.put(sockeHandle, socket);
                } else {
                    /* socket creation error - update the socket handle counter */
                    mGeneratedSocketHandle -= 1;

                    /* Get Error Status */
                    int errorStatus = mManager.doGetLastError();

                    switch (errorStatus) {
                        case ErrorCodes.ERROR_BUFFER_TO_SMALL:
                            return ErrorCodes.ERROR_BUFFER_TO_SMALL;
                        case ErrorCodes.ERROR_INSUFFICIENT_RESOURCES:
                            return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES;
                        default:
                            return ErrorCodes.ERROR_SOCKET_CREATION;
                    }
                }
            } else {

                /* Check SAP is not already used */
                if (!CheckSocketSap(sap)) {
                    return ErrorCodes.ERROR_SAP_USED;
                }

                /* Service Name */
                if (!CheckSocketServiceName(sn)) {
                    return ErrorCodes.ERROR_SERVICE_NAME_USED;
                }

                /* Check socket options */
                if (!CheckSocketOptions(miu, rw, linearBufferLength)) {
                    return ErrorCodes.ERROR_SOCKET_OPTIONS;
                }

                NativeLlcpServiceSocket socket = new NativeLlcpServiceSocket(sn);

                /* Add the socket into the socket map */
                mSocketMap.put(sockeHandle, socket);

                /* Update the number of socket created */
                mNbSocketCreated++;

                /* Create new registered socket */
                RegisteredSocket registeredSocket = new RegisteredSocket(LLCP_SERVICE_SOCKET_TYPE,
                        sockeHandle, sap, sn, miu, rw, linearBufferLength);

                /* Put this socket into a list of registered socket */
                mRegisteredSocketList.add(registeredSocket);
            }

            /* update socket handle generation */
            mGeneratedSocketHandle += 1;

            Log.d(TAG, "Llcp Service Socket Handle =" + sockeHandle);
            return sockeHandle;
        } else {
            /* No socket available */
            return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES;
        }
    }

    public int createLlcpSocket(int sap, int miu, int rw, int linearBufferLength)
            throws RemoteException {

        // Check if NFC is enabled
        if (!mIsNfcEnabled) {
            return ErrorCodes.ERROR_NOT_INITIALIZED;
        }

        mContext.enforceCallingPermission(android.Manifest.permission.NFC_LLCP,
                "NFC_LLCP permission required for LLCP operations with NFC service");

        if (mNbSocketCreated < LLCP_SOCKET_NB_MAX) {

            int sockeHandle = mGeneratedSocketHandle;

            if (mLlcpLinkState == NfcManager.LLCP_LINK_STATE_ACTIVATED) {
                NativeLlcpSocket socket;

                socket = mManager.doCreateLlcpSocket(sap, miu, rw, linearBufferLength);

                if (socket != null) {
                    /* Update the number of socket created */
                    mNbSocketCreated++;
                    /* Add the socket into the socket map */
                    mSocketMap.put(sockeHandle, socket);
                } else {
                    /*
                     * socket creation error - update the socket handle
                     * generation
                     */
                    mGeneratedSocketHandle -= 1;

                    /* Get Error Status */
                    int errorStatus = mManager.doGetLastError();

                    switch (errorStatus) {
                        case ErrorCodes.ERROR_BUFFER_TO_SMALL:
                            return ErrorCodes.ERROR_BUFFER_TO_SMALL;
                        case ErrorCodes.ERROR_INSUFFICIENT_RESOURCES:
                            return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES;
                        default:
                            return ErrorCodes.ERROR_SOCKET_CREATION;
                    }
                }
            } else {

                /* Check SAP is not already used */
                if (!CheckSocketSap(sap)) {
                    return ErrorCodes.ERROR_SAP_USED;
                }

                /* Check Socket options */
                if (!CheckSocketOptions(miu, rw, linearBufferLength)) {
                    return ErrorCodes.ERROR_SOCKET_OPTIONS;
                }

                NativeLlcpSocket socket = new NativeLlcpSocket(sap, miu, rw);

                /* Add the socket into the socket map */
                mSocketMap.put(sockeHandle, socket);

                /* Update the number of socket created */
                mNbSocketCreated++;
                /* Create new registered socket */
                RegisteredSocket registeredSocket = new RegisteredSocket(LLCP_SOCKET_TYPE,
                        sockeHandle, sap, miu, rw, linearBufferLength);

                /* Put this socket into a list of registered socket */
                mRegisteredSocketList.add(registeredSocket);
            }

            /* update socket handle generation */
            mGeneratedSocketHandle++;

            return sockeHandle;
        } else {
            /* No socket available */
            return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES;
        }
    }

    public int deselectSecureElement() throws RemoteException {
        // Check if NFC is enabled
        if (!mIsNfcEnabled) {
            return ErrorCodes.ERROR_NOT_INITIALIZED;
        }

        if (mSelectedSeId == 0) {
            return ErrorCodes.ERROR_NO_SE_CONNECTED;
        }

        mContext.enforceCallingPermission(android.Manifest.permission.NFC_ADMIN,
                "NFC_ADMIN permission required to deselect NFC Secure Element");

            mManager.doDeselectSecureElement(mSelectedSeId);
        mNfcSecureElementState = 0;
            mSelectedSeId = 0;
        
        /* Store that a secure element is deselected */
        Settings.System.putInt(mContext.getContentResolver(),
                Settings.System.NFC_SECURE_ELEMENT_ON, 0);

        /* Reset Secure Element ID */
        Settings.System.putInt(mContext.getContentResolver(),
                Settings.System.NFC_SECURE_ELEMENT_ID, 0);
        

        return ErrorCodes.SUCCESS; 
    }

    public boolean disable() throws RemoteException {
        boolean isSuccess = false;
        mContext.enforceCallingPermission(android.Manifest.permission.NFC_ADMIN,
                "NFC_ADMIN permission required to disable NFC service");
        if (isEnabled()) {
            isSuccess = mManager.deinitialize();
            if (isSuccess) {
                mIsNfcEnabled = false;
            }
        }

        updateNfcOnSetting();

        return isSuccess;
    }

    public boolean enable() throws RemoteException {
        boolean isSuccess = false;
        mContext.enforceCallingPermission(android.Manifest.permission.NFC_ADMIN,
                "NFC_ADMIN permission required to enable NFC service");
        if (!isEnabled()) {
            reset();
            isSuccess = _enable();
        }
        return isSuccess;
    }

    private boolean _enable() {
        boolean isSuccess = mManager.initialize();
        if (isSuccess) {
            /* Check persistent properties */
            checkProperties();

            /* Check Secure Element setting */
            mNfcSecureElementState = Settings.System.getInt(mContext.getContentResolver(),
                    Settings.System.NFC_SECURE_ELEMENT_ON, 0);

            if (mNfcSecureElementState == 1) {

                int secureElementId = Settings.System.getInt(mContext.getContentResolver(),
                        Settings.System.NFC_SECURE_ELEMENT_ID, 0);
                int[] Se_list = mManager.doGetSecureElementList();
                if (Se_list != null) {
                    for (int i = 0; i < Se_list.length; i++) {
                        if (Se_list[i] == secureElementId) {
                            mManager.doSelectSecureElement(Se_list[i]);
                            mSelectedSeId = Se_list[i];
                            break;
                        }
                    }
                }
            }

            /* Start polling loop */
            mManager.enableDiscovery(DISCOVERY_MODE_READER);

            mIsNfcEnabled = true;
        } else {
            mIsNfcEnabled = false;
        }

        updateNfcOnSetting();

        return isSuccess;
    }

    private void updateNfcOnSetting() {
        int state;

        if (mIsNfcEnabled) {
            state = NFC_STATE_ENABLED;
        } else {
            state = NFC_STATE_DISABLED;
        }

        Settings.System.putInt(mContext.getContentResolver(), Settings.System.NFC_ON, state);
    }

    private void checkProperties() {
        int value;

        /* LLCP LTO */
        value = Settings.System.getInt(mContext.getContentResolver(), Settings.System.NFC_LLCP_LTO,
                LLCP_LTO_DEFAULT_VALUE);
        Settings.System.putInt(mContext.getContentResolver(), Settings.System.NFC_LLCP_LTO, value);
        mManager.doSetProperties(PROPERTY_LLCP_LTO, value);

        /* LLCP MIU */
        value = Settings.System.getInt(mContext.getContentResolver(), Settings.System.NFC_LLCP_MIU,
                LLCP_MIU_DEFAULT_VALUE);
        Settings.System.putInt(mContext.getContentResolver(), Settings.System.NFC_LLCP_MIU, value);
        mManager.doSetProperties(PROPERTY_LLCP_MIU, value);

        /* LLCP WKS */
        value = Settings.System.getInt(mContext.getContentResolver(), Settings.System.NFC_LLCP_WKS,
                LLCP_WKS_DEFAULT_VALUE);
        Settings.System.putInt(mContext.getContentResolver(), Settings.System.NFC_LLCP_WKS, value);
        mManager.doSetProperties(PROPERTY_LLCP_WKS, value);

        /* LLCP OPT */
        value = Settings.System.getInt(mContext.getContentResolver(), Settings.System.NFC_LLCP_OPT,
                LLCP_OPT_DEFAULT_VALUE);
        Settings.System.putInt(mContext.getContentResolver(), Settings.System.NFC_LLCP_OPT, value);
        mManager.doSetProperties(PROPERTY_LLCP_OPT, value);

        /* NFC READER A */
        value = Settings.System.getInt(mContext.getContentResolver(),
                Settings.System.NFC_DISCOVERY_A, 1);
        Settings.System.putInt(mContext.getContentResolver(), Settings.System.NFC_DISCOVERY_A,
                value);
        mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_A, value);

        /* NFC READER B */
        value = Settings.System.getInt(mContext.getContentResolver(),
                Settings.System.NFC_DISCOVERY_B, 1);
        Settings.System.putInt(mContext.getContentResolver(), Settings.System.NFC_DISCOVERY_B,
                value);
        mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_B, value);

        /* NFC READER F */
        value = Settings.System.getInt(mContext.getContentResolver(),
                Settings.System.NFC_DISCOVERY_F, 1);
        Settings.System.putInt(mContext.getContentResolver(), Settings.System.NFC_DISCOVERY_F,
                value);
        mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_F, value);

        /* NFC READER 15693 */
        value = Settings.System.getInt(mContext.getContentResolver(),
                Settings.System.NFC_DISCOVERY_15693, 1);
        Settings.System.putInt(mContext.getContentResolver(), Settings.System.NFC_DISCOVERY_15693,
                value);
        mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_15693, value);

        /* NFC NFCIP */
        value = Settings.System.getInt(mContext.getContentResolver(),
                Settings.System.NFC_DISCOVERY_NFCIP, 1);
        Settings.System.putInt(mContext.getContentResolver(), Settings.System.NFC_DISCOVERY_NFCIP,
                value);
        mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_NFCIP, value);
    }

    public ILlcpConnectionlessSocket getLlcpConnectionlessInterface() throws RemoteException {
        return mLlcpConnectionlessSocketService;
    }

    public ILlcpSocket getLlcpInterface() throws RemoteException {
        return mLlcpSocket;
    }

    public ILlcpServiceSocket getLlcpServiceInterface() throws RemoteException {
        return mLlcpServerSocketService;
    }

    public INfcTag getNfcTagInterface() throws RemoteException {
        return mNfcTagService;
    }

    public int getOpenTimeout() throws RemoteException {
        return mTimeout;
    }

    public IP2pInitiator getP2pInitiatorInterface() throws RemoteException {
        return mP2pInitiatorService;
    }

    public IP2pTarget getP2pTargetInterface() throws RemoteException {
        return mP2pTargetService;
    }

    public String getProperties(String param) throws RemoteException {
        int value;

        if (param == null) {
            return "Wrong parameter";
        }

        if (param.equals(PROPERTY_LLCP_LTO_VALUE)) {
            value = Settings.System.getInt(mContext.getContentResolver(),
                    Settings.System.NFC_LLCP_LTO, 0);
        } else if (param.equals(PROPERTY_LLCP_MIU_VALUE)) {
            value = Settings.System.getInt(mContext.getContentResolver(),
                    Settings.System.NFC_LLCP_MIU, 0);
        } else if (param.equals(PROPERTY_LLCP_WKS_VALUE)) {
            value = Settings.System.getInt(mContext.getContentResolver(),
                    Settings.System.NFC_LLCP_WKS, 0);
        } else if (param.equals(PROPERTY_LLCP_OPT_VALUE)) {
            value = Settings.System.getInt(mContext.getContentResolver(),
                    Settings.System.NFC_LLCP_OPT, 0);
        } else if (param.equals(PROPERTY_NFC_DISCOVERY_A_VALUE)) {
            value = Settings.System.getInt(mContext.getContentResolver(),
                    Settings.System.NFC_DISCOVERY_A, 0);
        } else if (param.equals(PROPERTY_NFC_DISCOVERY_B_VALUE)) {
            value = Settings.System.getInt(mContext.getContentResolver(),
                    Settings.System.NFC_DISCOVERY_B, 0);
        } else if (param.equals(PROPERTY_NFC_DISCOVERY_F_VALUE)) {
            value = Settings.System.getInt(mContext.getContentResolver(),
                    Settings.System.NFC_DISCOVERY_F, 0);
        } else if (param.equals(PROPERTY_NFC_DISCOVERY_NFCIP_VALUE)) {
            value = Settings.System.getInt(mContext.getContentResolver(),
                    Settings.System.NFC_DISCOVERY_NFCIP, 0);
        } else if (param.equals(PROPERTY_NFC_DISCOVERY_15693_VALUE)) {
            value = Settings.System.getInt(mContext.getContentResolver(),
                    Settings.System.NFC_DISCOVERY_15693, 0);
        } else {
            return "Unknown property";
        }

        if (param.equals(PROPERTY_NFC_DISCOVERY_A_VALUE)
                || param.equals(PROPERTY_NFC_DISCOVERY_B_VALUE)
                || param.equals(PROPERTY_NFC_DISCOVERY_F_VALUE)
                || param.equals(PROPERTY_NFC_DISCOVERY_NFCIP_VALUE)
                || param.equals(PROPERTY_NFC_DISCOVERY_15693_VALUE)) {
            if (value == 0) {
                return "false";
            } else if (value == 1) {
                return "true";
            } else {
                return "Unknown Value";
            }
        }else{
            return "" + value;
        }

    }

    public int[] getSecureElementList() throws RemoteException {
        int[] list = null;
        if (mIsNfcEnabled == true) {
            list = mManager.doGetSecureElementList();
        }
        return list;
    }

    public int getSelectedSecureElement() throws RemoteException {
        return mSelectedSeId;
    }

    public boolean isEnabled() throws RemoteException {
        return mIsNfcEnabled;
    }

    public int openP2pConnection() throws RemoteException {
        // Check if NFC is enabled
        if (!mIsNfcEnabled) {
            return ErrorCodes.ERROR_NOT_INITIALIZED;
        }

        mContext.enforceCallingPermission(android.Manifest.permission.NFC_RAW,
                "NFC_RAW permission required to open NFC P2P connection");
        if (!mOpenPending) {
            NativeP2pDevice device;
            mOpenPending = true;
            device = mManager.doOpenP2pConnection(mTimeout);
            if (device != null) {
                /* add device to the Hmap */
                mObjectMap.put(device.getHandle(), device);
                return device.getHandle();
            } else {
                mOpenPending = false;
                /* Restart polling loop for notification */
                mManager.enableDiscovery(DISCOVERY_MODE_READER);
                return ErrorCodes.ERROR_IO;
            }
        } else {
            return ErrorCodes.ERROR_BUSY;
        }

    }

    public int openTagConnection() throws RemoteException {
        NativeNfcTag tag;
        // Check if NFC is enabled
        if (!mIsNfcEnabled) {
            return ErrorCodes.ERROR_NOT_INITIALIZED;
        }

        mContext.enforceCallingPermission(android.Manifest.permission.NFC_RAW,
                "NFC_RAW permission required to open NFC Tag connection");
        if (!mOpenPending) {
            mOpenPending = true;
            tag = mManager.doOpenTagConnection(mTimeout);
            if (tag != null) {
                mObjectMap.put(tag.getHandle(), tag);
                return tag.getHandle();
            } else {
                mOpenPending = false;
                /* Restart polling loop for notification */
                mManager.enableDiscovery(DISCOVERY_MODE_READER);
                return ErrorCodes.ERROR_IO;
            }
        } else {
            return ErrorCodes.ERROR_BUSY;
        }
    }

    public int selectSecureElement(int seId) throws RemoteException {
        // Check if NFC is enabled
        if (!mIsNfcEnabled) {
            return ErrorCodes.ERROR_NOT_INITIALIZED;
        }
        
        if (mSelectedSeId == seId) {
            return ErrorCodes.ERROR_SE_ALREADY_SELECTED;
        }

        if (mSelectedSeId != 0) {
            return ErrorCodes.ERROR_SE_CONNECTED;
        }

        mContext.enforceCallingPermission(android.Manifest.permission.NFC_ADMIN,
                "NFC_ADMIN permission required to select NFC Secure Element");

            mSelectedSeId = seId;
            mManager.doSelectSecureElement(mSelectedSeId);

        /* Store that a secure element is selected */
        Settings.System.putInt(mContext.getContentResolver(),
                Settings.System.NFC_SECURE_ELEMENT_ON, 1);

        /* Store the ID of the Secure Element Selected */
        Settings.System.putInt(mContext.getContentResolver(),
                Settings.System.NFC_SECURE_ELEMENT_ID, mSelectedSeId);
        
        mNfcSecureElementState = 1;

        return ErrorCodes.SUCCESS;

    }

    public void setOpenTimeout(int timeout) throws RemoteException {
        mContext.enforceCallingPermission(android.Manifest.permission.NFC_RAW,
                "NFC_RAW permission required to set NFC connection timeout");
        mTimeout = timeout;
    }

    public int setProperties(String param, String value) throws RemoteException {
        mContext.enforceCallingPermission(android.Manifest.permission.NFC_ADMIN,
                "NFC_ADMIN permission required to set NFC Properties");

        if (isEnabled()) {
            return ErrorCodes.ERROR_NFC_ON;
        }

        int val;

        /* Check params validity */
        if (param == null || value == null) {
            return ErrorCodes.ERROR_INVALID_PARAM;
        }

        if (param.equals(PROPERTY_LLCP_LTO_VALUE)) {
            val = Integer.parseInt(value);

            /* Check params */
            if (val > LLCP_LTO_MAX_VALUE)
                return ErrorCodes.ERROR_INVALID_PARAM;

            /* Store value */
            Settings.System
                    .putInt(mContext.getContentResolver(), Settings.System.NFC_LLCP_LTO, val);

            /* Update JNI */
            mManager.doSetProperties(PROPERTY_LLCP_LTO, val);

        } else if (param.equals(PROPERTY_LLCP_MIU_VALUE)) {
            val = Integer.parseInt(value);

            /* Check params */
            if ((val < LLCP_MIU_DEFAULT_VALUE) || (val > LLCP_MIU_MAX_VALUE))
                return ErrorCodes.ERROR_INVALID_PARAM;

            /* Store value */
            Settings.System
                    .putInt(mContext.getContentResolver(), Settings.System.NFC_LLCP_MIU, val);

            /* Update JNI */
            mManager.doSetProperties(PROPERTY_LLCP_MIU, val);

        } else if (param.equals(PROPERTY_LLCP_WKS_VALUE)) {
            val = Integer.parseInt(value);

            /* Check params */
            if (val > LLCP_WKS_MAX_VALUE)
                return ErrorCodes.ERROR_INVALID_PARAM;

            /* Store value */
            Settings.System
                    .putInt(mContext.getContentResolver(), Settings.System.NFC_LLCP_WKS, val);

            /* Update JNI */
            mManager.doSetProperties(PROPERTY_LLCP_WKS, val);

        } else if (param.equals(PROPERTY_LLCP_OPT_VALUE)) {
            val = Integer.parseInt(value);

            /* Check params */
            if (val > LLCP_OPT_MAX_VALUE)
                return ErrorCodes.ERROR_INVALID_PARAM;

            /* Store value */
            Settings.System
                    .putInt(mContext.getContentResolver(), Settings.System.NFC_LLCP_OPT, val);

            /* Update JNI */
            mManager.doSetProperties(PROPERTY_LLCP_OPT, val);

        } else if (param.equals(PROPERTY_NFC_DISCOVERY_A_VALUE)) {

            /* Check params */
            if (value.equals("true")) {
                val = 1;
            } else if (value.equals("false")) {
                val = 0;
            } else {
                return ErrorCodes.ERROR_INVALID_PARAM;
            }
            /* Store value */
            Settings.System.putInt(mContext.getContentResolver(), Settings.System.NFC_DISCOVERY_A,
                    val);

            /* Update JNI */
            mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_A, val);

        } else if (param.equals(PROPERTY_NFC_DISCOVERY_B_VALUE)) {

            /* Check params */
            if (value.equals("true")) {
                val = 1;
            } else if (value.equals("false")) {
                val = 0;
            } else {
                return ErrorCodes.ERROR_INVALID_PARAM;
            }

            /* Store value */
            Settings.System.putInt(mContext.getContentResolver(), Settings.System.NFC_DISCOVERY_B,
                    val);

            /* Update JNI */
            mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_B, val);

        } else if (param.equals(PROPERTY_NFC_DISCOVERY_F_VALUE)) {

            /* Check params */
            if (value.equals("true")) {
                val = 1;
            } else if (value.equals("false")) {
                val = 0;
            } else {
                return ErrorCodes.ERROR_INVALID_PARAM;
            }

            /* Store value */
            Settings.System.putInt(mContext.getContentResolver(), Settings.System.NFC_DISCOVERY_F,
                    val);

            /* Update JNI */
            mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_F, val);

        } else if (param.equals(PROPERTY_NFC_DISCOVERY_15693_VALUE)) {

            /* Check params */
            if (value.equals("true")) {
                val = 1;
            } else if (value.equals("false")) {
                val = 0;
            } else {
                return ErrorCodes.ERROR_INVALID_PARAM;
            }

            /* Store value */
            Settings.System.putInt(mContext.getContentResolver(),
                    Settings.System.NFC_DISCOVERY_15693, val);

            /* Update JNI */
            mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_15693, val);

        } else if (param.equals(PROPERTY_NFC_DISCOVERY_NFCIP_VALUE)) {

            /* Check params */
            if (value.equals("true")) {
                val = 1;
            } else if (value.equals("false")) {
                val = 0;
            } else {
                return ErrorCodes.ERROR_INVALID_PARAM;
            }

            /* Store value */
            Settings.System.putInt(mContext.getContentResolver(),
                    Settings.System.NFC_DISCOVERY_NFCIP, val);

            /* Update JNI */
            mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_NFCIP, val);
        } else {
            return ErrorCodes.ERROR_INVALID_PARAM;
        }

        return ErrorCodes.SUCCESS;
    }

    // Reset all internals
    private void reset() {

        // Clear tables
        mObjectMap.clear();
        mSocketMap.clear();
        mRegisteredSocketList.clear();

        // Reset variables
        mLlcpLinkState = NfcManager.LLCP_LINK_STATE_DEACTIVATED;
        mNbSocketCreated = 0;
        mIsNfcEnabled = false;
        mSelectedSeId = 0;
        mTimeout = 0;
        mNfcState = NFC_STATE_DISABLED;
        mOpenPending = false;
    }

    private Object findObject(int key) {
        Object device = null;

        device = mObjectMap.get(key);

        return device;
    }

    private void RemoveObject(int key) {
        mObjectMap.remove(key);
    }

    private Object findSocket(int key) {
        Object socket = null;

        socket = mSocketMap.get(key);

        return socket;
    }

    private void RemoveSocket(int key) {
        mSocketMap.remove(key);
    }

    private boolean CheckSocketSap(int sap) {
        /* List of sockets registered */
        ListIterator<RegisteredSocket> it = mRegisteredSocketList.listIterator();

        while (it.hasNext()) {
            RegisteredSocket registeredSocket = it.next();

            if (sap == registeredSocket.mSap) {
                /* SAP already used */
                return false;
            }
        }
        return true;
    }

    private boolean CheckSocketOptions(int miu, int rw, int linearBufferlength) {

        if (rw > LLCP_RW_MAX_VALUE || miu < LLCP_MIU_DEFAULT_VALUE || linearBufferlength < miu) {
            return false;
        }
        return true;
    }

    private boolean CheckSocketServiceName(String sn) {

        /* List of sockets registered */
        ListIterator<RegisteredSocket> it = mRegisteredSocketList.listIterator();

        while (it.hasNext()) {
            RegisteredSocket registeredSocket = it.next();

            if (sn.equals(registeredSocket.mServiceName)) {
                /* Service Name already used */
                return false;
            }
        }
        return true;
    }

    private void RemoveRegisteredSocket(int nativeHandle) {
        /* check if sockets are registered */
        ListIterator<RegisteredSocket> it = mRegisteredSocketList.listIterator();

        while (it.hasNext()) {
            RegisteredSocket registeredSocket = it.next();
            if (registeredSocket.mHandle == nativeHandle) {
                /* remove the registered socket from the list */
                it.remove();
                Log.d(TAG, "socket removed");
            }
        }
    }

    /*
     * RegisteredSocket class to store the creation request of socket until the
     * LLCP link in not activated
     */
    private class RegisteredSocket {
        private int mType;

        private int mHandle;

        private int mSap;

        private int mMiu;

        private int mRw;

        private String mServiceName;

        private int mlinearBufferLength;

        RegisteredSocket(int type, int handle, int sap, String sn, int miu, int rw,
                int linearBufferLength) {
            mType = type;
            mHandle = handle;
            mSap = sap;
            mServiceName = sn;
            mRw = rw;
            mMiu = miu;
            mlinearBufferLength = linearBufferLength;
        }

        RegisteredSocket(int type, int handle, int sap, int miu, int rw, int linearBufferLength) {
            mType = type;
            mHandle = handle;
            mSap = sap;
            mRw = rw;
            mMiu = miu;
            mlinearBufferLength = linearBufferLength;
        }

        RegisteredSocket(int type, int handle, int sap) {
            mType = type;
            mHandle = handle;
            mSap = sap;
        }
    }

    private BroadcastReceiver mNfcServiceReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "Internal NFC Intent received");

            /* LLCP Link deactivation */
            if (intent.getAction().equals(NfcManager.LLCP_LINK_STATE_CHANGED_ACTION)) {
                mLlcpLinkState = intent.getIntExtra(NfcManager.LLCP_LINK_STATE_CHANGED_EXTRA,
                        NfcManager.LLCP_LINK_STATE_DEACTIVATED);

                if (mLlcpLinkState == NfcManager.LLCP_LINK_STATE_DEACTIVATED) {
                    /* restart polling loop */
                    mManager.enableDiscovery(DISCOVERY_MODE_READER);
                }

            }
            /* LLCP Link activation */
            else if (intent.getAction().equals(
                    NativeNfcManager.INTERNAL_LLCP_LINK_STATE_CHANGED_ACTION)) {

                mLlcpLinkState = intent.getIntExtra(
                        NativeNfcManager.INTERNAL_LLCP_LINK_STATE_CHANGED_EXTRA,
                        NfcManager.LLCP_LINK_STATE_DEACTIVATED);

                if (mLlcpLinkState == NfcManager.LLCP_LINK_STATE_ACTIVATED) {
                    /* check if sockets are registered */
                    ListIterator<RegisteredSocket> it = mRegisteredSocketList.listIterator();

                    Log.d(TAG, "Nb socket resgistered = " + mRegisteredSocketList.size());

                    while (it.hasNext()) {
                        RegisteredSocket registeredSocket = it.next();

                        switch (registeredSocket.mType) {
                            case LLCP_SERVICE_SOCKET_TYPE:
                                Log.d(TAG, "Registered Llcp Service Socket");
                                NativeLlcpServiceSocket serviceSocket;

                                serviceSocket = mManager.doCreateLlcpServiceSocket(
                                        registeredSocket.mSap, registeredSocket.mServiceName,
                                        registeredSocket.mMiu, registeredSocket.mRw,
                                        registeredSocket.mlinearBufferLength);

                                if (serviceSocket != null) {
                                    /* Add the socket into the socket map */
                                    mSocketMap.put(registeredSocket.mHandle, serviceSocket);
                                } else {
                                    /*
                                     * socket creation error - update the socket
                                     * handle counter
                                     */
                                    mGeneratedSocketHandle -= 1;
                                }
                                break;

                            case LLCP_SOCKET_TYPE:
                                Log.d(TAG, "Registered Llcp Socket");
                                NativeLlcpSocket clientSocket;
                                clientSocket = mManager.doCreateLlcpSocket(registeredSocket.mSap,
                                        registeredSocket.mMiu, registeredSocket.mRw,
                                        registeredSocket.mlinearBufferLength);
                                if (clientSocket != null) {
                                    /* Add the socket into the socket map */
                                    mSocketMap.put(registeredSocket.mHandle, clientSocket);
                                } else {
                                    /*
                                     * socket creation error - update the socket
                                     * handle counter
                                     */
                                    mGeneratedSocketHandle -= 1;
                                }
                                break;

                            case LLCP_CONNECTIONLESS_SOCKET_TYPE:
                                Log.d(TAG, "Registered Llcp Connectionless Socket");
                                NativeLlcpConnectionlessSocket connectionlessSocket;
                                connectionlessSocket = mManager
                                        .doCreateLlcpConnectionlessSocket(registeredSocket.mSap);
                                if (connectionlessSocket != null) {
                                    /* Add the socket into the socket map */
                                    mSocketMap.put(registeredSocket.mHandle, connectionlessSocket);
                                } else {
                                    /*
                                     * socket creation error - update the socket
                                     * handle counter
                                     */
                                    mGeneratedSocketHandle -= 1;
                                }
                                break;

                        }
                    }

                    /* Remove all registered socket from the list */
                    mRegisteredSocketList.clear();

                    /* Broadcast Intent Link LLCP activated */
                    Intent LlcpLinkIntent = new Intent();
                    LlcpLinkIntent.setAction(NfcManager.LLCP_LINK_STATE_CHANGED_ACTION);

                    LlcpLinkIntent.putExtra(NfcManager.LLCP_LINK_STATE_CHANGED_EXTRA,
                            NfcManager.LLCP_LINK_STATE_ACTIVATED);

                    Log.d(TAG, "Broadcasting LLCP activation");
                    mContext.sendOrderedBroadcast(LlcpLinkIntent,
                            android.Manifest.permission.NFC_LLCP);
                }
            }            
            /* Target Deactivated */
            else if (intent.getAction().equals(
                    NativeNfcManager.INTERNAL_TARGET_DESELECTED_ACTION)) {
                if(mOpenPending != false){
                    mOpenPending = false;
                }
                /* Restart polling loop for notification */
                mManager.enableDiscovery(DISCOVERY_MODE_READER);
                
            }
        }
    };
}