Pylint, doc, and better raspi support

This commit is contained in:
Your Name 2018-08-25 20:39:16 +00:00
parent 3d55059ca6
commit a6c32449ef
6 changed files with 135 additions and 75 deletions

View file

@ -13,7 +13,7 @@ Introduction
:target: https://travis-ci.org/adafruit/adafruit_CircuitPython_PN532 :target: https://travis-ci.org/adafruit/adafruit_CircuitPython_PN532
:alt: Build Status :alt: Build Status
.. todo:: Describe what the library does. CircuitPython driver for the `PN532 NFC/RFID Breakout <https://www.adafruit.com/product/364>`_ and `PN532 NFC/RFID Shield <https://www.adafruit.com/product/789>`_
Dependencies Dependencies
============= =============
@ -29,7 +29,7 @@ This is easily achieved by downloading
Usage Example Usage Example
============= =============
.. todo:: Add a quick, simple example. It and other examples should live in the examples folder and be included in docs/examples.rst. Check examples/pn532_simpletest.py for usage example
Contributing Contributing
============ ============

View file

@ -23,7 +23,7 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE. # SOFTWARE.
""" """
`adafruit_PN532` ``adafruit_pn532``
==================================================== ====================================================
This module will let you communicate with a PN532 RFID/NFC shield or breakout This module will let you communicate with a PN532 RFID/NFC shield or breakout
@ -43,13 +43,12 @@ Implementation Notes
* Adafruit CircuitPython firmware for the supported boards: * Adafruit CircuitPython firmware for the supported boards:
https://github.com/adafruit/circuitpython/releases https://github.com/adafruit/circuitpython/releases
* Adafruit's Bus Device library: https://github.com/adafruit/Adafruit_CircuitPython_BusDevice
* Adafruit's Bus Device library: https://github.com/adafruit/Adafruit_CircuitPython_BusDevice
""" """
import time import time
from digitalio import DigitalInOut, Direction from digitalio import Direction
import adafruit_bus_device.i2c_device as i2c_device import adafruit_bus_device.i2c_device as i2c_device
import adafruit_bus_device.spi_device as spi_device import adafruit_bus_device.spi_device as spi_device
@ -58,7 +57,7 @@ from micropython import const
__version__ = "0.0.0-auto.0" __version__ = "0.0.0-auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_PN532.git" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_PN532.git"
# pylint: disable=bad-whitespace
_PREAMBLE = const(0x00) _PREAMBLE = const(0x00)
_STARTCODE1 = const(0x00) _STARTCODE1 = const(0x00)
_STARTCODE2 = const(0xFF) _STARTCODE2 = const(0xFF)
@ -174,8 +173,22 @@ _GPIO_P35 = const(5)
_ACK = b'\x00\x00\xFF\x00\xFF\x00' _ACK = b'\x00\x00\xFF\x00\xFF\x00'
_FRAME_START = b'\x00\x00\xFF' _FRAME_START = b'\x00\x00\xFF'
# pylint: enable=bad-whitespace
def _reset(pin):
"""Perform a hardware reset toggle"""
pin.direction = Direction.OUTPUT
pin.value = True
time.sleep(0.1)
pin.value = False
time.sleep(0.5)
pin.value = True
time.sleep(0.1)
def reverse_bit(num): def reverse_bit(num):
"""Turn an LSB byte to an MSB byte, and vice versa. Used for SPI as
it is LSB for the PN532, but 99% of SPI implementations are MSB only!"""
result = 0 result = 0
for _ in range(8): for _ in range(8):
result <<= 1 result <<= 1
@ -197,18 +210,15 @@ class PN532:
""" """
self.debug = debug self.debug = debug
if reset: if reset:
reset.direction = Direction.OUTPUT if debug:
reset.value = True print("Resetting")
time.sleep(0.1) _reset(reset)
reset.value = False
time.sleep(0.1)
reset.value = True
time.sleep(1)
try: try:
self._wakeup() self._wakeup()
self.get_firmware_version() # first time often fails, try 2ce self.get_firmware_version() # first time often fails, try 2ce
return return
except: except (BusyError, RuntimeError):
pass pass
self.get_firmware_version() self.get_firmware_version()
@ -227,10 +237,13 @@ class PN532:
# Subclasses MUST implement this! # Subclasses MUST implement this!
raise NotImplementedError raise NotImplementedError
def _wakeup(self):
# Send special command to wake up
raise NotImplementedError
def _write_frame(self, data): def _write_frame(self, data):
"""Write a frame to the PN532 with the specified data bytearray.""" """Write a frame to the PN532 with the specified data bytearray."""
assert data is not None and 0 < len(data) < 255, 'Data must be array of 1 to 255 bytes.' assert data is not None and 1 < len(data) < 255, 'Data must be array of 1 to 255 bytes.'
# Build frame to send as: # Build frame to send as:
# - Preamble (0x00) # - Preamble (0x00)
# - Start code (0x00, 0xFF) # - Start code (0x00, 0xFF)
@ -266,6 +279,7 @@ class PN532:
response = self._read_data(length+8) response = self._read_data(length+8)
if self.debug: if self.debug:
print('Read frame:', [hex(i) for i in response]) print('Read frame:', [hex(i) for i in response])
# Swallow all the 0x00 values that preceed 0xFF. # Swallow all the 0x00 values that preceed 0xFF.
offset = 0 offset = 0
while response[offset] == 0x00: while response[offset] == 0x00:
@ -288,7 +302,7 @@ class PN532:
# Return frame data. # Return frame data.
return response[offset+2:offset+2+frame_len] return response[offset+2:offset+2+frame_len]
def call_function(self, command, response_length=0, params=[], timeout=1): def call_function(self, command, response_length=0, params=[], timeout=1): # pylint: disable=dangerous-default-value
"""Send specified command to the PN532 and expect up to response_length """Send specified command to the PN532 and expect up to response_length
bytes back in a response. Note that less than the expected bytes might bytes back in a response. Note that less than the expected bytes might
be returned! Params can optionally specify an array of bytes to send as be returned! Params can optionally specify an array of bytes to send as
@ -300,10 +314,14 @@ class PN532:
data = bytearray(2+len(params)) data = bytearray(2+len(params))
data[0] = _HOSTTOPN532 data[0] = _HOSTTOPN532
data[1] = command & 0xFF data[1] = command & 0xFF
for i in range(len(params)): for i, val in enumerate(params):
data[2+i] = params[i] data[2+i] = val
# Send frame and wait for response. # Send frame and wait for response.
try:
self._write_frame(data) self._write_frame(data)
except OSError:
self._wakeup()
return None
if not self._wait_ready(timeout): if not self._wait_ready(timeout):
return None return None
# Verify ACK response and wait to be ready for function response. # Verify ACK response and wait to be ready for function response.
@ -328,7 +346,7 @@ class PN532:
raise RuntimeError('Failed to detect the PN532') raise RuntimeError('Failed to detect the PN532')
return tuple(response) return tuple(response)
def SAM_configuration(self): def SAM_configuration(self): # pylint: disable=invalid-name
"""Configure the PN532 to read MiFare cards.""" """Configure the PN532 to read MiFare cards."""
# Send SAM configuration command with configuration for: # Send SAM configuration command with configuration for:
# - 0x01, normal mode # - 0x01, normal mode
@ -362,7 +380,7 @@ class PN532:
# Return UID of card. # Return UID of card.
return response[6:6+response[5]] return response[6:6+response[5]]
def mifare_classic_authenticate_block(self, uid, block_number, key_number, key): def mifare_classic_authenticate_block(self, uid, block_number, key_number, key): # pylint: disable=invalid-name
"""Authenticate specified block number for a MiFare classic card. Uid """Authenticate specified block number for a MiFare classic card. Uid
should be a byte array with the UID of the card, block number should be should be a byte array with the UID of the card, block number should be
the block to authenticate, key number should be the key type (like the block to authenticate, key number should be the key type (like
@ -424,7 +442,8 @@ class PN532:
class PN532_UART(PN532): class PN532_UART(PN532):
"""Driver for the PN532 connected over Serial UART""" """Driver for the PN532 connected over Serial UART"""
def __init__(self, uart, *, irq=None, reset=None, debug=False): def __init__(self, uart, *, irq=None, reset=None, debug=False):
"""Create an instance of the PN532 class using Serial connection """Create an instance of the PN532 class using Serial connection.
Optional IRQ pin (not used), reset pin and debugging output.
""" """
self.debug = debug self.debug = debug
self._irq = irq self._irq = irq
@ -432,10 +451,12 @@ class PN532_UART(PN532):
super().__init__(debug=debug, reset=reset) super().__init__(debug=debug, reset=reset)
def _wakeup(self): def _wakeup(self):
"""Send any special commands/data to wake up PN532"""
#self._write_frame([_HOSTTOPN532, _COMMAND_SAMCONFIGURATION, 0x01]) #self._write_frame([_HOSTTOPN532, _COMMAND_SAMCONFIGURATION, 0x01])
self.SAM_configuration() self.SAM_configuration()
def _wait_ready(self, timeout=1): def _wait_ready(self, timeout=1):
"""Wait `timeout` seconds"""
time.sleep(timeout) time.sleep(timeout)
return True return True
@ -446,9 +467,12 @@ class PN532_UART(PN532):
raise BusyError("No data read from PN532") raise BusyError("No data read from PN532")
if self.debug: if self.debug:
print("Reading: ", [hex(i) for i in frame]) print("Reading: ", [hex(i) for i in frame])
else:
time.sleep(0.1)
return frame return frame
def _write_data(self, framebytes): def _write_data(self, framebytes):
"""Write a specified count of bytes to the PN532"""
while self._uart.read(1): # this would be a lot nicer if we could query the # of bytes while self._uart.read(1): # this would be a lot nicer if we could query the # of bytes
pass pass
self._uart.write('\x55\x55\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') # wake up! self._uart.write('\x55\x55\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') # wake up!
@ -456,31 +480,45 @@ class PN532_UART(PN532):
class PN532_I2C(PN532): class PN532_I2C(PN532):
"""Driver for the PN532 connected over I2C.""" """Driver for the PN532 connected over I2C."""
def __init__(self, i2c, *, irq=None, reset=None, debug=False): def __init__(self, i2c, *, irq=None, reset=None, req=None, debug=False):
"""Create an instance of the PN532 class using either software SPI (if """Create an instance of the PN532 class using I2C. Note that PN532
the sclk, mosi, and miso pins are specified) or hardware SPI if a uses clock stretching. Optional IRQ pin (not used),
spi parameter is passed. The cs pin must be a digital GPIO pin. reset pin and debugging output.
Optionally specify a GPIO controller to override the default that uses
the board's GPIO pins.
""" """
self.debug = debug self.debug = debug
self._irq = irq self._irq = irq
self._req = req
if reset:
_reset(reset)
self._i2c = i2c_device.I2CDevice(i2c, _I2C_ADDRESS) self._i2c = i2c_device.I2CDevice(i2c, _I2C_ADDRESS)
super().__init__(debug=debug, reset=reset) super().__init__(debug=debug, reset=reset)
def _wakeup(self): def _wakeup(self): # pylint: disable=no-self-use
"""Send any special commands/data to wake up PN532"""
if self._req:
self._req.direction = Direction.OUTPUT
self._req.value = True
time.sleep(0.1)
self._req.value = False
time.sleep(0.1)
self._req.value = True
time.sleep(0.5) time.sleep(0.5)
def _wait_ready(self, timeout=1): def _wait_ready(self, timeout=1):
"""Poll PN532 if status byte is ready, up to `timeout` seconds"""
status = bytearray(1) status = bytearray(1)
t = time.monotonic() timestamp = time.monotonic()
while (time.monotonic() - t) < timeout: while (time.monotonic() - timestamp) < timeout:
try:
with self._i2c: with self._i2c:
self._i2c.readinto(status) self._i2c.readinto(status)
except OSError:
self._wakeup()
continue
if status == b'\x01': if status == b'\x01':
return True # No longer busy return True # No longer busy
else: else:
time.sleep(0.1) # lets ask again soon! time.sleep(0.05) # lets ask again soon!
# Timed out! # Timed out!
return False return False
@ -495,15 +533,19 @@ class PN532_I2C(PN532):
i2c.readinto(frame) # ok get the data, plus statusbyte i2c.readinto(frame) # ok get the data, plus statusbyte
if self.debug: if self.debug:
print("Reading: ", [hex(i) for i in frame[1:]]) print("Reading: ", [hex(i) for i in frame[1:]])
else:
time.sleep(0.1)
return frame[1:] # don't return the status byte return frame[1:] # don't return the status byte
def _write_data(self, framebytes): def _write_data(self, framebytes):
"""Write a specified count of bytes to the PN532"""
with self._i2c as i2c: with self._i2c as i2c:
i2c.write(framebytes) i2c.write(framebytes)
class PN532_SPI(PN532): class PN532_SPI(PN532):
"""Driver for the PN532 connected over SPI. Pass in a hardware or bitbang SPI device & chip select """Driver for the PN532 connected over SPI. Pass in a hardware or bitbang
digitalInOut pin. Optional IRQ pin (not used), reset pin and debugging output.""" SPI device & chip select digitalInOut pin. Optional IRQ pin (not used),
reset pin and debugging output."""
def __init__(self, spi, cs_pin, *, irq=None, reset=None, debug=False): def __init__(self, spi, cs_pin, *, irq=None, reset=None, debug=False):
"""Create an instance of the PN532 class using SPI""" """Create an instance of the PN532 class using SPI"""
self.debug = debug self.debug = debug
@ -512,20 +554,25 @@ class PN532_SPI(PN532):
super().__init__(debug=debug, reset=reset) super().__init__(debug=debug, reset=reset)
def _wakeup(self): def _wakeup(self):
"""Send any special commands/data to wake up PN532"""
with self._spi as spi: with self._spi as spi:
time.sleep(1) time.sleep(1)
spi.write(bytearray([0x00]))
time.sleep(1)
def _wait_ready(self, timeout=1): def _wait_ready(self, timeout=1):
"""Poll PN532 if status byte is ready, up to `timeout` seconds"""
status = bytearray([reverse_bit(_SPI_STATREAD), 0]) status = bytearray([reverse_bit(_SPI_STATREAD), 0])
t = time.monotonic() timestamp = time.monotonic()
while (time.monotonic() - t) < timeout: while (time.monotonic() - timestamp) < timeout:
with self._spi as spi: with self._spi as spi:
time.sleep(0.02) # required
spi.write_readinto(status, status) spi.write_readinto(status, status)
if reverse_bit(status[1]) == 0x01: # LSB data is read in MSB if reverse_bit(status[1]) == 0x01: # LSB data is read in MSB
return True # Not busy anymore! return True # Not busy anymore!
else: else:
time.sleep(0.1) # pause a bit till we ask again time.sleep(0.01) # pause a bit till we ask again
# We timed out! # We timed out!
return False return False
@ -537,19 +584,21 @@ class PN532_SPI(PN532):
frame[0] = reverse_bit(_SPI_DATAREAD) frame[0] = reverse_bit(_SPI_DATAREAD)
with self._spi as spi: with self._spi as spi:
time.sleep(0.01) # required time.sleep(0.02) # required
spi.write_readinto(frame, frame) spi.write_readinto(frame, frame)
for i in range(len(frame)): for i, val in enumerate(frame):
frame[i] = reverse_bit(frame[i]) # turn LSB data to MSB frame[i] = reverse_bit(val) # turn LSB data to MSB
if self.debug: if self.debug:
print("Reading: ", [hex(i) for i in frame[1:]]) print("Reading: ", [hex(i) for i in frame[1:]])
return frame[1:] return frame[1:]
def _write_data(self, framebytes): def _write_data(self, framebytes):
# start by making a frame with data write in front, then rest of bytes, and LSBify it """Write a specified count of bytes to the PN532"""
reversed = [reverse_bit(x) for x in bytes([_SPI_DATAWRITE]) + framebytes] # start by making a frame with data write in front,
# then rest of bytes, and LSBify it
rev_frame = [reverse_bit(x) for x in bytes([_SPI_DATAWRITE]) + framebytes]
if self.debug: if self.debug:
print("Writing: ", [hex(i) for i in reversed]) print("Writing: ", [hex(i) for i in rev_frame])
with self._spi as spi: with self._spi as spi:
time.sleep(0.01) # required time.sleep(0.02) # required
spi.write(bytes(reversed)) spi.write(bytes(rev_frame))

View file

@ -20,7 +20,7 @@ extensions = [
# Uncomment the below if you use native CircuitPython modules such as # Uncomment the below if you use native CircuitPython modules such as
# digitalio, micropython and busio. List the modules you use. Without it, the # digitalio, micropython and busio. List the modules you use. Without it, the
# autodoc module docs will fail to generate with a warning. # autodoc module docs will fail to generate with a warning.
# autodoc_mock_imports = ["digitalio", "busio"] autodoc_mock_imports = ["digitalio", "busio", "adafruit_bus_device", "micropython"]
intersphinx_mapping = {'python': ('https://docs.python.org/3.4', None),'BusDevice': ('https://circuitpython.readthedocs.io/projects/busdevice/en/latest/', None),'CircuitPython': ('https://circuitpython.readthedocs.io/en/latest/', None)} intersphinx_mapping = {'python': ('https://docs.python.org/3.4', None),'BusDevice': ('https://circuitpython.readthedocs.io/projects/busdevice/en/latest/', None),'CircuitPython': ('https://circuitpython.readthedocs.io/en/latest/', None)}

View file

@ -23,14 +23,11 @@ Table of Contents
.. toctree:: .. toctree::
:caption: Tutorials :caption: Tutorials
.. todo:: Add any Learn guide links here. If there are none, then simply delete this todo and leave
the toctree above for use later.
.. toctree:: .. toctree::
:caption: Related Products :caption: Related Products
.. todo:: Add any product links here. If there are none, then simply delete this todo and leave `PN532 NFC/RFID Breakout <https://www.adafruit.com/product/364>` and `PN532 NFC/RFID Shield <https://www.adafruit.com/product/789>`_
the toctree above for use later.
.. toctree:: .. toctree::
:caption: Other Links :caption: Other Links

View file

@ -1,24 +1,37 @@
from Adafruit_Circuitpython_PN532 import adafruit_pn532 """
from digitalio import DigitalInOut, Direction, Pull This example shows connecting to the PN532 with I2C (requires clock
stretching support), SPI, or UART. SPI is best, it uses the most pins but
is the most reliable and universally supported.
After initialization, try waving various 13.56MHz RFID cards over it!
"""
import board import board
import time
import busio import busio
from digitalio import DigitalInOut
reset_pin = DigitalInOut(board.D3) from Adafruit_Circuitpython_PN532 import adafruit_pn532
# I2C connection: # I2C connection:
#i2c = busio.I2C(board.SCL, board.SDA) i2c = busio.I2C(board.SCL, board.SDA)
#pn532 = adafruit_pn532.PN532_I2C(i2c, debug=False, reset=reset_pin)
# Non-hardware
#pn532 = adafruit_pn532.PN532_I2C(i2c, debug=False)
# With I2C, we recommend connecting RSTPD_N (reset) to a digital pin for manual
# harware reset
reset_pin = DigitalInOut(board.D6)
# On Raspberry Pi, you must also connect a pin to P32 "H_Request" for hardware
# wakeup! this means we don't need to do the I2C clock-stretch thing
req_pin = DigitalInOut(board.D12)
pn532 = adafruit_pn532.PN532_I2C(i2c, debug=False, reset=reset_pin, req=req_pin)
# SPI connection: # SPI connection:
#spi = busio.SPI(board.SCK, board.MOSI, board.MISO) #spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
#cs_pin = DigitalInOut(board.D2) #cs_pin = DigitalInOut(board.D5)
#pn532 = adafruit_pn532.PN532_SPI(spi, cs_pin, debug=False, reset=reset_pin) #pn532 = adafruit_pn532.PN532_SPI(spi, cs_pin, debug=False)
# UART connection # UART connection
#uart = busio.UART(board.TX, board.RX, baudrate=115200, timeout=100) #uart = busio.UART(board.TX, board.RX, baudrate=115200, timeout=100)
#pn532 = adafruit_pn532.PN532_UART(uart, debug=False, reset=reset_pin) #pn532 = adafruit_pn532.PN532_UART(uart, debug=False)
ic, ver, rev, support = pn532.get_firmware_version() ic, ver, rev, support = pn532.get_firmware_version()
print('Found PN532 with firmware version: {0}.{1}'.format(ver, rev)) print('Found PN532 with firmware version: {0}.{1}'.format(ver, rev))
@ -26,10 +39,10 @@ print('Found PN532 with firmware version: {0}.{1}'.format(ver, rev))
# Configure PN532 to communicate with MiFare cards # Configure PN532 to communicate with MiFare cards
pn532.SAM_configuration() pn532.SAM_configuration()
print('Waiting for MiFare card...') print('Waiting for RFID/NFC card...')
while True: while True:
# Check if a card is available to read # Check if a card is available to read
uid = pn532.read_passive_target(timeout=0.25) uid = pn532.read_passive_target(timeout=0.5)
print('.', end="", flush=True) print('.', end="", flush=True)
# Try again if no card is available. # Try again if no card is available.
if uid is None: if uid is None:

View file

@ -1,2 +1,3 @@
Adafruit-Blinka
adafruit-circuitpython-busdevice adafruit-circuitpython-busdevice
pyserial pyserial