144
144
_ACK = b'\x00 \x00 \xFF \x00 \xFF \x00 '
145
145
_FRAME_START = b'\x00 \x00 \xFF '
146
146
147
+ def reverse_bit (num ):
148
+ result = 0
149
+ for _ in range (8 ):
150
+ result <<= 1
151
+ result += (num & 1 )
152
+ num >>= 1
153
+ return result
154
+
155
+
156
+
147
157
class BusyError (Exception ):
148
158
"""Base class for exceptions in this module."""
149
159
pass
@@ -156,7 +166,6 @@ def __init__(self, *, debug=False, reset=None):
156
166
"""
157
167
self .debug = debug
158
168
if reset :
159
- print ("resetting" )
160
169
reset .direction = Direction .OUTPUT
161
170
reset .value = True
162
171
time .sleep (0.1 )
@@ -408,7 +417,7 @@ def _wait_ready(self, timeout=1):
408
417
return True
409
418
else :
410
419
time .sleep (0.1 )
411
- return True
420
+ return False
412
421
413
422
def _read_data (self , count ):
414
423
"""Read a specified count of bytes from the PN532."""
@@ -426,3 +435,53 @@ def _read_data(self, count):
426
435
def _write_data (self , framebytes ):
427
436
with self ._i2c :
428
437
self ._i2c .write (framebytes )
438
+
439
+ class PN532_SPI (PN532 ):
440
+ """Driver for the PN532 connected over I2C."""
441
+ def __init__ (self , spi , cs_pin , * , irq = None , reset = None , debug = False ):
442
+ """Create an instance of the PN532 class using SPI
443
+ """
444
+ self .debug = debug
445
+ self ._irq = irq
446
+ self ._spi = spi_device .SPIDevice (spi , cs_pin )
447
+ super ().__init__ (debug = debug , reset = reset )
448
+
449
+ def _wait_ready (self , timeout = 1 ):
450
+ if self ._irq :
451
+ print ("TODO IRQ" )
452
+ else :
453
+ status = bytearray ([reverse_bit (_SPI_STATREAD ), 0 ])
454
+
455
+ t = time .monotonic ()
456
+ while (time .monotonic () - t ) < timeout :
457
+ with self ._spi as spi :
458
+ spi .write_readinto (status , status )
459
+ if reverse_bit (status [1 ]) == 0x01 : # LSB data is read in MSB
460
+ return True
461
+ else :
462
+ time .sleep (0.1 )
463
+ return False
464
+
465
+ def _read_data (self , count ):
466
+ """Read a specified count of bytes from the PN532."""
467
+ # Build a read request frame.
468
+ frame = bytearray (count + 1 )
469
+ # Add the SPI data read signal byte, but LSB'ify it
470
+ frame [0 ] = reverse_bit (_SPI_DATAREAD )
471
+
472
+ with self ._spi as spi :
473
+ time .sleep (0.01 )
474
+ spi .write_readinto (frame , frame )
475
+ for i in range (len (frame )):
476
+ frame [i ] = reverse_bit (frame [i ]) # turn LSB data to MSB
477
+ if self .debug :
478
+ print ("Reading: " , [hex (i ) for i in frame [1 :]])
479
+ return frame [1 :]
480
+
481
+ def _write_data (self , framebytes ):
482
+ with self ._spi as spi :
483
+ reversed = [reverse_bit (x ) for x in bytes ([_SPI_DATAWRITE ]) + framebytes ]
484
+ time .sleep (0.01 )
485
+ if self .debug :
486
+ print ("writing: " , [hex (i ) for i in reversed ])
487
+ spi .write (bytes (reversed ))
0 commit comments