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/.github/workflows/build.yml b/.github/workflows/build.yml index cb2f60e..041a337 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -10,68 +10,5 @@ jobs: test: runs-on: ubuntu-latest steps: - - name: Dump GitHub context - env: - GITHUB_CONTEXT: ${{ toJson(github) }} - run: echo "$GITHUB_CONTEXT" - - name: Translate Repo Name For Build Tools filename_prefix - id: repo-name - run: | - echo ::set-output name=repo-name::$( - echo ${{ github.repository }} | - awk -F '\/' '{ print tolower($2) }' | - tr '_' '-' - ) - - name: Set up Python 3.x - uses: actions/setup-python@v2 - with: - python-version: "3.x" - - name: Versions - run: | - python3 --version - - name: Checkout Current Repo - uses: actions/checkout@v1 - with: - submodules: true - - name: Checkout tools repo - uses: actions/checkout@v2 - with: - repository: adafruit/actions-ci-circuitpython-libs - path: actions-ci - - name: Install dependencies - # (e.g. - apt-get: gettext, etc; pip: circuitpython-build-tools, requirements.txt; etc.) - run: | - source actions-ci/install.sh - - name: Pip install Sphinx, pre-commit - run: | - pip install --force-reinstall Sphinx sphinx-rtd-theme pre-commit - - name: Library version - run: git describe --dirty --always --tags - - name: Setup problem matchers - uses: adafruit/circuitpython-action-library-ci-problem-matchers@v1 - - name: Pre-commit hooks - run: | - pre-commit run --all-files - - name: Build assets - run: circuitpython-build-bundles --filename_prefix ${{ steps.repo-name.outputs.repo-name }} --library_location . - - name: Archive bundles - uses: actions/upload-artifact@v2 - with: - name: bundles - path: ${{ github.workspace }}/bundles/ - - name: Build docs - working-directory: docs - run: sphinx-build -E -W -b html . _build/html - - name: Check For pyproject.toml - id: need-pypi - run: | - echo ::set-output name=pyproject-toml::$( find . -wholename './pyproject.toml' ) - - name: Build Python package - if: contains(steps.need-pypi.outputs.pyproject-toml, 'pyproject.toml') - run: | - pip install --upgrade build twine - for file in $(find -not -path "./.*" -not -path "./docs*" \( -name "*.py" -o -name "*.toml" \) ); do - sed -i -e "s/0.0.0+auto.0/1.2.3/" $file; - done; - python -m build - twine check dist/* + - name: Run Build CI workflow + uses: adafruit/workflows-circuitpython-libs/build@main diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml deleted file mode 100644 index f3a0325..0000000 --- a/.github/workflows/release.yml +++ /dev/null @@ -1,88 +0,0 @@ -# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries -# -# SPDX-License-Identifier: MIT - -name: Release Actions - -on: - release: - types: [published] - -jobs: - upload-release-assets: - runs-on: ubuntu-latest - steps: - - name: Dump GitHub context - env: - GITHUB_CONTEXT: ${{ toJson(github) }} - run: echo "$GITHUB_CONTEXT" - - name: Translate Repo Name For Build Tools filename_prefix - id: repo-name - run: | - echo ::set-output name=repo-name::$( - echo ${{ github.repository }} | - awk -F '\/' '{ print tolower($2) }' | - tr '_' '-' - ) - - name: Set up Python 3.x - uses: actions/setup-python@v2 - with: - python-version: "3.x" - - name: Versions - run: | - python3 --version - - name: Checkout Current Repo - uses: actions/checkout@v1 - with: - submodules: true - - name: Checkout tools repo - uses: actions/checkout@v2 - with: - repository: adafruit/actions-ci-circuitpython-libs - path: actions-ci - - name: Install deps - run: | - source actions-ci/install.sh - - name: Build assets - run: circuitpython-build-bundles --filename_prefix ${{ steps.repo-name.outputs.repo-name }} --library_location . - - name: Upload Release Assets - # the 'official' actions version does not yet support dynamically - # supplying asset names to upload. @csexton's version chosen based on - # discussion in the issue below, as its the simplest to implement and - # allows for selecting files with a pattern. - # https://github.com/actions/upload-release-asset/issues/4 - #uses: actions/upload-release-asset@v1.0.1 - uses: csexton/release-asset-action@master - with: - pattern: "bundles/*" - github-token: ${{ secrets.GITHUB_TOKEN }} - - upload-pypi: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v1 - - name: Check For pyproject.toml - id: need-pypi - run: | - echo ::set-output name=pyproject-toml::$( find . -wholename './pyproject.toml' ) - - name: Set up Python - if: contains(steps.need-pypi.outputs.pyproject-toml, 'pyproject.toml') - uses: actions/setup-python@v2 - with: - python-version: '3.x' - - name: Install dependencies - if: contains(steps.need-pypi.outputs.pyproject-toml, 'pyproject.toml') - run: | - python -m pip install --upgrade pip - pip install --upgrade build twine - - name: Build and publish - if: contains(steps.need-pypi.outputs.pyproject-toml, 'pyproject.toml') - env: - TWINE_USERNAME: ${{ secrets.pypi_username }} - TWINE_PASSWORD: ${{ secrets.pypi_password }} - run: | - for file in $(find -not -path "./.*" -not -path "./docs*" \( -name "*.py" -o -name "*.toml" \) ); do - sed -i -e "s/0.0.0+auto.0/${{github.event.release.tag_name}}/" $file; - done; - python -m build - twine upload dist/* diff --git a/.github/workflows/release_gh.yml b/.github/workflows/release_gh.yml new file mode 100644 index 0000000..9acec60 --- /dev/null +++ b/.github/workflows/release_gh.yml @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +name: GitHub Release Actions + +on: + release: + types: [published] + +jobs: + upload-release-assets: + runs-on: ubuntu-latest + steps: + - name: Run GitHub Release CI workflow + uses: adafruit/workflows-circuitpython-libs/release-gh@main + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + upload-url: ${{ github.event.release.upload_url }} diff --git a/.github/workflows/release_pypi.yml b/.github/workflows/release_pypi.yml new file mode 100644 index 0000000..65775b7 --- /dev/null +++ b/.github/workflows/release_pypi.yml @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +name: PyPI Release Actions + +on: + release: + types: [published] + +jobs: + upload-release-assets: + runs-on: ubuntu-latest + steps: + - name: Run PyPI Release CI workflow + uses: adafruit/workflows-circuitpython-libs/release-pypi@main + with: + pypi-username: ${{ secrets.pypi_username }} + pypi-password: ${{ secrets.pypi_password }} diff --git a/.gitignore b/.gitignore index 544ec4a..db3d538 100644 --- a/.gitignore +++ b/.gitignore @@ -37,6 +37,7 @@ _build # Virtual environment-specific files .env +.venv # MacOS-specific files *.DS_Store diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 3343606..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.11.1 + - 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 66d688f..0000000 --- a/.pylintrc +++ /dev/null @@ -1,436 +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= - -# 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,print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call -disable=print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call,import-error,bad-continuation,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 - -# List of optional constructs for which whitespace checking is disabled. `dict- -# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. -# `trailing-comma` allows a space between comma and closing bracket: (a, ). -# `empty-line` allows space-only lines. -no-space-check=trailing-comma,dict-separator - -# 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] - -# Naming hint for argument names -argument-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Regular expression matching correct argument names -argument-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Naming hint for attribute names -attr-name-hint=(([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 - -# Naming hint for class attribute names -class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ - -# Regular expression matching correct class attribute names -class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ - -# Naming hint for class names -# class-name-hint=[A-Z_][a-zA-Z0-9]+$ -class-name-hint=[A-Z_][a-zA-Z0-9_]+$ - -# Regular expression matching correct class names -# class-rgx=[A-Z_][a-zA-Z0-9]+$ -class-rgx=[A-Z_][a-zA-Z0-9_]+$ - -# Naming hint for constant names -const-name-hint=(([A-Z_][A-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 - -# Naming hint for function names -function-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# 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 - -# Naming hint for inline iteration names -inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$ - -# Regular expression matching correct inline iteration names -inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ - -# Naming hint for method names -method-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Regular expression matching correct method names -method-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Naming hint for module names -module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-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 - -# Naming hint for variable names -variable-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# 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=Exception diff --git a/.readthedocs.yaml b/.readthedocs.yaml index 33c2a61..255dafd 100644 --- a/.readthedocs.yaml +++ b/.readthedocs.yaml @@ -8,8 +8,11 @@ # Required version: 2 +sphinx: + configuration: docs/conf.py + build: - os: ubuntu-20.04 + os: ubuntu-lts-latest tools: python: "3" diff --git a/README.rst b/README.rst index 00c1d16..343482c 100644 --- a/README.rst +++ b/README.rst @@ -13,9 +13,9 @@ Introduction :target: https://github.com/adafruit/Adafruit_CircuitPython_CLUE/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 high level library representing all the features of the Adafruit CLUE diff --git a/adafruit_clue.py b/adafruit_clue.py index 9bca186..2454b78 100644 --- a/adafruit_clue.py +++ b/adafruit_clue.py @@ -39,21 +39,30 @@ https://github.com/adafruit/Adafruit_CircuitPython_NeoPixel """ -import time +try: + from typing import List, Optional, Tuple, Union +except ImportError: + pass + import array import math -import board -import digitalio -import neopixel +import time + import adafruit_apds9960.apds9960 import adafruit_bmp280 import adafruit_lis3mdl +import adafruit_lsm6ds.lsm6ds3trc import adafruit_lsm6ds.lsm6ds33 import adafruit_sht31d import audiobusio -import audiopwmio import audiocore +import audiopwmio +import board +import digitalio +import displayio +import neopixel import touchio +from microcontroller import Pin __version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_CLUE.git" @@ -62,21 +71,17 @@ class _ClueSimpleTextDisplay: """Easily display lines of text on CLUE display.""" - def __init__( # pylint: disable=too-many-arguments + def __init__( self, - title=None, - title_color=0xFFFFFF, - title_scale=1, - text_scale=1, - font=None, - colors=None, + title: Optional[str] = None, + title_color: Union[int, Tuple[int, int, int]] = 0xFFFFFF, + title_scale: int = 1, + text_scale: int = 1, + font: Optional[str] = None, + colors: Optional[Tuple[Tuple[int, int, int], ...]] = None, ): - # pylint: disable=import-outside-toplevel - import displayio - import terminalio - from adafruit_display_text import label - - # pylint: enable=import-outside-toplevel + import terminalio # noqa: PLC0415 + from adafruit_display_text import label # noqa: PLC0415 if not colors: colors = ( @@ -124,16 +129,14 @@ def __init__( # pylint: disable=too-many-arguments for num in range(1): self._lines.append(self.add_text_line(color=colors[num % len(colors)])) - def __getitem__(self, item): + def __getitem__(self, item: int): """Fetch the Nth text line Group""" if len(self._lines) - 1 < item: for _ in range(item - (len(self._lines) - 1)): - self._lines.append( - self.add_text_line(color=self._colors[item % len(self._colors)]) - ) + self._lines.append(self.add_text_line(color=self._colors[item % len(self._colors)])) return self._lines[item] - def add_text_line(self, color=0xFFFFFF): + def add_text_line(self, color: Union[int, Tuple[int, int, int]] = 0xFFFFFF): """Adds a line on the display of the specified color and returns the label object.""" text_label = self._label.Label(self._font, text="", color=color) text_label.x = 0 @@ -145,14 +148,14 @@ def add_text_line(self, color=0xFFFFFF): def show(self): """Call show() to display the data list.""" - self._display.show(self.text_group) + self._display.root_group = self.text_group def show_terminal(self): """Revert to terminalio screen.""" - self._display.show(None) + self._display.root_group = displayio.CIRCUITPYTHON_TERMINAL -class Clue: # pylint: disable=too-many-instance-attributes, too-many-public-methods +class Clue: """Represents a single CLUE.""" # Color variables available for import. @@ -183,12 +186,13 @@ def __init__(self): self._i2c = board.I2C() # Define touch: - # Initially, self._touches stores the pin used for a particular touch. When that touch is - # used for the first time, the pin is replaced with the corresponding TouchIn object. - # This saves a little RAM over using a separate read-only pin tuple. + # Initially, self._touches is an empty dictionary. When a touch is used + # for the first time, the pin is added as a key to the dictionary, with + # the corresponding TouchIn object added as the value. This saves a + # little RAM by only populating the dictionary as needed. # For example, after `clue.touch_2`, self._touches is equivalent to: - # [board.D0, board.D1, touchio.TouchIn(board.D2)] - self._touches = [board.D0, board.D1, board.D2] + # { board.P2, touchio.TouchIn(board.P2) } + self._touches = {} self._touch_threshold_adjustment = 0 # Define buttons: @@ -218,7 +222,10 @@ def __init__(self): # Define sensors: # Accelerometer/gyroscope: - self._accelerometer = adafruit_lsm6ds.lsm6ds33.LSM6DS33(self._i2c) + try: + self._accelerometer = adafruit_lsm6ds.lsm6ds33.LSM6DS33(self._i2c) + except RuntimeError: + self._accelerometer = adafruit_lsm6ds.lsm6ds3trc.LSM6DS3TRC(self._i2c) # Magnetometer: self._magnetometer = adafruit_lis3mdl.LIS3MDL(self._i2c) @@ -235,16 +242,17 @@ def __init__(self): # Create displayio object for passing. self.display = board.DISPLAY - def _touch(self, i): - if not isinstance(self._touches[i], touchio.TouchIn): - # First time referenced. Get the pin from the slot for this touch - # and replace it with a TouchIn object for the pin. - self._touches[i] = touchio.TouchIn(self._touches[i]) - self._touches[i].threshold += self._touch_threshold_adjustment - return self._touches[i].value + def _touch(self, pin: Pin) -> bool: + touchin = self._touches.get(pin) + if not touchin: + # First time referenced. Make TouchIn object for the pin + touchin = touchio.TouchIn(pin) + touchin.threshold += self._touch_threshold_adjustment + self._touches[pin] = touchin + return touchin.value @property - def touch_0(self): + def touch_0(self) -> bool: """Detect touch on capacitive touch pad 0. .. image :: ../docs/_static/pad_0.jpg @@ -262,10 +270,10 @@ def touch_0(self): if clue.touch_0: print("Touched pad 0") """ - return self._touch(0) + return self._touch(board.P0) @property - def touch_1(self): + def touch_1(self) -> bool: """Detect touch on capacitive touch pad 1. .. image :: ../docs/_static/pad_1.jpg @@ -283,10 +291,10 @@ def touch_1(self): if clue.touch_1: print("Touched pad 1") """ - return self._touch(1) + return self._touch(board.P1) @property - def touch_2(self): + def touch_2(self) -> bool: """Detect touch on capacitive touch pad 2. .. image :: ../docs/_static/pad_2.jpg @@ -304,10 +312,20 @@ def touch_2(self): if clue.touch_2: print("Touched pad 2") """ - return self._touch(2) + return self._touch(board.P2) @property - def button_a(self): + def touch_pins(self) -> List[Pin]: + """A list of all the pins that are set up as touchpad inputs""" + return list(self._touches.keys()) + + @property + def touched(self): + """A list of all the pins that are currently registering a touch""" + return [pin for pin, touchpad in self._touches.items() if touchpad.value] + + @property + def button_a(self) -> bool: """``True`` when Button A is pressed. ``False`` if not. .. image :: ../docs/_static/button_a.jpg @@ -328,7 +346,7 @@ def button_a(self): return not self._a.value @property - def button_b(self): + def button_b(self) -> bool: """``True`` when Button B is pressed. ``False`` if not. .. image :: ../docs/_static/button_b.jpg @@ -348,7 +366,9 @@ def button_b(self): """ return not self._b.value - def shake(self, shake_threshold=30, avg_count=10, total_delay=0.1): + def shake( + self, shake_threshold: int = 30, avg_count: int = 10, total_delay: float = 0.1 + ) -> bool: """ Detect when the accelerometer is shaken. Optional parameters: @@ -380,7 +400,7 @@ def shake(self, shake_threshold=30, avg_count=10, total_delay=0.1): return total_accel > shake_threshold @property - def acceleration(self): + def acceleration(self) -> Tuple[int, int, int]: """Obtain acceleration data from the x, y and z axes. .. image :: ../docs/_static/accelerometer.jpg @@ -400,7 +420,7 @@ def acceleration(self): return self._accelerometer.acceleration @property - def gyro(self): + def gyro(self) -> Tuple[int, int, int]: """Obtain x, y, z angular velocity values in degrees/second. .. image :: ../docs/_static/accelerometer.jpg @@ -420,7 +440,7 @@ def gyro(self): return self._accelerometer.gyro @property - def magnetic(self): + def magnetic(self) -> Tuple[int, int, int]: """Obtain x, y, z magnetic values in microteslas. .. image :: ../docs/_static/magnetometer.jpg @@ -440,7 +460,7 @@ def magnetic(self): return self._magnetometer.magnetic @property - def proximity(self): + def proximity(self) -> int: """A relative proximity to the sensor in values from 0 - 255. .. image :: ../docs/_static/proximity.jpg @@ -462,7 +482,7 @@ def proximity(self): return self._sensor.proximity @property - def color(self): + def color(self) -> Tuple[int, int, int, int]: """The red, green, blue, and clear light values. (r, g, b, c) .. image :: ../docs/_static/proximity.jpg @@ -484,7 +504,7 @@ def color(self): return self._sensor.color_data @property - def gesture(self): + def gesture(self) -> int: """A gesture code if gesture is detected. Shows ``0`` if no gesture detected. ``1`` if an UP gesture is detected, ``2`` if DOWN, ``3`` if LEFT, and ``4`` if RIGHT. @@ -512,7 +532,7 @@ def gesture(self): return self._sensor.gesture() @property - def humidity(self): + def humidity(self) -> float: """The measured relative humidity in percent. .. image :: ../docs/_static/humidity.jpg @@ -532,7 +552,7 @@ def humidity(self): return self._humidity.relative_humidity @property - def pressure(self): + def pressure(self) -> float: """The barometric pressure in hectoPascals. .. image :: ../docs/_static/pressure.jpg @@ -551,7 +571,7 @@ def pressure(self): return self._pressure.pressure @property - def temperature(self): + def temperature(self) -> float: """The temperature in degrees Celsius. .. image :: ../docs/_static/pressure.jpg @@ -570,7 +590,7 @@ def temperature(self): return self._pressure.temperature @property - def altitude(self): + def altitude(self) -> float: """The altitude in meters based on the sea level pressure at your location. You must set ``sea_level_pressure`` to receive an accurate reading. @@ -590,7 +610,7 @@ def altitude(self): return self._pressure.altitude @property - def sea_level_pressure(self): + def sea_level_pressure(self) -> float: """Set to the pressure at sea level at your location, before reading altitude for the most accurate altitude measurement. @@ -612,11 +632,11 @@ def sea_level_pressure(self): return self._pressure.sea_level_pressure @sea_level_pressure.setter - def sea_level_pressure(self, value): + def sea_level_pressure(self, value: float): self._pressure.sea_level_pressure = value @property - def white_leds(self): + def white_leds(self) -> bool: """The red led next to the USB plug labeled LED. .. image :: ../docs/_static/white_leds.jpg @@ -635,11 +655,11 @@ def white_leds(self): return self._white_leds.value @white_leds.setter - def white_leds(self, value): + def white_leds(self, value: bool): self._white_leds.value = value @property - def red_led(self): + def red_led(self) -> bool: """The red led next to the USB plug labeled LED. .. image :: ../docs/_static/red_led.jpg @@ -658,11 +678,11 @@ def red_led(self): return self._red_led.value @red_led.setter - def red_led(self, value): + def red_led(self, value: bool): self._red_led.value = value @property - def pixel(self): + def pixel(self) -> neopixel.NeoPixel: """The NeoPixel RGB LED. .. image :: ../docs/_static/neopixel.jpg @@ -682,20 +702,20 @@ def pixel(self): return self._pixel @staticmethod - def _sine_sample(length): + def _sine_sample(length: int): tone_volume = (2**15) - 1 shift = 2**15 for i in range(length): yield int(tone_volume * math.sin(2 * math.pi * (i / length)) + shift) - def _generate_sample(self, length=100): + def _generate_sample(self, length: int = 100): if self._audio_out is not None: return self._sine_wave = array.array("H", self._sine_sample(length)) self._audio_out = audiopwmio.PWMAudioOut(board.SPEAKER) self._sine_wave_sample = audiocore.RawSample(self._sine_wave) - def play_tone(self, frequency, duration): + def play_tone(self, frequency: int, duration: float): """Produce a tone using the speaker. Try changing frequency to change the pitch of the tone. @@ -720,7 +740,7 @@ def play_tone(self, frequency, duration): time.sleep(duration) self.stop_tone() - def start_tone(self, frequency): + def start_tone(self, frequency: int): """Produce a tone using the speaker. Try changing frequency to change the pitch of the tone. @@ -740,9 +760,9 @@ def start_tone(self, frequency): while True: if clue.button_a: - clue.start_tone(523) + clue.start_tone(1600) elif clue.button_b: - clue.start_tone(587) + clue.start_tone(2000) else: clue.stop_tone() """ @@ -772,9 +792,9 @@ def stop_tone(self): while True: if clue.button_a: - clue.start_tone(523) + clue.start_tone(1600) elif clue.button_b: - clue.start_tone(587) + clue.start_tone(2000) else: clue.stop_tone() """ @@ -785,18 +805,15 @@ def stop_tone(self): self._audio_out = None @staticmethod - def _normalized_rms(values): + def _normalized_rms(values) -> float: mean_values = int(sum(values) / len(values)) return math.sqrt( - sum( - float(sample - mean_values) * (sample - mean_values) - for sample in values - ) + sum(float(sample - mean_values) * (sample - mean_values) for sample in values) / len(values) ) @property - def sound_level(self): + def sound_level(self) -> float: """Obtain the sound level from the microphone (sound sensor). .. image :: ../docs/_static/microphone.jpg @@ -817,7 +834,7 @@ def sound_level(self): self._mic.record(self._mic_samples, len(self._mic_samples)) return self._normalized_rms(self._mic_samples) - def loud_sound(self, sound_threshold=200): + def loud_sound(self, sound_threshold: int = 200) -> bool: """Utilise a loud sound as an input. :param int sound_threshold: Threshold sound level must exceed to return true (Default: 200) @@ -860,13 +877,13 @@ def loud_sound(self, sound_threshold=200): return self.sound_level > sound_threshold @staticmethod - def simple_text_display( # pylint: disable=too-many-arguments - title=None, - title_color=(255, 255, 255), - title_scale=1, - text_scale=1, - font=None, - colors=None, + def simple_text_display( + title: Optional[str] = None, + title_color: Tuple = (255, 255, 255), + title_scale: int = 1, + text_scale: int = 1, + font: Optional[str] = None, + colors: Optional[Tuple[Tuple[int, int, int], ...]] = None, ): """Display lines of text on the CLUE display. Lines of text are created in order as shown in the example below. If you skip a number, the line will be shown blank on the display, @@ -927,7 +944,7 @@ def simple_text_display( # pylint: disable=too-many-arguments ) -clue = Clue() # pylint: disable=invalid-name +clue = Clue() """Object that is automatically created on import. To use, simply import it from the module: diff --git a/docs/api.rst b/docs/api.rst index 69e2c21..e6b2318 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -4,5 +4,8 @@ .. 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_clue :members: diff --git a/docs/conf.py b/docs/conf.py index a98b4d9..960610c 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("..")) @@ -17,6 +15,7 @@ # ones. extensions = [ "sphinx.ext.autodoc", + "sphinxcontrib.jquery", "sphinx.ext.intersphinx", "sphinx.ext.napoleon", "sphinx.ext.todo", @@ -69,9 +68,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 + " Kattni Rembor" author = "Kattni Rembor" @@ -122,19 +119,9 @@ # 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" - -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(), "."] - except: - html_theme = "default" - html_theme_path = ["."] -else: - html_theme_path = ["."] +import sphinx_rtd_theme + +html_theme = "sphinx_rtd_theme" # 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, diff --git a/docs/requirements.txt b/docs/requirements.txt index 88e6733..979f568 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -2,4 +2,6 @@ # # SPDX-License-Identifier: Unlicense -sphinx>=4.0.0 +sphinx +sphinxcontrib-jquery +sphinx-rtd-theme diff --git a/examples/clue_ams_remote.py b/examples/clue_ams_remote.py index 508f2ca..2991d91 100644 --- a/examples/clue_ams_remote.py +++ b/examples/clue_ams_remote.py @@ -12,13 +12,15 @@ """ import time + import adafruit_ble from adafruit_ble.advertising.standard import SolicitServicesAdvertisement from adafruit_ble_apple_media import AppleMediaService + from adafruit_clue import clue # PyLint can't find BLERadio for some reason so special case it here. -radio = adafruit_ble.BLERadio() # pylint: disable=no-member +radio = adafruit_ble.BLERadio() a = SolicitServicesAdvertisement() a.solicited_services.append(AppleMediaService) radio.start_advertising(a) @@ -44,7 +46,7 @@ play_str = "Playing" else: play_str = "Paused" - print("{} - {}, {}".format(ams.title, ams.artist, play_str)) + print(f"{ams.title} - {ams.artist}, {play_str}") # Capacitive touch pad marked 0 goes to the previous track if clue.touch_0: diff --git a/examples/clue_ams_remote_advanced.py b/examples/clue_ams_remote_advanced.py index 1f2b002..dbf2f97 100644 --- a/examples/clue_ams_remote_advanced.py +++ b/examples/clue_ams_remote_advanced.py @@ -1,6 +1,6 @@ # SPDX-FileCopyrightText: 2020 Eva Herrada for Adafruit Industries # SPDX-License-Identifier: MIT -""" This example solicits that apple devices that provide notifications connect to it, initiates +"""This example solicits that apple devices that provide notifications connect to it, initiates pairing, then allows the user to use a CLUE board as a media remote through both the buttons and capacitive touch pads. @@ -16,20 +16,20 @@ """ import time + +import adafruit_ble import board import displayio -from adafruit_display_text import label -import adafruit_ble -from adafruit_ble.advertising.standard import SolicitServicesAdvertisement -from adafruit_ble_apple_media import AppleMediaService -from adafruit_ble_apple_media import UnsupportedCommand from adafruit_bitmap_font import bitmap_font +from adafruit_ble.advertising.standard import SolicitServicesAdvertisement +from adafruit_ble_apple_media import AppleMediaService, UnsupportedCommand from adafruit_display_shapes.rect import Rect -from adafruit_clue import clue +from adafruit_display_text import label +from adafruit_clue import clue # PyLint can't find BLERadio for some reason so special case it here. -radio = adafruit_ble.BLERadio() # pylint: disable=no-member +radio = adafruit_ble.BLERadio() a = SolicitServicesAdvertisement() a.solicited_services.append(AppleMediaService) radio.start_advertising(a) @@ -84,7 +84,7 @@ volume_inner = Rect(15, 170, 1, 20, fill=0xFFFFFF, outline=0xFFFFFF) group.append(volume_inner) -display.show(group) +display.root_group = group time.sleep(0.01) width1 = 1 @@ -105,9 +105,7 @@ if not width: width = 1 if ams.duration and ams.playing: - width1 = int( - 210 * ((time.time() - ref_time + ela_time) / float(ams.duration)) - ) + width1 = int(210 * ((time.time() - ref_time + ela_time) / float(ams.duration))) if not width1: width1 = 1 elif not ams.duration: @@ -115,9 +113,7 @@ time_inner = Rect(15, 210, width1, 20, fill=0xFFFFFF) # , outline=0xFFFFFF) group[-2] = time_inner - volume_inner = Rect( - 15, 170, width, 20, fill=0xFFFFFF - ) # , outline=0xFFFFFF) + volume_inner = Rect(15, 170, width, 20, fill=0xFFFFFF) # , outline=0xFFFFFF) group[-1] = volume_inner # Capacitive touch pad marked 0 goes to the previous track diff --git a/examples/clue_ble_color_patchwork.py b/examples/clue_ble_color_patchwork.py index ca5bddc..4f0ec3b 100644 --- a/examples/clue_ble_color_patchwork.py +++ b/examples/clue_ble_color_patchwork.py @@ -1,6 +1,6 @@ # SPDX-FileCopyrightText: 2019 Kattni Rembor, written for Adafruit Industries # -# SPDX-License-Identifier: Unlicense +# SPDX-License-Identifier: MIT """ Circuit Python BLE Color Patchwork This demo uses advertising to broadcast a color of the users choice. @@ -8,15 +8,17 @@ advertisement that we find. """ -import time import random +import time + import board import displayio -from adafruit_display_text import label import terminalio from adafruit_ble import BLERadio from adafruit_ble.advertising.adafruit import AdafruitColor from adafruit_display_shapes.rect import Rect +from adafruit_display_text import label + from adafruit_clue import clue MODE_COLOR_SELECT = 0 @@ -62,9 +64,7 @@ def make_white(): def draw_grid(): for i, color in enumerate(nearby_colors): if i < 64: - palette_mapping[i + 2] = ( - color & 0xFFFFFF - ) # Mask 0xFFFFFF to avoid invalid color. + palette_mapping[i + 2] = color & 0xFFFFFF # Mask 0xFFFFFF to avoid invalid color. print(i) print(color) @@ -150,9 +150,7 @@ def change_advertisement(color): left_btn_lbl = label.Label(terminalio.FONT, text="A", color=0x000000) right_btn_lbl = label.Label(terminalio.FONT, text="B", color=0x000000) -left_btn_action = label.Label( - terminalio.FONT, text="Next\nColor", color=0x000000, line_spacing=1 -) +left_btn_action = label.Label(terminalio.FONT, text="Next\nColor", color=0x000000, line_spacing=1) right_btn_action = label.Label(terminalio.FONT, text="Save", color=0x000000) color_select_text_group.append(left_btn_lbl) @@ -207,7 +205,7 @@ def change_advertisement(color): group.append(patchwork_group) # Add the Group to the Display -display.show(group) +display.root_group = group cur_color = 0 @@ -239,7 +237,7 @@ def change_advertisement(color): if last_scan_time + SCAN_INTERVAL < now: ble_scan() last_scan_time = now - print("after scan found {} results".format(len(nearby_colors))) + print(f"after scan found {len(nearby_colors)} results") # print(nearby_addresses) draw_grid() @@ -248,9 +246,7 @@ def change_advertisement(color): while clue.proximity >= PROXIMITY_LIMIT: r, g, b, w = clue.color clue.pixel.fill(((r >> 8) & 0xFF, (g >> 8) & 0xFF, (b >> 8) & 0xFF)) - change_advertisement( - ((r & 0xFF00) << 8) + (g & 0xFF00) + ((b >> 8) & 0xFF) - ) + change_advertisement(((r & 0xFF00) << 8) + (g & 0xFF00) + ((b >> 8) & 0xFF)) time.sleep(0.1) clue.white_leds = False diff --git a/examples/clue_display_sensor_data.py b/examples/clue_display_sensor_data.py index 8a3f551..06a60fa 100644 --- a/examples/clue_display_sensor_data.py +++ b/examples/clue_display_sensor_data.py @@ -1,6 +1,6 @@ # SPDX-FileCopyrightText: 2019 Kattni Rembor, written for Adafruit Industries # -# SPDX-License-Identifier: Unlicense +# SPDX-License-Identifier: MIT from adafruit_clue import clue clue.sea_level_pressure = 1020 @@ -8,21 +8,19 @@ clue_data = clue.simple_text_display(title="CLUE Sensor Data!", title_scale=2) while True: - clue_data[0].text = "Acceleration: {:.2f} {:.2f} {:.2f} m/s^2".format( - *clue.acceleration - ) + clue_data[0].text = "Acceleration: {:.2f} {:.2f} {:.2f} m/s^2".format(*clue.acceleration) clue_data[1].text = "Gyro: {:.2f} {:.2f} {:.2f} dps".format(*clue.gyro) clue_data[2].text = "Magnetic: {:.3f} {:.3f} {:.3f} uTesla".format(*clue.magnetic) - clue_data[3].text = "Pressure: {:.3f} hPa".format(clue.pressure) - clue_data[4].text = "Altitude: {:.1f} m".format(clue.altitude) - clue_data[5].text = "Temperature: {:.1f} C".format(clue.temperature) - clue_data[6].text = "Humidity: {:.1f} %".format(clue.humidity) - clue_data[7].text = "Proximity: {}".format(clue.proximity) - clue_data[8].text = "Gesture: {}".format(clue.gesture) + clue_data[3].text = f"Pressure: {clue.pressure:.3f} hPa" + clue_data[4].text = f"Altitude: {clue.altitude:.1f} m" + clue_data[5].text = f"Temperature: {clue.temperature:.1f} C" + clue_data[6].text = f"Humidity: {clue.humidity:.1f} %" + clue_data[7].text = f"Proximity: {clue.proximity}" + clue_data[8].text = f"Gesture: {clue.gesture}" clue_data[9].text = "Color: R: {} G: {} B: {} C: {}".format(*clue.color) - clue_data[10].text = "Button A: {}".format(clue.button_a) - clue_data[11].text = "Button B: {}".format(clue.button_b) - clue_data[12].text = "Touch 0: {}".format(clue.touch_0) - clue_data[13].text = "Touch 1: {}".format(clue.touch_1) - clue_data[14].text = "Touch 2: {}".format(clue.touch_2) + clue_data[10].text = f"Button A: {clue.button_a}" + clue_data[11].text = f"Button B: {clue.button_b}" + clue_data[12].text = f"Touch 0: {clue.touch_0}" + clue_data[13].text = f"Touch 1: {clue.touch_1}" + clue_data[14].text = f"Touch 2: {clue.touch_2}" clue_data.show() diff --git a/examples/clue_height_calculator.py b/examples/clue_height_calculator.py index 64f0b27..c6a450e 100755 --- a/examples/clue_height_calculator.py +++ b/examples/clue_height_calculator.py @@ -1,8 +1,9 @@ # SPDX-FileCopyrightText: 2019 Kattni Rembor, written for Adafruit Industries # -# SPDX-License-Identifier: Unlicense +# SPDX-License-Identifier: MIT """Calculate the height of an object. Press button A to reset initial height and then lift the CLUE to find the height.""" + from adafruit_clue import clue # Set to the sea level pressure in hPa at your location for the most accurate altitude measurement. @@ -26,6 +27,6 @@ else: clue.pixel.fill(0) - clue_display[5].text = "Altitude: {:.1f} m".format(clue.altitude) - clue_display[7].text = "Height: {:.1f} m".format(clue.altitude - initial_height) + clue_display[5].text = f"Altitude: {clue.altitude:.1f} m" + clue_display[7].text = f"Height: {clue.altitude - initial_height:.1f} m" clue_display.show() diff --git a/examples/clue_simpletest.py b/examples/clue_simpletest.py index 12ec856..5376ae6 100644 --- a/examples/clue_simpletest.py +++ b/examples/clue_simpletest.py @@ -1,6 +1,6 @@ # SPDX-FileCopyrightText: 2019 Kattni Rembor, written for Adafruit Industries # -# SPDX-License-Identifier: Unlicense +# SPDX-License-Identifier: MIT from adafruit_clue import clue clue.sea_level_pressure = 1020 @@ -9,11 +9,11 @@ print("Acceleration: {:.2f} {:.2f} {:.2f} m/s^2".format(*clue.acceleration)) print("Gyro: {:.2f} {:.2f} {:.2f} dps".format(*clue.gyro)) print("Magnetic: {:.3f} {:.3f} {:.3f} uTesla".format(*clue.magnetic)) - print("Pressure: {:.3f} hPa".format(clue.pressure)) - print("Altitude: {:.1f} m".format(clue.altitude)) - print("Temperature: {:.1f} C".format(clue.temperature)) - print("Humidity: {:.1f} %".format(clue.humidity)) - print("Proximity: {}".format(clue.proximity)) - print("Gesture: {}".format(clue.gesture)) + print(f"Pressure: {clue.pressure:.3f} hPa") + print(f"Altitude: {clue.altitude:.1f} m") + print(f"Temperature: {clue.temperature:.1f} C") + print(f"Humidity: {clue.humidity:.1f} %") + print(f"Proximity: {clue.proximity}") + print(f"Gesture: {clue.gesture}") print("Color: R: {} G: {} B: {} C: {}".format(*clue.color)) print("--------------------------------") diff --git a/examples/clue_slideshow/clue_slideshow.py b/examples/clue_slideshow/clue_slideshow.py index 59230b0..826b186 100755 --- a/examples/clue_slideshow/clue_slideshow.py +++ b/examples/clue_slideshow/clue_slideshow.py @@ -1,13 +1,14 @@ # SPDX-FileCopyrightText: 2019 Kattni Rembor, written for Adafruit Industries # -# SPDX-License-Identifier: Unlicense +# SPDX-License-Identifier: MIT """Display a series of bitmaps using the buttons to advance through the list. To use: place supported bitmap files on your CIRCUITPY drive, then press the buttons on your CLUE to advance through them. Requires the Adafruit CircuitPython Slideshow library!""" -from adafruit_slideshow import SlideShow, PlayBackDirection +from adafruit_slideshow import PlayBackDirection, SlideShow + from adafruit_clue import clue slideshow = SlideShow(clue.display, auto_advance=False) diff --git a/examples/clue_spirit_level.py b/examples/clue_spirit_level.py index 6a24400..b32050a 100755 --- a/examples/clue_spirit_level.py +++ b/examples/clue_spirit_level.py @@ -1,10 +1,12 @@ # SPDX-FileCopyrightText: 2019 Kattni Rembor, written for Adafruit Industries # -# SPDX-License-Identifier: Unlicense +# SPDX-License-Identifier: MIT """CLUE Spirit Level Demo""" + import board import displayio from adafruit_display_shapes.circle import Circle + from adafruit_clue import clue display = board.DISPLAY @@ -23,7 +25,7 @@ bubble_group.append(level_bubble) clue_group.append(bubble_group) -display.show(clue_group) +display.root_group = clue_group while True: x, y, _ = clue.acceleration diff --git a/examples/clue_temperature_humidity_monitor.py b/examples/clue_temperature_humidity_monitor.py index c1090fd..a0f7b7d 100755 --- a/examples/clue_temperature_humidity_monitor.py +++ b/examples/clue_temperature_humidity_monitor.py @@ -2,6 +2,7 @@ # SPDX-License-Identifier: MIT """Monitor customisable temperature and humidity ranges, with an optional audible alarm tone.""" + from adafruit_clue import clue # Set desired temperature range in degrees Celsius. @@ -26,8 +27,8 @@ temperature = clue.temperature humidity = clue.humidity - clue_display[3].text = "Temp: {:.1f} C".format(temperature) - clue_display[5].text = "Humi: {:.1f} %".format(humidity) + clue_display[3].text = f"Temp: {temperature:.1f} C" + clue_display[5].text = f"Humi: {humidity:.1f} %" if temperature < min_temperature: clue_display[3].color = clue.BLUE diff --git a/examples/clue_touch_all.py b/examples/clue_touch_all.py new file mode 100644 index 0000000..f3a8048 --- /dev/null +++ b/examples/clue_touch_all.py @@ -0,0 +1,36 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""This example prints to the serial console when you touch the capacitive touch pads.""" + +import time + +import board + +from adafruit_clue import clue + +# You'll need to first use the touchpads individually to register them as active touchpads +# You don't have to use the result though +is_p0_touched = clue.touch_0 # This result can be used if you want +if is_p0_touched: + print("P0/D0 was touched upon startup!") +is_p1_touched = clue.touch_1 +is_p2_touched = clue.touch_2 + + +print("Pads that are currently setup as touchpads:") +print(clue.touch_pins) + +while True: + current_touched = clue.touched + + if current_touched: + print("Touchpads currently registering a touch:") + print(current_touched) + else: + print("No touchpads are currently registering a touch.") + + if all(pad in current_touched for pad in (board.P0, board.P1, board.P2)): + print("This only prints when P0, P1, and P2 are being held at the same time!") + + time.sleep(0.25) 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"
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: