forked from nanoframework/nanoFramework.IoT.Device
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPn5180.cs
1663 lines (1473 loc) · 63.5 KB
/
Pn5180.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Buffers.Binary;
using System.Collections;
using System.Collections.Generic;
using System.Device.Gpio;
using System.Device.Spi;
using System.Diagnostics;
using System.IO;
using System.Threading;
using Iot.Device.Card;
using Iot.Device.Card.Mifare;
using Iot.Device.Rfid;
#if DEBUG
using Microsoft.Extensions.Logging;
using nanoFramework.Logging;
#endif
namespace Iot.Device.Pn5180
{
/// <summary>
/// A PN5180 class offering RFID and NFC functionalities. Implement the CardTransceiver class to
/// allow Mifare, Credit Card support
/// </summary>
public class Pn5180 : CardTransceiver, IDisposable
{
private const int TimeoutWaitingMilliseconds = 2_000;
private static ListSelectedPiccInformation _activeSelected = new ListSelectedPiccInformation();
private readonly SpiDevice _spiDevice;
private readonly GpioController _gpioController;
private bool _shouldDispose;
private int _pinBusy;
private int _pinNss;
#if DEBUG
private ILogger _logger;
#endif
/// <summary>
/// A radio Frequency configuration element size is 5 bytes
/// Byte 1 = Register Address
/// next 4 bytes = data of the register
/// </summary>
public const int RadioFrequencyConfigurationSize = 5;
/// <summary>
/// PN532 SPI Clock Frequency
/// </summary>
public const int MaximumSpiClockFrequency = 7_000_000;
/// <summary>
/// Only SPI Mode supported is Mode0
/// </summary>
public const SpiMode DefaultSpiMode = System.Device.Spi.SpiMode.Mode0;
/// <summary>
/// Create a PN5180 RFID/NFC reader
/// </summary>
/// <param name="spiDevice">The SPI device</param>
/// <param name="pinBusy">The pin for the busy line</param>
/// <param name="pinNss">The pin for the SPI select line. This has to be handle differently than thru the normal process as PN5180 has a specific way of working</param>
/// <param name="gpioController">A GPIO controller, null will use a default one</param>
/// <param name="shouldDispose">Dispose the SPI and the GPIO controller at the end if true</param>
public Pn5180(SpiDevice spiDevice, int pinBusy, int pinNss, GpioController? gpioController = null, bool shouldDispose = true)
{
if (pinBusy < 0)
{
throw new ArgumentException(nameof(pinBusy), "Value must be a legal pin number. cannot be negative.");
}
if (pinNss < 0)
{
throw new ArgumentException(nameof(pinBusy), "Value must be a legal pin number. cannot be negative.");
}
#if DEBUG
_logger = this.GetCurrentClassLogger();
_logger.LogDebug($"Opening PN5180, pin busy: {pinBusy}, pin NSS: {pinNss}");
#endif
_spiDevice = spiDevice ?? throw new ArgumentNullException(nameof(spiDevice));
_gpioController = gpioController ?? new GpioController(PinNumberingScheme.Logical);
_shouldDispose = shouldDispose || gpioController is null;
_pinBusy = pinBusy;
_pinNss = pinNss;
_gpioController.OpenPin(_pinBusy, PinMode.Input);
_gpioController.OpenPin(_pinNss, PinMode.Output);
// Check the version
var versions = GetVersions();
if ((versions.Product == null) || (versions.Product.Major == 0) || (versions.Firmware.Major == 0) || (versions.Eeprom.Major == 0))
{
throw new IOException($"Not a valid PN5180");
}
}
/// <summary>
/// Dispose
/// </summary>
public void Dispose()
{
SetRadioFrequency(false);
if (_shouldDispose)
{
_spiDevice?.Dispose();
_gpioController?.Dispose();
}
}
#region EEPROM
/// <summary>
/// Get the Product, Firmware and EEPROM versions of the PN8150
/// </summary>
/// <returns>A tuple with the Product, Firmware and EEPROM versions</returns>
public TripletVersion GetVersions()
{
SpanByte versionAnswer = new byte[6];
var ret = ReadEeprom(EepromAddress.ProductVersion, versionAnswer);
if (!ret)
{
return new TripletVersion(null, null, null);
}
var product = new Version(versionAnswer[1], versionAnswer[0]);
var firmware = new Version(versionAnswer[3], versionAnswer[2]);
var eeprom = new Version(versionAnswer[5], versionAnswer[4]);
return new TripletVersion(product, firmware, eeprom);
}
/// <summary>
/// Get the PN5180 identifier, this is a 16 byte long
/// </summary>
/// <param name="outputIdentifier">A 16 byte buffer</param>
/// <returns>True if success</returns>
public bool GetIdentifier(SpanByte outputIdentifier)
{
if (outputIdentifier.Length != 16)
{
throw new ArgumentException(nameof(outputIdentifier), "Value must be 16 bytes long");
}
return ReadEeprom(EepromAddress.DieIdentifier, outputIdentifier);
}
/// <summary>
/// Read the full EEPROM
/// </summary>
/// <param name="eeprom">At 255 bytes buffer</param>
/// <returns>True if success</returns>
public bool ReadAllEeprom(SpanByte eeprom)
{
if (eeprom.Length != 255)
{
throw new ArgumentException(nameof(eeprom), "Size of EEPROM is 255 bytes. Value must match.");
}
return ReadEeprom(EepromAddress.DieIdentifier, eeprom);
}
/// <summary>
/// Write all the EEPROM
/// </summary>
/// <param name="eeprom">A 255 bytes buffer</param>
/// <returns>True if success</returns>
public bool WriteAllEeprom(SpanByte eeprom)
{
if (eeprom.Length != 255)
{
throw new ArgumentException(nameof(eeprom), "Size of EEPROM is 255 bytes. Value must match.");
}
return WriteEeprom(EepromAddress.DieIdentifier, eeprom);
}
/// <summary>
/// Read a specific part of the EEPROM
/// </summary>
/// <param name="address">The EEPROM address</param>
/// <param name="eeprom">A span of byte to read the EEPROM</param>
/// <returns>True if success</returns>
public bool ReadEeprom(EepromAddress address, SpanByte eeprom)
{
if ((byte)address + eeprom.Length > 255)
{
throw new ArgumentException(nameof(eeprom), "Size of EEPROM is 255 bytes. Value must 255 bytes or less.");
}
SpanByte dumpEeprom = new byte[3];
dumpEeprom[0] = (byte)Command.READ_EEPROM;
dumpEeprom[1] = (byte)address;
dumpEeprom[2] = (byte)eeprom.Length;
#if DEBUG
_logger.LogDebug($"{nameof(ReadEeprom)}, {nameof(dumpEeprom)}: {BitConverter.ToString(dumpEeprom.ToArray())}");
#endif
try
{
SpiWriteRead(dumpEeprom, eeprom);
#if DEBUG
_logger.LogDebug($"{nameof(ReadEeprom)}, {nameof(dumpEeprom)}: {BitConverter.ToString(dumpEeprom.ToArray())}");
#endif
}
catch (TimeoutException tx)
{
#if DEBUG
_logger.LogError(tx, $"{nameof(ReadEeprom)}: {nameof(TimeoutException)} during {nameof(SpiWriteRead)}");
#endif
return false;
}
return true;
}
/// <summary>
/// Write the EEPROM at a specific address
/// </summary>
/// <param name="address">The EEPROM address</param>
/// <param name="eeprom">A span of byte to write the EEPROM</param>
/// <returns>True if success</returns>
public bool WriteEeprom(EepromAddress address, SpanByte eeprom)
{
if ((byte)address + eeprom.Length > 255)
{
throw new ArgumentException(nameof(eeprom), "Size of EEPROM is 255 bytes. Value must 255 bytes or less.");
}
SpanByte dumpEeprom = new byte[2 + eeprom.Length];
bool ret;
dumpEeprom[0] = (byte)Command.WRITE_EEPROM;
dumpEeprom[1] = (byte)address;
eeprom.CopyTo(dumpEeprom.Slice(2));
#if DEBUG
_logger.LogDebug($"{nameof(WriteEeprom)}, {nameof(eeprom)}: {BitConverter.ToString(eeprom.ToArray())}");
#endif
try
{
SpiWrite(dumpEeprom);
#if DEBUG
_logger.LogDebug($"{nameof(WriteEeprom)}, {nameof(dumpEeprom)}: {BitConverter.ToString(dumpEeprom.ToArray())}");
#endif
SpanByte irqStatus = new byte[4];
ret = GetIrqStatus(irqStatus);
ret &= !((irqStatus[2] & 0b0000_0010) == 0b0000_0010);
// Clear IRQ
SpiWriteRegister(Command.WRITE_REGISTER, Register.IRQ_CLEAR, new byte[] { 0xFF, 0xFF, 0x0F, 0x00 });
}
catch (TimeoutException tx)
{
#if DEBUG
_logger.LogError(tx, $"{nameof(WriteEeprom)}: {nameof(TimeoutException)} during {nameof(SpiWrite)}");
#endif
return false;
}
return ret;
}
#endregion
#region SEND and READ data from card
/// <summary>
/// Send data to a card.
/// </summary>
/// <param name="toSend">The span of byte to send</param>
/// <param name="numberValidBitsLastByte">The number of bits valid in the last byte, 8 is the default.
/// If validBits == 3 then it's equivalent to apply a mask of 0b000_0111 to get the correct valid bits</param>
/// <returns>True if success</returns>
/// <remarks>Using this function you'll have to manage yourself the possible low level communication protocol.
/// This function write directly to the card all the bytes. Please make sure you'll first load specific radio frequence settings,
/// detect a card, select it and then send data</remarks>
public bool SendDataToCard(SpanByte toSend, int numberValidBitsLastByte = 8)
{
if (toSend.Length > 260)
{
throw new ArgumentException(nameof(toSend), "Data to send can't be larger than 260 bytes");
}
if ((numberValidBitsLastByte < 1) || (numberValidBitsLastByte > 8))
{
throw new ArgumentException(nameof(numberValidBitsLastByte), "Number of valid bits in last byte can only be between 1 and 8");
}
SpanByte sendData = new byte[2 + toSend.Length];
sendData[0] = (byte)Command.SEND_DATA;
sendData[1] = (byte)(numberValidBitsLastByte == 8 ? 0 : numberValidBitsLastByte);
toSend.CopyTo(sendData.Slice(2));
#if DEBUG
_logger.LogDebug($"{nameof(SendDataToCard)}: {nameof(sendData)}, {BitConverter.ToString(sendData.ToArray())}");
#endif
try
{
SpiWrite(sendData);
}
catch (TimeoutException tx)
{
#if DEBUG
_logger.LogError(tx, $"{nameof(SendDataToCard)}: {nameof(TimeoutException)} in {nameof(SpiWrite)}");
#endif
return false;
}
return true;
}
/// <summary>
/// Read data from a card.
/// </summary>
/// <param name="toRead">The span of byte to read</param>
/// <returns>True if success</returns>
/// <remarks>Using this function you'll have to manage yourself the possible low level communication protocol.
/// This function write directly to the card all the bytes. Please make sure you'll first load specific radio frequence settings,
/// detect a card, select it and then send data</remarks>
public bool ReadDataFromCard(SpanByte toRead)
{
if (toRead.Length > 508)
{
throw new ArgumentException(nameof(toRead), "Data to read can't be larger than 508 bytes");
}
SpanByte sendData = new byte[2];
sendData[0] = (byte)Command.READ_DATA;
sendData[1] = 0x00;
#if DEBUG
_logger.LogDebug($"{nameof(ReadDataFromCard)}: {nameof(sendData)}, {BitConverter.ToString(sendData.ToArray())}");
#endif
try
{
SpiWriteRead(sendData, toRead);
#if DEBUG
_logger.LogDebug($"{nameof(ReadDataFromCard)}: {nameof(toRead)}, {BitConverter.ToString(toRead.ToArray())}");
#endif
}
catch (TimeoutException tx)
{
#if DEBUG
_logger.LogError(tx, $"{nameof(ReadDataFromCard)}: {nameof(TimeoutException)} in {nameof(SpiWriteRead)}");
#endif
return false;
}
return true;
}
/// <summary>
/// Read data from a card.
/// </summary>
/// <param name="toRead">>The span of byte to read</param>
/// <param name="expectedToRead">The expected number of bytes to read</param>
/// <returns>True if success. Will return false if the number of bytes to read is not the same as the expected number to read</returns>
/// <remarks>Using this function you'll have to manage yourself the possible low level communication protocol.
/// This function write directly to the card all the bytes. Please make sure you'll first load specific radio frequence settings,
/// detect a card, select it and then send data</remarks>
private bool ReadDataFromCard(SpanByte toRead, int expectedToRead)
{
var ret = GetNumberOfBytesReceivedAndValidBits();
int numBytes = ret.Bytes;
if (numBytes == expectedToRead)
{
#if DEBUG
_logger.LogDebug($"{nameof(ReadDataFromCard)}: right number of expected bytes to read");
#endif
return ReadDataFromCard(toRead);
}
else if (numBytes > expectedToRead)
{
#if DEBUG
_logger.LogDebug($"{nameof(ReadDataFromCard)}: wrong number of expected bytes, clearing the cache");
#endif
// Clear all
ReadDataFromCard(new byte[numBytes]);
}
return false;
}
/// <summary>
/// Read all the data from the card
/// </summary>
/// <param name="toRead">>The span of byte to read</param>
/// <param name="bytesRead">number of bytes read</param>
/// <returns>A byte array with all the read elements, null if nothing can be read</returns>
/// <remarks>Using this function you'll have to manage yourself the possible low level communication protocol.
/// This function write directly to the card all the bytes. Please make sure you'll first load specific radio frequence settings,
/// detect a card, select it and then send data</remarks>
public bool ReadDataFromCard(SpanByte toRead, out int bytesRead)
{
#if DEBUG
_logger.LogDebug($"{nameof(ReadDataFromCard)}: ");
#endif
var num = GetNumberOfBytesReceivedAndValidBits();
int numBytes = num.Bytes;
if (numBytes < 0)
{
bytesRead = 0;
return false;
}
var ret = ReadDataFromCard(toRead);
if (ret)
{
bytesRead = numBytes;
return true;
}
bytesRead = 0;
return false;
}
/// <summary>
/// Get the number of bytes to read and the valid number of bits in the last byte
/// If the full byte is valid then the value of the valid bit is 0
/// </summary>
/// <returns>A tuple whit the number of bytes to read and the number of valid bits in the last byte. If all bits are valid, then the value of valid bits is 0</returns>
public Doublet GetNumberOfBytesReceivedAndValidBits()
{
try
{
SpanByte status = new byte[4];
SpiReadRegister(Register.RX_STATUS, status);
// from NXP documentation PN5180AXX-C3.pdf, Page 98
return new Doublet((status[0] + ((status[1] & 0x01) << 8)), (status[1] & 0b1110_0000) >> 5);
}
catch (TimeoutException tx)
{
#if DEBUG
_logger.LogError(tx, $"{nameof(SendDataToCard)}: {nameof(TimeoutException)} in {nameof(SpiReadRegister)}");
#endif
return new Doublet(-1, -1);
}
}
/// <inheritdoc/>
public override int Transceive(byte targetNumber, SpanByte dataToSend, SpanByte dataFromCard)
{
// Check if we have a Mifare Card authentication request
// Only valid for Type A card so with a target number equal to 0
if (((targetNumber == 0) && ((dataToSend[0] == (byte)MifareCardCommand.AuthenticationA) || (dataToSend[0] == (byte)MifareCardCommand.AuthenticationB))) && (dataFromCard.Length == 0))
{
var ret = MifareAuthenticate(dataToSend.Slice(2, 6).ToArray(), (MifareCardCommand)dataToSend[0], dataToSend[1], dataToSend.Slice(8).ToArray());
return ret ? 0 : -1;
}
else
{
return TransceiveClassic(targetNumber, dataToSend, dataFromCard);
}
}
/// <inheritdoc/>
public override bool ReselectTarget(byte targetNumber)
{
if (targetNumber == 0)
{
// TODO: this should be implemented this for Type A card for this reader
// This will need to send WUPA (0x52 coded on 7 bits), Anti-collision and select loops like for initial detection
// We don't throw an exception, this is just telling that the selection failed
return false;
}
else
{
SelectedPiccInformation card = null;
for (int i = 0; i < _activeSelected.Count; i++)
{
if (_activeSelected[i].Card.TargetNumber == targetNumber)
{
card = _activeSelected[i];
break;
}
}
if (card is null)
{
return false;
}
DeselectCardTypeB(card.Card);
// Deselect may fail but if selection succeed it's ok
var ret = SelectCardTypeB(card.Card);
return ret;
}
}
private int TransceiveClassic(byte targetNumber, SpanByte dataToSend, SpanByte dataFromCard)
{
// type B card have a tag number which is always more than 1
if (targetNumber == 0)
{
// Case of a type A card
return TransceiveBuffer(dataToSend, dataFromCard);
}
else
{
const int MaxTries = 5;
// All the type B protocol 14443-4 is from the ISO14443-4.pdf from ISO website
// Original code: var card = _activeSelected.Where(m => m.Card.TargetNumber == targetNumber).FirstOrDefault();
SelectedPiccInformation card = null;
for (int i = 0; i < _activeSelected.Count; i++)
{
if (_activeSelected[i].Card.TargetNumber == targetNumber)
{
card = _activeSelected[i];
break;
}
}
if (card is null)
{
throw new ArgumentException(nameof(targetNumber), $"Device with target number {targetNumber} is not part of the list of selected devices. Card may have been removed.");
}
SpanByte toSend = new byte[dataToSend.Length + 2];
SpanByte toReceive = new byte[dataFromCard.Length + 2];
int maxTries = 0;
int maxTriesTimeout = 0;
// I-BLOCK command
// bit 8, 7, 6 to 0, bit 5 is chaining but we are not supporting it, so 0,
// bit 4 is CID and should be set to 1 as we have a device selected
// Bit 3 is NAD but we are not adding any prologue field
// bit 2 to 1
// bit 1 is tracking block
toSend[0] = (byte)(card.LastBlockMark ? 0b0000_1011 : 0b0000_1010);
// Second byte it the number (CID)
toSend[1] = targetNumber;
dataToSend.CopyTo(toSend.Slice(2));
var numBytes = TransceiveTypeB(card, toSend, toReceive);
RetryBlock:
if (numBytes == 0)
{
// That means timeout so sending an non acknowledged
SpanByte rBlock = new byte[2] { (byte)(0b1010_1010 | (card.LastBlockMark ? 1 : 0)), targetNumber };
var ret = SendDataToCard(rBlock);
if (!ret)
{
return -1;
}
if (maxTriesTimeout++ > MaxTries)
{
return -1;
}
numBytes = ReadWithTimeout(dataFromCard, (int)(toReceive[2] * card.Card.FrameWaitingTime / 1000));
goto RetryBlock;
}
if (numBytes < 0)
{
return -1;
}
IBlock:
if (numBytes >= 2)
{
// If not the right target, then not for us
if (toReceive[1] != targetNumber)
{
return -1;
}
// Is it a valid packet?
if (toReceive[0] == (0b0000_1010 | (card.LastBlockMark ? 1 : 0)))
{
toReceive.Slice(2).CopyTo(dataFromCard);
card.LastBlockMark = !card.LastBlockMark;
return numBytes - 2;
}
// Case of a chained packet, we need to send acknowledgment and read more data
if (toReceive[0] == (0b0001_1010 | (card.LastBlockMark ? 1 : 0)))
{
// Copy what we have already
toReceive.Slice(2, numBytes - 2).CopyTo(dataFromCard);
// Send Ack with the right mark
card.LastBlockMark = !card.LastBlockMark;
SpanByte rBlockChain = new byte[2] { (byte)(0b1010_1010 | (card.LastBlockMark ? 1 : 0)), targetNumber };
var numBytes2 = TransceiveTypeB(card, rBlockChain, toReceive);
if (numBytes2 >= 2)
{
// If not the right target, then not for us
if ((toReceive[1] & 0x0F) != targetNumber)
{
return -1;
}
if (toReceive[0] != (0b0000_1010 | (card.LastBlockMark ? 1 : 0)))
{
return -1;
}
toReceive.Slice(2, numBytes2 - 2).CopyTo(dataFromCard.Slice(numBytes - 2));
card.LastBlockMark = !card.LastBlockMark;
return numBytes - 2 + numBytes2 - 2;
}
}
// Is it an extension time block request block?
if (toReceive[0] == 0b1111_1010)
{
// Agree and send the same
SpanByte sBlock = new byte[] { 0b1111_1010, card.Card.TargetNumber, toReceive[2] };
var ret = SendDataToCard(sBlock);
if (maxTries++ == MaxTries)
{
return -1;
}
numBytes = ReadWithTimeout(dataFromCard, (int)(toReceive[2] * card.Card.FrameWaitingTime / 1000));
goto IBlock;
}
}
return numBytes;
}
}
private int TransceiveTypeB(SelectedPiccInformation card, SpanByte dataToSend, SpanByte dataFromCard)
{
var ret = SendDataToCard(dataToSend.ToArray());
if (!ret)
{
return -1;
}
return ReadWithTimeout(dataFromCard, (int)(card.Card.FrameWaitingTime / 1000));
}
private int ReadWithTimeout(SpanByte dataFromCard, int timeoutMilliseconds)
{
int numBytes = 0;
int numBytesPrevious = 0;
Doublet num;
// 10 etu needed for 1 byte, 1 etu = 9.4 µs, so about 100 µs are needed to transfer 1 character
DateTime dtTimeout = DateTime.UtcNow.AddMilliseconds(timeoutMilliseconds);
do
{
num = GetNumberOfBytesReceivedAndValidBits();
numBytes = num.Bytes;
// Do we have bytes?
if (numBytes > 0)
{
// Do we have read the same?
if (numBytes == numBytesPrevious)
{
break;
}
numBytesPrevious = numBytes;
}
// Wait to see if more characters are transmitted
// 10 etu needed for 1 byte, 1 etu = 9.4 µs, so about 100 µs are needed to transfer 1 character
// So waiting for 1 milliseconds will allow to make sure once done, all characters are
// transmitted between 2 reads
Thread.Sleep(1);
}
while (dtTimeout > DateTime.UtcNow);
if (numBytes > 0)
{
var ret = ReadDataFromCard(dataFromCard.Slice(0, numBytes));
if (!ret)
{
return -1;
}
}
return numBytes;
}
private int TransceiveBuffer(SpanByte dataToSend, SpanByte dataFromCard)
{
var ret = SendDataToCard(dataToSend.ToArray());
if (!ret)
{
return -1;
}
// 10 etu needed for 1 byte, 1 etu = 9.4 µs, so about 100 µs are needed to transfer 1 character
return ReadWithTimeout(dataFromCard, dataFromCard.Length / 100);
}
private bool SendRBlock(byte targetNumber, RBlock ack, int blockNumber)
{
if (!((blockNumber == 1) || (blockNumber == 0)))
{
throw new ArgumentException(nameof(blockNumber), "Value can be only 0 or 1.");
}
SpanByte rBlock = new byte[2] { (byte)(0b1010_1010 | (byte)ack | blockNumber), targetNumber };
var ret = SendDataToCard(rBlock);
var num = GetNumberOfBytesReceivedAndValidBits();
int numBytes = num.Bytes;
if (numBytes == 2)
{
ret = ReadDataFromCard(rBlock, numBytes);
return ret;
}
return false;
}
#endregion
#region Mifare specific
/// <summary>
/// Specific function to authenticate Mifare cards
/// </summary>
/// <param name="key">A 6 bytes key</param>
/// <param name="mifareCommand">MifareCardCommand.AuthenticationA or MifareCardCommand.AuthenticationB</param>
/// <param name="blockAddress">The block address to authenticate</param>
/// <param name="cardUid">The 4 bytes UUID of the card</param>
/// <returns>True if success</returns>
public bool MifareAuthenticate(SpanByte key, MifareCardCommand mifareCommand, byte blockAddress, SpanByte cardUid)
{
#if DEBUG
_logger.LogDebug($"{nameof(MifareAuthenticate)}: ");
#endif
if (key.Length != 6)
{
throw new ArgumentException(nameof(key), "Value must be 6 bytes.");
}
if (cardUid.Length != 4)
{
throw new ArgumentException(nameof(cardUid), "Value must be 4 bytes.");
}
if (!((mifareCommand == MifareCardCommand.AuthenticationA) || (mifareCommand == MifareCardCommand.AuthenticationB)))
{
throw new ArgumentException(nameof(mifareCommand), $"{nameof(MifareCardCommand.AuthenticationA)} and {nameof(MifareCardCommand.AuthenticationB)} are the only supported commands");
}
SpanByte toAuthenticate = new byte[13];
SpanByte response = new byte[1];
toAuthenticate[0] = (byte)Command.MIFARE_AUTHENTICATE;
key.CopyTo(toAuthenticate.Slice(1));
// Page 32 documentation PN5180A0XX-C3
toAuthenticate[7] = (byte)(mifareCommand == MifareCardCommand.AuthenticationA ? 0x60 : 0x61);
toAuthenticate[8] = blockAddress;
cardUid.CopyTo(toAuthenticate.Slice(9));
#if DEBUG
_logger.LogDebug($"{nameof(MifareAuthenticate)}: {nameof(toAuthenticate)}: {BitConverter.ToString(toAuthenticate.ToArray())}");
#endif
try
{
SpiWriteRead(toAuthenticate, response);
#if DEBUG
_logger.LogDebug($"{nameof(MifareAuthenticate)}: {nameof(response)}: {BitConverter.ToString(response.ToArray())}");
#endif
}
catch (TimeoutException tx)
{
#if DEBUG
_logger.LogError(tx, $"{nameof(ReadDataFromCard)}: {nameof(TimeoutException)} in {nameof(SpiWriteRead)}");
#endif
return false;
}
// Success is 0
return response[0] == 0;
}
#endregion
#region RadioFrequency
/// <summary>
/// Load a specific radio frequency configuration
/// </summary>
/// <param name="transmitter">The transmitter configuration</param>
/// <param name="receiver">The receiver configuration</param>
/// <returns>True if success</returns>
public bool LoadRadioFrequencyConfiguration(TransmitterRadioFrequencyConfiguration transmitter, ReceiverRadioFrequencyConfiguration receiver)
{
SpanByte rfConfig = new byte[3];
rfConfig[0] = (byte)Command.LOAD_RF_CONFIG;
rfConfig[1] = (byte)transmitter;
rfConfig[2] = (byte)receiver;
try
{
SpiWrite(rfConfig);
}
catch (TimeoutException)
{
return false;
}
return true;
}
/// <summary>
/// Get the size of the configuration of a specific transmitter configuration
/// </summary>
/// <param name="transmitter">The transmitter configuration</param>
/// <returns>True if success</returns>
public int GetRadioFrequencyConfigSize(TransmitterRadioFrequencyConfiguration transmitter) => GetRadioFrequencyConfigSize((byte)transmitter);
/// <summary>
/// Get the size of the configuration of a specific receiver configuration
/// </summary>
/// <param name="receiver">The receiver configuration</param>
/// <returns>True if success</returns>
public int GetRadioFrequencyConfigSize(ReceiverRadioFrequencyConfiguration receiver) => GetRadioFrequencyConfigSize((byte)receiver);
private int GetRadioFrequencyConfigSize(byte config)
{
SpanByte rfConfig = new byte[2];
SpanByte response = new byte[1];
rfConfig[0] = (byte)Command.RETRIEVE_RF_CONFIG_SIZE;
rfConfig[1] = config;
try
{
SpiWriteRead(rfConfig, response);
}
catch (TimeoutException)
{
return -1;
}
return response[0];
}
/// <summary>
/// Retrieve the radio frequency configuration
/// </summary>
/// <param name="transmitter">The transmitter configuration</param>
/// <param name="configuration">A span of bytes for the configuration. Should be a multiple of 5 with the size of <see ref="GetRadioFrequenceConfigSize"/></param>
/// <returns>True if success</returns>
public bool RetrieveRadioFrequencyConfiguration(TransmitterRadioFrequencyConfiguration transmitter, SpanByte configuration) => RetrieveRadioFrequencyConfiguration((byte)transmitter, configuration);
/// <summary>
/// Retrieve the radio frequency configuration
/// </summary>
/// <param name="receiver">The receiver configuration</param>
/// <param name="configuration">A span of bytes for the configuration. Should be a multiple of 5 with the size of <see ref="GetRadioFrequenceConfigSize"/></param>
/// <returns>True if success</returns>
public bool RetrieveRadioFrequencyConfiguration(ReceiverRadioFrequencyConfiguration receiver, SpanByte configuration) => RetrieveRadioFrequencyConfiguration((byte)receiver, configuration);
private bool RetrieveRadioFrequencyConfiguration(byte config, SpanByte configuration)
{
// Page 41 documentation PN5180A0XX-C3.pdf
if ((configuration.Length > 195) || (configuration.Length % 5 != 0) || (configuration.Length == 0))
{
throw new ArgumentException(nameof(configuration), "Value must be a positive multiple of 5 and no larger than 195 bytes.");
}
SpanByte rfConfig = new byte[2];
rfConfig[0] = (byte)Command.RETRIEVE_RF_CONFIG;
rfConfig[1] = (byte)config;
try
{
SpiWriteRead(rfConfig, configuration);
}
catch (TimeoutException)
{
return false;
}
return true;
}
/// <summary>
/// Update the radio frequency configuration
/// </summary>
/// <param name="transmitter">The transmitter configuration</param>
/// <param name="configuration">A span of bytes for the configuration. Should be a multiple of 5 with the size of <see ref="GetRadioFrequenceConfigSize"/></param>
/// <returns>True if success</returns>
public bool UpdateRadioFrequencyConfiguration(TransmitterRadioFrequencyConfiguration transmitter, SpanByte configuration) => UpdateRadioFrequenceConfiguration((byte)transmitter, configuration);
/// <summary>
/// Update the radio frequency configuration
/// </summary>
/// <param name="receiver">The receiver configuration</param>
/// <param name="configuration">A span of bytes for the configuration. Should be a multiple of 5 with the size of <see ref="GetRadioFrequenceConfigSize"/></param>
/// <returns>True if success</returns>
public bool UpdateRadioFrequencyConfiguration(ReceiverRadioFrequencyConfiguration receiver, SpanByte configuration) => UpdateRadioFrequenceConfiguration((byte)receiver, configuration);
private bool UpdateRadioFrequenceConfiguration(byte config, SpanByte configuration)
{
// Page 41 documentation PN5180A0XX-C3.pdf
if ((configuration.Length > 252) || (configuration.Length % 6 != 0) || (configuration.Length == 0))
{
throw new ArgumentException(nameof(configuration), "Value must be a positive multiple of 6 and no larger than 252 bytes.");
}
SpanByte rfConfig = new byte[1 + configuration.Length];
rfConfig[0] = (byte)Command.UPDATE_RF_CONFIG;
configuration.CopyTo(rfConfig.Slice(1));
try
{
SpiWrite(rfConfig);
}
catch (TimeoutException)
{
return false;
}
return true;
}
/// <summary>
/// True to disable the Radio Frequency collision avoidance according to ISO/IEC 18092
/// False to use Active Communication mode according to ISO/IEC 18092
/// </summary>
public RadioFrequencyCollision RadioFrequencyCollision { get; set; } = RadioFrequencyCollision.Normal;
/// <summary>
/// Get or set the radio frequency field. True for on, false for off
/// </summary>
public bool RadioFrequencyField
{
get
{
SpanByte status = new byte[4];
try
{
SpiReadRegister(Register.RF_STATUS, status);
}
catch (TimeoutException)
{
return false;
}
return (status[2] & 0b1000_0000) == 0b1000_0000;
}
set
{
SetRadioFrequency(value);
}
}
/// <summary>
/// Get the radio frenquency status
/// </summary>
/// <returns>The radio frequence status</returns>
public RadioFrequencyStatus GetRadioFrequencyStatus()
{
SpanByte status = new byte[4];
try
{
SpiReadRegister(Register.RF_STATUS, status);
}
catch (TimeoutException)
{
return RadioFrequencyStatus.Error;
}
return (RadioFrequencyStatus)((status[2] >> 1) & 0x07);
}
/// <summary>
/// Is the external field activated?
/// </summary>
/// <returns>True if active, false if not</returns>
public bool IsRadioFrequencyFieldExternal()
{
SpanByte status = new byte[4];
try
{
SpiReadRegister(Register.RF_STATUS, status);
}
catch (TimeoutException)
{
return false;
}
return (status[2] & 0b0000_0100) == 0b0000_0100;
}
private bool SetRadioFrequency(bool fieldOn)
{
SpanByte rfConfig = new byte[2];
rfConfig[0] = (byte)(fieldOn ? Command.RF_ON : Command.RF_OFF);
rfConfig[1] = (byte)RadioFrequencyCollision;
try
{
SpiWrite(rfConfig);
}