forked from nanoframework/nanoFramework.IoT.Device
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Pn532.cs
2278 lines (2060 loc) · 82.1 KB
/
Pn532.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.Generic;
using System.Device.Gpio;
using System.Device.I2c;
using System.Device.Spi;
using System.IO;
using System.IO.Ports;
using System.Threading;
using Iot.Device.Card;
using Iot.Device.Pn532.AsTarget;
using Iot.Device.Pn532.ListPassive;
using Iot.Device.Pn532.RfConfiguration;
using Iot.Device.Rfid;
using Iot.Device.Pn532;
#if DEBUG
using Microsoft.Extensions.Logging;
using nanoFramework.Logging;
#endif
namespace Iot.Device.Pn532
{
/// <summary>
/// PN532 RFID/NFC reader
/// </summary>
public class Pn532 : CardTransceiver, IDisposable
{
private const int I2cMaxBuffer = 1024;
// Communication way
private const byte ToHostCheckSumD5 = 0xD5;
private const byte FromHostCheckSumD4 = 0xD4;
// Preamble, codes and postamble
private const byte Preamble = 0x00;
private const byte Postamble = 0x00;
private const byte StartCode1 = 0x00;
private const byte StartCode2 = 0xFF;
// Operation type for SPI
private const byte WriteData = 0b0000_0001;
private const byte ReadStatus = 0b0000_0010;
private const byte ReadData = 0b0000_0011;
// Acknowledge
private byte[] _ackBuffer = { 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00 };
// Specific buffer to wake up the sensor in serial HSU mode
private byte[] _serialWakeUp = new byte[]
{
0x55, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
private byte[] _i2CWakeUp = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
private ParametersFlags _parametersFlags;
private SpiDevice _spiDevice = null;
private I2cDevice _i2cDevice = null;
private GpioController _controller = null;
private SerialPort _serialPort = null;
private int _pin = 18;
private bool _shouldDispose;
private SecurityAccessModuleMode _securityAccessModuleMode = SecurityAccessModuleMode.Normal;
private uint _virtualCardTimeout = 0x17;
#if DEBUG
private ILogger _logger;
#endif
/// <summary>
/// Set or get the read timeout for I2C and SPI
/// Please refer to the documentation to set the right
/// timeout value depending on the communication
/// mode you are using
/// </summary>
public int ReadTimeOut { get; set; } = 500;
/// <summary>
/// Firmware version information
/// </summary>
public FirmwareVersion? FirmwareVersion { get; internal set; }
#region Spi and I2c Settings
/// <summary>
/// PN532 SPI Clock Frequency
/// </summary>
public const int SpiClockFrequency = 2_000_000;
/// <summary>
/// Only SPI Mode supported is Mode0
/// </summary>
public const SpiMode SpiMode = System.Device.Spi.SpiMode.Mode0;
/// <summary>
/// The default I2C address
/// </summary>
public const byte I2cDefaultAddress = 0x24;
#endregion
/// <summary>
/// Create a PN532 using Serial Port
/// </summary>
/// <param name="portName">The port name</param>
public Pn532(string portName)
{
#if DEBUG
_logger = this.GetCurrentClassLogger();
#endif
// Data bit : 8 bits,
// Parity bit : none,
// Stop bit : 1 bit,
// Baud rate : 115 200 bauds,
#if DEBUG
_logger.LogDebug("Opening serial port 115200, Parity.None, 8 bits, StopBits.One");
#endif
_serialPort = new SerialPort(portName, 115200, Parity.None, 8, StopBits.One);
// Documentation page 39, serial timeout is 89 ms for 115 200
_serialPort.ReadTimeout = 89;
_serialPort.WriteTimeout = 89;
_serialPort.Open();
// Setting up internals as default version
_parametersFlags = ParametersFlags.AutomaticATR_RES | ParametersFlags.AutomaticRATS |
ParametersFlags.ISO14443_4_PICC;
_securityAccessModuleMode = SecurityAccessModuleMode.Normal;
_virtualCardTimeout = 0x17;
WakeUp();
// Set the SAM
bool ret = SetSecurityAccessModule();
#if DEBUG
_logger.LogInformation($"Setting SAM changed: {ret}");
#endif
// Check the version
if (!IsPn532())
{
throw new Exception("Can't find a PN532");
}
// Apply default parameters
ret = SetParameters(ParametersFlags.AutomaticATR_RES | ParametersFlags.AutomaticRATS);
#if DEBUG
_logger.LogInformation($"Setting Parameters Flags changed: {ret}");
#endif
}
/// <summary>
/// Create a PN532 using SPI
/// </summary>
/// <param name="spiDevice">The SPI Device</param>
/// <param name="pinChipSelect">The GPIO pin number for the chip select</param>
/// <param name="controller">A GPIO controller</param>
/// <param name="shouldDispose">Dispose the GPIO Controller at the end</param>
public Pn532(SpiDevice spiDevice, int pinChipSelect, GpioController? controller = null, bool shouldDispose = false)
{
#if DEBUG
_logger = this.GetCurrentClassLogger();
#endif
_spiDevice = spiDevice ?? throw new ArgumentNullException(nameof(spiDevice));
_shouldDispose = shouldDispose || controller == null;
_controller = controller ?? new GpioController();
_pin = pinChipSelect >= 0 ? pinChipSelect : throw new ArgumentException($"Pin ChipSelect can only be positive");
_controller.OpenPin(_pin, PinMode.Output);
_controller.Write(_pin, PinValue.High);
Thread.Sleep(2);
WakeUp();
// The first time we apply SAM after waking up the device, it always
// returns false, some timeout appear. So we will need to apply a second time
bool ret = SetSecurityAccessModule();
#if DEBUG
_logger.LogInformation($"Setting SAM changed: {ret}");
#endif
// Check the version
if (!IsPn532())
{
throw new Exception("Can't find a PN532");
}
// Apply default parameters
ret = SetParameters(ParametersFlags.AutomaticATR_RES | ParametersFlags.AutomaticRATS);
#if DEBUG
_logger.LogInformation($"Setting Parameters Flags changed: {ret}");
#endif
ret = SetSecurityAccessModule();
#if DEBUG
_logger.LogInformation($"Setting SAM changed: {ret}");
#endif
}
/// <summary>
/// Create a PN532 using I2C
/// </summary>
/// <param name="i2cDevice">The I2C device</param>
public Pn532(I2cDevice i2cDevice)
{
#if DEBUG
_logger = this.GetCurrentClassLogger();
#endif
_i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
WakeUp();
bool ret = SetSecurityAccessModule();
#if DEBUG
_logger.LogInformation($"Setting SAM changed: {ret}");
#endif
// Check the version
if (!IsPn532())
{
throw new Exception("Can't find a PN532");
}
// Apply default parameters
ret = SetParameters(ParametersFlags.AutomaticATR_RES | ParametersFlags.AutomaticRATS);
#if DEBUG
_logger.LogInformation($"Setting Parameters Flags changed: {ret}");
#endif
ret = SetSecurityAccessModule();
#if DEBUG
_logger.LogInformation($"Setting SAM changed: {ret}");
#endif
}
/// <summary>
/// Run self tests
/// Note: some self tests are not implemented yet
/// </summary>
/// <param name="diagnoseMode">The self test to run</param>
/// <returns>True when success</returns>
public bool RunSelfTest(DiagnoseMode diagnoseMode)
{
int ret = 0;
SpanByte singleParam = new byte[1]
{
(byte)diagnoseMode
};
switch (diagnoseMode)
{
case DiagnoseMode.CommunicationLineTest:
// NumTst = 0x00: Communication Line Test
// This test is for communication test between host controller and the PN532. “Parameter
// Length” and “Parameters” in response packet are same as “Parameter Length” and
// “Parameter” in command packet.
// − Parameter Length : m (0 <= m <= 262),
// − Parameter : Data,
// − Result Length : Same value of m + 1.
// OutParam consists of NumTst concatenate with InParam.
SpanByte toTest = new byte[9]
{
(byte)DiagnoseMode.CommunicationLineTest,
0x11,
0x22,
0x33,
0x44,
0x55,
0x66,
0x77,
0x88
};
ret = WriteCommand(CommandSet.Diagnose, toTest);
if (ret < 0)
{
return false;
}
SpanByte resultTest = new byte[9];
ret = ReadResponse(CommandSet.Diagnose, resultTest);
#if DEBUG
_logger.LogDebug($"{diagnoseMode} received: {BitConverter.ToString(resultTest.ToArray())}, ret: {ret}");
#endif
return resultTest.SequenceEqual(toTest) && (ret >= 0);
case DiagnoseMode.ROMTest:
// NumTst = 0x01: ROM Test
// This test is for checking ROM data by 8 bits checksum.
// − Parameter Length : 0,
// − Result Length : 1,
// − Result : 0x00 is OK,
// 0xFF is Not Good
ret = WriteCommand(CommandSet.Diagnose, singleParam);
if (ret < 0)
{
return false;
}
// Wait for the test to run
Thread.Sleep(1500);
SpanByte romTest = new byte[1];
ret = ReadResponse(CommandSet.Diagnose, romTest);
#if DEBUG
_logger.LogDebug($"{diagnoseMode} received: {BitConverter.ToString(romTest.ToArray())}, ret: {ret}");
#endif
// Wait for the test to run
// TODO: find the right timing, this is empirical
Thread.Sleep(100);
return (romTest[0] == 0) && (ret >= 0);
case DiagnoseMode.RAMTest:
// NumTst = 0x02: RAM Test
// This test is for checking RAM; 768 bytes of XRAM and 128 bytes of IDATA.
// The test method used consists of saving original content, writing test data, checking test
// data and finally restore original data. So, this test is non destructive.
// − Parameter Length : 0,
// − Result Length : 1,
// − Result : 0x00 is OK,
// 0xFF is Not Good.
ret = WriteCommand(CommandSet.Diagnose, singleParam);
if (ret < 0)
{
return false;
}
// Wait for the test to run
// TODO: find the right timing, this is empirical
Thread.Sleep(1500);
SpanByte ramTest = new byte[1];
ret = ReadResponse(CommandSet.Diagnose, ramTest);
#if DEBUG
_logger.LogDebug($"{diagnoseMode} received: {BitConverter.ToString(ramTest.ToArray())}, ret: {ret}");
#endif
Thread.Sleep(100);
return (ramTest[0] == 0) && (ret >= 0);
case DiagnoseMode.PollingTestToTarget:
// NumTst = 0x04 : Polling Test to Target
// This test is for checking the percentage of failure regarding response packet receiving
// after polling command transmission. In this test, the PN532 sends a FeliCa polling
// command packet 128 times to target. The PN532 counts the number of fails and returns
// the failed number to host controller. This test doesn’t require specific system code for
// target.
// Polling is done with system code (0xFF, 0xFF). The baud rate used is either 212 kbps or
// 424 kbps.
// One polling is considered as defective after no correct polling response within 4 ms.
// During this test, the analog settings used are those defined in command
// RFConfiguration within the item n°7 (§7.3.1, p: 101).
// − Parameter Length : 1,
// − Parameter : 0x01 is 212 kbps,
// 0x02 is 424 kbps.
// − Result Length : 1,
// − Result : Number of fails (Maximum 128).
throw new NotImplementedException($"Test {diagnoseMode} not implemented");
case DiagnoseMode.EchoBackTest:
// NumTst = 0x05 : Echo Back Test
// In this test, the PN532 is configured in target mode. The analog settings used are those
// defined by using the command RFConfiguration with the item n°6 (§7.3.1, p: 101).
// This test is running as long as a new command is not received from the host controller.
// The principle of this test is that the PN532 waits for a command frame coming from the
// initiator and after the Reply Delay, sends it back to it whatever its content and its length
// are.
// − Parameter Length : 3,
// − Parameter 1 : Reply Delay (step of 0.5 ms),
// − Parameter 2 : Content of the CIU_TxMode (@0x6302) register
// defining the baud rate and the modulation type in
// transmission,
// − Parameter 3 : Content of the CIU_RxMode (@0x6303) register
// defining the baud rate and the modulation type in
// reception,
// − Result Length : no result, the test runs infinitely, so no output frame is
// sent to the host controller.
// For example:
// − The PN532 is configured to receive frame with passive 106 kbps modulation
// type. The frames are sent back immediately.
// The MSB bit (CRC enable) of CIU_TxMode and CIU_RxMode must be set to 0.
// D4 00 05 00 00 00
// − The PN532 is configured to receive frame with passive 212 kbps modulation
// type. The frames are sent back with a delay of 64 ms.
// The MSB bit (CRC enable) of CIU_TxMode and CIU_RxMode must be set to 1.
// D4 00 05 80 92 92
// − The PN532 is configured to receive frame with passive 424 kbps modulation
// type. The frames are sent back immediately.
// The MSB bit (CRC enable) of CIU_TxMode and CIU_RxMode must be set to 1.
// D4 00 05 00 A2 A2
throw new NotImplementedException($"Test {diagnoseMode} not implemented");
case DiagnoseMode.AttentionRequestTest:
// NumTst = 0x06 : Attention Request Test or ISO/IEC14443-4 card presence detection
// This test can be used by an initiator to ensure that a target/card is still in the field:
// o In case of DEP target, an Attention Request command is sent to the target, and it
// is expected to receive the same answer from the target. In that case, the test is
// declared as successful;
// o In case of ISO/IEC14443-4 card, a R(NACK) block is sent to the card and it is
// expected to receive either a R(ACK) block or the last I-Block. In that case, the test
// is declared as successful (ISO/IEC14443-4 card is still in the RF field).
// In case of no or incorrect response, the Result informs about the status of the transaction
// (refer. to §7.1, p:67)
// − Parameter Length : 0,
// − Result Length : 1,
// − Result : 0x00 is OK,
// different from 0x00 is Not OK, Status byte.
throw new NotImplementedException($"Test {diagnoseMode} not implemented");
case DiagnoseMode.SelfAntenaTest:
// NumTst = 0x07 : Self Antenna Test
// This test is used to check the continuity of the transmission paths of the antenna.
// − Parameter Length : 1,
// − Parameter : Threshold used for antenna detection
// (applied in register Andet_Control (@610C), see Error!
// Reference source not found.),
// 7 6 5 4 3 2 1 0
// andet_bot andet_up andet_ithl[1:0] andet_ithh[1:0] andet_en
// − Result Length : 1,
// − Result : 0x00 is OK (antenna is detected),
// different from 0x00 is not OK (no antenna is detected).
throw new NotImplementedException($"Test {diagnoseMode} not implemented");
default:
break;
}
return false;
}
/// <summary>
/// Get or set the timeout when PN532 is in virtual card mode
/// </summary>
public uint VirtualCardTimeout
{
get => _virtualCardTimeout * 50;
set
{
// Timeout defines the time-out only in Virtual card configuration (Mode = 0x02).
// In Virtual Card mode, this field is mandatory; whereas in the other mode, it is optional.
// This parameter indicates the timeout value with a LSB of 50ms.
// There is no timeout control if the value is null (Timeout = 0).
// The maximum value for the timeout is 12.75 sec (Timeout = 0xFF).
if (value / 50 > 0xFF)
{
throw new ArgumentException(nameof(VirtualCardTimeout), "Value must be 12750 milliseconds or less.");
}
_virtualCardTimeout = value / 50;
bool ret = SetSecurityAccessModule();
#if DEBUG
_logger.LogDebug($"{nameof(VirtualCardTimeout)} changed: {ret}");
#endif
}
}
/// <summary>
/// Get or set the Security Access Module Mode
/// </summary>
public SecurityAccessModuleMode SecurityAccessModuleMode
{
get => _securityAccessModuleMode;
set
{
bool ret = SetSecurityAccessModule();
#if DEBUG
_logger.LogDebug($"{nameof(SecurityAccessModuleMode)} changed: {ret}");
#endif
}
}
private bool SetSecurityAccessModule()
{
// Pass the SAM, the virtual card timeout and remove IRQ
SpanByte toSend = new byte[3]
{
(byte)_securityAccessModuleMode,
(byte)(_virtualCardTimeout),
0x00
};
var ret = WriteCommand(CommandSet.SAMConfiguration, toSend);
#if DEBUG
_logger.LogDebug($"{nameof(SetSecurityAccessModule)} Write: {ret}");
#endif
if (ret < 0)
{
return false;
}
// We don't expect any result, just that the command went well
ret = ReadResponse(CommandSet.SAMConfiguration, SpanByte.Empty);
#if DEBUG
_logger.LogDebug($"{nameof(SetSecurityAccessModule)} read: {ret}");
#endif
return ret >= 0;
}
private bool IsPn532()
{
var ret = WriteCommand(CommandSet.GetFirmwareVersion);
#if DEBUG
_logger.LogInformation($"GetFirmwareVersion write command returned: {ret}");
#endif
if (ret < 0)
{
return false;
}
SpanByte firmware = new byte[4];
ret = ReadResponse(CommandSet.GetFirmwareVersion, firmware);
var ver = firmware.ToArray();
if (ret >= 0)
{
FirmwareVersion = new FirmwareVersion(
firmware[0], // IdentificationCode
new Version(firmware[1], firmware[2]), // Version
(VersionSupported)(firmware[3] & 0b0000_0111)); // VersionSupported
}
#if DEBUG
_logger.LogInformation($"GetFirmwareVersion read command returned: {ret} - Bytes {BitConverter.ToString(ver)}");
#endif
return ret >= 0;
}
/// <summary>
/// Get or set the Security Access Module parameters
/// </summary>
public ParametersFlags ParametersFlags
{
get => _parametersFlags;
set
{
if (SetParameters(value))
{
_parametersFlags = value;
}
}
}
private bool SetParameters(ParametersFlags parametersFlags)
{
SpanByte toSend = new byte[1]
{
(byte)parametersFlags
};
var ret = WriteCommand(CommandSet.SetParameters, toSend);
if (ret < 0)
{
return false;
}
ret = ReadResponse(CommandSet.SetParameters, SpanByte.Empty);
#if DEBUG
_logger.LogDebug($"{nameof(SetParameters)}: {ret}");
#endif
return ret >= 0;
}
/// <summary>
/// List all targets cards in range
/// When using this function, you can't determine which target you've read
/// So you'll need to use the Decode functions to try to get a card type
/// So use this function only with a specific card type. Prefer the AutoPoll function
/// As the type identified is returned
/// </summary>
/// <param name="maxTarget">The maximum number of targets</param>
/// <param name="targetBaudRate">The baud rate to use</param>
/// <returns>A raw byte array with the data of the targets if any has been identified</returns>
public byte[] ListPassiveTarget(MaxTarget maxTarget, TargetBaudRate targetBaudRate)
{
return ListPassiveTarget(maxTarget, targetBaudRate, SpanByte.Empty);
}
/// <summary>
/// List all targets cards in range
/// When using this function, you can't determine which target you've read
/// So you'll need to use the Decode functions to try to get a card type
/// So use this function only with a specific card type. Prefer the AutoPoll function
/// As the type identified is returned
/// </summary>
/// <param name="maxTarget">The maximum number of targets</param>
/// <param name="targetBaudRate">The baud rate to use to find cards</param>
/// <param name="initiatorData">Specific initialization data</param>
/// <returns>A raw byte array with the data of the targets if any has been identified</returns>
public byte[] ListPassiveTarget(MaxTarget maxTarget, TargetBaudRate targetBaudRate,
SpanByte initiatorData)
{
SpanByte toSend = new byte[2 + initiatorData.Length];
toSend[0] = (byte)maxTarget;
toSend[1] = (byte)targetBaudRate;
if (initiatorData.Length > 0)
{
initiatorData.CopyTo(toSend.Slice(2));
}
var ret = WriteCommand(CommandSet.InListPassiveTarget, toSend);
if (ret < 0)
{
return null;
}
// TODO: check what is the real maximum size
SpanByte listData = new byte[1024];
ret = ReadResponse(CommandSet.InListPassiveTarget, listData);
#if DEBUG
_logger.LogDebug($"{nameof(ListPassiveTarget)}: {ret}, number tags: {listData[0]}");
#endif
if ((ret >= 0) && (listData[0] > 0))
{
return listData.Slice(0, ret).ToArray();
}
return null;
}
/// <summary>
/// Try to decode a raw byte array containing target information
/// to a 106 kbps Type A card
/// </summary>
/// <param name="toDecode">The raw byte array</param>
/// <returns>A decoded card of null if it can't</returns>
public Data106kbpsTypeA TryDecode106kbpsTypeA(SpanByte toDecode)
{
try
{
byte[] nfcId = new byte[toDecode[4]];
byte[] ats = new byte[0];
for (int i = 0; i < nfcId.Length; i++)
{
nfcId[i] = toDecode[5 + i];
}
if ((5 + nfcId.Length) > toDecode.Length)
{
ats = new byte[toDecode[5 + nfcId.Length]];
for (int i = 0; i < ats.Length; i++)
{
ats[i] = toDecode[6 + nfcId.Length + i];
}
}
Data106kbpsTypeA data = new Data106kbpsTypeA(
toDecode[0], // TargetNumber
BinaryPrimitives.ReadUInt16BigEndian(toDecode.Slice(1)), // Atqa
toDecode[3], // Sak
nfcId,
ats);
return data;
}
catch (ArgumentOutOfRangeException)
{
return null;
}
}
/// <summary>
/// Try to decode a raw byte array containing target information
/// to a 106 kbps Type B card
/// </summary>
/// <param name="toDecode">The raw byte array</param>
/// <returns>A decoded card of null if it can't</returns>
public Data106kbpsTypeB TryDecodeData106kbpsTypeB(SpanByte toDecode)
{
try
{
Data106kbpsTypeB data = new Data106kbpsTypeB(toDecode.Slice(1).ToArray());
data.TargetNumber = toDecode[0];
return data;
}
catch (ArgumentOutOfRangeException)
{
return null;
}
}
/// <summary>
/// Try to decode a raw byte array containing target information
/// to a 212 424 kbps card
/// </summary>
/// <param name="toDecode">The raw byte array</param>
/// <returns>A decoded card of null if it can't</returns>
public Data212_424kbps TryDecodeData212_424Kbps(SpanByte toDecode)
{
try
{
if ((toDecode[1] != 18) || (toDecode[1] != 20))
{
return null;
}
byte[] systemCode = new byte[2];
byte[] nfcId = new byte[8];
byte[] pad = new byte[8];
toDecode.Slice(3, 8).CopyTo(nfcId);
toDecode.Slice(11, 8).CopyTo(pad);
if (toDecode[1] == 20)
{
toDecode.Slice(19, 2).CopyTo(systemCode);
}
Data212_424kbps data = new Data212_424kbps(
toDecode[0], // TargetNumber
toDecode[2], // ResponseCode
nfcId,
pad,
systemCode);
return data;
}
catch (ArgumentOutOfRangeException)
{
return null;
}
}
/// <summary>
/// Try to decode a raw byte array containing target information
/// to a 106 kbps Innovision Jewel card
/// </summary>
/// <param name="toDecode">The raw byte array</param>
/// <returns>A decoded card of null if it can't</returns>
public Data106kbpsInnovisionJewel TryDecodeData106kbpsInnovisionJewel(SpanByte toDecode)
{
try
{
Data106kbpsInnovisionJewel data = new Data106kbpsInnovisionJewel(
toDecode[0], // TargetNumber
new byte[2] { toDecode[1], toDecode[2] }, // Atqa
new byte[4] { toDecode[3], toDecode[4], toDecode[5], toDecode[6] }); // JewelId
return data;
}
catch (ArgumentOutOfRangeException)
{
return null;
}
}
/// <summary>
/// Deselect a specific target number card
/// </summary>
/// <param name="targetNumber">Target number card</param>
/// <returns>True if success</returns>
public bool DeselectTarget(byte targetNumber)
{
SpanByte toSend = new byte[1]
{
targetNumber
};
var ret = WriteCommand(CommandSet.InDeselect, toSend);
if (ret < 0)
{
return false;
}
ret = ReadResponse(CommandSet.InDeselect, toSend);
return (toSend[0] == (byte)ErrorCode.None) && (ret >= 0);
}
/// <summary>
/// Select a specific target number card
/// </summary>
/// <param name="targetNumber">Target number card</param>
/// <returns>True if success</returns>
public bool SelectTarget(byte targetNumber)
{
SpanByte toSend = new byte[1]
{
targetNumber
};
var ret = WriteCommand(CommandSet.InSelect, toSend);
if (ret < 0)
{
return false;
}
ret = ReadResponse(CommandSet.InSelect, toSend);
return (toSend[0] == (byte)ErrorCode.None) && (ret >= 0);
}
/// <summary>
/// Release a specific target number card
/// </summary>
/// <param name="targetNumber">Target number card</param>
/// <returns>True if success</returns>
public bool ReleaseTarget(byte targetNumber)
{
SpanByte toSend = new byte[1]
{
targetNumber
};
var ret = WriteCommand(CommandSet.InRelease, toSend);
if (ret < 0)
{
return false;
}
ret = ReadResponse(CommandSet.InRelease, toSend);
return (toSend[0] == (byte)ErrorCode.None) && (ret >= 0);
}
/// <summary>
/// Write an array of data directly to the card without adding anything
/// from the PN532 and read the raw data
/// </summary>
/// <param name="dataToSend">The data to write to the card</param>
/// <param name="dataFromCard">The potential data to receive</param>
/// <returns>The number of bytes read</returns>
public int WriteReadDirect(SpanByte dataToSend, SpanByte dataFromCard)
{
var ret = WriteCommand(CommandSet.InCommunicateThru, dataToSend);
if (ret < 0)
{
return -1;
}
if (dataFromCard.Length > 0)
{
SpanByte toReceive = new byte[1 + dataFromCard.Length];
ret = ReadResponse(CommandSet.InCommunicateThru, toReceive);
toReceive.Slice(1).CopyTo(dataFromCard);
if ((toReceive[0] == (byte)ErrorCode.None) && (ret > 0))
{
return ret - 1;
}
return -1;
}
else
{
return 0;
}
}
/// <summary>
/// Write data to a card and read what the card responses
/// </summary>
/// <param name="targetNumber">The card target number</param>
/// <param name="dataToSend">The data to write to the card</param>
/// <param name="dataFromCard">The potential data to receive</param>
/// <returns>The number of bytes read</returns>
public override int Transceive(byte targetNumber, SpanByte dataToSend, SpanByte dataFromCard)
{
// We need to add some logic here to understand what the command is and the size of the needed buffer.
// For Mifare card, the authentications needs to use the native part.
// For non Mifare card, it should not.
if (((dataToSend[0] == 0x60) || (dataToSend[0] == 0x61)) && (dataFromCard.Length == 0))
{
return TransceiveAdvance(targetNumber, dataToSend, dataFromCard);
}
else
{
return WriteReadDirect(dataToSend, dataFromCard);
}
}
/// <summary>
/// Use the build in feature to transceive the data to the card. This add specific logic for some cards.
/// </summary>
/// <param name="targetNumber">The card target number</param>
/// <param name="dataToSend">The data to write to the card</param>
/// <param name="dataFromCard">The potential data to receive</param>
/// <returns>The number of bytes read</returns>
public int TransceiveAdvance(byte targetNumber, SpanByte dataToSend, SpanByte dataFromCard)
{
SpanByte toSend = new byte[1 + dataToSend.Length];
toSend[0] = targetNumber;
if (dataToSend.Length > 0)
{
dataToSend.CopyTo(toSend.Slice(1));
}
var ret = WriteCommand(CommandSet.InDataExchange, toSend);
if (ret < 0)
{
return -1;
}
SpanByte toReceive = new byte[1 + dataFromCard.Length];
ret = ReadResponse(CommandSet.InDataExchange, toReceive);
toReceive.Slice(1).CopyTo(dataFromCard);
if ((toReceive[0] == (byte)ErrorCode.None) && (ret > 0))
{
return ret - 1;
}
return -1;
}
/// <inheritdoc/>
public override bool ReselectTarget(byte targetNumber)
{
// First one doesn't need to succeed, only the select needs
DeselectTarget(targetNumber);
var ret = SelectTarget(targetNumber);
return ret;
}
/// <summary>
/// Automatically poll specific types of devices
/// </summary>
/// <param name="numberPolling">The number of polling before accepting a card</param>
/// <param name="periodMilliSecond">The period of polling before accepting a card</param>
/// <param name="pollingType">The type of cards to poll</param>
/// <returns>A raw byte array containing the number of cards, the card type and the raw data. Null if nothing has been polled</returns>
public byte[] AutoPoll(byte numberPolling, ushort periodMilliSecond, PollingType[] pollingType)
{
if (pollingType is null or { Length: > 15 })
{
return null;
}
SpanByte toSend = new byte[2 + pollingType.Length];
toSend[0] = numberPolling;
if ((periodMilliSecond / 150) > 0xFF)
{
toSend[1] = 0xFF;
}
else
{
toSend[1] = (byte)(periodMilliSecond / 150);
}
for (int i = 0; i < pollingType.Length; i++)
{
toSend[2 + i] = (byte)pollingType[i];
}
var ret = WriteCommand(CommandSet.InAutoPoll, toSend);
if (ret < 0)
{
return null;
}
SpanByte receivedData = new byte[1024];
ret = ReadResponse(CommandSet.InAutoPoll, receivedData);
#if DEBUG
_logger.LogDebug($"{nameof(AutoPoll)}, success: {ret}");
#endif
if (ret >= 0)
{
return receivedData.Slice(0, ret).ToArray();
}
return null;
}
#region PN532 as Target
/// <summary>
/// Set the PN532 as a target, so as a card
/// </summary>
public AsTargetInitialized InitAsTarget(TargetModeInitialization mode,
TargetMifareParameters mifare, TargetFeliCaParameters feliCa, TargetPiccParameters picc)
{
// First make sure we have the right mode in the parameters for the PICC only case
if (mode == TargetModeInitialization.PiccOnly)
{
#if DEBUG
_logger.LogDebug($"{nameof(InitAsTarget)} - changing mode for Picc only");
#endif
ParametersFlags |= ParametersFlags.ISO14443_4_PICC;
}
else
{
if (ParametersFlags.HasFlag(ParametersFlags.ISO14443_4_PICC))
{
#if DEBUG
_logger.LogDebug($"{nameof(InitAsTarget)} - removing mode for Picc only");
#endif
ParametersFlags = ParametersFlags & ~ParametersFlags.ISO14443_4_PICC;
}
}
// Then serialize all buffer and add them
ListByte toSend = new ListByte();
toSend.Add((byte)mode);
toSend.AddRange(mifare.Serialize());
toSend.AddRange(feliCa.Serialize());
toSend.AddRange(picc.Serialize());
var ret = WriteCommand(CommandSet.TgInitAsTarget, toSend.ToArray());
if (ret < 0)
{
return new AsTargetInitialized(null, null);
}
SpanByte receivedData = new byte[1024];
ret = ReadResponse(CommandSet.TgInitAsTarget, receivedData);
#if DEBUG
_logger.LogDebug($"{nameof(InitAsTarget)}, success: {ret}");
#endif
if (ret >= 0)
{
TargetModeInitialized modeInitialized = new TargetModeInitialized();
modeInitialized.IsDep = (receivedData[0] & 0b0000_0100) == 0b0000_0100;
modeInitialized.IsISO14443_4Picc = (receivedData[0] & 0b0000_1000) == 0b0000_1000;
modeInitialized.TargetFramingType = (TargetFramingType)(receivedData[0] & 0b0000_0011);
modeInitialized.TargetBaudRate = (TargetBaudRateInialized)(receivedData[0] & 0b0111_0000);
return new AsTargetInitialized(modeInitialized, receivedData.Slice(1, ret - 1).ToArray());
}
return new AsTargetInitialized(null, null);
}
/// <summary>
/// read data from the reader when PN532 is a target
/// </summary>
/// <param name="receivedData">A Span byte array for the read data. Note the first byte contains the status</param>
/// <returns>Number of byte read</returns>
public int ReadDataAsTarget(SpanByte receivedData)
{
var ret = WriteCommand(CommandSet.TgGetData);
if (ret < 0)
{
return -1;
}
ret = ReadResponse(CommandSet.TgGetData, receivedData);
#if DEBUG
_logger.LogDebug($"{nameof(InitAsTarget)}, success: {ret}");
if (ret > 0)
{
_logger.LogDebug($"{nameof(WriteDataAsTarget)} - error: {(ErrorCode)receivedData[0]}, received array: {BitConverter.ToString(receivedData.Slice(1, ret - 1).ToArray())}");