From d022cb7fe7d09b0da6f4f28ec6046aeb8b9deb02 Mon Sep 17 00:00:00 2001 From: dherrada Date: Sun, 15 Mar 2020 16:22:55 -0400 Subject: [PATCH 1/2] Ran black, updated to pylint 2.x --- .github/workflows/build.yml | 2 +- ; | 386 ++++++++++++++++++++++++++++++++ adafruit_fram.py | 104 +++++---- docs/conf.py | 120 ++++++---- examples/fram_i2c_simpletest.py | 12 +- examples/fram_spi_simpletest.py | 6 +- setup.py | 52 ++--- 7 files changed, 555 insertions(+), 127 deletions(-) create mode 100644 ; diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index fff3aa9..1dad804 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -40,7 +40,7 @@ jobs: source actions-ci/install.sh - name: Pip install pylint, black, & Sphinx run: | - pip install --force-reinstall pylint==1.9.2 black==19.10b0 Sphinx sphinx-rtd-theme + pip install --force-reinstall pylint black==19.10b0 Sphinx sphinx-rtd-theme - name: Library version run: git describe --dirty --always --tags - name: PyLint diff --git a/; b/; new file mode 100644 index 0000000..1956be6 --- /dev/null +++ b/; @@ -0,0 +1,386 @@ +# The MIT License (MIT) +# +# Copyright (c) 2018 Michael Schroeder +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +""" +`adafruit_fram` +==================================================== + +CircuitPython/Python library to support the I2C and SPI FRAM Breakouts. + +* Author(s): Michael Schroeder + +Implementation Notes +-------------------- + +**Hardware:** + + * Adafruit `I2C Non-Volatile FRAM Breakout + `_ (Product ID: 1895) + * Adafruit `SPI Non-Volatile FRAM Breakout + `_ (Product ID: 1897) + +**Software and Dependencies:** + +* Adafruit CircuitPython firmware for the supported boards: + https://github.com/adafruit/circuitpython/releases + + * Adafruit's Bus Device library: https://github.com/adafruit/Adafruit_CircuitPython_BusDevice +""" + +# imports +from micropython import const + +__version__ = "0.0.0-auto.0" +__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_FRAM.git" + +_MAX_SIZE_I2C = const(32768) +_MAX_SIZE_SPI = const(8192) + +_I2C_MANF_ID = const(0x0A) +_I2C_PROD_ID = const(0x510) + +_SPI_MANF_ID = const(0x04) +_SPI_PROD_ID = const(0x302) + + +class FRAM: + """ + Driver base for the FRAM Breakout. + """ + + def __init__(self, max_size, write_protect=False, wp_pin=None): + self._max_size = max_size + self._wp = write_protect + self._wraparound = False + if not wp_pin is None: + self._wp_pin = wp_pin + # Make sure write_prot is set to output + self._wp_pin.switch_to_output() + self._wp_pin.value = self._wp + else: + self._wp_pin = wp_pin + + @property + def write_wraparound(self): + """ Determines if sequential writes will wrapaound highest memory address + (``len(FRAM) - 1``) address. If ``False``, and a requested write will + extend beyond the maximum size, an exception is raised. + """ + return self._wraparound + + @write_wraparound.setter + def write_wraparound(self, value): + if not value in (True, False): + raise ValueError("Write wraparound must be 'True' or 'False'.") + self._wraparound = value + + @property + def write_protected(self): + """ The status of write protection. Default value on initialization is + ``False``. + + When a ``WP`` pin is supplied during initialization, or using + ``write_protect_pin``, the status is tied to that pin and enables + hardware-level protection. + + When no ``WP`` pin is supplied, protection is only at the software + level in this library. + """ + return self._wp if self._wp_pin is None else self._wp_pin.value + + def __len__(self): + """ The size of the current FRAM chip. This is one more than the highest + address location that can be read or written to. + + .. code-block:: python + + fram = adafruit_fram.FRAM_xxx() # xxx = 'I2C' or 'SPI' + + # size returned by len() + len(fram) + + # can be used with range + for i in range(0, len(fram)) + """ + return self._max_size + + def __getitem__(self, address): + """ Read the value at the given index, or values in a slice. + + .. code-block:: python + + # read single index + fram[0] + + # read values 0 thru 9 with a slice + fram[0:9] + """ + if isinstance(address, int): + if not 0 <= address < self._max_size: + raise ValueError( + "Address '{0}' out of range. It must be 0 <= address < {1}.".format( + address, self._max_size + ) + ) + buffer = bytearray(1) + read_buffer = self._read_address(address, buffer) + elif isinstance(address, slice): + if address.step is not None: + raise ValueError("Slice stepping is not currently available.") + + regs = list( + range( + address.start if address.start is not None else 0, + address.stop + 1 if address.stop is not None else self._max_size, + ) + ) + if regs[0] < 0 or (regs[0] + len(regs)) > self._max_size: + raise ValueError( + "Address slice out of range. It must be 0 <= [starting address" + ":stopping address] < {0}.".format(self._max_size) + ) + + buffer = bytearray(len(regs)) + read_buffer = self._read_address(regs[0], buffer) + + return read_buffer + + def __setitem__(self, address, value): + """ Write the value at the given starting index. + + .. code-block:: python + + # write single index + fram[0] = 1 + + # write values 0 thru 4 with a list + fram[0] = [0,1,2,3] + """ + if self.write_protected: + raise RuntimeError("FRAM currently write protected.") + + if isinstance(address, int): + if not isinstance(value, (int, bytearray, list, tuple)): + raise ValueError( + "Data must be a single integer, or a bytearray," " list, or tuple." + ) + if not 0 <= address < self._max_size: + raise ValueError( + "Address '{0}' out of range. It must be 0 <= address < {1}.".format( + address, self._max_size + ) + ) + + self._write(address, value, self._wraparound) + + elif isinstance(address, slice): + raise ValueError("Slicing not available during write operations.") + + def _read_address(self, address, read_buffer): + # Implemented by subclass + raise NotImplementedError + + def _write(self, start_address, data, wraparound): + # Implemened by subclass + raise NotImplementedError + + +class FRAM_I2C(FRAM): + """ I2C class for FRAM. + + :param: ~busio.I2C i2c_bus: The I2C bus the FRAM is connected to. + :param: int address: I2C address of FRAM. Default address is ``0x50``. + :param: bool write_protect: Turns on/off initial write protection. + Default is ``False``. + :param: wp_pin: (Optional) Physical pin connected to the ``WP`` breakout pin. + Must be a ``digitalio.DigitalInOut`` object. + """ + + # pylint: disable=too-many-arguments + def __init__(self, i2c_bus, address=0x50, write_protect=False, wp_pin=None): + from adafruit_bus_device.i2c_device import ( # pylint: disable=import-outside-toplevel + I2CDevice as i2cdev, + ) + + dev_id_addr = 0xF8 >> 1 + read_buf = bytearray(3) + with i2cdev(i2c_bus, dev_id_addr) as dev_id: + dev_id.write_then_readinto(bytearray([(address << 1)]), read_buf) + manf_id = (read_buf[0] << 4) + (read_buf[1] >> 4) + prod_id = ((read_buf[1] & 0x0F) << 8) + read_buf[2] + if (manf_id != _I2C_MANF_ID) and (prod_id != _I2C_PROD_ID): + raise OSError("FRAM I2C device not found.") + + self._i2c = i2cdev(i2c_bus, address) + super().__init__(_MAX_SIZE_I2C, write_protect, wp_pin) + + def _read_address(self, address, read_buffer): + write_buffer = bytearray(2) + write_buffer[0] = address >> 8 + write_buffer[1] = address & 0xFF + with self._i2c as i2c: + i2c.write_then_readinto(write_buffer, read_buffer) + return read_buffer + + def _write(self, start_address, data, wraparound=False): + # Decided against using the chip's "Page Write", since that would require + # doubling the memory usage by creating a buffer that includes the passed + # in data so that it can be sent all in one `i2c.write`. The single-write + # method is slower, and forces us to handle wraparound, but I feel this + # is a better tradeoff for limiting the memory required for large writes. + buffer = bytearray(3) + if not isinstance(data, int): + data_length = len(data) + else: + data_length = 1 + data = [data] + if (start_address + data_length) > self._max_size: + if wraparound: + pass + else: + raise ValueError( + "Starting address + data length extends beyond" + " FRAM maximum address. Use ``write_wraparound`` to" + " override this warning." + ) + with self._i2c as i2c: + for i in range(0, data_length): + if not (start_address + i) > self._max_size - 1: + buffer[0] = (start_address + i) >> 8 + buffer[1] = (start_address + i) & 0xFF + else: + buffer[0] = ((start_address + i) - self._max_size + 1) >> 8 + buffer[1] = ((start_address + i) - self._max_size + 1) & 0xFF + buffer[2] = data[i] + i2c.write(buffer) + + # pylint: disable=no-member + @FRAM.write_protected.setter + def write_protected(self, value): + if value not in (True, False): + raise ValueError("Write protected value must be 'True' or 'False'.") + self._wp = value + if not self._wp_pin is None: + self._wp_pin.value = value + + +# the following pylint disables are related to the '_SPI_OPCODE' consts, the super +# class setter '@FRAM.write_protected.setter', and pylint not being able to see +# 'spi.write()' in SPIDevice. Travis run for reference: +# https://travis-ci.com/sommersoft/Adafruit_CircuitPython_FRAM/builds/87112669 + +# pylint: disable=no-member,undefined-variable +class FRAM_SPI(FRAM): + """ SPI class for FRAM. + + :param: ~busio.SPI spi_bus: The SPI bus the FRAM is connected to. + :param: ~digitalio.DigitalInOut spi_cs: The SPI CS pin. + :param: bool write_protect: Turns on/off initial write protection. + Default is ``False``. + :param: wp_pin: (Optional) Physical pin connected to the ``WP`` breakout pin. + Must be a ``digitalio.DigitalInOut`` object. + :param int baudrate: SPI baudrate to use. Default is ``1000000``. + """ + + _SPI_OPCODE_WREN = const(0x6) # Set write enable latch + _SPI_OPCODE_WRDI = const(0x4) # Reset write enable latch + _SPI_OPCODE_RDSR = const(0x5) # Read status register + _SPI_OPCODE_WRSR = const(0x1) # Write status register + _SPI_OPCODE_READ = const(0x3) # Read memory code + _SPI_OPCODE_WRITE = const(0x2) # Write memory code + _SPI_OPCODE_RDID = const(0x9F) # Read device ID + + # pylint: disable=too-many-arguments,too-many-locals + def __init__( + self, spi_bus, spi_cs, write_protect=False, wp_pin=None, baudrate=100000 + ): + from adafruit_bus_device.spi_device import ( # pylint: disable=import-outside-toplevel + SPIDevice as spidev, + ) + _spi = spidev(spi_bus, spi_cs, baudrate=baudrate) + + read_buffer = bytearray(4) + with _spi as spi: + spi.write(bytearray([_SPI_OPCODE_RDID])) + spi.readinto(read_buffer) + prod_id = (read_buffer[3] << 8) + (read_buffer[2]) + if (read_buffer[0] != _SPI_MANF_ID) and (prod_id != _SPI_PROD_ID): + raise OSError("FRAM SPI device not found.") + + self._spi = _spi + super().__init__(_MAX_SIZE_SPI, write_protect, wp_pin) + + def _read_address(self, address, read_buffer): + write_buffer = bytearray(3) + write_buffer[0] = _SPI_OPCODE_READ + write_buffer[1] = address >> 8 + write_buffer[2] = address & 0xFF + with self._spi as spi: + spi.write(write_buffer) + spi.readinto(read_buffer) + return read_buffer + + def _write(self, start_address, data, wraparound=False): + buffer = bytearray(3) + if not isinstance(data, int): + data_length = len(data) + else: + data_length = 1 + data = [data] + if (start_address + data_length) > self._max_size: + if wraparound: + pass + else: + raise ValueError( + "Starting address + data length extends beyond" + " FRAM maximum address. Use 'wraparound=True' to" + " override this warning." + ) + with self._spi as spi: + spi.write(bytearray([_SPI_OPCODE_WREN])) + with self._spi as spi: + buffer[0] = _SPI_OPCODE_WRITE + buffer[1] = start_address >> 8 + buffer[2] = start_address & 0xFF + spi.write(buffer) + for i in range(0, data_length): + spi.write(bytearray([data[i]])) + with self._spi as spi: + spi.write(bytearray([_SPI_OPCODE_WRDI])) + + @FRAM.write_protected.setter + def write_protected(self, value): + # While it is possible to protect block ranges on the SPI chip, + # it seems superfluous to do so. So, block protection always protects + # the entire memory (BP0 and BP1). + if value not in (True, False): + raise ValueError("Write protected value must be 'True' or 'False'.") + self._wp = value + write_buffer = bytearray(2) + write_buffer[0] = _SPI_OPCODE_WRSR + if value: + write_buffer[1] = 0x8C # set WPEN, BP0, and BP1 + else: + write_buffer[1] = 0x00 # clear WPEN, BP0, and BP1 + with self._spi as spi: + spi.write(write_buffer) + if self._wp_pin is not None: + self._wp_pin.value = value diff --git a/adafruit_fram.py b/adafruit_fram.py index 7ab0b2b..5d8d53a 100755 --- a/adafruit_fram.py +++ b/adafruit_fram.py @@ -60,6 +60,7 @@ _SPI_MANF_ID = const(0x04) _SPI_PROD_ID = const(0x302) + class FRAM: """ Driver base for the FRAM Breakout. @@ -121,7 +122,6 @@ def __len__(self): """ return self._max_size - def __getitem__(self, address): """ Read the value at the given index, or values in a slice. @@ -135,20 +135,28 @@ def __getitem__(self, address): """ if isinstance(address, int): if not 0 <= address < self._max_size: - raise ValueError("Address '{0}' out of range. It must be 0 <= address < {1}." - .format(address, self._max_size)) + raise ValueError( + "Address '{0}' out of range. It must be 0 <= address < {1}.".format( + address, self._max_size + ) + ) buffer = bytearray(1) read_buffer = self._read_address(address, buffer) elif isinstance(address, slice): if address.step is not None: raise ValueError("Slice stepping is not currently available.") - regs = list(range(address.start if address.start is not None else 0, - address.stop + 1 if address.stop is not None else self._max_size)) + regs = list( + range( + address.start if address.start is not None else 0, + address.stop + 1 if address.stop is not None else self._max_size, + ) + ) if regs[0] < 0 or (regs[0] + len(regs)) > self._max_size: - raise ValueError("Address slice out of range. It must be 0 <= [starting address" - ":stopping address] < {0}." - .format(self._max_size)) + raise ValueError( + "Address slice out of range. It must be 0 <= [starting address" + ":stopping address] < {0}.".format(self._max_size) + ) buffer = bytearray(len(regs)) read_buffer = self._read_address(regs[0], buffer) @@ -171,11 +179,15 @@ def __setitem__(self, address, value): if isinstance(address, int): if not isinstance(value, (int, bytearray, list, tuple)): - raise ValueError("Data must be a single integer, or a bytearray," - " list, or tuple.") + raise ValueError( + "Data must be a single integer, or a bytearray," " list, or tuple." + ) if not 0 <= address < self._max_size: - raise ValueError("Address '{0}' out of range. It must be 0 <= address < {1}." - .format(address, self._max_size)) + raise ValueError( + "Address '{0}' out of range. It must be 0 <= address < {1}.".format( + address, self._max_size + ) + ) self._write(address, value, self._wraparound) @@ -190,6 +202,7 @@ def _write(self, start_address, data, wraparound): # Implemened by subclass raise NotImplementedError + class FRAM_I2C(FRAM): """ I2C class for FRAM. @@ -200,17 +213,19 @@ class FRAM_I2C(FRAM): :param: wp_pin: (Optional) Physical pin connected to the ``WP`` breakout pin. Must be a ``digitalio.DigitalInOut`` object. """ - #pylint: disable=too-many-arguments - def __init__(self, i2c_bus, address=0x50, write_protect=False, - wp_pin=None): - from adafruit_bus_device.i2c_device import I2CDevice as i2cdev + + # pylint: disable=too-many-arguments + def __init__(self, i2c_bus, address=0x50, write_protect=False, wp_pin=None): + from adafruit_bus_device.i2c_device import ( # pylint: disable=import-outside-toplevel + I2CDevice as i2cdev, + ) + dev_id_addr = 0xF8 >> 1 read_buf = bytearray(3) with i2cdev(i2c_bus, dev_id_addr) as dev_id: - dev_id.write_then_readinto(bytearray([(address << 1)]), - read_buf) - manf_id = (((read_buf[0] << 4) +(read_buf[1] >> 4))) - prod_id = (((read_buf[1] & 0x0F) << 8) + read_buf[2]) + dev_id.write_then_readinto(bytearray([(address << 1)]), read_buf) + manf_id = (read_buf[0] << 4) + (read_buf[1] >> 4) + prod_id = ((read_buf[1] & 0x0F) << 8) + read_buf[2] if (manf_id != _I2C_MANF_ID) and (prod_id != _I2C_PROD_ID): raise OSError("FRAM I2C device not found.") @@ -241,9 +256,11 @@ def _write(self, start_address, data, wraparound=False): if wraparound: pass else: - raise ValueError("Starting address + data length extends beyond" - " FRAM maximum address. Use ``write_wraparound`` to" - " override this warning.") + raise ValueError( + "Starting address + data length extends beyond" + " FRAM maximum address. Use ``write_wraparound`` to" + " override this warning." + ) with self._i2c as i2c: for i in range(0, data_length): if not (start_address + i) > self._max_size - 1: @@ -264,6 +281,7 @@ def write_protected(self, value): if not self._wp_pin is None: self._wp_pin.value = value + # the following pylint disables are related to the '_SPI_OPCODE' consts, the super # class setter '@FRAM.write_protected.setter', and pylint not being able to see # 'spi.write()' in SPIDevice. Travis run for reference: @@ -282,18 +300,22 @@ class FRAM_SPI(FRAM): :param int baudrate: SPI baudrate to use. Default is ``1000000``. """ - _SPI_OPCODE_WREN = const(0x6) # Set write enable latch - _SPI_OPCODE_WRDI = const(0x4) # Reset write enable latch - _SPI_OPCODE_RDSR = const(0x5) # Read status register - _SPI_OPCODE_WRSR = const(0x1) # Write status register - _SPI_OPCODE_READ = const(0x3) # Read memory code - _SPI_OPCODE_WRITE = const(0x2) # Write memory code - _SPI_OPCODE_RDID = const(0x9F) # Read device ID - - #pylint: disable=too-many-arguments,too-many-locals - def __init__(self, spi_bus, spi_cs, write_protect=False, - wp_pin=None, baudrate=100000): - from adafruit_bus_device.spi_device import SPIDevice as spidev + _SPI_OPCODE_WREN = const(0x6) # Set write enable latch + _SPI_OPCODE_WRDI = const(0x4) # Reset write enable latch + _SPI_OPCODE_RDSR = const(0x5) # Read status register + _SPI_OPCODE_WRSR = const(0x1) # Write status register + _SPI_OPCODE_READ = const(0x3) # Read memory code + _SPI_OPCODE_WRITE = const(0x2) # Write memory code + _SPI_OPCODE_RDID = const(0x9F) # Read device ID + + # pylint: disable=too-many-arguments,too-many-locals + def __init__( + self, spi_bus, spi_cs, write_protect=False, wp_pin=None, baudrate=100000 + ): + from adafruit_bus_device.spi_device import ( # pylint: disable=import-outside-toplevel + SPIDevice as spidev, + ) + _spi = spidev(spi_bus, spi_cs, baudrate=baudrate) read_buffer = bytearray(4) @@ -328,9 +350,11 @@ def _write(self, start_address, data, wraparound=False): if wraparound: pass else: - raise ValueError("Starting address + data length extends beyond" - " FRAM maximum address. Use 'wraparound=True' to" - " override this warning.") + raise ValueError( + "Starting address + data length extends beyond" + " FRAM maximum address. Use 'wraparound=True' to" + " override this warning." + ) with self._spi as spi: spi.write(bytearray([_SPI_OPCODE_WREN])) with self._spi as spi: @@ -354,9 +378,9 @@ def write_protected(self, value): write_buffer = bytearray(2) write_buffer[0] = _SPI_OPCODE_WRSR if value: - write_buffer[1] = 0x8C # set WPEN, BP0, and BP1 + write_buffer[1] = 0x8C # set WPEN, BP0, and BP1 else: - write_buffer[1] = 0x00 # clear WPEN, BP0, and BP1 + write_buffer[1] = 0x00 # clear WPEN, BP0, and BP1 with self._spi as spi: spi.write(write_buffer) if self._wp_pin is not None: diff --git a/docs/conf.py b/docs/conf.py index 8339085..03ea325 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -2,7 +2,8 @@ import os import sys -sys.path.insert(0, os.path.abspath('..')) + +sys.path.insert(0, os.path.abspath("..")) # -- General configuration ------------------------------------------------ @@ -10,10 +11,10 @@ # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ - 'sphinx.ext.autodoc', - 'sphinx.ext.intersphinx', - 'sphinx.ext.napoleon', - 'sphinx.ext.todo', + "sphinx.ext.autodoc", + "sphinx.ext.intersphinx", + "sphinx.ext.napoleon", + "sphinx.ext.todo", ] # Uncomment the below if you use native CircuitPython modules such as @@ -22,29 +23,40 @@ # autodoc_mock_imports = ["digitalio", "busio", "micropython"] -intersphinx_mapping = {'python': ('https://docs.python.org/3.4', None),'BusDevice': ('https://circuitpython.readthedocs.io/projects/busdevice/en/latest/', None),'Register': ('https://circuitpython.readthedocs.io/projects/register/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, + ), + "Register": ( + "https://circuitpython.readthedocs.io/projects/register/en/latest/", + None, + ), + "CircuitPython": ("https://circuitpython.readthedocs.io/en/latest/", None), +} # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] -source_suffix = '.rst' +source_suffix = ".rst" # The master toctree document. -master_doc = 'index' +master_doc = "index" # General information about the project. -project = u'Adafruit FRAM Library' -copyright = u'2018 Michael Schroeder' -author = u'Michael Schroeder' +project = u"Adafruit FRAM Library" +copyright = u"2018 Michael Schroeder" +author = u"Michael Schroeder" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. -version = u'1.0' +version = u"1.0" # The full version, including alpha/beta/rc tags. -release = u'1.0' +release = u"1.0" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. @@ -56,7 +68,7 @@ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path -exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', '.env', 'CODE_OF_CONDUCT.md'] +exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", ".env", "CODE_OF_CONDUCT.md"] # The reST default role (used for this markup: `text`) to use for all # documents. @@ -68,7 +80,7 @@ add_function_parentheses = True # The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' +pygments_style = "sphinx" # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False @@ -83,59 +95,62 @@ # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # -on_rtd = os.environ.get('READTHEDOCS', None) == 'True' +on_rtd = os.environ.get("READTHEDOCS", None) == "True" if not on_rtd: # only import and set the theme if we're building docs locally try: import sphinx_rtd_theme - html_theme = 'sphinx_rtd_theme' - html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), '.'] + + html_theme = "sphinx_rtd_theme" + html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), "."] except: - html_theme = 'default' - html_theme_path = ['.'] + html_theme = "default" + html_theme_path = ["."] else: - html_theme_path = ['.'] + html_theme_path = ["."] # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] +html_static_path = ["_static"] # The name of an image file (relative to this directory) to use as a favicon of # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # -html_favicon = '_static/favicon.ico' +html_favicon = "_static/favicon.ico" # Output file base name for HTML help builder. -htmlhelp_basename = 'AdafruitFramLibrarydoc' +htmlhelp_basename = "AdafruitFramLibrarydoc" # -- Options for LaTeX output --------------------------------------------- latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # - # 'papersize': 'letterpaper', - - # The font size ('10pt', '11pt' or '12pt'). - # - # 'pointsize': '10pt', - - # Additional stuff for the LaTeX preamble. - # - # 'preamble': '', - - # Latex figure (float) alignment - # - # 'figure_align': 'htbp', + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ - (master_doc, 'AdafruitFRAMLibrary.tex', u'AdafruitFRAM Library Documentation', - author, 'manual'), + ( + master_doc, + "AdafruitFRAMLibrary.tex", + u"AdafruitFRAM Library Documentation", + author, + "manual", + ), ] # -- Options for manual page output --------------------------------------- @@ -143,8 +158,13 @@ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - (master_doc, 'AdafruitFRAMlibrary', u'Adafruit FRAM Library Documentation', - [author], 1) + ( + master_doc, + "AdafruitFRAMlibrary", + u"Adafruit FRAM Library Documentation", + [author], + 1, + ) ] # -- Options for Texinfo output ------------------------------------------- @@ -153,7 +173,13 @@ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - (master_doc, 'AdafruitFRAMLibrary', u'Adafruit FRAM Library Documentation', - author, 'AdafruitFRAMLibrary', 'One line description of project.', - 'Miscellaneous'), + ( + master_doc, + "AdafruitFRAMLibrary", + u"Adafruit FRAM Library Documentation", + author, + "AdafruitFRAMLibrary", + "One line description of project.", + "Miscellaneous", + ), ] diff --git a/examples/fram_i2c_simpletest.py b/examples/fram_i2c_simpletest.py index 116d8ee..15e48fc 100644 --- a/examples/fram_i2c_simpletest.py +++ b/examples/fram_i2c_simpletest.py @@ -13,9 +13,9 @@ ## pin on breakout). 'write_protected()' can be used ## independent of the hardware pin. -#import digitalio -#wp = digitalio.DigitalInOut(board.D10) -#fram = adafruit_fram.FRAM_I2C(i2c, +# import digitalio +# wp = digitalio.DigitalInOut(board.D10) +# fram = adafruit_fram.FRAM_I2C(i2c, # address=0x53, # wp_pin=wp) @@ -33,6 +33,6 @@ ## a buffer the size of slice, which may cause ## problems on memory-constrained platforms. -#values = list(range(100)) # or bytearray or tuple -#fram[0] = values -#print(fram[0:99]) +# values = list(range(100)) # or bytearray or tuple +# fram[0] = values +# print(fram[0:99]) diff --git a/examples/fram_spi_simpletest.py b/examples/fram_spi_simpletest.py index 2deb5f5..3b6eec7 100644 --- a/examples/fram_spi_simpletest.py +++ b/examples/fram_spi_simpletest.py @@ -24,6 +24,6 @@ ## a buffer the size of 'length', which may cause ## problems on memory-constrained platforms. -#values = list(range(100)) # or bytearray or tuple -#fram[0] = values -#print(fram[0:99]) +# values = list(range(100)) # or bytearray or tuple +# fram[0] = values +# print(fram[0:99]) diff --git a/setup.py b/setup.py index 654b28d..a0fca0c 100644 --- a/setup.py +++ b/setup.py @@ -7,6 +7,7 @@ # Always prefer setuptools over distutils from setuptools import setup, find_packages + # To use a consistent encoding from codecs import open from os import path @@ -14,47 +15,38 @@ here = path.abspath(path.dirname(__file__)) # Get the long description from the README file -with open(path.join(here, 'README.rst'), encoding='utf-8') as f: +with open(path.join(here, "README.rst"), encoding="utf-8") as f: long_description = f.read() setup( - name='adafruit-circuitpython-fram', - + name="adafruit-circuitpython-fram", use_scm_version=True, - setup_requires=['setuptools_scm'], - - description='CircuitPython/Python library to support the I2C and SPI FRAM Breakouts.', + setup_requires=["setuptools_scm"], + description="CircuitPython/Python library to support the I2C and SPI FRAM Breakouts.", long_description=long_description, - long_description_content_type='text/x-rst', - + long_description_content_type="text/x-rst", # The project's main homepage. - url='https://github.com/adafruit/Adafruit_CircuitPython_FRAM', - + url="https://github.com/adafruit/Adafruit_CircuitPython_FRAM", # Author details - author='Adafruit Industries', - author_email='circuitpython@adafruit.com', - - install_requires=['Adafruit-Blinka', 'adafruit-circuitpython-busdevice'], - + author="Adafruit Industries", + author_email="circuitpython@adafruit.com", + install_requires=["Adafruit-Blinka", "adafruit-circuitpython-busdevice"], # Choose your license - license='MIT', - + license="MIT", # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Topic :: Software Development :: Libraries', - 'Topic :: System :: Hardware', - 'License :: OSI Approved :: MIT License', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.4', - 'Programming Language :: Python :: 3.5', + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "Topic :: Software Development :: Libraries", + "Topic :: System :: Hardware", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.4", + "Programming Language :: Python :: 3.5", ], - # What does your project relate to? - keywords='adafruit spi fram 12c hardware micropython circuitpython', - + keywords="adafruit spi fram 12c hardware micropython circuitpython", # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). - py_modules=['adafruit_fram'], -) \ No newline at end of file + py_modules=["adafruit_fram"], +) From a894b343b250ca10fad045f457c5ced1a1d28104 Mon Sep 17 00:00:00 2001 From: dherrada Date: Tue, 17 Mar 2020 12:58:45 -0400 Subject: [PATCH 2/2] Removed duplicate file --- ; | 386 -------------------------------------------------------------- 1 file changed, 386 deletions(-) delete mode 100644 ; diff --git a/; b/; deleted file mode 100644 index 1956be6..0000000 --- a/; +++ /dev/null @@ -1,386 +0,0 @@ -# The MIT License (MIT) -# -# Copyright (c) 2018 Michael Schroeder -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -""" -`adafruit_fram` -==================================================== - -CircuitPython/Python library to support the I2C and SPI FRAM Breakouts. - -* Author(s): Michael Schroeder - -Implementation Notes --------------------- - -**Hardware:** - - * Adafruit `I2C Non-Volatile FRAM Breakout - `_ (Product ID: 1895) - * Adafruit `SPI Non-Volatile FRAM Breakout - `_ (Product ID: 1897) - -**Software and Dependencies:** - -* Adafruit CircuitPython firmware for the supported boards: - https://github.com/adafruit/circuitpython/releases - - * Adafruit's Bus Device library: https://github.com/adafruit/Adafruit_CircuitPython_BusDevice -""" - -# imports -from micropython import const - -__version__ = "0.0.0-auto.0" -__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_FRAM.git" - -_MAX_SIZE_I2C = const(32768) -_MAX_SIZE_SPI = const(8192) - -_I2C_MANF_ID = const(0x0A) -_I2C_PROD_ID = const(0x510) - -_SPI_MANF_ID = const(0x04) -_SPI_PROD_ID = const(0x302) - - -class FRAM: - """ - Driver base for the FRAM Breakout. - """ - - def __init__(self, max_size, write_protect=False, wp_pin=None): - self._max_size = max_size - self._wp = write_protect - self._wraparound = False - if not wp_pin is None: - self._wp_pin = wp_pin - # Make sure write_prot is set to output - self._wp_pin.switch_to_output() - self._wp_pin.value = self._wp - else: - self._wp_pin = wp_pin - - @property - def write_wraparound(self): - """ Determines if sequential writes will wrapaound highest memory address - (``len(FRAM) - 1``) address. If ``False``, and a requested write will - extend beyond the maximum size, an exception is raised. - """ - return self._wraparound - - @write_wraparound.setter - def write_wraparound(self, value): - if not value in (True, False): - raise ValueError("Write wraparound must be 'True' or 'False'.") - self._wraparound = value - - @property - def write_protected(self): - """ The status of write protection. Default value on initialization is - ``False``. - - When a ``WP`` pin is supplied during initialization, or using - ``write_protect_pin``, the status is tied to that pin and enables - hardware-level protection. - - When no ``WP`` pin is supplied, protection is only at the software - level in this library. - """ - return self._wp if self._wp_pin is None else self._wp_pin.value - - def __len__(self): - """ The size of the current FRAM chip. This is one more than the highest - address location that can be read or written to. - - .. code-block:: python - - fram = adafruit_fram.FRAM_xxx() # xxx = 'I2C' or 'SPI' - - # size returned by len() - len(fram) - - # can be used with range - for i in range(0, len(fram)) - """ - return self._max_size - - def __getitem__(self, address): - """ Read the value at the given index, or values in a slice. - - .. code-block:: python - - # read single index - fram[0] - - # read values 0 thru 9 with a slice - fram[0:9] - """ - if isinstance(address, int): - if not 0 <= address < self._max_size: - raise ValueError( - "Address '{0}' out of range. It must be 0 <= address < {1}.".format( - address, self._max_size - ) - ) - buffer = bytearray(1) - read_buffer = self._read_address(address, buffer) - elif isinstance(address, slice): - if address.step is not None: - raise ValueError("Slice stepping is not currently available.") - - regs = list( - range( - address.start if address.start is not None else 0, - address.stop + 1 if address.stop is not None else self._max_size, - ) - ) - if regs[0] < 0 or (regs[0] + len(regs)) > self._max_size: - raise ValueError( - "Address slice out of range. It must be 0 <= [starting address" - ":stopping address] < {0}.".format(self._max_size) - ) - - buffer = bytearray(len(regs)) - read_buffer = self._read_address(regs[0], buffer) - - return read_buffer - - def __setitem__(self, address, value): - """ Write the value at the given starting index. - - .. code-block:: python - - # write single index - fram[0] = 1 - - # write values 0 thru 4 with a list - fram[0] = [0,1,2,3] - """ - if self.write_protected: - raise RuntimeError("FRAM currently write protected.") - - if isinstance(address, int): - if not isinstance(value, (int, bytearray, list, tuple)): - raise ValueError( - "Data must be a single integer, or a bytearray," " list, or tuple." - ) - if not 0 <= address < self._max_size: - raise ValueError( - "Address '{0}' out of range. It must be 0 <= address < {1}.".format( - address, self._max_size - ) - ) - - self._write(address, value, self._wraparound) - - elif isinstance(address, slice): - raise ValueError("Slicing not available during write operations.") - - def _read_address(self, address, read_buffer): - # Implemented by subclass - raise NotImplementedError - - def _write(self, start_address, data, wraparound): - # Implemened by subclass - raise NotImplementedError - - -class FRAM_I2C(FRAM): - """ I2C class for FRAM. - - :param: ~busio.I2C i2c_bus: The I2C bus the FRAM is connected to. - :param: int address: I2C address of FRAM. Default address is ``0x50``. - :param: bool write_protect: Turns on/off initial write protection. - Default is ``False``. - :param: wp_pin: (Optional) Physical pin connected to the ``WP`` breakout pin. - Must be a ``digitalio.DigitalInOut`` object. - """ - - # pylint: disable=too-many-arguments - def __init__(self, i2c_bus, address=0x50, write_protect=False, wp_pin=None): - from adafruit_bus_device.i2c_device import ( # pylint: disable=import-outside-toplevel - I2CDevice as i2cdev, - ) - - dev_id_addr = 0xF8 >> 1 - read_buf = bytearray(3) - with i2cdev(i2c_bus, dev_id_addr) as dev_id: - dev_id.write_then_readinto(bytearray([(address << 1)]), read_buf) - manf_id = (read_buf[0] << 4) + (read_buf[1] >> 4) - prod_id = ((read_buf[1] & 0x0F) << 8) + read_buf[2] - if (manf_id != _I2C_MANF_ID) and (prod_id != _I2C_PROD_ID): - raise OSError("FRAM I2C device not found.") - - self._i2c = i2cdev(i2c_bus, address) - super().__init__(_MAX_SIZE_I2C, write_protect, wp_pin) - - def _read_address(self, address, read_buffer): - write_buffer = bytearray(2) - write_buffer[0] = address >> 8 - write_buffer[1] = address & 0xFF - with self._i2c as i2c: - i2c.write_then_readinto(write_buffer, read_buffer) - return read_buffer - - def _write(self, start_address, data, wraparound=False): - # Decided against using the chip's "Page Write", since that would require - # doubling the memory usage by creating a buffer that includes the passed - # in data so that it can be sent all in one `i2c.write`. The single-write - # method is slower, and forces us to handle wraparound, but I feel this - # is a better tradeoff for limiting the memory required for large writes. - buffer = bytearray(3) - if not isinstance(data, int): - data_length = len(data) - else: - data_length = 1 - data = [data] - if (start_address + data_length) > self._max_size: - if wraparound: - pass - else: - raise ValueError( - "Starting address + data length extends beyond" - " FRAM maximum address. Use ``write_wraparound`` to" - " override this warning." - ) - with self._i2c as i2c: - for i in range(0, data_length): - if not (start_address + i) > self._max_size - 1: - buffer[0] = (start_address + i) >> 8 - buffer[1] = (start_address + i) & 0xFF - else: - buffer[0] = ((start_address + i) - self._max_size + 1) >> 8 - buffer[1] = ((start_address + i) - self._max_size + 1) & 0xFF - buffer[2] = data[i] - i2c.write(buffer) - - # pylint: disable=no-member - @FRAM.write_protected.setter - def write_protected(self, value): - if value not in (True, False): - raise ValueError("Write protected value must be 'True' or 'False'.") - self._wp = value - if not self._wp_pin is None: - self._wp_pin.value = value - - -# the following pylint disables are related to the '_SPI_OPCODE' consts, the super -# class setter '@FRAM.write_protected.setter', and pylint not being able to see -# 'spi.write()' in SPIDevice. Travis run for reference: -# https://travis-ci.com/sommersoft/Adafruit_CircuitPython_FRAM/builds/87112669 - -# pylint: disable=no-member,undefined-variable -class FRAM_SPI(FRAM): - """ SPI class for FRAM. - - :param: ~busio.SPI spi_bus: The SPI bus the FRAM is connected to. - :param: ~digitalio.DigitalInOut spi_cs: The SPI CS pin. - :param: bool write_protect: Turns on/off initial write protection. - Default is ``False``. - :param: wp_pin: (Optional) Physical pin connected to the ``WP`` breakout pin. - Must be a ``digitalio.DigitalInOut`` object. - :param int baudrate: SPI baudrate to use. Default is ``1000000``. - """ - - _SPI_OPCODE_WREN = const(0x6) # Set write enable latch - _SPI_OPCODE_WRDI = const(0x4) # Reset write enable latch - _SPI_OPCODE_RDSR = const(0x5) # Read status register - _SPI_OPCODE_WRSR = const(0x1) # Write status register - _SPI_OPCODE_READ = const(0x3) # Read memory code - _SPI_OPCODE_WRITE = const(0x2) # Write memory code - _SPI_OPCODE_RDID = const(0x9F) # Read device ID - - # pylint: disable=too-many-arguments,too-many-locals - def __init__( - self, spi_bus, spi_cs, write_protect=False, wp_pin=None, baudrate=100000 - ): - from adafruit_bus_device.spi_device import ( # pylint: disable=import-outside-toplevel - SPIDevice as spidev, - ) - _spi = spidev(spi_bus, spi_cs, baudrate=baudrate) - - read_buffer = bytearray(4) - with _spi as spi: - spi.write(bytearray([_SPI_OPCODE_RDID])) - spi.readinto(read_buffer) - prod_id = (read_buffer[3] << 8) + (read_buffer[2]) - if (read_buffer[0] != _SPI_MANF_ID) and (prod_id != _SPI_PROD_ID): - raise OSError("FRAM SPI device not found.") - - self._spi = _spi - super().__init__(_MAX_SIZE_SPI, write_protect, wp_pin) - - def _read_address(self, address, read_buffer): - write_buffer = bytearray(3) - write_buffer[0] = _SPI_OPCODE_READ - write_buffer[1] = address >> 8 - write_buffer[2] = address & 0xFF - with self._spi as spi: - spi.write(write_buffer) - spi.readinto(read_buffer) - return read_buffer - - def _write(self, start_address, data, wraparound=False): - buffer = bytearray(3) - if not isinstance(data, int): - data_length = len(data) - else: - data_length = 1 - data = [data] - if (start_address + data_length) > self._max_size: - if wraparound: - pass - else: - raise ValueError( - "Starting address + data length extends beyond" - " FRAM maximum address. Use 'wraparound=True' to" - " override this warning." - ) - with self._spi as spi: - spi.write(bytearray([_SPI_OPCODE_WREN])) - with self._spi as spi: - buffer[0] = _SPI_OPCODE_WRITE - buffer[1] = start_address >> 8 - buffer[2] = start_address & 0xFF - spi.write(buffer) - for i in range(0, data_length): - spi.write(bytearray([data[i]])) - with self._spi as spi: - spi.write(bytearray([_SPI_OPCODE_WRDI])) - - @FRAM.write_protected.setter - def write_protected(self, value): - # While it is possible to protect block ranges on the SPI chip, - # it seems superfluous to do so. So, block protection always protects - # the entire memory (BP0 and BP1). - if value not in (True, False): - raise ValueError("Write protected value must be 'True' or 'False'.") - self._wp = value - write_buffer = bytearray(2) - write_buffer[0] = _SPI_OPCODE_WRSR - if value: - write_buffer[1] = 0x8C # set WPEN, BP0, and BP1 - else: - write_buffer[1] = 0x00 # clear WPEN, BP0, and BP1 - with self._spi as spi: - spi.write(write_buffer) - if self._wp_pin is not None: - self._wp_pin.value = value