/
NfcManager.java
1259 lines (1141 loc) · 50 KB
/
NfcManager.java
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
package community.revteltech.nfc;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import androidx.annotation.Nullable;
import android.util.Log;
import android.provider.Settings;
import com.facebook.react.bridge.*;
import com.facebook.react.modules.core.RCTNativeAppEventEmitter;
import android.app.PendingIntent;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.TagLostException;
import android.nfc.tech.TagTechnology;
import android.nfc.tech.Ndef;
import android.nfc.tech.NfcA;
import android.nfc.tech.NfcB;
import android.nfc.tech.NfcF;
import android.nfc.tech.NfcV;
import android.nfc.tech.IsoDep;
import android.nfc.tech.NdefFormatable;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.MifareUltralight;
import android.os.Parcelable;
import android.os.Bundle;
import org.json.JSONObject;
import org.json.JSONException;
import java.util.*;
class NfcManager extends ReactContextBaseJavaModule implements ActivityEventListener, LifecycleEventListener {
private static final String LOG_TAG = "ReactNativeNfcManager";
private final List<IntentFilter> intentFilters = new ArrayList<IntentFilter>();
private final ArrayList<String[]> techLists = new ArrayList<String[]>();
private Context context;
private ReactApplicationContext reactContext;
private Boolean isForegroundEnabled = false;
private Boolean isResumed = false;
private WriteNdefRequest writeNdefRequest = null;
private TagTechnologyRequest techRequest = null;
private Tag tag = null;
// Use NFC reader mode instead of listening to a dispatch
private Boolean isReaderModeEnabled = false;
private int readerModeFlags = 0;
private int readerModeDelay = 0;
class WriteNdefRequest {
NdefMessage message;
Callback callback;
boolean format;
boolean formatReadOnly;
WriteNdefRequest(NdefMessage message, Callback callback, boolean format, boolean formatReadOnly) {
this.message = message;
this.callback = callback;
this.format = format;
this.formatReadOnly = formatReadOnly;
}
}
public NfcManager(ReactApplicationContext reactContext) {
super(reactContext);
context = reactContext;
this.reactContext = reactContext;
reactContext.addActivityEventListener(this);
reactContext.addLifecycleEventListener(this);
Log.d(LOG_TAG, "NfcManager created");
}
@Override
public String getName() {
return "NfcManager";
}
@Override
public Map<String, Object> getConstants() {
final Map<String, Object> constants = new HashMap<>();
constants.put("MIFARE_BLOCK_SIZE", MifareClassic.BLOCK_SIZE);
constants.put("MIFARE_ULTRALIGHT_PAGE_SIZE", MifareUltralight.PAGE_SIZE);
constants.put("MIFARE_ULTRALIGHT_TYPE", MifareUltralight.TYPE_ULTRALIGHT);
constants.put("MIFARE_ULTRALIGHT_TYPE_C", MifareUltralight.TYPE_ULTRALIGHT_C);
constants.put("MIFARE_ULTRALIGHT_TYPE_UNKNOWN", MifareUltralight.TYPE_UNKNOWN);
return constants;
}
private boolean hasPendingRequest() {
return writeNdefRequest != null || techRequest != null;
}
@ReactMethod
public void cancelTechnologyRequest(Callback callback) {
synchronized(this) {
if (techRequest != null) {
techRequest.close();
try {
techRequest.getPendingCallback().invoke("cancelled");
} catch (RuntimeException ex) {
// the pending callback might already been invoked when there is an ongoing
// connected tag, bypass this case explicitly
}
techRequest = null;
callback.invoke();
} else {
// explicitly allow this
callback.invoke();
}
}
}
@ReactMethod
public void requestTechnology(ReadableArray techs, Callback callback) {
synchronized(this) {
if (!isForegroundEnabled) {
callback.invoke("you should requestTagEvent first");
return;
}
if (hasPendingRequest()) {
callback.invoke("You can only issue one request at a time");
} else {
techRequest = new TagTechnologyRequest(techs.toArrayList(), callback);
}
}
}
@ReactMethod
public void closeTechnology(Callback callback) {
synchronized(this) {
if (techRequest != null) {
techRequest.close();
techRequest = null;
callback.invoke();
} else {
// explicitly allow this
callback.invoke();
}
}
}
@ReactMethod
public void getTag(Callback callback) {
synchronized(this) {
if (techRequest != null) {
try {
Tag tag = techRequest.getTagHandle();
WritableMap parsed = null;
if (Arrays.asList(tag.getTechList()).contains(Ndef.class.getName())) {
Ndef ndef = Ndef.get(tag);
parsed = ndef2React(ndef, new NdefMessage[] { ndef.getCachedNdefMessage() });
} else {
parsed = tag2React(tag);
}
callback.invoke(null, parsed);
} catch (Exception ex) {
Log.d(LOG_TAG, "getTag fail");
callback.invoke("getTag fail");
}
} else {
callback.invoke("no tech request available");
}
}
}
@ReactMethod
public void getCachedNdefMessage(Callback callback) {
synchronized(this) {
if (techRequest != null) {
try {
Ndef ndef = Ndef.get(techRequest.getTagHandle());
WritableMap parsed = ndef2React(ndef, new NdefMessage[] { ndef.getCachedNdefMessage() });
callback.invoke(null, parsed);
} catch (Exception ex) {
Log.d(LOG_TAG, "getCachedNdefMessage fail");
callback.invoke("getCachedNdefMessage fail");
}
} else {
callback.invoke("no tech request available");
}
}
}
@ReactMethod
public void getNdefMessage(Callback callback) {
synchronized(this) {
if (techRequest != null) {
try {
Ndef ndef = Ndef.get(techRequest.getTagHandle());
WritableMap parsed = ndef2React(null, new NdefMessage[] { ndef.getNdefMessage() });
callback.invoke(null, parsed);
} catch (Exception ex) {
Log.d(LOG_TAG, "getNdefMessage fail");
callback.invoke("getNdefMessage fail");
}
} else {
callback.invoke("no tech request available");
}
}
}
@ReactMethod
public void writeNdefMessage(ReadableArray rnArray, Callback callback) {
synchronized(this) {
if (techRequest != null) {
try {
Ndef ndef = (Ndef)techRequest.getTechHandle();
byte[] bytes = rnArrayToBytes(rnArray);
ndef.writeNdefMessage(new NdefMessage(bytes));
callback.invoke();
} catch (Exception ex) {
Log.d(LOG_TAG, "writeNdefMessage fail");
callback.invoke("writeNdefMessage fail");
}
} else {
callback.invoke("no tech request available");
}
}
}
private void mifareClassicAuthenticate(char type, int sector, ReadableArray key, Callback callback) {
if (techRequest != null) {
try {
MifareClassic mifareTag = (MifareClassic) techRequest.getTechHandle();
if (mifareTag == null || mifareTag.getType() == MifareClassic.TYPE_UNKNOWN) {
// Not a mifare card, fail
callback.invoke("mifareClassicAuthenticate fail: TYPE_UNKNOWN");
return;
} else if (sector >= mifareTag.getSectorCount()) {
// Check if in range
String msg = String.format("mifareClassicAuthenticate fail: invalid sector %d (max %d)", sector, mifareTag.getSectorCount());
callback.invoke(msg);
return;
} else if (key.size() != 6) {
// Invalid key length
String msg = String.format("mifareClassicAuthenticate fail: invalid key (needs length 6 but has %d characters)", key.size());
callback.invoke(msg);
return;
}
boolean result = false;
if (type == 'A') {
result = mifareTag.authenticateSectorWithKeyA(sector, rnArrayToBytes(key));
} else {
result = mifareTag.authenticateSectorWithKeyB(sector, rnArrayToBytes(key));
}
if (!result) {
callback.invoke("mifareClassicAuthenticate fail: AUTH_FAIL");
return;
}
callback.invoke(null, true);
} catch (TagLostException ex) {
callback.invoke("mifareClassicAuthenticate fail: TAG_LOST");
} catch (Exception ex) {
callback.invoke("mifareClassicAuthenticate fail: " + ex.toString());
}
} else {
callback.invoke("no tech request available");
}
}
@ReactMethod
public void mifareClassicAuthenticateA(int sector, ReadableArray key, Callback callback) {
synchronized(this) {
mifareClassicAuthenticate('A', sector, key, callback);
}
}
@ReactMethod
public void mifareClassicAuthenticateB(int sector, ReadableArray key, Callback callback) {
synchronized(this) {
mifareClassicAuthenticate('B', sector, key, callback);
}
}
@ReactMethod
public void mifareClassicGetBlockCountInSector(int sectorIndex, Callback callback) {
synchronized(this) {
if (techRequest != null) {
try {
MifareClassic mifareTag = (MifareClassic) techRequest.getTechHandle();
if (mifareTag == null || mifareTag.getType() == MifareClassic.TYPE_UNKNOWN) {
// Not a mifare card, fail
callback.invoke("mifareClassicGetBlockCountInSector fail: TYPE_UNKNOWN");
return;
} else if (sectorIndex >= mifareTag.getSectorCount()) {
// Check if in range
String msg = String.format("mifareClassicGetBlockCountInSector fail: invalid sector %d (max %d)", sectorIndex, mifareTag.getSectorCount());
callback.invoke(msg);
return;
}
callback.invoke(null, mifareTag.getBlockCountInSector(sectorIndex));
} catch (Exception ex) {
callback.invoke("mifareClassicGetBlockCountInSector fail: " + ex.toString());
}
} else {
callback.invoke("no tech request available");
}
}
}
@ReactMethod
public void mifareClassicGetSectorCount(Callback callback) {
synchronized(this) {
if (techRequest != null) {
try {
MifareClassic mifareTag = (MifareClassic) techRequest.getTechHandle();
if (mifareTag == null || mifareTag.getType() == MifareClassic.TYPE_UNKNOWN) {
// Not a mifare card, fail
callback.invoke("mifareClassicGetSectorCount fail: TYPE_UNKNOWN");
return;
}
callback.invoke(null, mifareTag.getSectorCount());
} catch (Exception ex) {
callback.invoke("mifareClassicGetSectorCount fail: " + ex.toString());
}
} else {
callback.invoke("no tech request available");
}
}
}
@ReactMethod
public void mifareClassicSectorToBlock(int sectorIndex, Callback callback) {
synchronized(this) {
if (techRequest != null) {
try {
MifareClassic mifareTag = (MifareClassic) techRequest.getTechHandle();
if (mifareTag == null || mifareTag.getType() == MifareClassic.TYPE_UNKNOWN) {
// Not a mifare card, fail
callback.invoke("mifareClassicSectorToBlock fail: TYPE_UNKNOWN");
return;
} else if (sectorIndex >= mifareTag.getSectorCount()) {
// Check if in range
String msg = String.format("mifareClassicSectorToBlock fail: invalid sector %d (max %d)", sectorIndex, mifareTag.getSectorCount());
callback.invoke(msg);
return;
}
callback.invoke(null, mifareTag.sectorToBlock(sectorIndex));
} catch (Exception ex) {
callback.invoke("mifareClassicSectorToBlock fail: " + ex.toString());
}
} else {
callback.invoke("no tech request available");
}
}
}
@ReactMethod
public void mifareClassicReadBlock(int blockIndex, Callback callback) {
synchronized(this) {
if (techRequest != null) {
try {
MifareClassic mifareTag = (MifareClassic) techRequest.getTechHandle();
if (mifareTag == null || mifareTag.getType() == MifareClassic.TYPE_UNKNOWN) {
// Not a mifare card, fail
callback.invoke("mifareClassicReadBlock fail: TYPE_UNKNOWN");
return;
} else if (blockIndex >= mifareTag.getBlockCount()) {
// Check if in range
String msg = String.format("mifareClassicReadBlock fail: invalid block %d (max %d)", blockIndex, mifareTag.getBlockCount());
callback.invoke(msg);
return;
}
byte[] buffer = new byte[MifareClassic.BLOCK_SIZE];
buffer = mifareTag.readBlock(blockIndex);
WritableArray result = bytesToRnArray(buffer);
callback.invoke(null, result);
} catch (TagLostException ex) {
callback.invoke("mifareClassicReadBlock fail: TAG_LOST");
} catch (Exception ex) {
callback.invoke("mifareClassicReadBlock fail: " + ex.toString());
}
} else {
callback.invoke("no tech request available");
}
}
}
@ReactMethod
public void mifareClassicReadSector(int sectorIndex, Callback callback) {
synchronized(this) {
if (techRequest != null) {
try {
MifareClassic mifareTag = (MifareClassic) techRequest.getTechHandle();
if (mifareTag == null || mifareTag.getType() == MifareClassic.TYPE_UNKNOWN) {
// Not a mifare card, fail
callback.invoke("mifareClassicReadSector fail: TYPE_UNKNOWN");
return;
} else if (sectorIndex >= mifareTag.getSectorCount()) {
// Check if in range
String msg = String.format("mifareClassicReadSector fail: invalid sector %d (max %d)", sectorIndex, mifareTag.getSectorCount());
callback.invoke(msg);
return;
}
WritableArray result = Arguments.createArray();
int blocks = mifareTag.getBlockCountInSector(sectorIndex);
byte[] buffer = new byte[MifareClassic.BLOCK_SIZE];
for (int i = 0; i < blocks; i++) {
buffer = mifareTag.readBlock(mifareTag.sectorToBlock(sectorIndex)+i);
appendBytesToRnArray(result, buffer);
}
callback.invoke(null, result);
} catch (TagLostException ex) {
callback.invoke("mifareClassicReadSector fail: TAG_LOST");
} catch (Exception ex) {
callback.invoke("mifareClassicReadSector fail: " + ex.toString());
}
} else {
callback.invoke("no tech request available");
}
}
}
@ReactMethod
public void mifareClassicWriteBlock(int blockIndex, ReadableArray block, Callback callback) {
synchronized(this) {
if (techRequest != null) {
try {
MifareClassic mifareTag = (MifareClassic) techRequest.getTechHandle();
if (mifareTag == null || mifareTag.getType() == MifareClassic.TYPE_UNKNOWN) {
// Not a mifare card, fail
callback.invoke("mifareClassicWriteBlock fail: TYPE_UNKNOWN");
return;
} else if (blockIndex >= mifareTag.getBlockCount()) {
// Check if in range
String msg = String.format("mifareClassicWriteBlock fail: invalid block %d (max %d)", blockIndex, mifareTag.getBlockCount());
callback.invoke(msg);
return;
} else if (block.size() != MifareClassic.BLOCK_SIZE) {
// Wrong block count
String msg = String.format("mifareClassicWriteBlock fail: invalid block size %d (should be %d)", block.size(), MifareClassic.BLOCK_SIZE);
callback.invoke(msg);
return;
}
byte[] buffer = rnArrayToBytes(block);
mifareTag.writeBlock(blockIndex, buffer);
callback.invoke(null, true);
} catch (TagLostException ex) {
callback.invoke("mifareClassicWriteBlock fail: TAG_LOST");
} catch (Exception ex) {
callback.invoke("mifareClassicWriteBlock fail: " + ex.toString());
}
} else {
callback.invoke("no tech request available");
}
}
}
@ReactMethod
public void mifareUltralightReadPages(int pageOffset, Callback callback) {
synchronized(this) {
if (techRequest != null) {
try {
MifareUltralight techHandle = (MifareUltralight)techRequest.getTechHandle();
byte[] resultBytes = techHandle.readPages(pageOffset);
WritableArray resultRnArray = bytesToRnArray(resultBytes);
callback.invoke(null, resultRnArray);
return;
} catch (TagLostException ex) {
callback.invoke("mifareUltralight fail: TAG_LOST");
} catch (Exception ex) {
callback.invoke("mifareUltralight fail: " + ex.toString());
}
} else {
callback.invoke("no tech request available");
}
}
}
@ReactMethod
public void mifareUltralightWritePage(int pageOffset, ReadableArray rnArray, Callback callback) {
synchronized(this) {
if (techRequest != null) {
try {
byte[] bytes = rnArrayToBytes(rnArray);
MifareUltralight techHandle = (MifareUltralight)techRequest.getTechHandle();
techHandle.writePage(pageOffset, bytes);
callback.invoke();
return;
} catch (TagLostException ex) {
callback.invoke("mifareUltralight fail: TAG_LOST");
} catch (Exception ex) {
callback.invoke("mifareUltralight fail: " + ex.toString());
}
} else {
callback.invoke("no tech request available");
}
}
}
@ReactMethod
public void makeReadOnly(Callback callback) {
synchronized(this) {
if (techRequest != null) {
try {
Ndef ndef = (Ndef)techRequest.getTechHandle();
boolean result = ndef.makeReadOnly();
callback.invoke(null, result);
} catch (Exception ex) {
Log.d(LOG_TAG, "makeReadOnly fail");
callback.invoke("makeReadOnly fail");
}
} else {
callback.invoke("no tech request available");
}
}
}
@ReactMethod
public void setTimeout(int timeout, Callback callback) {
synchronized (this) {
if (techRequest != null) {
try {
String tech = techRequest.getTechType();
TagTechnology baseTechHandle = techRequest.getTechHandle();
// TagTechnology is the base class for each tech (ex, NfcA, NfcB, IsoDep ...)
// but it doesn't provide transceive in its interface, so we need to explicitly cast it
if (tech.equals("NfcA")) {
NfcA techHandle = (NfcA) baseTechHandle;
techHandle.setTimeout(timeout);
callback.invoke();
return;
} else if (tech.equals("NfcF")) {
NfcF techHandle = (NfcF) baseTechHandle;
techHandle.setTimeout(timeout);
callback.invoke();
return;
} else if (tech.equals("IsoDep")) {
IsoDep techHandle = (IsoDep) baseTechHandle;
techHandle.setTimeout(timeout);
callback.invoke();
return;
} else if (tech.equals("MifareClassic")) {
MifareClassic techHandle = (MifareClassic) baseTechHandle;
techHandle.setTimeout(timeout);
callback.invoke();
return;
} else if (tech.equals("MifareUltralight")) {
MifareUltralight techHandle = (MifareUltralight) baseTechHandle;
techHandle.setTimeout(timeout);
callback.invoke();
return;
}
Log.d(LOG_TAG, "setTimeout not supported");
} catch (Exception ex) {
Log.d(LOG_TAG, "setTimeout fail");
}
callback.invoke("setTimeout fail");
} else {
callback.invoke("no tech request available");
}
}
}
@ReactMethod
public void connect(ReadableArray techs, Callback callback){
synchronized(this) {
try {
techRequest = new TagTechnologyRequest(techs.toArrayList(), callback);
techRequest.connect(this.tag);
callback.invoke(null, null);
return;
} catch (Exception ex) {
callback.invoke(ex.toString());
}
}
}
@ReactMethod
public void close(Callback callback){
synchronized(this) {
try {
techRequest.close();
callback.invoke(null, null);
return;
} catch (Exception ex) {
callback.invoke(ex.toString());
}
}
}
@ReactMethod
public void transceive(ReadableArray rnArray, Callback callback) {
synchronized(this) {
if (techRequest != null) {
try {
String tech = techRequest.getTechType();
byte[] bytes = rnArrayToBytes(rnArray);
TagTechnology baseTechHandle = techRequest.getTechHandle();
// TagTechnology is the base class for each tech (ex, NfcA, NfcB, IsoDep ...)
// but it doesn't provide transceive in its interface, so we need to explicitly cast it
if (tech.equals("NfcA")) {
NfcA techHandle = (NfcA)baseTechHandle;
byte[] resultBytes = techHandle.transceive(bytes);
WritableArray resultRnArray = bytesToRnArray(resultBytes);
callback.invoke(null, resultRnArray);
return;
} else if (tech.equals("NfcB")) {
NfcB techHandle = (NfcB)baseTechHandle;
byte[] resultBytes = techHandle.transceive(bytes);
WritableArray resultRnArray = bytesToRnArray(resultBytes);
callback.invoke(null, resultRnArray);
return;
} else if (tech.equals("NfcF")) {
NfcF techHandle = (NfcF)baseTechHandle;
byte[] resultBytes = techHandle.transceive(bytes);
WritableArray resultRnArray = bytesToRnArray(resultBytes);
callback.invoke(null, resultRnArray);
return;
} else if (tech.equals("NfcV")) {
NfcV techHandle = (NfcV)baseTechHandle;
byte[] resultBytes = techHandle.transceive(bytes);
WritableArray resultRnArray = bytesToRnArray(resultBytes);
callback.invoke(null, resultRnArray);
return;
} else if (tech.equals("IsoDep")) {
IsoDep techHandle = (IsoDep)baseTechHandle;
byte[] resultBytes = techHandle.transceive(bytes);
WritableArray resultRnArray = bytesToRnArray(resultBytes);
callback.invoke(null, resultRnArray);
return;
} else if (tech.equals("MifareClassic")) {
MifareClassic techHandle = (MifareClassic) baseTechHandle;
byte[] resultBytes = techHandle.transceive(bytes);
WritableArray resultRnArray = bytesToRnArray(resultBytes);
callback.invoke(null, resultRnArray);
return;
} else if (tech.equals("MifareUltralight")) {
MifareUltralight techHandle = (MifareUltralight)baseTechHandle;
byte[] resultBytes = techHandle.transceive(bytes);
WritableArray resultRnArray = bytesToRnArray(resultBytes);
callback.invoke(null, resultRnArray);
return;
}
Log.d(LOG_TAG, "transceive not supported");
} catch (Exception ex) {
Log.d(LOG_TAG, "transceive fail");
}
callback.invoke("transceive fail");
} else {
callback.invoke("no tech request available");
}
}
}
@ReactMethod
public void getMaxTransceiveLength(Callback callback) {
synchronized(this) {
if (techRequest != null) {
try {
String tech = techRequest.getTechType();
TagTechnology baseTechHandle = techRequest.getTechHandle();
// TagTechnology is the base class for each tech (ex, NfcA, NfcB, IsoDep ...)
// but it doesn't provide transceive in its interface, so we need to explicitly cast it
if (tech.equals("NfcA")) {
NfcA techHandle = (NfcA)baseTechHandle;
int max = techHandle.getMaxTransceiveLength();
callback.invoke(null, max);
return;
} else if (tech.equals("NfcB")) {
NfcB techHandle = (NfcB)baseTechHandle;
int max = techHandle.getMaxTransceiveLength();
callback.invoke(null, max);
return;
} else if (tech.equals("NfcF")) {
NfcF techHandle = (NfcF)baseTechHandle;
int max = techHandle.getMaxTransceiveLength();
callback.invoke(null, max);
return;
} else if (tech.equals("NfcV")) {
NfcV techHandle = (NfcV)baseTechHandle;
int max = techHandle.getMaxTransceiveLength();
callback.invoke(null, max);
return;
} else if (tech.equals("IsoDep")) {
IsoDep techHandle = (IsoDep)baseTechHandle;
int max = techHandle.getMaxTransceiveLength();
callback.invoke(null, max);
return;
} else if (tech.equals("MifareUltralight")) {
MifareUltralight techHandle = (MifareUltralight)baseTechHandle;
int max = techHandle.getMaxTransceiveLength();
callback.invoke(null, max);
return;
}
Log.d(LOG_TAG, "getMaxTransceiveLength not supported");
} catch (Exception ex) {
Log.d(LOG_TAG, "getMaxTransceiveLength fail");
}
callback.invoke("getMaxTransceiveLength fail");
} else {
callback.invoke("no tech request available");
}
}
}
@ReactMethod
public void cancelNdefWrite(Callback callback) {
synchronized(this) {
if (writeNdefRequest != null) {
writeNdefRequest.callback.invoke("cancelled");
writeNdefRequest = null;
callback.invoke();
} else {
callback.invoke("no writing request available");
}
}
}
@ReactMethod
public void requestNdefWrite(ReadableArray rnArray, ReadableMap options, Callback callback) {
synchronized(this) {
if (!isForegroundEnabled) {
callback.invoke("you should requestTagEvent first");
return;
}
if (hasPendingRequest()) {
callback.invoke("You can only issue one request at a time");
} else {
boolean format = options.getBoolean("format");
boolean formatReadOnly = options.getBoolean("formatReadOnly");
try {
NdefMessage msgToWrite;
/// the only case we allow ndef message to be null is when formatting, see:
/// https://developer.android.com/reference/android/nfc/tech/NdefFormatable.html#format(android.nfc.NdefMessage)
/// this API allows the `firstMessage` to be null
if (format && rnArray == null) {
msgToWrite = null;
} else {
byte[] bytes = rnArrayToBytes(rnArray);
msgToWrite = new NdefMessage(bytes);
}
writeNdefRequest = new WriteNdefRequest(
msgToWrite,
callback, // defer the callback
format,
formatReadOnly
);
} catch (FormatException e) {
callback.invoke("Incorrect ndef format");
}
}
}
}
@ReactMethod
public void setNdefPushMessage(ReadableArray rnArray, Callback callback) {
synchronized(this) {
if (techRequest == null && writeNdefRequest == null) {
try {
Activity currentActivity = getCurrentActivity();
if (currentActivity == null) {
throw new RuntimeException("cannot get current activity");
}
NdefMessage msgToPush = null;
if (rnArray != null) {
msgToPush = new NdefMessage(rnArrayToBytes(rnArray));
}
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context);
nfcAdapter.setNdefPushMessage(msgToPush, currentActivity);
callback.invoke();
} catch (Exception ex) {
Log.d(LOG_TAG, "sendNdefPushMessage fail, " + ex.getMessage());
callback.invoke("sendNdefPushMessage fail");
}
} else {
callback.invoke("please first cancel existing tech or write request");
}
}
}
@ReactMethod
public void start(Callback callback) {
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context);
if (nfcAdapter != null) {
Log.d(LOG_TAG, "start");
IntentFilter filter = new IntentFilter(NfcAdapter.ACTION_ADAPTER_STATE_CHANGED);
Activity currentActivity = getCurrentActivity();
if (currentActivity == null) {
callback.invoke("fail to get current activity");
return;
}
currentActivity.registerReceiver(mReceiver, filter);
callback.invoke();
} else {
Log.d(LOG_TAG, "not support in this device");
callback.invoke("no nfc support");
}
}
@ReactMethod
public void isSupported(String tech, Callback callback){
Log.d(LOG_TAG, "isSupported");
Activity currentActivity = getCurrentActivity();
if (currentActivity == null) {
callback.invoke("fail to get current activity");
return;
}
if (!currentActivity.getPackageManager().hasSystemFeature(PackageManager.FEATURE_NFC)) {
callback.invoke(null, false);
return;
}
// If we ask for MifareClassic support, so some extra checks, since not all chips and devices are
// compatible with MifareClassic
// TODO: Check if it's the same case with MifareUltralight
if (tech.equals("MifareClassic")) {
if (!MifareUtil.isDeviceSupported(currentActivity)) {
callback.invoke(null, false);
return;
}
}
callback.invoke(null, true);
}
@ReactMethod
public void isEnabled(Callback callback) {
Log.d(LOG_TAG, "isEnabled");
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context);
if (nfcAdapter != null) {
callback.invoke(null, nfcAdapter.isEnabled());
} else {
callback.invoke(null, false);
}
}
@ReactMethod
public void goToNfcSetting(Callback callback) {
Log.d(LOG_TAG, "goToNfcSetting");
Activity currentActivity = getCurrentActivity();
if (currentActivity == null) {
callback.invoke("fail to get current activity");
return;
}
currentActivity.startActivity(new Intent(Settings.ACTION_NFC_SETTINGS));
callback.invoke();
}
@ReactMethod
public void getLaunchTagEvent(Callback callback) {
Activity currentActivity = getCurrentActivity();
if (currentActivity == null) {
callback.invoke("fail to get current activity");
return;
}
Intent launchIntent = currentActivity.getIntent();
WritableMap nfcTag = parseNfcIntent(launchIntent);
callback.invoke(null, nfcTag);
}
@ReactMethod
private void registerTagEvent(ReadableMap options, Callback callback) {
this.isReaderModeEnabled = options.getBoolean("isReaderModeEnabled");
this.readerModeFlags = options.getInt("readerModeFlags");
this.readerModeDelay = options.getInt("readerModeDelay");
Log.d(LOG_TAG, "registerTag");
isForegroundEnabled = true;
// capture all mime-based dispatch NDEF
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
ndef.addDataType("*/*");
} catch (MalformedMimeTypeException e) {
throw new RuntimeException("fail", e);
}
intentFilters.add(ndef);
// capture all rest NDEF, such as uri-based
intentFilters.add(new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED));
techLists.add(new String[]{Ndef.class.getName()});
// for those without NDEF, get them as tags
intentFilters.add(new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED));
if (isResumed) {
enableDisableForegroundDispatch(true);
}
callback.invoke();
}
@ReactMethod
private void unregisterTagEvent(Callback callback) {
Log.d(LOG_TAG, "registerTag");
isForegroundEnabled = false;
intentFilters.clear();
if (isResumed) {
enableDisableForegroundDispatch(false);
}
callback.invoke();
}
@ReactMethod
private void hasTagEventRegistration(Callback callback) {
Log.d(LOG_TAG, "isSessionAvailable");
callback.invoke(null, isForegroundEnabled);
}
@Override
public void onHostResume() {
Log.d(LOG_TAG, "onResume");
isResumed = true;
if (isForegroundEnabled) {
enableDisableForegroundDispatch(true);
}
}
@Override
public void onHostPause() {
Log.d(LOG_TAG, "onPause");
isResumed = false;
enableDisableForegroundDispatch(false);
}
@Override
public void onHostDestroy() {
Log.d(LOG_TAG, "onDestroy");
}
private void enableDisableForegroundDispatch(boolean enable) {
Log.i(LOG_TAG, "enableForegroundDispatch, enable = " + enable);
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context);
Activity currentActivity = getCurrentActivity();
final NfcManager manager = this;
if (nfcAdapter != null && currentActivity != null && !currentActivity.isFinishing()) {
try {
if (isReaderModeEnabled) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
throw new RuntimeException("minSdkVersion must be Honeycomb (19) or later.");
}
if (enable) {
Log.i(LOG_TAG, "enableReaderMode");
Bundle readerModeExtras = new Bundle();
readerModeExtras.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, readerModeDelay * 1000);
nfcAdapter.enableReaderMode(currentActivity, new NfcAdapter.ReaderCallback() {
@Override
public void onTagDiscovered(Tag tag) {
manager.tag = tag;
Log.d(LOG_TAG, "readerMode onTagDiscovered");
WritableMap nfcTag = null;
// if the tag contains NDEF, we want to report the content
if (Arrays.asList(tag.getTechList()).contains(Ndef.class.getName())) {
Ndef ndef = Ndef.get(tag);
nfcTag = ndef2React(ndef, new NdefMessage[] { ndef.getCachedNdefMessage() });
} else {
nfcTag = tag2React(tag);
}
if (nfcTag != null) {
sendEvent("NfcManagerDiscoverTag", nfcTag);
}
}
}, readerModeFlags, readerModeExtras);
} else {
Log.i(LOG_TAG, "disableReaderMode");
nfcAdapter.disableReaderMode(currentActivity);
}
} else {
if (enable) {
nfcAdapter.enableForegroundDispatch(currentActivity, getPendingIntent(), getIntentFilters(), getTechLists());
} else {
nfcAdapter.disableForegroundDispatch(currentActivity);