-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathMFRC522Extended.cpp
1160 lines (1007 loc) · 34 KB
/
MFRC522Extended.cpp
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
/*
* Library extends MFRC522.h to support RATS for ISO-14443-4 PICC.
* RATS - Request for Answer To Select.
* NOTE: Please also check the comments in MFRC522Extended.h
* @author JPG-Consulting
*/
#include "MFRC522Extended.h"
/////////////////////////////////////////////////////////////////////////////////////
// Functions for communicating with PICCs
/////////////////////////////////////////////////////////////////////////////////////
/**
* Transmits SELECT/ANTICOLLISION commands to select a single PICC.
* Before calling this function the PICCs must be placed in the READY(*) state by calling PICC_RequestA() or PICC_WakeupA().
* On success:
* - The chosen PICC is in state ACTIVE(*) and all other PICCs have returned to state IDLE/HALT. (Figure 7 of the ISO/IEC 14443-3 draft.)
* - The UID size and value of the chosen PICC is returned in *uid along with the SAK.
*
* A PICC UID consists of 4, 7 or 10 bytes.
* Only 4 bytes can be specified in a SELECT command, so for the longer UIDs two or three iterations are used:
* UID size Number of UID bytes Cascade levels Example of PICC
* ======== =================== ============== ===============
* single 4 1 MIFARE Classic
* double 7 2 MIFARE Ultralight
* triple 10 3 Not currently in use?
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522::StatusCode MFRC522Extended::PICC_Select( Uid *uid, ///< Pointer to Uid struct. Normally output, but can also be used to supply a known UID.
byte validBits ///< The number of known UID bits supplied in *uid. Normally 0. If set you must also supply uid->size.
) {
bool uidComplete;
bool selectDone;
bool useCascadeTag;
byte cascadeLevel = 1;
MFRC522::StatusCode result;
byte count;
byte index;
byte uidIndex; // The first index in uid->uidByte[] that is used in the current Cascade Level.
int8_t currentLevelKnownBits; // The number of known UID bits in the current Cascade Level.
byte buffer[9]; // The SELECT/ANTICOLLISION commands uses a 7 byte standard frame + 2 bytes CRC_A
byte bufferUsed; // The number of bytes used in the buffer, ie the number of bytes to transfer to the FIFO.
byte rxAlign; // Used in BitFramingReg. Defines the bit position for the first bit received.
byte txLastBits; // Used in BitFramingReg. The number of valid bits in the last transmitted byte.
byte *responseBuffer;
byte responseLength;
// Description of buffer structure:
// Byte 0: SEL Indicates the Cascade Level: PICC_CMD_SEL_CL1, PICC_CMD_SEL_CL2 or PICC_CMD_SEL_CL3
// Byte 1: NVB Number of Valid Bits (in complete command, not just the UID): High nibble: complete bytes, Low nibble: Extra bits.
// Byte 2: UID-data or CT See explanation below. CT means Cascade Tag.
// Byte 3: UID-data
// Byte 4: UID-data
// Byte 5: UID-data
// Byte 6: BCC Block Check Character - XOR of bytes 2-5
// Byte 7: CRC_A
// Byte 8: CRC_A
// The BCC and CRC_A are only transmitted if we know all the UID bits of the current Cascade Level.
//
// Description of bytes 2-5: (Section 6.5.4 of the ISO/IEC 14443-3 draft: UID contents and cascade levels)
// UID size Cascade level Byte2 Byte3 Byte4 Byte5
// ======== ============= ===== ===== ===== =====
// 4 bytes 1 uid0 uid1 uid2 uid3
// 7 bytes 1 CT uid0 uid1 uid2
// 2 uid3 uid4 uid5 uid6
// 10 bytes 1 CT uid0 uid1 uid2
// 2 CT uid3 uid4 uid5
// 3 uid6 uid7 uid8 uid9
// Sanity checks
if (validBits > 80) {
return STATUS_INVALID;
}
// Prepare MFRC522
PCD_ClearRegisterBitMask(CollReg, 0x80); // ValuesAfterColl=1 => Bits received after collision are cleared.
// Repeat Cascade Level loop until we have a complete UID.
uidComplete = false;
while (!uidComplete) {
// Set the Cascade Level in the SEL byte, find out if we need to use the Cascade Tag in byte 2.
switch (cascadeLevel) {
case 1:
buffer[0] = PICC_CMD_SEL_CL1;
uidIndex = 0;
useCascadeTag = validBits && uid->size > 4; // When we know that the UID has more than 4 bytes
break;
case 2:
buffer[0] = PICC_CMD_SEL_CL2;
uidIndex = 3;
useCascadeTag = validBits && uid->size > 7; // When we know that the UID has more than 7 bytes
break;
case 3:
buffer[0] = PICC_CMD_SEL_CL3;
uidIndex = 6;
useCascadeTag = false; // Never used in CL3.
break;
default:
return STATUS_INTERNAL_ERROR;
break;
}
// How many UID bits are known in this Cascade Level?
currentLevelKnownBits = validBits - (8 * uidIndex);
if (currentLevelKnownBits < 0) {
currentLevelKnownBits = 0;
}
// Copy the known bits from uid->uidByte[] to buffer[]
index = 2; // destination index in buffer[]
if (useCascadeTag) {
buffer[index++] = PICC_CMD_CT;
}
byte bytesToCopy = currentLevelKnownBits / 8 + (currentLevelKnownBits % 8 ? 1 : 0); // The number of bytes needed to represent the known bits for this level.
if (bytesToCopy) {
byte maxBytes = useCascadeTag ? 3 : 4; // Max 4 bytes in each Cascade Level. Only 3 left if we use the Cascade Tag
if (bytesToCopy > maxBytes) {
bytesToCopy = maxBytes;
}
for (count = 0; count < bytesToCopy; count++) {
buffer[index++] = uid->uidByte[uidIndex + count];
}
}
// Now that the data has been copied we need to include the 8 bits in CT in currentLevelKnownBits
if (useCascadeTag) {
currentLevelKnownBits += 8;
}
// Repeat anti collision loop until we can transmit all UID bits + BCC and receive a SAK - max 32 iterations.
selectDone = false;
while (!selectDone) {
// Find out how many bits and bytes to send and receive.
if (currentLevelKnownBits >= 32) { // All UID bits in this Cascade Level are known. This is a SELECT.
//Serial.print(F("SELECT: currentLevelKnownBits=")); Serial.println(currentLevelKnownBits, DEC);
buffer[1] = 0x70; // NVB - Number of Valid Bits: Seven whole bytes
// Calculate BCC - Block Check Character
buffer[6] = buffer[2] ^ buffer[3] ^ buffer[4] ^ buffer[5];
// Calculate CRC_A
result = PCD_CalculateCRC(buffer, 7, &buffer[7]);
if (result != STATUS_OK) {
return result;
}
txLastBits = 0; // 0 => All 8 bits are valid.
bufferUsed = 9;
// Store response in the last 3 bytes of buffer (BCC and CRC_A - not needed after tx)
responseBuffer = &buffer[6];
responseLength = 3;
}
else { // This is an ANTICOLLISION.
//Serial.print(F("ANTICOLLISION: currentLevelKnownBits=")); Serial.println(currentLevelKnownBits, DEC);
txLastBits = currentLevelKnownBits % 8;
count = currentLevelKnownBits / 8; // Number of whole bytes in the UID part.
index = 2 + count; // Number of whole bytes: SEL + NVB + UIDs
buffer[1] = (index << 4) + txLastBits; // NVB - Number of Valid Bits
bufferUsed = index + (txLastBits ? 1 : 0);
// Store response in the unused part of buffer
responseBuffer = &buffer[index];
responseLength = sizeof(buffer) - index;
}
// Set bit adjustments
rxAlign = txLastBits; // Having a separate variable is overkill. But it makes the next line easier to read.
PCD_WriteRegister(BitFramingReg, (rxAlign << 4) + txLastBits); // RxAlign = BitFramingReg[6..4]. TxLastBits = BitFramingReg[2..0]
// Transmit the buffer and receive the response.
result = PCD_TransceiveData(buffer, bufferUsed, responseBuffer, &responseLength, &txLastBits, rxAlign);
if (result == STATUS_COLLISION) { // More than one PICC in the field => collision.
byte valueOfCollReg = PCD_ReadRegister(CollReg); // CollReg[7..0] bits are: ValuesAfterColl reserved CollPosNotValid CollPos[4:0]
if (valueOfCollReg & 0x20) { // CollPosNotValid
return STATUS_COLLISION; // Without a valid collision position we cannot continue
}
byte collisionPos = valueOfCollReg & 0x1F; // Values 0-31, 0 means bit 32.
if (collisionPos == 0) {
collisionPos = 32;
}
if (collisionPos <= currentLevelKnownBits) { // No progress - should not happen
return STATUS_INTERNAL_ERROR;
}
// Choose the PICC with the bit set.
currentLevelKnownBits = collisionPos;
count = (currentLevelKnownBits - 1) % 8; // The bit to modify
index = 1 + (currentLevelKnownBits / 8) + (count ? 1 : 0); // First byte is index 0.
buffer[index] |= (1 << count);
}
else if (result != STATUS_OK) {
return result;
}
else { // STATUS_OK
if (currentLevelKnownBits >= 32) { // This was a SELECT.
selectDone = true; // No more anticollision
// We continue below outside the while.
}
else { // This was an ANTICOLLISION.
// We now have all 32 bits of the UID in this Cascade Level
currentLevelKnownBits = 32;
// Run loop again to do the SELECT.
}
}
} // End of while (!selectDone)
// We do not check the CBB - it was constructed by us above.
// Copy the found UID bytes from buffer[] to uid->uidByte[]
index = (buffer[2] == PICC_CMD_CT) ? 3 : 2; // source index in buffer[]
bytesToCopy = (buffer[2] == PICC_CMD_CT) ? 3 : 4;
for (count = 0; count < bytesToCopy; count++) {
uid->uidByte[uidIndex + count] = buffer[index++];
}
// Check response SAK (Select Acknowledge)
if (responseLength != 3 || txLastBits != 0) { // SAK must be exactly 24 bits (1 byte + CRC_A).
return STATUS_ERROR;
}
// Verify CRC_A - do our own calculation and store the control in buffer[2..3] - those bytes are not needed anymore.
result = PCD_CalculateCRC(responseBuffer, 1, &buffer[2]);
if (result != STATUS_OK) {
return result;
}
if ((buffer[2] != responseBuffer[1]) || (buffer[3] != responseBuffer[2])) {
return STATUS_CRC_WRONG;
}
if (responseBuffer[0] & 0x04) { // Cascade bit set - UID not complete yes
cascadeLevel++;
}
else {
uidComplete = true;
uid->sak = responseBuffer[0];
}
} // End of while (!uidComplete)
// Set correct uid->size
uid->size = 3 * cascadeLevel + 1;
// IF SAK bit 6 = 1 then it is ISO/IEC 14443-4 (T=CL)
// A Request ATS command should be sent
// We also check SAK bit 3 is cero, as it stands for UID complete (1 would tell us it is incomplete)
if ((uid->sak & 0x24) == 0x20) {
Ats ats;
result = PICC_RequestATS(&ats);
if (result == STATUS_OK) {
// Check the ATS
if (ats.size > 0)
{
// TA1 has been transmitted?
// PPS must be supported...
if (ats.ta1.transmitted)
{
// TA1
// 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | Description
// ---+---+---+---+---+---+---+---+------------------------------------------
// 0 | - | - | - | 0 | - | - | - | Different D for each direction supported
// 1 | - | - | - | 0 | - | - | - | Only same D for both direction supported
// - | x | x | x | 0 | - | - | - | DS (Send D)
// - | - | - | - | 0 | x | x | x | DR (Receive D)
//
// D to bitrate table
// 3 | 2 | 1 | Value
// ---+---+---+-----------------------------
// 1 | - | - | 848 kBaud is supported
// - | 1 | - | 424 kBaud is supported
// - | - | 1 | 212 kBaud is supported
// 0 | 0 | 0 | Only 106 kBaud is supported
//
// Note: 106 kBaud is always supported
//
// I have almost constant timeouts when changing speeds :(
// default never used, so only delarate
//TagBitRates ds = BITRATE_106KBITS;
//TagBitRates dr = BITRATE_106KBITS;
TagBitRates ds;
TagBitRates dr;
//// TODO Not working at 848 or 424
//if (ats.ta1.ds & 0x04)
//{
// ds = BITRATE_848KBITS;
//}
//else if (ats.ta1.ds & 0x02)
//{
// ds = BITRATE_424KBITS;
//}
//else if (ats.ta1.ds & 0x01)
//{
// ds = BITRATE_212KBITS;
//}
//else
//{
// ds = BITRATE_106KBITS;
//}
if (ats.ta1.ds & 0x01)
{
ds = BITRATE_212KBITS;
}
else
{
ds = BITRATE_106KBITS;
}
//// Not working at 848 or 424
//if (ats.ta1.dr & 0x04)
//{
// dr = BITRATE_848KBITS;
//}
//else if (ats.ta1.dr & 0x02)
//{
// dr = BITRATE_424KBITS;
//}
//else if (ats.ta1.dr & 0x01)
//{
// dr = BITRATE_212KBITS;
//}
//else
//{
// dr = BITRATE_106KBITS;
//}
if (ats.ta1.dr & 0x01)
{
dr = BITRATE_212KBITS;
}
else
{
dr = BITRATE_106KBITS;
}
PICC_PPS(ds, dr);
}
}
}
}
return STATUS_OK;
} // End PICC_Select()
/**
* Transmits a Request command for Answer To Select (ATS).
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522::StatusCode MFRC522Extended::PICC_RequestATS(Ats *ats)
{
// TODO unused variable
//byte count;
MFRC522::StatusCode result;
byte bufferATS[FIFO_SIZE];
byte bufferSize = FIFO_SIZE;
memset(bufferATS, 0, FIFO_SIZE);
// Build command buffer
bufferATS[0] = PICC_CMD_RATS;
// The CID defines the logical number of the addressed card and has a range of 0
// through 14; 15 is reserved for future use (RFU).
//
// FSDI codes the maximum frame size (FSD) that the terminal can receive.
//
// FSDI | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9-F
// ------------+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----------
// FSD (bytes) | 16 | 24 | 32 | 40 | 48 | 64 | 96 | 128 | 256 | RFU > 256
//
bufferATS[1] = 0x50; // FSD=64, CID=0
// Calculate CRC_A
result = PCD_CalculateCRC(bufferATS, 2, &bufferATS[2]);
if (result != STATUS_OK) {
return result;
}
// Transmit the buffer and receive the response, validate CRC_A.
result = PCD_TransceiveData(bufferATS, 4, bufferATS, &bufferSize, NULL, 0, true);
if (result != STATUS_OK) {
PICC_HaltA();
}
// Set the ats structure data
ats->size = bufferATS[0];
// T0 byte:
//
// b8 | b7 | b6 | b5 | b4 | b3 | b2 | b1 | Meaning
//----+----+----+----+----+----+----+----+---------------------------
// 0 | ...| ...| ...| ...|... | ...| ...| Set to 0 (RFU)
// 0 | 1 | x | x | ...|... | ...| ...| TC1 transmitted
// 0 | x | 1 | x | ...|... | ...| ...| TB1 transmitted
// 0 | x | x | 1 | ...|... | ...| ...| TA1 transmitted
// 0 | ...| ...| ...| x | x | x | x | Maximum frame size (FSCI)
//
// FSCI | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9-F
// ------------+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----------
// FSC (bytes) | 16 | 24 | 32 | 40 | 48 | 64 | 96 | 128 | 256 | RFU > 256
//
// Default FSCI is 2 (32 bytes)
if (ats->size > 0x01)
{
// TC1, TB1 and TA1 where NOT transmitted
ats->ta1.transmitted = (bool)(bufferATS[1] & 0x40);
ats->tb1.transmitted = (bool)(bufferATS[1] & 0x20);
ats->tc1.transmitted = (bool)(bufferATS[1] & 0x10);
// Decode FSCI
switch (bufferATS[1] & 0x0F)
{
case 0x00:
ats->fsc = 16;
break;
case 0x01:
ats->fsc = 24;
break;
case 0x02:
ats->fsc = 32;
break;
case 0x03:
ats->fsc = 40;
break;
case 0x04:
ats->fsc = 48;
break;
case 0x05:
ats->fsc = 64;
break;
case 0x06:
ats->fsc = 96;
break;
case 0x07:
ats->fsc = 128;
break;
case 0x08:
// This value cannot be hold by a byte
// The reason I ignore it is that MFRC255 FIFO is 64 bytes so this is not a possible value (or atleast it shouldn't)
//ats->fsc = 256;
break;
// TODO: What to do with RFU (Reserved for future use)?
default:
break;
}
// TA1
if (ats->ta1.transmitted)
{
ats->ta1.sameD = (bool)(bufferATS[2] & 0x80);
ats->ta1.ds = (TagBitRates)((bufferATS[2] & 0x70) >> 4);
ats->ta1.dr = (TagBitRates)(bufferATS[2] & 0x07);
}
else
{
// Default TA1
ats->ta1.ds = BITRATE_106KBITS;
ats->ta1.dr = BITRATE_106KBITS;
}
// TB1
if (ats->tb1.transmitted)
{
uint8_t tb1Index = 2;
if (ats->ta1.transmitted)
tb1Index++;
ats->tb1.fwi = (bufferATS[tb1Index] & 0xF0) >> 4;
ats->tb1.sfgi = bufferATS[tb1Index] & 0x0F;
}
else
{
// Defaults for TB1
ats->tb1.fwi = 0; // TODO: Don't know the default for this!
ats->tb1.sfgi = 0; // The default value of SFGI is 0 (meaning that the card does not need any particular SFGT)
}
// TC1
if (ats->tc1.transmitted)
{
uint8_t tc1Index = 2;
if (ats->ta1.transmitted)
tc1Index++;
if (ats->tb1.transmitted)
tc1Index++;
ats->tc1.supportsCID = (bool)(bufferATS[tc1Index] & 0x02);
ats->tc1.supportsNAD = (bool)(bufferATS[tc1Index] & 0x01);
}
else
{
// Defaults for TC1
ats->tc1.supportsCID = true;
ats->tc1.supportsNAD = false;
}
}
else
{
// TC1, TB1 and TA1 where NOT transmitted
ats->ta1.transmitted = false;
ats->tb1.transmitted = false;
ats->tc1.transmitted = false;
// Default FSCI
ats->fsc = 32; // Defaults to FSCI 2 (32 bytes)
// Default TA1
ats->ta1.sameD = false;
ats->ta1.ds = BITRATE_106KBITS;
ats->ta1.dr = BITRATE_106KBITS;
// Defaults for TB1
ats->tb1.transmitted = false;
ats->tb1.fwi = 0; // TODO: Don't know the default for this!
ats->tb1.sfgi = 0; // The default value of SFGI is 0 (meaning that the card does not need any particular SFGT)
// Defaults for TC1
ats->tc1.transmitted = false;
ats->tc1.supportsCID = true;
ats->tc1.supportsNAD = false;
}
memcpy(ats->data, bufferATS, bufferSize - 2);
return result;
} // End PICC_RequestATS()
/**
* Transmits Protocol and Parameter Selection Request (PPS) without parameter 1
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522::StatusCode MFRC522Extended::PICC_PPS()
{
StatusCode result;
byte ppsBuffer[4];
byte ppsBufferSize = 4;
// Start byte: The start byte (PPS) consists of two parts:
// –The upper nibble(b8–b5) is set to’D'to identify the PPS. All other values are RFU.
// -The lower nibble(b4–b1), which is called the ‘card identifier’ (CID), defines the logical number of the addressed card.
ppsBuffer[0] = 0xD0; // CID is hardcoded as 0 in RATS
ppsBuffer[1] = 0x00; // PPS0 indicates whether PPS1 is present
// Calculate CRC_A
result = PCD_CalculateCRC(ppsBuffer, 2, &ppsBuffer[2]);
if (result != STATUS_OK) {
return result;
}
// Transmit the buffer and receive the response, validate CRC_A.
result = PCD_TransceiveData(ppsBuffer, 4, ppsBuffer, &ppsBufferSize, NULL, 0, true);
if (result == STATUS_OK)
{
// Enable CRC for T=CL
byte txReg = PCD_ReadRegister(TxModeReg) | 0x80;
byte rxReg = PCD_ReadRegister(RxModeReg) | 0x80;
PCD_WriteRegister(TxModeReg, txReg);
PCD_WriteRegister(RxModeReg, rxReg);
}
return result;
} // End PICC_PPS()
/**
* Transmits Protocol and Parameter Selection Request (PPS)
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522::StatusCode MFRC522Extended::PICC_PPS(TagBitRates sendBitRate, ///< DS
TagBitRates receiveBitRate ///< DR
) {
StatusCode result;
// TODO not used
//byte txReg = PCD_ReadRegister(TxModeReg) & 0x8F;
//byte rxReg = PCD_ReadRegister(RxModeReg) & 0x8F;
byte ppsBuffer[5];
byte ppsBufferSize = 5;
// Start byte: The start byte (PPS) consists of two parts:
// –The upper nibble(b8–b5) is set to’D'to identify the PPS. All other values are RFU.
// -The lower nibble(b4–b1), which is called the ‘card identifier’ (CID), defines the logical number of the addressed card.
ppsBuffer[0] = 0xD0; // CID is hardcoded as 0 in RATS
ppsBuffer[1] = 0x11; // PPS0 indicates whether PPS1 is present
// Bit 8 - Set to '0' as MFRC522 allows different bit rates for send and receive
// Bit 4 - Set to '0' as it is Reserved for future use.
//ppsBuffer[2] = (((sendBitRate & 0x03) << 4) | (receiveBitRate & 0x03)) & 0xE7;
ppsBuffer[2] = (((sendBitRate & 0x03) << 2) | (receiveBitRate & 0x03)) & 0xE7;
// Calculate CRC_A
result = PCD_CalculateCRC(ppsBuffer, 3, &ppsBuffer[3]);
if (result != STATUS_OK) {
return result;
}
// Transmit the buffer and receive the response, validate CRC_A.
result = PCD_TransceiveData(ppsBuffer, 5, ppsBuffer, &ppsBufferSize, NULL, 0, true);
if (result == STATUS_OK)
{
// Make sure it is an answer to our PPS
// We should receive our PPS byte and 2 CRC bytes
if ((ppsBufferSize == 3) && (ppsBuffer[0] == 0xD0)) {
byte txReg = PCD_ReadRegister(TxModeReg) & 0x8F;
byte rxReg = PCD_ReadRegister(RxModeReg) & 0x8F;
// Set bit rate and enable CRC for T=CL
txReg = (txReg & 0x8F) | ((receiveBitRate & 0x03) << 4) | 0x80;
rxReg = (rxReg & 0x8F) | ((sendBitRate & 0x03) << 4) | 0x80;
rxReg &= 0xF0; //Enforce although this should be set already
// From ConfigIsoType
//rxReg |= 0x06;
PCD_WriteRegister(TxModeReg, txReg);
PCD_WriteRegister(RxModeReg, rxReg);
// At 212kBps
switch (sendBitRate) {
case BITRATE_212KBITS:
{
//PCD_WriteRegister(ModWidthReg, 0x13);
PCD_WriteRegister(ModWidthReg, 0x15);
}
break;
case BITRATE_424KBITS:
{
PCD_WriteRegister(ModWidthReg, 0x0A);
}
break;
case BITRATE_848KBITS:
{
PCD_WriteRegister(ModWidthReg, 0x05);
}
break;
default:
{
PCD_WriteRegister(ModWidthReg, 0x26); // Default value
}
break;
}
//PCD_WriteRegister(RxThresholdReg, 0x84); // ISO-14443.4 Type A (default)
//PCD_WriteRegister(ControlReg, 0x10);
delayMicroseconds(10);
}
else
{
return STATUS_ERROR;
}
}
return result;
} // End PICC_PPS()
/////////////////////////////////////////////////////////////////////////////////////
// Functions for communicating with ISO/IEC 14433-4 cards
/////////////////////////////////////////////////////////////////////////////////////
MFRC522::StatusCode MFRC522Extended::TCL_Transceive(PcbBlock *send, PcbBlock *back)
{
MFRC522::StatusCode result;
byte inBuffer[FIFO_SIZE];
byte inBufferSize = FIFO_SIZE;
byte outBuffer[send->inf.size + 5]; // PCB + CID + NAD + INF + EPILOGUE (CRC)
byte outBufferOffset = 1;
byte inBufferOffset = 1;
// Set the PCB byte
outBuffer[0] = send->prologue.pcb;
// Set the CID byte if available
if (send->prologue.pcb & 0x08) {
outBuffer[outBufferOffset] = send->prologue.cid;
outBufferOffset++;
}
// Set the NAD byte if available
if (send->prologue.pcb & 0x04) {
outBuffer[outBufferOffset] = send->prologue.nad;
outBufferOffset++;
}
// Copy the INF field if available
if (send->inf.size > 0) {
memcpy(&outBuffer[outBufferOffset], send->inf.data, send->inf.size);
outBufferOffset += send->inf.size;
}
// Is the CRC enabled for transmission?
byte txModeReg = PCD_ReadRegister(TxModeReg);
if ((txModeReg & 0x80) != 0x80) {
// Calculate CRC_A
result = PCD_CalculateCRC(outBuffer, outBufferOffset, &outBuffer[outBufferOffset]);
if (result != STATUS_OK) {
return result;
}
outBufferOffset += 2;
}
// Transceive the block
result = PCD_TransceiveData(outBuffer, outBufferOffset, inBuffer, &inBufferSize);
if (result != STATUS_OK) {
return result;
}
// We want to turn the received array back to a PcbBlock
back->prologue.pcb = inBuffer[0];
// CID byte is present?
if (send->prologue.pcb & 0x08) {
back->prologue.cid = inBuffer[inBufferOffset];
inBufferOffset++;
}
// NAD byte is present?
if (send->prologue.pcb & 0x04) {
back->prologue.nad = inBuffer[inBufferOffset];
inBufferOffset++;
}
// Check if CRC is taken care of by MFRC522
byte rxModeReg = PCD_ReadRegister(TxModeReg);
if ((rxModeReg & 0x80) != 0x80) {
Serial.print("CRC is not taken care of by MFRC522: ");
Serial.println(rxModeReg, HEX);
// Check the CRC
// We need at least the CRC_A value.
if ((int)(inBufferSize - inBufferOffset) < 2) {
return STATUS_CRC_WRONG;
}
// Verify CRC_A - do our own calculation and store the control in controlBuffer.
byte controlBuffer[2];
MFRC522::StatusCode status = PCD_CalculateCRC(inBuffer, inBufferSize - 2, controlBuffer);
if (status != STATUS_OK) {
return status;
}
if ((inBuffer[inBufferSize - 2] != controlBuffer[0]) || (inBuffer[inBufferSize - 1] != controlBuffer[1])) {
return STATUS_CRC_WRONG;
}
// Take away the CRC bytes
inBufferSize -= 2;
}
// Got more data?
if (inBufferSize > inBufferOffset) {
if ((inBufferSize - inBufferOffset) > back->inf.size) {
return STATUS_NO_ROOM;
}
memcpy(back->inf.data, &inBuffer[inBufferOffset], inBufferSize - inBufferOffset);
back->inf.size = inBufferSize - inBufferOffset;
} else {
back->inf.size = 0;
}
// If the response is a R-Block check NACK
if (((inBuffer[0] & 0xC0) == 0x80) && (inBuffer[0] & 0x20)) {
return STATUS_MIFARE_NACK;
}
return result;
}
/**
* Send an I-Block (Application)
*/
MFRC522::StatusCode MFRC522Extended::TCL_Transceive(TagInfo *tag, byte *sendData, byte sendLen, byte *backData, byte *backLen)
{
MFRC522::StatusCode result;
PcbBlock out;
PcbBlock in;
byte outBuffer[FIFO_SIZE];
byte outBufferSize = FIFO_SIZE;
byte totalBackLen = *backLen;
// This command sends an I-Block
out.prologue.pcb = 0x02;
if (tag->ats.tc1.supportsCID) {
out.prologue.pcb |= 0x08;
out.prologue.cid = 0x00; // CID is curentlly hardcoded as 0x00
}
// This command doe not support NAD
out.prologue.pcb &= 0xFB;
out.prologue.nad = 0x00;
// Set the block number
if (tag->blockNumber) {
out.prologue.pcb |= 0x01;
}
// Do we have data to send?
if (sendData && (sendLen > 0)) {
out.inf.size = sendLen;
out.inf.data = sendData;
} else {
out.inf.size = 0;
out.inf.data = NULL;
}
// Initialize the receiving data
// TODO Warning: Value escapes the local scope
in.inf.data = outBuffer;
in.inf.size = outBufferSize;
result = TCL_Transceive(&out, &in);
if (result != STATUS_OK) {
return result;
}
// Swap block number on success
tag->blockNumber = !tag->blockNumber;
if (backData && (backLen > 0)) {
if (*backLen < in.inf.size)
return STATUS_NO_ROOM;
*backLen = in.inf.size;
memcpy(backData, in.inf.data, in.inf.size);
}
// Check chaining
if ((in.prologue.pcb & 0x10) == 0x00)
return result;
// Result is chained
// Send an ACK to receive more data
// TODO: Should be checked I've never needed to send an ACK
while (in.prologue.pcb & 0x10) {
byte ackData[FIFO_SIZE];
byte ackDataSize = FIFO_SIZE;
result = TCL_TransceiveRBlock(tag, true, ackData, &ackDataSize);
if (result != STATUS_OK)
return result;
if (backData && (backLen > 0)) {
if ((*backLen + ackDataSize) > totalBackLen)
return STATUS_NO_ROOM;
memcpy(&(backData[*backLen]), ackData, ackDataSize);
*backLen += ackDataSize;
}
}
return result;
} // End TCL_Transceive()
/**
* Send R-Block to the PICC.
*/
MFRC522::StatusCode MFRC522Extended::TCL_TransceiveRBlock(TagInfo *tag, bool ack, byte *backData, byte *backLen)
{
MFRC522::StatusCode result;
PcbBlock out;
PcbBlock in;
byte outBuffer[FIFO_SIZE];
byte outBufferSize = FIFO_SIZE;
// This command sends an R-Block
if (ack)
out.prologue.pcb = 0xA2; // ACK
else
out.prologue.pcb = 0xB2; // NAK
if (tag->ats.tc1.supportsCID) {
out.prologue.pcb |= 0x08;
out.prologue.cid = 0x00; // CID is curentlly hardcoded as 0x00
}
// This command doe not support NAD
out.prologue.pcb &= 0xFB;
out.prologue.nad = 0x00;
// Set the block number
if (tag->blockNumber) {
out.prologue.pcb |= 0x01;
}
// No INF data for R-Block
out.inf.size = 0;
out.inf.data = NULL;
// Initialize the receiving data
// TODO Warning: Value escapes the local scope
in.inf.data = outBuffer;
in.inf.size = outBufferSize;
result = TCL_Transceive(&out, &in);
if (result != STATUS_OK) {
return result;
}
// Swap block number on success
tag->blockNumber = !tag->blockNumber;
if (backData && backLen) {
if (*backLen < in.inf.size)
return STATUS_NO_ROOM;
*backLen = in.inf.size;
memcpy(backData, in.inf.data, in.inf.size);
}
return result;
} // End TCL_TransceiveRBlock()
/**
* Send an S-Block to deselect the card.
*/
MFRC522::StatusCode MFRC522Extended::TCL_Deselect(TagInfo *tag)
{
MFRC522::StatusCode result;
byte outBuffer[4];
byte outBufferSize = 1;
byte inBuffer[FIFO_SIZE];
byte inBufferSize = FIFO_SIZE;
outBuffer[0] = 0xC2;
if (tag->ats.tc1.supportsCID)
{
outBuffer[0] |= 0x08;
outBuffer[1] = 0x00; // CID is hardcoded
outBufferSize = 2;
}
result = PCD_TransceiveData(outBuffer, outBufferSize, inBuffer, &inBufferSize);
if (result != STATUS_OK) {
return result;
}
// TODO:Maybe do some checks? In my test it returns: CA 00 (Same data as I sent to my card)
return result;
} // End TCL_Deselect()
/////////////////////////////////////////////////////////////////////////////////////
// Support functions
/////////////////////////////////////////////////////////////////////////////////////
/**
* Get the PICC type.
*
* @return PICC_Type
*/
MFRC522::PICC_Type MFRC522Extended::PICC_GetType(TagInfo *tag ///< The TagInfo returned from PICC_Select().
) {
// http://www.nxp.com/documents/application_note/AN10833.pdf
// 3.2 Coding of Select Acknowledge (SAK)
// ignore 8-bit (iso14443 starts with LSBit = bit 1)
// fixes wrong type for manufacturer Infineon (http://nfc-tools.org/index.php?title=ISO14443A)
byte sak = tag->uid.sak & 0x7F;
switch (sak) {
case 0x04: return PICC_TYPE_NOT_COMPLETE; // UID not complete
case 0x09: return PICC_TYPE_MIFARE_MINI;
case 0x08: return PICC_TYPE_MIFARE_1K;
case 0x18: return PICC_TYPE_MIFARE_4K;
case 0x00: return PICC_TYPE_MIFARE_UL;
case 0x10:
case 0x11: return PICC_TYPE_MIFARE_PLUS;
case 0x01: return PICC_TYPE_TNP3XXX;
case 0x20:
if (tag->atqa == 0x0344)
return PICC_TYPE_MIFARE_DESFIRE;
return PICC_TYPE_ISO_14443_4;
case 0x40: return PICC_TYPE_ISO_18092;
default: return PICC_TYPE_UNKNOWN;
}
} // End PICC_GetType()
/**
* Dumps debug info about the selected PICC to Serial.
* On success the PICC is halted after dumping the data.
* For MIFARE Classic the factory default key of 0xFFFFFFFFFFFF is tried.
*/
void MFRC522Extended::PICC_DumpToSerial(TagInfo *tag)
{
MIFARE_Key key;
// Dump UID, SAK and Type
PICC_DumpDetailsToSerial(tag);
// Dump contents
PICC_Type piccType = MFRC522::PICC_GetType(tag->uid.sak);
switch (piccType) {
case PICC_TYPE_MIFARE_MINI:
case PICC_TYPE_MIFARE_1K:
case PICC_TYPE_MIFARE_4K: