From 9a2a49c2ff08b98918684d0245995cf1dffe1919 Mon Sep 17 00:00:00 2001 From: Justin Myers Date: Sat, 23 Mar 2024 07:52:24 -0700 Subject: [PATCH 01/11] Add ruff formatter --- .gitattributes | 5 +++++ .pre-commit-config.yaml | 41 +++++++++-------------------------------- adafruit_bme680.py | 4 ++-- pyproject.toml | 6 ++++++ 4 files changed, 22 insertions(+), 34 deletions(-) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..d54c593 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,5 @@ +# SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense + +* text eol=lf diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 70ade69..0981ef3 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,42 +1,19 @@ -# 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: 23.3.0 - hooks: - - id: black - - repo: https://github.com/fsfe/reuse-tool - rev: v1.1.2 - hooks: - - id: reuse - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.4.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.17.4 + - 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 + - repo: https://github.com/fsfe/reuse-tool + rev: v3.0.1 + hooks: + - id: reuse diff --git a/adafruit_bme680.py b/adafruit_bme680.py index b3651e3..4e502b4 100644 --- a/adafruit_bme680.py +++ b/adafruit_bme680.py @@ -662,7 +662,7 @@ def __init__( address: int = 0x77, debug: bool = False, *, - refresh_rate: int = 10 + refresh_rate: int = 10, ) -> None: """Initialize the I2C device at the 'address' given""" from adafruit_bus_device import ( # pylint: disable=import-outside-toplevel @@ -751,7 +751,7 @@ def __init__( baudrate: int = 100000, debug: bool = False, *, - refresh_rate: int = 10 + refresh_rate: int = 10, ) -> None: from adafruit_bus_device import ( # pylint: disable=import-outside-toplevel spi_device, diff --git a/pyproject.toml b/pyproject.toml index 2092d51..e83f188 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -41,6 +41,12 @@ classifiers = [ ] dynamic = ["dependencies", "optional-dependencies"] +[tool.ruff] +target-version = "py38" + +[tool.ruff.format] +line-ending = "lf" + [tool.setuptools] py-modules = ["adafruit_bme680"] From 1db71cca7401cf61b8183847d6d5757948e53289 Mon Sep 17 00:00:00 2001 From: Justin Myers Date: Sat, 23 Mar 2024 08:08:30 -0700 Subject: [PATCH 02/11] Add ruff isort --- .pre-commit-config.yaml | 2 ++ adafruit_bme680.py | 5 +++-- docs/conf.py | 2 +- examples/bme680_simpletest.py | 2 ++ examples/bme680_spi.py | 2 ++ pyproject.toml | 3 +++ 6 files changed, 13 insertions(+), 3 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 0981ef3..ff19dde 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -13,6 +13,8 @@ repos: rev: v0.3.4 hooks: - id: ruff-format + - id: ruff + args: ["--fix"] - repo: https://github.com/fsfe/reuse-tool rev: v3.0.1 hooks: diff --git a/adafruit_bme680.py b/adafruit_bme680.py index 4e502b4..97cf01a 100644 --- a/adafruit_bme680.py +++ b/adafruit_bme680.py @@ -30,9 +30,10 @@ * Adafruit's Bus Device library: https://github.com/adafruit/Adafruit_CircuitPython_BusDevice """ +import math import struct import time -import math + from micropython import const @@ -46,8 +47,8 @@ def delay_microseconds(nusec): import typing # pylint: disable=unused-import - from circuitpython_typing import ReadableBuffer from busio import I2C, SPI + from circuitpython_typing import ReadableBuffer from digitalio import DigitalInOut except ImportError: diff --git a/docs/conf.py b/docs/conf.py index 432529a..d4ded73 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -4,9 +4,9 @@ # # SPDX-License-Identifier: MIT +import datetime import os import sys -import datetime sys.path.insert(0, os.path.abspath("..")) diff --git a/examples/bme680_simpletest.py b/examples/bme680_simpletest.py index ff77675..5b8c984 100644 --- a/examples/bme680_simpletest.py +++ b/examples/bme680_simpletest.py @@ -2,7 +2,9 @@ # SPDX-License-Identifier: MIT import time + import board + import adafruit_bme680 # Create sensor object, communicating over the board's default I2C bus diff --git a/examples/bme680_spi.py b/examples/bme680_spi.py index f8161dd..eb699a9 100644 --- a/examples/bme680_spi.py +++ b/examples/bme680_spi.py @@ -2,8 +2,10 @@ # SPDX-License-Identifier: MIT import time + import board import digitalio + import adafruit_bme680 # Create sensor object, communicating over the board's default SPI bus diff --git a/pyproject.toml b/pyproject.toml index e83f188..23b6dba 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -44,6 +44,9 @@ dynamic = ["dependencies", "optional-dependencies"] [tool.ruff] target-version = "py38" +[tool.ruff.lint] +select = ["I"] + [tool.ruff.format] line-ending = "lf" From a692e477fcf236f968e7549570aba2c0aa57367c Mon Sep 17 00:00:00 2001 From: Justin Myers Date: Sat, 23 Mar 2024 09:13:26 -0700 Subject: [PATCH 03/11] Add ruff lint --- .pylintrc | 399 --------------------------------------------- adafruit_bme680.py | 17 +- pyproject.toml | 3 +- 3 files changed, 9 insertions(+), 410 deletions(-) delete mode 100644 .pylintrc 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/adafruit_bme680.py b/adafruit_bme680.py index 97cf01a..11abdc3 100644 --- a/adafruit_bme680.py +++ b/adafruit_bme680.py @@ -2,9 +2,6 @@ # # SPDX-License-Identifier: MIT AND BSD-3-Clause -# We have a lot of attributes for this complex sensor. -# pylint: disable=too-many-instance-attributes -# pylint: disable=no_self_use """ `adafruit_bme680` @@ -45,7 +42,7 @@ def delay_microseconds(nusec): try: # Used only for type annotations. - import typing # pylint: disable=unused-import + import typing from busio import I2C, SPI from circuitpython_typing import ReadableBuffer @@ -666,7 +663,7 @@ def __init__( refresh_rate: int = 10, ) -> None: """Initialize the I2C device at the 'address' given""" - from adafruit_bus_device import ( # pylint: disable=import-outside-toplevel + from adafruit_bus_device import ( i2c_device, ) @@ -745,7 +742,7 @@ class Adafruit_BME680_SPI(Adafruit_BME680): """ - def __init__( + def __init__( # noqa: PLR0913 Too many arguments in function definition self, spi: SPI, cs: DigitalInOut, @@ -754,7 +751,7 @@ def __init__( *, refresh_rate: int = 10, ) -> None: - from adafruit_bus_device import ( # pylint: disable=import-outside-toplevel + from adafruit_bus_device import ( spi_device, ) @@ -770,9 +767,9 @@ def _read(self, register: int, length: int) -> bytearray: register = (register | 0x80) & 0xFF # Read single, bit 7 high. with self._spi as spi: - spi.write(bytearray([register])) # pylint: disable=no-member + spi.write(bytearray([register])) result = bytearray(length) - spi.readinto(result) # pylint: disable=no-member + spi.readinto(result) if self._debug: print("\t$%02X => %s" % (register, [hex(i) for i in result])) return result @@ -788,7 +785,7 @@ def _write(self, register: int, values: ReadableBuffer) -> None: for i, value in enumerate(values): buffer[2 * i] = register + i buffer[2 * i + 1] = value & 0xFF - spi.write(buffer) # pylint: disable=no-member + spi.write(buffer) if self._debug: print("\t$%02X <= %s" % (values[0], [hex(i) for i in values[1:]])) diff --git a/pyproject.toml b/pyproject.toml index 23b6dba..51fe85e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -45,7 +45,8 @@ dynamic = ["dependencies", "optional-dependencies"] target-version = "py38" [tool.ruff.lint] -select = ["I"] +select = ["I", "PL"] +ignore = ["PLR2004"] [tool.ruff.format] line-ending = "lf" From 12f3d14db7c04ead9dfdd4d8cb62acb8a0d499c8 Mon Sep 17 00:00:00 2001 From: Justin Myers Date: Sat, 23 Mar 2024 09:32:29 -0700 Subject: [PATCH 04/11] Add ruff upgrade --- docs/conf.py | 2 -- pyproject.toml | 4 ++-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/docs/conf.py b/docs/conf.py index d4ded73..c8c8cbc 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # # SPDX-License-Identifier: MIT diff --git a/pyproject.toml b/pyproject.toml index 51fe85e..ab10cbe 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -45,8 +45,8 @@ dynamic = ["dependencies", "optional-dependencies"] target-version = "py38" [tool.ruff.lint] -select = ["I", "PL"] -ignore = ["PLR2004"] +select = ["I", "PL", "UP"] +ignore = ["PLR2004", "UP028", "UP030", "UP031", "UP032"] [tool.ruff.format] line-ending = "lf" From 3c91cd1304bf6206f567864207158dadb12e6ff9 Mon Sep 17 00:00:00 2001 From: Justin Myers Date: Sat, 23 Mar 2024 09:47:28 -0700 Subject: [PATCH 05/11] remove upgrade UP028 --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index ab10cbe..1c28a2d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -46,7 +46,7 @@ target-version = "py38" [tool.ruff.lint] select = ["I", "PL", "UP"] -ignore = ["PLR2004", "UP028", "UP030", "UP031", "UP032"] +ignore = ["PLR2004", "UP030", "UP031", "UP032"] [tool.ruff.format] line-ending = "lf" From e9f2da40312ecb8b205fcd35c66377a3f7f16b89 Mon Sep 17 00:00:00 2001 From: Justin Myers Date: Sat, 23 Mar 2024 09:52:20 -0700 Subject: [PATCH 06/11] remove upgrade UP031 --- adafruit_bme680.py | 8 ++++---- pyproject.toml | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/adafruit_bme680.py b/adafruit_bme680.py index 11abdc3..8f3a569 100644 --- a/adafruit_bme680.py +++ b/adafruit_bme680.py @@ -678,7 +678,7 @@ def _read(self, register: int, length: int) -> bytearray: result = bytearray(length) i2c.readinto(result) if self._debug: - print("\t$%02X => %s" % (register, [hex(i) for i in result])) + print("\t${:02X} => {}".format(register, [hex(i) for i in result])) return result def _write(self, register: int, values: ReadableBuffer) -> None: @@ -690,7 +690,7 @@ def _write(self, register: int, values: ReadableBuffer) -> None: buffer[2 * i + 1] = value i2c.write(buffer) if self._debug: - print("\t$%02X <= %s" % (values[0], [hex(i) for i in values[1:]])) + print("\t${:02X} <= {}".format(values[0], [hex(i) for i in values[1:]])) class Adafruit_BME680_SPI(Adafruit_BME680): @@ -771,7 +771,7 @@ def _read(self, register: int, length: int) -> bytearray: result = bytearray(length) spi.readinto(result) if self._debug: - print("\t$%02X => %s" % (register, [hex(i) for i in result])) + print("\t${:02X} => {}".format(register, [hex(i) for i in result])) return result def _write(self, register: int, values: ReadableBuffer) -> None: @@ -787,7 +787,7 @@ def _write(self, register: int, values: ReadableBuffer) -> None: buffer[2 * i + 1] = value & 0xFF spi.write(buffer) if self._debug: - print("\t$%02X <= %s" % (values[0], [hex(i) for i in values[1:]])) + print("\t${:02X} <= {}".format(values[0], [hex(i) for i in values[1:]])) def _set_spi_mem_page(self, register: int) -> None: spi_mem_page = 0x00 diff --git a/pyproject.toml b/pyproject.toml index 1c28a2d..1fa3b41 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -46,7 +46,7 @@ target-version = "py38" [tool.ruff.lint] select = ["I", "PL", "UP"] -ignore = ["PLR2004", "UP030", "UP031", "UP032"] +ignore = ["PLR2004", "UP030", "UP032"] [tool.ruff.format] line-ending = "lf" From 7084383bd1cd2cfa5a6814bb9550d0340ca10aa8 Mon Sep 17 00:00:00 2001 From: Justin Myers Date: Sat, 23 Mar 2024 09:56:03 -0700 Subject: [PATCH 07/11] remove upgrade UP032 --- adafruit_bme680.py | 8 ++++---- pyproject.toml | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/adafruit_bme680.py b/adafruit_bme680.py index 8f3a569..52b7b47 100644 --- a/adafruit_bme680.py +++ b/adafruit_bme680.py @@ -678,7 +678,7 @@ def _read(self, register: int, length: int) -> bytearray: result = bytearray(length) i2c.readinto(result) if self._debug: - print("\t${:02X} => {}".format(register, [hex(i) for i in result])) + print(f"\t${register:02X} => {[hex(i) for i in result]}") return result def _write(self, register: int, values: ReadableBuffer) -> None: @@ -690,7 +690,7 @@ def _write(self, register: int, values: ReadableBuffer) -> None: buffer[2 * i + 1] = value i2c.write(buffer) if self._debug: - print("\t${:02X} <= {}".format(values[0], [hex(i) for i in values[1:]])) + print(f"\t${values[0]:02X} <= {[hex(i) for i in values[1:]]}") class Adafruit_BME680_SPI(Adafruit_BME680): @@ -771,7 +771,7 @@ def _read(self, register: int, length: int) -> bytearray: result = bytearray(length) spi.readinto(result) if self._debug: - print("\t${:02X} => {}".format(register, [hex(i) for i in result])) + print(f"\t${register:02X} => {[hex(i) for i in result]}") return result def _write(self, register: int, values: ReadableBuffer) -> None: @@ -787,7 +787,7 @@ def _write(self, register: int, values: ReadableBuffer) -> None: buffer[2 * i + 1] = value & 0xFF spi.write(buffer) if self._debug: - print("\t${:02X} <= {}".format(values[0], [hex(i) for i in values[1:]])) + print(f"\t${values[0]:02X} <= {[hex(i) for i in values[1:]]}") def _set_spi_mem_page(self, register: int) -> None: spi_mem_page = 0x00 diff --git a/pyproject.toml b/pyproject.toml index 1fa3b41..50a8a0e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -46,7 +46,7 @@ target-version = "py38" [tool.ruff.lint] select = ["I", "PL", "UP"] -ignore = ["PLR2004", "UP030", "UP032"] +ignore = ["PLR2004", "UP030"] [tool.ruff.format] line-ending = "lf" From 057cbb030be2cb4c404817fdeb8587f0a129d976 Mon Sep 17 00:00:00 2001 From: Justin Myers Date: Sun, 24 Mar 2024 07:41:07 -0700 Subject: [PATCH 08/11] Update README badge --- README.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.rst b/README.rst index d430106..c498d76 100644 --- a/README.rst +++ b/README.rst @@ -14,9 +14,9 @@ Introduction :target: https://github.com/adafruit/Adafruit_CircuitPython_BME680/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 CircuitPython driver for BME680 sensor over I2C From 95336a4708c327b6e36eb74ae6b6a5f3301cde8f Mon Sep 17 00:00:00 2001 From: foamyguy Date: Mon, 15 Jul 2024 16:35:50 -0500 Subject: [PATCH 09/11] move ruff config to it's own file --- adafruit_bme680.py | 44 ++++++--------------- docs/conf.py | 4 +- pyproject.toml | 10 ----- ruff.toml | 99 ++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 111 insertions(+), 46 deletions(-) create mode 100644 ruff.toml diff --git a/adafruit_bme680.py b/adafruit_bme680.py index 52b7b47..ca2d6c9 100644 --- a/adafruit_bme680.py +++ b/adafruit_bme680.py @@ -285,19 +285,15 @@ def pressure(self) -> float: var2 = (var2 * self._pressure_calibration[5]) / 4 var2 = var2 + (var1 * self._pressure_calibration[4] * 2) var2 = (var2 / 4) + (self._pressure_calibration[3] * 65536) - var1 = ( - (((var1 / 4) * (var1 / 4)) / 8192) - * (self._pressure_calibration[2] * 32) - / 8 - ) + ((self._pressure_calibration[1] * var1) / 2) + var1 = ((((var1 / 4) * (var1 / 4)) / 8192) * (self._pressure_calibration[2] * 32) / 8) + ( + (self._pressure_calibration[1] * var1) / 2 + ) var1 = var1 / 262144 var1 = ((32768 + var1) * self._pressure_calibration[0]) / 32768 calc_pres = 1048576 - self._adc_pres calc_pres = (calc_pres - (var2 / 4096)) * 3125 calc_pres = (calc_pres / var1) * 2 - var1 = ( - self._pressure_calibration[8] * (((calc_pres / 8) * (calc_pres / 8)) / 8192) - ) / 4096 + var1 = (self._pressure_calibration[8] * (((calc_pres / 8) * (calc_pres / 8)) / 8192)) / 4096 var2 = ((calc_pres / 4) * self._pressure_calibration[7]) / 8192 var3 = (((calc_pres / 256) ** 3) * self._pressure_calibration[9]) / 131072 calc_pres += (var1 + var2 + var3 + (self._pressure_calibration[6] * 128)) / 16 @@ -321,13 +317,7 @@ def humidity(self) -> float: * ( ((temp_scaled * self._humidity_calibration[3]) / 100) + ( - ( - ( - temp_scaled - * ((temp_scaled * self._humidity_calibration[4]) / 100) - ) - / 64 - ) + ((temp_scaled * ((temp_scaled * self._humidity_calibration[4]) / 100)) / 64) / 100 ) + 16384 @@ -365,9 +355,7 @@ def gas(self) -> int: calc_gas_res = (10000 * var1) / var2 calc_gas_res = calc_gas_res * 100 else: - var1 = ( - (1340 + (5 * self._sw_err)) * (_LOOKUP_TABLE_1[self._gas_range]) - ) / 65536 + var1 = ((1340 + (5 * self._sw_err)) * (_LOOKUP_TABLE_1[self._gas_range])) / 65536 var2 = ((self._adc_gas * 32768) - 16777216) + var1 var3 = (_LOOKUP_TABLE_2[self._gas_range] * var1) / 512 calc_gas_res = (var3 + (var2 / 2)) / var2 @@ -428,9 +416,7 @@ def _read_calibration(self) -> None: # print("\n\n",coeff) coeff = [float(i) for i in coeff] self._temp_calibration = [coeff[x] for x in [23, 0, 1]] - self._pressure_calibration = [ - coeff[x] for x in [3, 4, 5, 7, 8, 10, 9, 12, 13, 14] - ] + self._pressure_calibration = [coeff[x] for x in [3, 4, 5, 7, 8, 10, 9, 12, 13, 14]] self._humidity_calibration = [coeff[x] for x in [17, 16, 18, 19, 20, 21, 22]] self._gas_calibration = [coeff[x] for x in [25, 24, 26]] @@ -469,9 +455,7 @@ def set_gas_heater(self, heater_temp: int, heater_time: int) -> bool: return False return True - def _set_heatr_conf( - self, heater_temp: int, heater_time: int, enable: bool = True - ) -> None: + def _set_heatr_conf(self, heater_temp: int, heater_time: int, enable: bool = True) -> None: # restrict to BME68X_FORCED_MODE op_mode: int = _BME68X_FORCED_MODE nb_conv: int = 0 @@ -498,9 +482,7 @@ def _set_heatr_conf( ctrl_gas_data_0 = bme_set_bits( ctrl_gas_data_0, _BME68X_HCTRL_MSK, _BME68X_HCTRL_POS, hctrl ) - ctrl_gas_data_1 = bme_set_bits_pos_0( - ctrl_gas_data_1, _BME68X_NBCONV_MSK, nb_conv - ) + ctrl_gas_data_1 = bme_set_bits_pos_0(ctrl_gas_data_1, _BME68X_NBCONV_MSK, nb_conv) ctrl_gas_data_1 = bme_set_bits( ctrl_gas_data_1, _BME68X_RUN_GAS_MSK, _BME68X_RUN_GAS_POS, run_gas ) @@ -530,9 +512,7 @@ def _set_op_mode(self, op_mode: int) -> None: delay_microseconds(_BME68X_PERIOD_POLL) # Already in sleep if op_mode != _BME68X_SLEEP_MODE: - tmp_pow_mode = (tmp_pow_mode & ~_BME68X_MODE_MSK) | ( - op_mode & _BME68X_MODE_MSK - ) + tmp_pow_mode = (tmp_pow_mode & ~_BME68X_MODE_MSK) | (op_mode & _BME68X_MODE_MSK) self._write(_BME680_REG_CTRL_MEAS, [tmp_pow_mode]) def _set_conf(self, heater_temp: int, heater_time: int, op_mode: int) -> None: @@ -588,9 +568,7 @@ def _calc_res_heat(self, temp: int) -> int: var3: float = gh3 / (1024.0) var4: float = var1 * (1.0 + (var2 * float(temp))) var5: float = var4 + (var3 * amb) - res_heat: int = int( - 3.4 * ((var5 * (4 / (4 + htr)) * (1 / (1 + (htv * 0.002)))) - 25) - ) + res_heat: int = int(3.4 * ((var5 * (4 / (4 + htr)) * (1 / (1 + (htv * 0.002)))) - 25)) return res_heat def _calc_gas_wait(self, dur: int) -> int: diff --git a/docs/conf.py b/docs/conf.py index c8c8cbc..b60a1c2 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -42,9 +42,7 @@ creation_year = "2017" 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 + " ladyada" author = "ladyada" diff --git a/pyproject.toml b/pyproject.toml index 50a8a0e..2092d51 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -41,16 +41,6 @@ classifiers = [ ] dynamic = ["dependencies", "optional-dependencies"] -[tool.ruff] -target-version = "py38" - -[tool.ruff.lint] -select = ["I", "PL", "UP"] -ignore = ["PLR2004", "UP030"] - -[tool.ruff.format] -line-ending = "lf" - [tool.setuptools] py-modules = ["adafruit_bme680"] diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 0000000..db37c83 --- /dev/null +++ b/ruff.toml @@ -0,0 +1,99 @@ +# SPDX-FileCopyrightText: 2024 Tim Cocks for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +target-version = "py38" +line-length = 100 + +[lint] +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 + +] + +[format] +line-ending = "lf" From db9a0d60c0809bf394851e72946e102bfe3e65a7 Mon Sep 17 00:00:00 2001 From: foamyguy Date: Mon, 15 Jul 2024 16:40:37 -0500 Subject: [PATCH 10/11] merge main --- adafruit_bme680.py | 8 ++------ examples/bme680_displayio_simpletest.py | 10 +++++----- 2 files changed, 7 insertions(+), 11 deletions(-) diff --git a/adafruit_bme680.py b/adafruit_bme680.py index a353123..f484f97 100644 --- a/adafruit_bme680.py +++ b/adafruit_bme680.py @@ -479,12 +479,8 @@ def _set_heatr_conf(self, heater_temp: int, heater_time: int, enable: bool = Tru run_gas = _BME68X_DISABLE_GAS_MEAS self._run_gas = ~(run_gas - 1) - ctrl_gas_data_0 = bme_set_bits( - ctrl_gas_data_0, _BME68X_HCTRL_MSK, _BME68X_HCTRL_POS, hctrl - ) - ctrl_gas_data_1 = bme_set_bits_pos_0( - ctrl_gas_data_1, _BME68X_NBCONV_MSK, nb_conv - ) + ctrl_gas_data_0 = bme_set_bits(ctrl_gas_data_0, _BME68X_HCTRL_MSK, _BME68X_HCTRL_POS, hctrl) + ctrl_gas_data_1 = bme_set_bits_pos_0(ctrl_gas_data_1, _BME68X_NBCONV_MSK, nb_conv) ctrl_gas_data_1 = bme_set_bits( ctrl_gas_data_1, _BME68X_RUN_GAS_MSK, _BME68X_RUN_GAS_POS, run_gas ) diff --git a/examples/bme680_displayio_simpletest.py b/examples/bme680_displayio_simpletest.py index 41272b4..fd5ff81 100644 --- a/examples/bme680_displayio_simpletest.py +++ b/examples/bme680_displayio_simpletest.py @@ -2,10 +2,12 @@ # SPDX-License-Identifier: MIT import time + import board from adafruit_display_text.bitmap_label import Label -from terminalio import FONT from displayio import Group +from terminalio import FONT + import adafruit_bme680 # create a main_group to hold anything we want to show on the display. @@ -41,10 +43,8 @@ # begin main loop while True: # Update the label.text property to change the text on the display - display_output_label.text = """Temperature: {:.1f} C -Humidity: {:.1f} %""".format( - bme680.temperature + temperature_offset, bme680.relative_humidity - ) + display_output_label.text = f"""Temperature: {bme680.temperature + temperature_offset:.1f} C +Humidity: {bme680.relative_humidity:.1f} %""" # wait for a bit time.sleep(1) From c789ca03041efe0c1f7f49aaaad834d037161f7c Mon Sep 17 00:00:00 2001 From: foamyguy Date: Mon, 15 Jul 2024 16:48:15 -0500 Subject: [PATCH 11/11] fix docs build --- adafruit_bme680.py | 4 ++-- docs/conf.py | 6 ++++++ docs/requirements.txt | 1 + 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/adafruit_bme680.py b/adafruit_bme680.py index f484f97..e38198e 100644 --- a/adafruit_bme680.py +++ b/adafruit_bme680.py @@ -601,7 +601,7 @@ class Adafruit_BME680_I2C(Adafruit_BME680): import board import adafruit_bme680 - Once this is done you can define your `board.I2C` object and define your sensor object + Once this is done you can define your ``board.I2C`` object and define your sensor object .. code-block:: python @@ -688,7 +688,7 @@ class Adafruit_BME680_SPI(Adafruit_BME680): from digitalio import DigitalInOut, Direction import adafruit_bme680 - Once this is done you can define your `board.SPI` object and define your sensor object + Once this is done you can define your ``board.SPI`` object and define your sensor object .. code-block:: python diff --git a/docs/conf.py b/docs/conf.py index b60a1c2..5c68f93 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -20,6 +20,12 @@ "sphinx.ext.viewcode", ] +# Uncomment the below if you use native CircuitPython modules such as +# digitalio, micropython and busio. List the modules you use. Without it, the +# autodoc module docs will fail to generate with a warning. +autodoc_mock_imports = ["micropython"] + + intersphinx_mapping = { "python": ("https://docs.python.org/3", None), "BusDevice": ( diff --git a/docs/requirements.txt b/docs/requirements.txt index 979f568..2887ca5 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -5,3 +5,4 @@ sphinx sphinxcontrib-jquery sphinx-rtd-theme +adafruit-circuitpython-typing