diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..21c125c --- /dev/null +++ b/.gitattributes @@ -0,0 +1,11 @@ +# SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense + +.py text eol=lf +.rst text eol=lf +.txt text eol=lf +.yaml text eol=lf +.toml text eol=lf +.license text eol=lf +.md text eol=lf diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 0e5fccc..ff19dde 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,42 +1,21 @@ -# SPDX-FileCopyrightText: 2020 Diego Elio Pettenò +# SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries # # SPDX-License-Identifier: Unlicense repos: - - repo: https://github.com/python/black - rev: 22.3.0 - hooks: - - id: black - - repo: https://github.com/fsfe/reuse-tool - rev: v0.14.0 - hooks: - - id: reuse - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.2.0 + rev: v4.5.0 hooks: - id: check-yaml - id: end-of-file-fixer - id: trailing-whitespace - - repo: https://github.com/pycqa/pylint - rev: v2.15.5 + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.3.4 hooks: - - id: pylint - name: pylint (library code) - types: [python] - args: - - --disable=consider-using-f-string - exclude: "^(docs/|examples/|tests/|setup.py$)" - - id: pylint - name: pylint (example code) - description: Run pylint rules on "examples/*.py" files - types: [python] - files: "^examples/" - args: - - --disable=missing-docstring,invalid-name,consider-using-f-string,duplicate-code - - id: pylint - name: pylint (test code) - description: Run pylint rules on "tests/*.py" files - types: [python] - files: "^tests/" - args: - - --disable=missing-docstring,consider-using-f-string,duplicate-code + - id: ruff-format + - id: ruff + args: ["--fix"] + - repo: https://github.com/fsfe/reuse-tool + rev: v3.0.1 + hooks: + - id: reuse diff --git a/.pylintrc b/.pylintrc deleted file mode 100644 index f945e92..0000000 --- a/.pylintrc +++ /dev/null @@ -1,399 +0,0 @@ -# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries -# -# SPDX-License-Identifier: Unlicense - -[MASTER] - -# A comma-separated list of package or module names from where C extensions may -# be loaded. Extensions are loading into the active Python interpreter and may -# run arbitrary code -extension-pkg-whitelist= - -# Add files or directories to the ignore-list. They should be base names, not -# paths. -ignore=CVS - -# Add files or directories matching the regex patterns to the ignore-list. The -# regex matches against base names, not paths. -ignore-patterns= - -# Python code to execute, usually for sys.path manipulation such as -# pygtk.require(). -#init-hook= - -# Use multiple processes to speed up Pylint. -jobs=1 - -# List of plugins (as comma separated values of python modules names) to load, -# usually to register additional checkers. -load-plugins=pylint.extensions.no_self_use - -# Pickle collected data for later comparisons. -persistent=yes - -# Specify a configuration file. -#rcfile= - -# Allow loading of arbitrary C extensions. Extensions are imported into the -# active Python interpreter and may run arbitrary code. -unsafe-load-any-extension=no - - -[MESSAGES CONTROL] - -# Only show warnings with the listed confidence levels. Leave empty to show -# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED -confidence= - -# Disable the message, report, category or checker with the given id(s). You -# can either give multiple identifiers separated by comma (,) or put this -# option multiple times (only on the command line, not in the configuration -# file where it should appear only once).You can also use "--disable=all" to -# disable everything first and then reenable specific checks. For example, if -# you want to run only the similarities checker, you can use "--disable=all -# --enable=similarities". If you want to run only the classes checker, but have -# no Warning level messages displayed, use"--disable=all --enable=classes -# --disable=W" -# disable=import-error,raw-checker-failed,bad-inline-option,locally-disabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,deprecated-str-translate-call -disable=raw-checker-failed,bad-inline-option,locally-disabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,import-error,pointless-string-statement,unspecified-encoding - -# Enable the message, report, category or checker with the given id(s). You can -# either give multiple identifier separated by comma (,) or put this option -# multiple time (only on the command line, not in the configuration file where -# it should appear only once). See also the "--disable" option for examples. -enable= - - -[REPORTS] - -# Python expression which should return a note less than 10 (10 is the highest -# note). You have access to the variables errors warning, statement which -# respectively contain the number of errors / warnings messages and the total -# number of statements analyzed. This is used by the global evaluation report -# (RP0004). -evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) - -# Template used to display messages. This is a python new-style format string -# used to format the message information. See doc for all details -#msg-template= - -# Set the output format. Available formats are text, parseable, colorized, json -# and msvs (visual studio).You can also give a reporter class, eg -# mypackage.mymodule.MyReporterClass. -output-format=text - -# Tells whether to display a full report or only the messages -reports=no - -# Activate the evaluation score. -score=yes - - -[REFACTORING] - -# Maximum number of nested blocks for function / method body -max-nested-blocks=5 - - -[LOGGING] - -# Logging modules to check that the string format arguments are in logging -# function parameter format -logging-modules=logging - - -[SPELLING] - -# Spelling dictionary name. Available dictionaries: none. To make it working -# install python-enchant package. -spelling-dict= - -# List of comma separated words that should not be checked. -spelling-ignore-words= - -# A path to a file that contains private dictionary; one word per line. -spelling-private-dict-file= - -# Tells whether to store unknown words to indicated private dictionary in -# --spelling-private-dict-file option instead of raising a message. -spelling-store-unknown-words=no - - -[MISCELLANEOUS] - -# List of note tags to take in consideration, separated by a comma. -# notes=FIXME,XXX,TODO -notes=FIXME,XXX - - -[TYPECHECK] - -# List of decorators that produce context managers, such as -# contextlib.contextmanager. Add to this list to register other decorators that -# produce valid context managers. -contextmanager-decorators=contextlib.contextmanager - -# List of members which are set dynamically and missed by pylint inference -# system, and so shouldn't trigger E1101 when accessed. Python regular -# expressions are accepted. -generated-members= - -# Tells whether missing members accessed in mixin class should be ignored. A -# mixin class is detected if its name ends with "mixin" (case insensitive). -ignore-mixin-members=yes - -# This flag controls whether pylint should warn about no-member and similar -# checks whenever an opaque object is returned when inferring. The inference -# can return multiple potential results while evaluating a Python object, but -# some branches might not be evaluated, which results in partial inference. In -# that case, it might be useful to still emit no-member and other checks for -# the rest of the inferred objects. -ignore-on-opaque-inference=yes - -# List of class names for which member attributes should not be checked (useful -# for classes with dynamically set attributes). This supports the use of -# qualified names. -ignored-classes=optparse.Values,thread._local,_thread._local - -# List of module names for which member attributes should not be checked -# (useful for modules/projects where namespaces are manipulated during runtime -# and thus existing member attributes cannot be deduced by static analysis. It -# supports qualified module names, as well as Unix pattern matching. -ignored-modules=board - -# Show a hint with possible names when a member name was not found. The aspect -# of finding the hint is based on edit distance. -missing-member-hint=yes - -# The minimum edit distance a name should have in order to be considered a -# similar match for a missing member name. -missing-member-hint-distance=1 - -# The total number of similar names that should be taken in consideration when -# showing a hint for a missing member. -missing-member-max-choices=1 - - -[VARIABLES] - -# List of additional names supposed to be defined in builtins. Remember that -# you should avoid to define new builtins when possible. -additional-builtins= - -# Tells whether unused global variables should be treated as a violation. -allow-global-unused-variables=yes - -# List of strings which can identify a callback function by name. A callback -# name must start or end with one of those strings. -callbacks=cb_,_cb - -# A regular expression matching the name of dummy variables (i.e. expectedly -# not used). -dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ - -# Argument names that match this expression will be ignored. Default to name -# with leading underscore -ignored-argument-names=_.*|^ignored_|^unused_ - -# Tells whether we should check for unused import in __init__ files. -init-import=no - -# List of qualified module names which can have objects that can redefine -# builtins. -redefining-builtins-modules=six.moves,future.builtins - - -[FORMAT] - -# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. -# expected-line-ending-format= -expected-line-ending-format=LF - -# Regexp for a line that is allowed to be longer than the limit. -ignore-long-lines=^\s*(# )??$ - -# Number of spaces of indent required inside a hanging or continued line. -indent-after-paren=4 - -# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 -# tab). -indent-string=' ' - -# Maximum number of characters on a single line. -max-line-length=100 - -# Maximum number of lines in a module -max-module-lines=1000 - -# Allow the body of a class to be on the same line as the declaration if body -# contains single statement. -single-line-class-stmt=no - -# Allow the body of an if to be on the same line as the test if there is no -# else. -single-line-if-stmt=no - - -[SIMILARITIES] - -# Ignore comments when computing similarities. -ignore-comments=yes - -# Ignore docstrings when computing similarities. -ignore-docstrings=yes - -# Ignore imports when computing similarities. -ignore-imports=yes - -# Minimum lines number of a similarity. -min-similarity-lines=12 - - -[BASIC] - -# Regular expression matching correct argument names -argument-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Regular expression matching correct attribute names -attr-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Bad variable names which should always be refused, separated by a comma -bad-names=foo,bar,baz,toto,tutu,tata - -# Regular expression matching correct class attribute names -class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ - -# Regular expression matching correct class names -# class-rgx=[A-Z_][a-zA-Z0-9]+$ -class-rgx=[A-Z_][a-zA-Z0-9_]+$ - -# Regular expression matching correct constant names -const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ - -# Minimum line length for functions/classes that require docstrings, shorter -# ones are exempt. -docstring-min-length=-1 - -# Regular expression matching correct function names -function-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Good variable names which should always be accepted, separated by a comma -# good-names=i,j,k,ex,Run,_ -good-names=r,g,b,w,i,j,k,n,x,y,z,ex,ok,Run,_ - -# Include a hint for the correct naming format with invalid-name -include-naming-hint=no - -# Regular expression matching correct inline iteration names -inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ - -# Regular expression matching correct method names -method-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Regular expression matching correct module names -module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ - -# Colon-delimited sets of names that determine each other's naming style when -# the name regexes allow several styles. -name-group= - -# Regular expression which should only match function or class names that do -# not require a docstring. -no-docstring-rgx=^_ - -# List of decorators that produce properties, such as abc.abstractproperty. Add -# to this list to register other decorators that produce valid properties. -property-classes=abc.abstractproperty - -# Regular expression matching correct variable names -variable-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - - -[IMPORTS] - -# Allow wildcard imports from modules that define __all__. -allow-wildcard-with-all=no - -# Analyse import fallback blocks. This can be used to support both Python 2 and -# 3 compatible code, which means that the block might have code that exists -# only in one or another interpreter, leading to false positives when analysed. -analyse-fallback-blocks=no - -# Deprecated modules which should not be used, separated by a comma -deprecated-modules=optparse,tkinter.tix - -# Create a graph of external dependencies in the given file (report RP0402 must -# not be disabled) -ext-import-graph= - -# Create a graph of every (i.e. internal and external) dependencies in the -# given file (report RP0402 must not be disabled) -import-graph= - -# Create a graph of internal dependencies in the given file (report RP0402 must -# not be disabled) -int-import-graph= - -# Force import order to recognize a module as part of the standard -# compatibility libraries. -known-standard-library= - -# Force import order to recognize a module as part of a third party library. -known-third-party=enchant - - -[CLASSES] - -# List of method names used to declare (i.e. assign) instance attributes. -defining-attr-methods=__init__,__new__,setUp - -# List of member names, which should be excluded from the protected access -# warning. -exclude-protected=_asdict,_fields,_replace,_source,_make - -# List of valid names for the first argument in a class method. -valid-classmethod-first-arg=cls - -# List of valid names for the first argument in a metaclass class method. -valid-metaclass-classmethod-first-arg=mcs - - -[DESIGN] - -# Maximum number of arguments for function / method -max-args=5 - -# Maximum number of attributes for a class (see R0902). -# max-attributes=7 -max-attributes=11 - -# Maximum number of boolean expressions in a if statement -max-bool-expr=5 - -# Maximum number of branch for function / method body -max-branches=12 - -# Maximum number of locals for function / method body -max-locals=15 - -# Maximum number of parents for a class (see R0901). -max-parents=7 - -# Maximum number of public methods for a class (see R0904). -max-public-methods=20 - -# Maximum number of return / yield for function / method body -max-returns=6 - -# Maximum number of statements in function / method body -max-statements=50 - -# Minimum number of public methods for a class (see R0903). -min-public-methods=1 - - -[EXCEPTIONS] - -# Exceptions that will emit a warning when being caught. Defaults to -# "Exception" -overgeneral-exceptions=builtins.Exception diff --git a/README.rst b/README.rst index 9562909..b94c691 100644 --- a/README.rst +++ b/README.rst @@ -13,9 +13,9 @@ Introduction :target: https://github.com/adafruit/Adafruit_CircuitPython_MCP2515/actions :alt: Build Status -.. image:: https://img.shields.io/badge/code%20style-black-000000.svg - :target: https://github.com/psf/black - :alt: Code Style: Black +.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json + :target: https://github.com/astral-sh/ruff + :alt: Code Style: Ruff A CircuitPython library for working with the MCP2515 CAN bus controller diff --git a/adafruit_mcp2515/__init__.py b/adafruit_mcp2515/__init__.py index a96ccf5..42bfac0 100644 --- a/adafruit_mcp2515/__init__.py +++ b/adafruit_mcp2515/__init__.py @@ -25,10 +25,12 @@ """ from collections import namedtuple -from struct import unpack_from, pack_into +from struct import pack_into, unpack_from from time import sleep -from micropython import const + from adafruit_bus_device import spi_device +from micropython import const + from .canio import * from .timer import Timer @@ -125,15 +127,13 @@ EXTID_BOTTOM_18_MASK = (1 << 18) - 1 # bottom 18 bits STDID_BOTTOM_11_MASK = 0x7FF -EXTID_FLAG_MASK = ( - 1 << 19 -) # to set/get the "is an extended id?" flag from a 4-byte ID buffer +EXTID_FLAG_MASK = 1 << 19 # to set/get the "is an extended id?" flag from a 4-byte ID buffer # masks _MODE_MASK = const(0xE0) _RXB_RX_MASK = const(0x60) -_RXB_BUKT_MASK = const((1 << 2)) +_RXB_BUKT_MASK = const(1 << 2) _RXB_RX_STDEXT = const(0x00) _STAT_RXIF_MASK = const(0x03) @@ -292,7 +292,6 @@ def __init__( auto_restart: bool = False, debug: bool = False, ): - if loopback and not silent: raise AttributeError("Loopback mode requires silent to be set") if auto_restart: @@ -322,7 +321,6 @@ def __init__( self.initialize() def _init_buffers(self): - self._tx_buffers = [ _TransmitBuffer( CTRL_REG=_TXB0CTRL, @@ -427,7 +425,7 @@ def read_message(self): return self._unread_message_queue.pop(0) def _read_rx_buffer(self, read_command): - for i in range(len(self._buffer)): # pylint: disable=consider-using-enumerate + for i in range(len(self._buffer)): self._buffer[i] = 0 # read from buffer @@ -453,9 +451,7 @@ def _read_rx_buffer(self, read_command): message_length = min(8, dlc & 0xF) if (dlc & _RTR_MASK) > 0: - frame_obj = RemoteTransmissionRequest( - sender_id, message_length, extended=extended - ) + frame_obj = RemoteTransmissionRequest(sender_id, message_length, extended=extended) else: frame_obj = Message( sender_id, @@ -480,7 +476,6 @@ def _read_from_rx_buffers(self): self._read_rx_buffer(_READ_RX1) def _write_message(self, tx_buffer, message_obj): - if tx_buffer is None: raise RuntimeError("No transmit buffer available to send") if isinstance(message_obj, RemoteTransmissionRequest): @@ -531,7 +526,6 @@ def _write_message(self, tx_buffer, message_obj): # TODO: Priority def _start_transmit(self, tx_buffer): - # self._buffer[0] = tx_buffer.SEND_CMD with self._bus_device_obj as spi: spi.write_readinto( @@ -639,7 +633,7 @@ def _tx_buffers_in_use(self): # TODO: this should return a tuple of busy states # byte status = mcp2515_readStatus() & MCP_STAT_TX_PENDING_MASK status = self._read_status() - self._dbg("Status byte:", "{:#010b}".format(status)) + self._dbg("Status byte:", f"{status:#010b}") return ( bool(status & _STAT_TX0_PENDING), bool(status & _STAT_TX1_PENDING), @@ -688,7 +682,6 @@ def _set_mode(self, mode): return self._timer.rewind_to(5) while not self._timer.expired: - new_mode_set = self._request_new_mode(mode) if new_mode_set: self._mode = mode @@ -766,9 +759,7 @@ def _get_bus_status(self): self._rx1_overflow, ) = flags if self._rx0_overflow or self._rx0_overflow: - self._mod_register( - _EFLG, 0xC0, 0 - ) # clear overflow bits now that we've recorded them + self._mod_register(_EFLG, 0xC0, 0) # clear overflow bits now that we've recorded them if buss_off: self._bus_state = BusState.BUS_OFF @@ -806,7 +797,6 @@ def _create_mask(self, match): raise RuntimeError("No Masks Available") def _create_filter(self, match, mask_index): - next_filter_index = len(self._filters_in_use[mask_index]) if next_filter_index == len(FILTERS[mask_index]): raise RuntimeError("No Filters Available") diff --git a/adafruit_mcp2515/canio/__init__.py b/adafruit_mcp2515/canio/__init__.py index 41ff222..4204391 100644 --- a/adafruit_mcp2515/canio/__init__.py +++ b/adafruit_mcp2515/canio/__init__.py @@ -2,8 +2,10 @@ # # SPDX-License-Identifier: MIT """Python implementation of the CircuitPython core `canio` API""" + # pylint:disable=too-few-public-methods, invalid-name, redefined-builtin import time + from ..timer import Timer @@ -36,15 +38,12 @@ def data(self): @data.setter def data(self, new_data): - if (new_data is None) or (not (type(new_data) in [bytes, bytearray])): - + if (new_data is None) or (not (type(new_data) in {bytes, bytearray})): raise AttributeError( "non-RTR canio.Message must have a `data` argument of type `bytes`" ) if len(new_data) > 8: - raise AttributeError( - "`canio.Message` object data must be of length 8 or less" - ) + raise AttributeError("`canio.Message` object data must be of length 8 or less") # self.rtr = False # self._data = new_data self._data = bytearray(new_data) diff --git a/adafruit_mcp2515/timer.py b/adafruit_mcp2515/timer.py index 814fb0c..db4b875 100644 --- a/adafruit_mcp2515/timer.py +++ b/adafruit_mcp2515/timer.py @@ -2,6 +2,7 @@ # # SPDX-License-Identifier: MIT """Provides a simple timer class; see `Timer`""" + from time import monotonic diff --git a/docs/api.rst b/docs/api.rst index 3651a76..6bab2b7 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -4,6 +4,9 @@ .. If your library file(s) are nested in a directory (e.g. /adafruit_foo/foo.py) .. use this format as the module name: "adafruit_foo.foo" +API Reference +############# + .. automodule:: adafruit_mcp2515 :members: .. automodule:: adafruit_mcp2515.canio diff --git a/docs/conf.py b/docs/conf.py index d4aa0c8..70025fa 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,12 +1,10 @@ -# -*- coding: utf-8 -*- - # SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries # # SPDX-License-Identifier: MIT +import datetime import os import sys -import datetime sys.path.insert(0, os.path.abspath("..")) @@ -52,9 +50,7 @@ creation_year = "2020" current_year = str(datetime.datetime.now().year) year_duration = ( - current_year - if current_year == creation_year - else creation_year + " - " + current_year + current_year if current_year == creation_year else creation_year + " - " + current_year ) copyright = year_duration + " Bryan Siepert" author = "Bryan Siepert" diff --git a/examples/mcp2515_canio_test.py b/examples/mcp2515_canio_test.py index eadd5bf..3537d05 100644 --- a/examples/mcp2515_canio_test.py +++ b/examples/mcp2515_canio_test.py @@ -11,35 +11,33 @@ CAN_TYPE = None try: + from board import CAN_RX, CAN_TX from canio import ( CAN, + BusState, + Match, Message, RemoteTransmissionRequest, - Match, - BusState, ) - from board import CAN_RX, CAN_TX CAN_TYPE = "SAM-E" def builtin_bus_factory(): return CAN(rx=CAN_RX, tx=CAN_TX, baudrate=1000000, loopback=True) -except ImportError as e: +except ImportError: print("no native canio, trying mcp") - from digitalio import DigitalInOut - import board + from digitalio import DigitalInOut + from adafruit_mcp2515 import MCP2515 as CAN from adafruit_mcp2515.canio import ( + BusState, + Match, Message, RemoteTransmissionRequest, - Match, - BusState, ) - from adafruit_mcp2515 import MCP2515 as CAN - CAN_TYPE = "MCP2515" def builtin_bus_factory(): @@ -68,7 +66,6 @@ def test_message(_can=builtin_bus_factory): def test_rtr_constructor(): - print("Testing RemoteTransmissionRequest") assert RemoteTransmissionRequest(id=0, length=0).id == 0 assert RemoteTransmissionRequest(id=1, length=0).id == 1 @@ -80,9 +77,7 @@ def test_rtr_constructor(): def test_rtr_receive(can=builtin_bus_factory): - with can() as b, b.listen(timeout=0.1) as l: - for length in lengths: print("Test messages of length", length) @@ -92,9 +87,7 @@ def test_rtr_receive(can=builtin_bus_factory): mi = l.receive() assert mi assert isinstance(mi, RemoteTransmissionRequest) - assert mi.id == 0x5555555, "Extended ID does not match: 0x{:07X}".format( - mi.id - ) + assert mi.id == 0x5555555, f"Extended ID does not match: 0x{mi.id:07X}" assert mi.extended assert mi.length == length @@ -103,9 +96,9 @@ def test_rtr_receive(can=builtin_bus_factory): mi = l.receive() assert mi assert isinstance(mi, RemoteTransmissionRequest) - assert ( - mi.id == max_standard_id - ), "Max standard ID not sent/received properly: %s" % hex(mi.id) + assert mi.id == max_standard_id, "Max standard ID not sent/received properly: %s" % hex( + mi.id + ) assert mi.length == length mo = RemoteTransmissionRequest(id=0x555, length=length) @@ -116,17 +109,13 @@ def test_rtr_receive(can=builtin_bus_factory): assert mi.id == 0x555 assert mi.length == length - mo = RemoteTransmissionRequest( - id=max_extended_id, extended=True, length=length - ) + mo = RemoteTransmissionRequest(id=max_extended_id, extended=True, length=length) assert mo.extended b.send(mo) mi = l.receive() assert mi assert isinstance(mi, RemoteTransmissionRequest) - assert ( - mi.id == max_extended_id - ), "Max extended ID not sent/received properly" + assert mi.id == max_extended_id, "Max extended ID not sent/received properly" assert mi.length == length data = bytes(range(length)) @@ -146,7 +135,6 @@ def test_rtr_receive(can=builtin_bus_factory): def test_filters1(can=builtin_bus_factory): - matches = [ Match(0x408), Match(0x700, mask=0x7F0), @@ -257,7 +245,6 @@ def test_filters2(can=builtin_bus_factory): def test_iter(can=builtin_bus_factory): - print("Test iter()") with can() as b, b.listen(timeout=0.1) as l: assert iter(l) is l @@ -283,7 +270,6 @@ def test_iter(can=builtin_bus_factory): def test_mcp_standard_id_exact_filters(can=builtin_bus_factory): - print("Test MCP Standard ID filters") standard_matches = [ Match(0x408), @@ -317,7 +303,6 @@ def test_mcp_standard_id_exact_filters(can=builtin_bus_factory): def test_mcp_standard_id_masked_filters(can=builtin_bus_factory): - print("Test MCP Standard ID masked filters") standard_matches = [ Match(0x400, mask=0x7F0), # should allow 0x40* @@ -422,12 +407,12 @@ def test_bus_state(can=builtin_bus_factory): print("Test `BusState` support") with can() as b: - assert b.state in [ + assert b.state in { BusState.BUS_OFF, BusState.ERROR_PASSIVE, BusState.ERROR_WARNING, BusState.ERROR_ACTIVE, - ] + } def test_listener_deinit(can=builtin_bus_factory): diff --git a/examples/mcp2515_loopback_test.py b/examples/mcp2515_loopback_test.py index 8ea3034..939b034 100644 --- a/examples/mcp2515_loopback_test.py +++ b/examples/mcp2515_loopback_test.py @@ -9,10 +9,12 @@ # from adafruit_mcp2515.canio import Timer +from board import D5 as CS_PIN +from board import SPI from digitalio import DigitalInOut -from board import D5 as CS_PIN, SPI -from adafruit_mcp2515.canio import Timer, Message, RemoteTransmissionRequest + from adafruit_mcp2515 import MCP2515 as CAN +from adafruit_mcp2515.canio import Message, RemoteTransmissionRequest, Timer # from board import CAN_RX, CAN_TX @@ -29,7 +31,6 @@ def bus(): t = Timer(timeout=5) while True: with bus() as can, can.listen(timeout=1.0) as listener: - mb1.insert(0, mb2.pop()) mb2.insert(0, mb1.pop()) message = Message(id=0xFFAA, data=bytes(mb1 + mb2), extended=True) @@ -43,7 +44,7 @@ def bus(): msg = listener.receive() print("Message from ", hex(msg.id)) print("message data:", msg.data) - message_str = "::".join(["0x{:02X}".format(i) for i in msg.data]) + message_str = "::".join([f"0x{i:02X}" for i in msg.data]) print(message_str) # instead of sleeping, pool for messages to fill queue diff --git a/examples/mcp2515_receive.py b/examples/mcp2515_receive.py index 7b23483..b922c81 100644 --- a/examples/mcp2515_receive.py +++ b/examples/mcp2515_receive.py @@ -2,12 +2,12 @@ # # SPDX-License-Identifier: MIT -import digitalio import board import busio -from adafruit_mcp2515.canio import Timer -from adafruit_mcp2515.canio import RemoteTransmissionRequest, Message +import digitalio + from adafruit_mcp2515 import MCP2515 as CAN +from adafruit_mcp2515.canio import Message, RemoteTransmissionRequest, Timer cs = digitalio.DigitalInOut(board.D5) cs.switch_to_output() @@ -38,7 +38,7 @@ if isinstance(msg, Message): if len(msg.data) > 0: print("Data:", end="") - message_str = ",".join(["0x{:02X}".format(i) for i in msg.data]) + message_str = ",".join([f"0x{i:02X}" for i in msg.data]) print(message_str) if isinstance(msg, RemoteTransmissionRequest): diff --git a/examples/mcp2515_send_and_receive.py b/examples/mcp2515_send_and_receive.py index a132440..72cbf3f 100644 --- a/examples/mcp2515_send_and_receive.py +++ b/examples/mcp2515_send_and_receive.py @@ -4,8 +4,9 @@ import board import busio from digitalio import DigitalInOut -from adafruit_mcp2515.canio import Message, RemoteTransmissionRequest + from adafruit_mcp2515 import MCP2515 as CAN +from adafruit_mcp2515.canio import Message, RemoteTransmissionRequest NODE_ID = 0x1234ABCD @@ -16,7 +17,6 @@ can_bus = CAN(spi, cs) while True: with can_bus.listen(timeout=1.0) as listener: - message = Message(id=NODE_ID, data=b"adafruit", extended=True) send_success = can_bus.send(message) print("Send success:", send_success) diff --git a/examples/mcp2515_simpletest.py b/examples/mcp2515_simpletest.py index b162b90..b66cb6a 100644 --- a/examples/mcp2515_simpletest.py +++ b/examples/mcp2515_simpletest.py @@ -2,23 +2,21 @@ # # SPDX-License-Identifier: MIT from time import sleep + import board import busio from digitalio import DigitalInOut -from adafruit_mcp2515.canio import Message, RemoteTransmissionRequest -from adafruit_mcp2515 import MCP2515 as CAN +from adafruit_mcp2515 import MCP2515 as CAN +from adafruit_mcp2515.canio import Message, RemoteTransmissionRequest cs = DigitalInOut(board.D5) cs.switch_to_output() spi = busio.SPI(board.SCK, board.MOSI, board.MISO) -can_bus = CAN( - spi, cs, loopback=True, silent=True -) # use loopback to test without another device +can_bus = CAN(spi, cs, loopback=True, silent=True) # use loopback to test without another device while True: with can_bus.listen(timeout=1.0) as listener: - message = Message(id=0x1234ABCD, data=b"adafruit", extended=True) send_success = can_bus.send(message) print("Send success:", send_success) diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 0000000..36332ff --- /dev/null +++ b/ruff.toml @@ -0,0 +1,105 @@ +# SPDX-FileCopyrightText: 2024 Tim Cocks for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +target-version = "py38" +line-length = 100 + +[lint] +preview = true +select = ["I", "PL", "UP"] + +extend-select = [ + "D419", # empty-docstring + "E501", # line-too-long + "W291", # trailing-whitespace + "PLC0414", # useless-import-alias + "PLC2401", # non-ascii-name + "PLC2801", # unnecessary-dunder-call + "PLC3002", # unnecessary-direct-lambda-call + "E999", # syntax-error + "PLE0101", # return-in-init + "F706", # return-outside-function + "F704", # yield-outside-function + "PLE0116", # continue-in-finally + "PLE0117", # nonlocal-without-binding + "PLE0241", # duplicate-bases + "PLE0302", # unexpected-special-method-signature + "PLE0604", # invalid-all-object + "PLE0605", # invalid-all-format + "PLE0643", # potential-index-error + "PLE0704", # misplaced-bare-raise + "PLE1141", # dict-iter-missing-items + "PLE1142", # await-outside-async + "PLE1205", # logging-too-many-args + "PLE1206", # logging-too-few-args + "PLE1307", # bad-string-format-type + "PLE1310", # bad-str-strip-call + "PLE1507", # invalid-envvar-value + "PLE2502", # bidirectional-unicode + "PLE2510", # invalid-character-backspace + "PLE2512", # invalid-character-sub + "PLE2513", # invalid-character-esc + "PLE2514", # invalid-character-nul + "PLE2515", # invalid-character-zero-width-space + "PLR0124", # comparison-with-itself + "PLR0202", # no-classmethod-decorator + "PLR0203", # no-staticmethod-decorator + "UP004", # useless-object-inheritance + "PLR0206", # property-with-parameters + "PLR0904", # too-many-public-methods + "PLR0911", # too-many-return-statements + "PLR0912", # too-many-branches + "PLR0913", # too-many-arguments + "PLR0914", # too-many-locals + "PLR0915", # too-many-statements + "PLR0916", # too-many-boolean-expressions + "PLR1702", # too-many-nested-blocks + "PLR1704", # redefined-argument-from-local + "PLR1711", # useless-return + "C416", # unnecessary-comprehension + "PLR1733", # unnecessary-dict-index-lookup + "PLR1736", # unnecessary-list-index-lookup + + # ruff reports this rule is unstable + #"PLR6301", # no-self-use + + "PLW0108", # unnecessary-lambda + "PLW0120", # useless-else-on-loop + "PLW0127", # self-assigning-variable + "PLW0129", # assert-on-string-literal + "B033", # duplicate-value + "PLW0131", # named-expr-without-context + "PLW0245", # super-without-brackets + "PLW0406", # import-self + "PLW0602", # global-variable-not-assigned + "PLW0603", # global-statement + "PLW0604", # global-at-module-level + + # fails on the try: import typing used by libraries + #"F401", # unused-import + + "F841", # unused-variable + "E722", # bare-except + "PLW0711", # binary-op-exception + "PLW1501", # bad-open-mode + "PLW1508", # invalid-envvar-default + "PLW1509", # subprocess-popen-preexec-fn + "PLW2101", # useless-with-lock + "PLW3301", # nested-min-max +] + +ignore = [ + "PLR2004", # magic-value-comparison + "UP030", # format literals + "PLW1514", # unspecified-encoding + "PLR0913", # too-many-arguments + "PLR0915", # too-many-statements + "PLR0917", # too-many-positional-arguments + "PLR0904", # too-many-public-methods + "PLR0912", # too-many-branches + "PLR0916", # too-many-boolean-expressions +] + +[format] +line-ending = "lf"