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/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md b/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md new file mode 100644 index 0000000..8de294e --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md @@ -0,0 +1,13 @@ +# SPDX-FileCopyrightText: 2021 Adafruit Industries +# +# SPDX-License-Identifier: MIT + +Thank you for contributing! Before you submit a pull request, please read the following. + +Make sure any changes you're submitting are in line with the CircuitPython Design Guide, available here: https://docs.circuitpython.org/en/latest/docs/design_guide.html + +If your changes are to documentation, please verify that the documentation builds locally by following the steps found here: https://adafru.it/build-docs + +Before submitting the pull request, make sure you've run Pylint and Black locally on your code. You can do this manually or using pre-commit. Instructions are available here: https://adafru.it/check-your-code + +Please remove all of this text before submitting. Include an explanation or list of changes included in your PR, as well as, if applicable, a link to any related issues. diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 59baa53..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.6 - uses: actions/setup-python@v1 - with: - python-version: 3.6 - - 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 pylint, Sphinx, pre-commit - run: | - pip install --force-reinstall pylint Sphinx sphinx-rtd-theme pre-commit - - name: Library version - run: git describe --dirty --always --tags - - name: Pre-commit hooks - run: | - pre-commit run --all-files - - name: PyLint - run: | - pylint $( find . -path './adafruit*.py' ) - ([[ ! -d "examples" ]] || pylint --disable=missing-docstring,invalid-name,bad-whitespace $( find . -path "./examples/*.py" )) - - 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 setup.py - id: need-pypi - run: | - echo ::set-output name=setup-py::$( find . -wholename './setup.py' ) - - name: Build Python package - if: contains(steps.need-pypi.outputs.setup-py, 'setup.py') - run: | - pip install --upgrade setuptools wheel twine readme_renderer testresources - python setup.py sdist - python setup.py bdist_wheel --universal - twine check dist/* + - name: Run Build CI workflow + uses: adafruit/workflows-circuitpython-libs/build@main diff --git a/.github/workflows/failure-help-text.yml b/.github/workflows/failure-help-text.yml new file mode 100644 index 0000000..0b1194f --- /dev/null +++ b/.github/workflows/failure-help-text.yml @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: 2021 Scott Shawcroft for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +name: Failure help text + +on: + workflow_run: + workflows: ["Build CI"] + types: + - completed + +jobs: + post-help: + runs-on: ubuntu-latest + if: ${{ github.event.workflow_run.conclusion == 'failure' && github.event.workflow_run.event == 'pull_request' }} + steps: + - name: Post comment to help + uses: adafruit/circuitpython-action-library-ci-failed@v1 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml deleted file mode 100644 index 6d0015a..0000000 --- a/.github/workflows/release.yml +++ /dev/null @@ -1,85 +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.6 - uses: actions/setup-python@v1 - with: - python-version: 3.6 - - 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 setup.py - id: need-pypi - run: | - echo ::set-output name=setup-py::$( find . -wholename './setup.py' ) - - name: Set up Python - if: contains(steps.need-pypi.outputs.setup-py, 'setup.py') - uses: actions/setup-python@v1 - with: - python-version: '3.x' - - name: Install dependencies - if: contains(steps.need-pypi.outputs.setup-py, 'setup.py') - run: | - python -m pip install --upgrade pip - pip install setuptools wheel twine - - name: Build and publish - if: contains(steps.need-pypi.outputs.setup-py, 'setup.py') - env: - TWINE_USERNAME: ${{ secrets.pypi_username }} - TWINE_PASSWORD: ${{ secrets.pypi_password }} - run: | - python setup.py sdist - 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 9647e71..db3d538 100644 --- a/.gitignore +++ b/.gitignore @@ -1,15 +1,48 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-FileCopyrightText: 2022 Kattni Rembor, written for Adafruit Industries # -# SPDX-License-Identifier: Unlicense +# SPDX-License-Identifier: MIT +# Do not include files and directories created by your personal work environment, such as the IDE +# you use, except for those already listed here. Pull requests including changes to this file will +# not be accepted. + +# This .gitignore file contains rules for files generated by working with CircuitPython libraries, +# including building Sphinx, testing with pip, and creating a virual environment, as well as the +# MacOS and IDE-specific files generated by using MacOS in general, or the PyCharm or VSCode IDEs. + +# If you find that there are files being generated on your machine that should not be included in +# your git commit, you should create a .gitignore_global file on your computer to include the +# files created by your personal setup. To do so, follow the two steps below. + +# First, create a file called .gitignore_global somewhere convenient for you, and add rules for +# the files you want to exclude from git commits. + +# Second, configure Git to use the exclude file for all Git repositories by running the +# following via commandline, replacing "path/to/your/" with the actual path to your newly created +# .gitignore_global file: +# git config --global core.excludesfile path/to/your/.gitignore_global + +# CircuitPython-specific files *.mpy -.idea + +# Python-specific files __pycache__ -_build *.pyc + +# Sphinx build-specific files +_build + +# This file results from running `pip -e install .` in a local repository +*.egg-info + +# Virtual environment-specific files .env -bundles +.venv + +# MacOS-specific files *.DS_Store -.eggs -dist -**/*.egg-info + +# IDE-specific files +.idea +.vscode +*~ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index aab5f1c..ff19dde 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,19 +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: stable + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.5.0 hooks: - - id: black -- repo: https://github.com/fsfe/reuse-tool - rev: latest + - id: check-yaml + - id: end-of-file-fixer + - id: trailing-whitespace + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.3.4 hooks: - - id: reuse -- repo: https://github.com/pre-commit/pre-commit-hooks - rev: v2.3.0 + - id: ruff-format + - id: ruff + args: ["--fix"] + - repo: https://github.com/fsfe/reuse-tool + rev: v3.0.1 hooks: - - id: check-yaml - - id: end-of-file-fixer - - id: trailing-whitespace + - id: reuse diff --git a/.pylintrc b/.pylintrc deleted file mode 100644 index 5c31f66..0000000 --- a/.pylintrc +++ /dev/null @@ -1,437 +0,0 @@ -# SPDX-FileCopyrightText: 2021 ladyada 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 blacklist. They should be base names, not -# paths. -ignore=CVS - -# Add files or directories matching the regex patterns to the blacklist. 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 -jobs=2 - -# 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 - -# 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=no - -# Minimum lines number of a similarity. -min-similarity-lines=4 - - -[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 new file mode 100644 index 0000000..255dafd --- /dev/null +++ b/.readthedocs.yaml @@ -0,0 +1,22 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense + +# Read the Docs configuration file +# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details + +# Required +version: 2 + +sphinx: + configuration: docs/conf.py + +build: + os: ubuntu-lts-latest + tools: + python: "3" + +python: + install: + - requirements: docs/requirements.txt + - requirements: requirements.txt diff --git a/.readthedocs.yml b/.readthedocs.yml deleted file mode 100644 index ffa84c4..0000000 --- a/.readthedocs.yml +++ /dev/null @@ -1,7 +0,0 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries -# -# SPDX-License-Identifier: Unlicense - -python: - version: 3 -requirements_file: requirements.txt diff --git a/README.rst b/README.rst index 69e56be..811883b 100644 --- a/README.rst +++ b/README.rst @@ -2,10 +2,10 @@ Introduction ============ .. image:: https://readthedocs.org/projects/adafruit-circuitpython-pybadger/badge/?version=latest - :target: https://circuitpython.readthedocs.io/projects/pybadger/en/latest/ + :target: https://docs.circuitpython.org/projects/pybadger/en/latest/ :alt: Documentation Status -.. image:: https://img.shields.io/discord/327254708534116352.svg +.. image:: https://raw.githubusercontent.com/adafruit/Adafruit_CircuitPython_Bundle/main/badges/adafruit_discord.svg :target: https://adafru.it/discord :alt: Discord @@ -13,6 +13,10 @@ Introduction :target: https://github.com/adafruit/Adafruit_CircuitPython_PyBadger/actions/ :alt: Build Status +.. 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 + Badge-focused CircuitPython helper library for PyBadge, PyBadge LC, PyGamer, CLUE, and Mag Tag. @@ -46,8 +50,8 @@ To install in a virtual environment in your current project: .. code-block:: shell mkdir project-name && cd project-name - python3 -m venv .env - source .env/bin/activate + python3 -m venv .venv + source .venv/bin/activate pip3 install adafruit-circuitpython-pybadger Usage Example @@ -70,14 +74,16 @@ Usage Example pybadger.show_badge(name_string="Blinka", hello_scale=2, my_name_is_scale=2, name_scale=3) +Documentation +============= + +API documentation for this library can be found on `Read the Docs `_. + +For information on building library documentation, please check out `this guide `_. + Contributing ============ Contributions are welcome! Please read our `Code of Conduct -`_ +`_ before contributing to help this project stay welcoming. - -Documentation -============= - -For information on building library documentation, please check out `this guide `_. diff --git a/adafruit_pybadger/__init__.py b/adafruit_pybadger/__init__.py old mode 100755 new mode 100644 index c322ff8..159826a --- a/adafruit_pybadger/__init__.py +++ b/adafruit_pybadger/__init__.py @@ -21,4 +21,4 @@ elif "Circuit Playground Bluefruit" in os.uname().machine: from .cpb_gizmo import cpb_gizmo as pybadger elif "MagTag with ESP32S2" in os.uname().machine: - from .mag_tag import mag_tag as pybadger + from .magtag import magtag as pybadger diff --git a/adafruit_pybadger/clue.py b/adafruit_pybadger/clue.py old mode 100755 new mode 100644 index 4998612..f99e14a --- a/adafruit_pybadger/clue.py +++ b/adafruit_pybadger/clue.py @@ -26,15 +26,17 @@ """ from collections import namedtuple -import board -import digitalio -import audiopwmio -from gamepad import GamePad + +import adafruit_lsm6ds.lsm6ds3trc import adafruit_lsm6ds.lsm6ds33 +import audiopwmio +import board +import keypad import neopixel -from adafruit_pybadger.pybadger_base import PyBadgerBase -__version__ = "0.0.0-auto.0" +from adafruit_pybadger.pybadger_base import KeyStates, PyBadgerBase + +__version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_PyBadger.git" Buttons = namedtuple("Buttons", "a b") @@ -46,26 +48,29 @@ class Clue(PyBadgerBase): _audio_out = audiopwmio.PWMAudioOut _neopixel_count = 1 - def __init__(self): + def __init__(self) -> None: super().__init__() i2c = board.I2C() if i2c is not None: - self._accelerometer = adafruit_lsm6ds.lsm6ds33.LSM6DS33(i2c) + try: + self._accelerometer = adafruit_lsm6ds.lsm6ds33.LSM6DS33(i2c) + except RuntimeError: + self._accelerometer = adafruit_lsm6ds.lsm6ds3trc.LSM6DS3TRC(i2c) # NeoPixels self._neopixels = neopixel.NeoPixel( board.NEOPIXEL, self._neopixel_count, brightness=1, pixel_order=neopixel.GRB ) - self._buttons = GamePad( - digitalio.DigitalInOut(board.BUTTON_A), - digitalio.DigitalInOut(board.BUTTON_B), + self._keys = keypad.Keys( + [board.BUTTON_A, board.BUTTON_B], value_when_pressed=False, pull=True ) + self._buttons = KeyStates(self._keys) @property - def button(self): + def button(self) -> Buttons: """The buttons on the board. Example use: @@ -80,10 +85,9 @@ def button(self): elif pybadger.button.b: print("Button B") """ - button_values = self._buttons.get_pressed() - return Buttons( - button_values & PyBadgerBase.BUTTON_B, button_values & PyBadgerBase.BUTTON_A - ) + self._buttons.update() + button_values = tuple(self._buttons.was_pressed(i) for i in range(self._keys.key_count)) + return Buttons(button_values[0], button_values[1]) @property def _unsupported(self): @@ -97,5 +101,5 @@ def _unsupported(self): light = _unsupported -clue = Clue() # pylint: disable=invalid-name +clue = Clue() """Object that is automatically created on import.""" diff --git a/adafruit_pybadger/cpb_gizmo.py b/adafruit_pybadger/cpb_gizmo.py index 39530fb..dffdab7 100644 --- a/adafruit_pybadger/cpb_gizmo.py +++ b/adafruit_pybadger/cpb_gizmo.py @@ -27,18 +27,20 @@ """ from collections import namedtuple -import board -import digitalio + +import adafruit_lis3dh import analogio -import busio import audiopwmio -from adafruit_gizmo import tft_gizmo -from gamepad import GamePad -import adafruit_lis3dh +import board +import busio +import digitalio +import keypad import neopixel -from adafruit_pybadger.pybadger_base import PyBadgerBase +from adafruit_gizmo import tft_gizmo + +from adafruit_pybadger.pybadger_base import KeyStates, PyBadgerBase -__version__ = "0.0.0-auto.0" +__version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_PyBadger.git" Buttons = namedtuple("Buttons", "a b") @@ -51,7 +53,7 @@ class CPB_Gizmo(PyBadgerBase): _audio_out = audiopwmio.PWMAudioOut _neopixel_count = 10 - def __init__(self): + def __init__(self) -> None: super().__init__() _i2c = busio.I2C(board.ACCELEROMETER_SCL, board.ACCELEROMETER_SDA) @@ -66,15 +68,15 @@ def __init__(self): self._neopixels = neopixel.NeoPixel( board.NEOPIXEL, self._neopixel_count, brightness=1, pixel_order=neopixel.GRB ) - _a_btn = digitalio.DigitalInOut(board.BUTTON_A) - _a_btn.switch_to_input(pull=digitalio.Pull.DOWN) - _b_btn = digitalio.DigitalInOut(board.BUTTON_B) - _b_btn.switch_to_input(pull=digitalio.Pull.DOWN) - self._buttons = GamePad(_a_btn, _b_btn) + + self._keys = keypad.Keys( + [board.BUTTON_A, board.BUTTON_B], value_when_pressed=True, pull=True + ) + self._buttons = KeyStates(self._keys) self._light_sensor = analogio.AnalogIn(board.LIGHT) @property - def button(self): + def button(self) -> Buttons: """The buttons on the board. Example use: @@ -89,10 +91,9 @@ def button(self): elif pybadger.button.b: print("Button B") """ - button_values = self._buttons.get_pressed() - return Buttons( - button_values & PyBadgerBase.BUTTON_B, button_values & PyBadgerBase.BUTTON_A - ) + self._buttons.update() + button_values = tuple(self._buttons.was_pressed(i) for i in range(self._keys.key_count)) + return Buttons(button_values[0], button_values[1]) @property def _unsupported(self): @@ -104,5 +105,5 @@ def _unsupported(self): # NotImplementedError raised in the property above. -cpb_gizmo = CPB_Gizmo() # pylint: disable=invalid-name +cpb_gizmo = CPB_Gizmo() """Object that is automatically created on import.""" diff --git a/adafruit_pybadger/mag_tag.py b/adafruit_pybadger/magtag.py old mode 100755 new mode 100644 similarity index 73% rename from adafruit_pybadger/mag_tag.py rename to adafruit_pybadger/magtag.py index 2f8b849..0f3251c --- a/adafruit_pybadger/mag_tag.py +++ b/adafruit_pybadger/magtag.py @@ -3,7 +3,7 @@ # SPDX-License-Identifier: MIT """ -`adafruit_pybadger.mag_tag` +`adafruit_pybadger.magtag` ================================================================================ Badge-focused CircuitPython helper library for Mag Tag. @@ -26,14 +26,13 @@ """ from collections import namedtuple -import board -# import digitalio -# from gamepad import GamePad +import board import neopixel + from adafruit_pybadger.pybadger_base import PyBadgerBase -__version__ = "0.0.0-auto.0" +__version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_PyBadger.git" Buttons = namedtuple("Buttons", "a b c d") @@ -44,7 +43,7 @@ class MagTag(PyBadgerBase): _neopixel_count = 4 - def __init__(self): + def __init__(self) -> None: super().__init__() # NeoPixels @@ -52,15 +51,8 @@ def __init__(self): board.NEOPIXEL, self._neopixel_count, brightness=1, pixel_order=neopixel.GRB ) - # self._buttons = GamePad( - # , - # digitalio.DigitalInOut(board.BUTTON_B), - # digitalio.DigitalInOut(board.BUTTON_C), - # digitalio.DigitalInOut(board.BUTTON_D), - # ) - @property - def button(self): + def button(self) -> Buttons: """The buttons on the board. Example use: @@ -75,11 +67,6 @@ def button(self): elif pybadger.button.b: print("Button B") """ - # button_values = self._buttons.get_pressed() - # return Buttons( - # button_values & PyBadgerBase.BUTTON_B, button_values & PyBadgerBase.BUTTON_A, - # button_values & PyBadgerBase.BUTTON_START, button_values & PyBadgerBase.BUTTON_SELECT - # ) @property def _unsupported(self): @@ -95,5 +82,5 @@ def _unsupported(self): button = _unsupported -mag_tag = MagTag() # pylint: disable=invalid-name +magtag = MagTag() """Object that is automatically created on import.""" diff --git a/adafruit_pybadger/pewpewm4.py b/adafruit_pybadger/pewpewm4.py index 045365f..cd8f3cd 100644 --- a/adafruit_pybadger/pewpewm4.py +++ b/adafruit_pybadger/pewpewm4.py @@ -3,7 +3,7 @@ # SPDX-License-Identifier: MIT """ -`adafruit_pybadger.clue` +`adafruit_pybadger.pewpewm4` ================================================================================ Badge-focused CircuitPython helper library for Pew Pew M4. @@ -26,13 +26,14 @@ """ from collections import namedtuple -import board -import digitalio + import audioio -from gamepad import GamePad -from adafruit_pybadger.pybadger_base import PyBadgerBase +import board +import keypad -__version__ = "0.0.0-auto.0" +from adafruit_pybadger.pybadger_base import KeyStates, PyBadgerBase + +__version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_PyBadger.git" Buttons = namedtuple("Buttons", ("o", "x", "z", "right", "down", "up", "left")) @@ -44,21 +45,27 @@ class PewPewM4(PyBadgerBase): _audio_out = audioio.AudioOut _neopixel_count = 0 - def __init__(self): + def __init__(self) -> None: super().__init__() - self._buttons = GamePad( - digitalio.DigitalInOut(board.BUTTON_O), - digitalio.DigitalInOut(board.BUTTON_X), - digitalio.DigitalInOut(board.BUTTON_Z), - digitalio.DigitalInOut(board.BUTTON_RIGHT), - digitalio.DigitalInOut(board.BUTTON_DOWN), - digitalio.DigitalInOut(board.BUTTON_UP), - digitalio.DigitalInOut(board.BUTTON_LEFT), + self._keys = keypad.Keys( + [ + board.BUTTON_O, + board.BUTTON_X, + board.BUTTON_Z, + board.BUTTON_RIGHT, + board.BUTTON_DOWN, + board.BUTTON_UP, + board.BUTTON_LEFT, + ], + value_when_pressed=False, + pull=True, ) + self._buttons = KeyStates(self._keys) + @property - def button(self): + def button(self) -> Buttons: """The buttons on the board. Example use: @@ -73,20 +80,16 @@ def button(self): elif pybadger.button.o: print("Button O") """ - button_values = self._buttons.get_pressed() + self._buttons.update() + button_values = tuple(self._buttons.was_pressed(i) for i in range(self._keys.key_count)) return Buttons( - *[ - button_values & button - for button in ( - PyBadgerBase.BUTTON_B, - PyBadgerBase.BUTTON_A, - PyBadgerBase.BUTTON_START, - PyBadgerBase.BUTTON_SELECT, - PyBadgerBase.BUTTON_RIGHT, - PyBadgerBase.BUTTON_DOWN, - PyBadgerBase.BUTTON_UP, - ) - ] + button_values[0], + button_values[1], + button_values[2], + button_values[3], + button_values[4], + button_values[5], + button_values[6], ) @property @@ -102,5 +105,5 @@ def _unsupported(self): pixels = _unsupported -pewpewm4 = PewPewM4() # pylint: disable=invalid-name +pewpewm4 = PewPewM4() """Object that is automatically created on import.""" diff --git a/adafruit_pybadger/pybadge.py b/adafruit_pybadger/pybadge.py old mode 100755 new mode 100644 index 083b727..312750a --- a/adafruit_pybadger/pybadge.py +++ b/adafruit_pybadger/pybadge.py @@ -31,16 +31,18 @@ """ from collections import namedtuple -import board -import digitalio + +import adafruit_lis3dh import analogio import audioio -from gamepadshift import GamePadShift -import adafruit_lis3dh +import board +import digitalio +import keypad import neopixel -from adafruit_pybadger.pybadger_base import PyBadgerBase -__version__ = "0.0.0-auto.0" +from adafruit_pybadger.pybadger_base import KeyStates, PyBadgerBase + +__version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_PyBadger.git" Buttons = namedtuple("Buttons", "b a start select right down up left") @@ -52,7 +54,7 @@ class PyBadge(PyBadgerBase): _audio_out = audioio.AudioOut _neopixel_count = 5 - def __init__(self): + def __init__(self) -> None: super().__init__() i2c = None @@ -64,29 +66,41 @@ def __init__(self): self._accelerometer = None if i2c is not None: - int1 = digitalio.DigitalInOut(board.ACCELEROMETER_INTERRUPT) - try: - self._accelerometer = adafruit_lis3dh.LIS3DH_I2C( - i2c, address=0x19, int1=int1 - ) - except ValueError: - self._accelerometer = adafruit_lis3dh.LIS3DH_I2C(i2c, int1=int1) + _i2c_devices = [] + + for _ in range(10): + # try lock 10 times to avoid infinite loop in sphinx build + if i2c.try_lock(): + _i2c_devices = i2c.scan() + i2c.unlock() + break + + # PyBadge LC doesn't have accelerometer + if 0x18 in _i2c_devices or 0x19 in _i2c_devices: + int1 = digitalio.DigitalInOut(board.ACCELEROMETER_INTERRUPT) + try: + self._accelerometer = adafruit_lis3dh.LIS3DH_I2C(i2c, address=0x19, int1=int1) + except ValueError: + self._accelerometer = adafruit_lis3dh.LIS3DH_I2C(i2c, int1=int1) # NeoPixels self._neopixels = neopixel.NeoPixel( board.NEOPIXEL, self._neopixel_count, brightness=1, pixel_order=neopixel.GRB ) - self._buttons = GamePadShift( - digitalio.DigitalInOut(board.BUTTON_CLOCK), - digitalio.DigitalInOut(board.BUTTON_OUT), - digitalio.DigitalInOut(board.BUTTON_LATCH), + self._keys = keypad.ShiftRegisterKeys( + clock=board.BUTTON_CLOCK, + data=board.BUTTON_OUT, + latch=board.BUTTON_LATCH, + key_count=8, + value_when_pressed=True, ) + self._buttons = KeyStates(self._keys) self._light_sensor = analogio.AnalogIn(board.A7) @property - def button(self): + def button(self) -> Buttons: """The buttons on the board. Example use: @@ -106,23 +120,19 @@ def button(self): print("Button select") """ - button_values = self._buttons.get_pressed() + self._buttons.update() + button_values = tuple(self._buttons.was_pressed(i) for i in range(self._keys.key_count)) return Buttons( - *[ - button_values & button - for button in ( - PyBadgerBase.BUTTON_B, - PyBadgerBase.BUTTON_A, - PyBadgerBase.BUTTON_START, - PyBadgerBase.BUTTON_SELECT, - PyBadgerBase.BUTTON_RIGHT, - PyBadgerBase.BUTTON_DOWN, - PyBadgerBase.BUTTON_UP, - PyBadgerBase.BUTTON_LEFT, - ) - ] + button_values[0], + button_values[1], + button_values[2], + button_values[3], + button_values[4], + button_values[5], + button_values[6], + button_values[7], ) -pybadge = PyBadge() # pylint: disable=invalid-name +pybadge = PyBadge() """Object that is automatically created on import.""" diff --git a/adafruit_pybadger/pybadger_base.py b/adafruit_pybadger/pybadger_base.py old mode 100755 new mode 100644 index fbd2824..67f4443 --- a/adafruit_pybadger/pybadger_base.py +++ b/adafruit_pybadger/pybadger_base.py @@ -27,18 +27,21 @@ """ -import time +from __future__ import annotations + import array import math +import time + +import adafruit_miniqr import board -from micropython import const import digitalio -from adafruit_bitmap_font import bitmap_font import displayio -from adafruit_display_shapes.rect import Rect -from adafruit_display_text import label import terminalio -import adafruit_miniqr +from adafruit_bitmap_font import bitmap_font +from adafruit_display_shapes.rect import Rect +from adafruit_display_text import bitmap_label as label +from micropython import const AUDIO_ENABLED = False try: @@ -53,11 +56,27 @@ except ImportError: # Allow to work with no audio pass -__version__ = "0.0.0-auto.0" + +try: + from typing import TYPE_CHECKING +except ImportError: + TYPE_CHECKING = const(0) + +if TYPE_CHECKING: + from typing import Generator, Optional, Union + + from adafruit_bitmap_font.bdf import BDF + from adafruit_bitmap_font.pcf import PCF + from fontio import BuiltinFont + from keypad import Keys, ShiftRegisterKeys + from neopixel import NeoPixel + + +__version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_PyBadger.git" -def load_font(fontname, text): +def load_font(fontname: str, text: str) -> Union[BDF, PCF]: """Load a font and glyphs in the text string :param str fontname: The full path to the font file. @@ -69,7 +88,6 @@ def load_font(fontname, text): return font -# pylint: disable=too-many-instance-attributes class PyBadgerBase: """PyBadger base class.""" @@ -112,7 +130,7 @@ class PyBadgerBase: BUTTON_A = const(2) BUTTON_B = const(1) - def __init__(self): + def __init__(self) -> None: self._light_sensor = None self._accelerometer = None self._label = label @@ -141,51 +159,43 @@ def __init__(self): self._sine_wave = None self._sine_wave_sample = None - def _create_badge_background(self): + def _create_badge_background(self) -> None: self._created_background = True if self._background_group is None: - self._background_group = displayio.Group(max_size=30) + self._background_group = displayio.Group() - self.display.show(self._background_group) + self.root_group = self._background_group if self._background_image_filename: - with open(self._background_image_filename, "rb") as file_handle: - on_disk_bitmap = displayio.OnDiskBitmap(file_handle) - background_image = displayio.TileGrid( - on_disk_bitmap, pixel_shader=displayio.ColorConverter() - ) - self._background_group.append(background_image) - for image_label in self._lines: - self._background_group.append(image_label) - - try: - # Refresh display in CircuitPython 5 - self.display.refresh() - except AttributeError: - # Refresh display in CircuitPython 4 - self.display.wait_for_frame() - else: - for background_label in self._lines: - self._background_group.append(background_label) + on_disk_bitmap = displayio.OnDiskBitmap(self._background_image_filename) + background_image = displayio.TileGrid( + on_disk_bitmap, + pixel_shader=on_disk_bitmap.pixel_shader, + ) + self._background_group.append(background_image) + for image_label in self._lines: + self._background_group.append(image_label) def badge_background( self, - background_color=(255, 0, 0), - rectangle_color=(255, 255, 255), - rectangle_drop=0.4, - rectangle_height=0.5, - ): + background_color: tuple[int, int, int] = RED, + rectangle_color: tuple[int, int, int] = WHITE, + rectangle_drop: float = 0.4, + rectangle_height: float = 0.5, + ) -> displayio.Group: """Create a customisable badge background made up of a background color with a rectangle color block over it. Defaults are for ``show_badge``. - :param tuple background_color: The color to fill the entire screen as a background. - :param tuple rectangle_color: The color of a rectangle that displays over the background. + :param tuple background_color: The color to fill the entire screen as a background, as + RGB values. + :param tuple rectangle_color: The color of a rectangle that displays over the background, + as RGB values. :param float rectangle_drop: The distance from the top of the display to begin displaying the rectangle. Float represents a percentage of the display, e.g. 0.4 = 40% of the display. Defaults to ``0.4``. - :param float rectangle_height: The height of the rectangle. Float represents a percentage of - the display, e.g. 0.5 = 50% of the display. Defaults to + :param float rectangle_height: The height of the rectangle. Float represents a percentage + of the display, e.g. 0.5 = 50% of the display. Defaults to ``0.5``. .. code-block:: python @@ -206,21 +216,19 @@ def badge_background( def _badge_background( self, - background_color=(255, 0, 0), - rectangle_color=(255, 255, 255), - rectangle_drop=0.4, - rectangle_height=0.5, - ): + background_color: tuple[int, int, int] = RED, + rectangle_color: tuple[int, int, int] = WHITE, + rectangle_drop: float = 0.4, + rectangle_height: float = 0.5, + ) -> displayio.Group: """Populate the background color with a rectangle color block over it as the background for a name badge.""" - background_group = displayio.Group(max_size=30) + background_group = displayio.Group() color_bitmap = displayio.Bitmap(self.display.width, self.display.height, 1) color_palette = displayio.Palette(1) color_palette[0] = background_color - bg_sprite = displayio.TileGrid( - color_bitmap, pixel_shader=color_palette, x=0, y=0 - ) + bg_sprite = displayio.TileGrid(color_bitmap, pixel_shader=color_palette, x=0, y=0) background_group.append(bg_sprite) rectangle = Rect( @@ -233,7 +241,7 @@ def _badge_background( background_group.append(rectangle) return background_group - def image_background(self, image_name=None): + def image_background(self, image_name: Optional[str] = None) -> None: """Create a bitmap image background. :param str image_name: The name of the bitmap image as a string including ``.bmp``, e.g. @@ -250,16 +258,15 @@ def image_background(self, image_name=None): """ self._background_image_filename = image_name - # pylint: disable=too-many-arguments def badge_line( self, - text=" ", - color=(0, 0, 0), - scale=1, - font=terminalio.FONT, - left_justify=False, - padding_above=0, - ): + text: str = " ", + color: tuple[int, int, int] = BLACK, + scale: int = 1, + font: Union[BuiltinFont, BDF, PCF] = terminalio.FONT, + left_justify: bool = False, + padding_above: float = 0, + ) -> None: """Add a line of text to the display. Designed to work with ``badge_background`` for a color-block style badge, or with ``image_background`` for a badge with a background image. @@ -268,8 +275,8 @@ def badge_line( :param tuple color: The color of the line of text. Defaults to ``(0, 0, 0)``. :param int scale: The scale of the text. Must be an integer 1 or higher. Defaults to ``1``. :param font: The font used for displaying the text. Defaults to ``terminalio.FONT``. - :param left_justify: Left-justify the line of text. Defaults to ``False`` which centers the - font on the display. + :param bool left_justify: Left-justify the line of text. Defaults to ``False`` which centers + the font on the display. :param int padding_above: Add padding above the displayed line of text. A ``padding_above`` of ``1`` is equivalent to the height of one line of text, ``2`` is equivalent to the height of two lines of text, etc. Defaults @@ -302,9 +309,7 @@ def badge_line( if isinstance(font, str): font = load_font(font, text) - text_label = self._label.Label( - font=font, text=text, max_glyphs=45, color=color, scale=scale - ) + text_label = self._label.Label(font=font, text=text, color=color, scale=scale) self._lines.append(text_label) _, _, width, height = text_label.bounding_box @@ -317,7 +322,7 @@ def badge_line( trim_padding = 0 if font is terminalio.FONT: trim_y = 4 * scale - trim_padding = 4 * padding_above + trim_padding = round(4 * padding_above) if not padding_above: text_label.y = self._y_position + ((height // 2) * scale) - trim_y @@ -328,46 +333,51 @@ def badge_line( self._y_position += height * scale + 4 else: - text_label.y = ( + text_label.y = round( self._y_position + (((height // 2) * scale) - trim_y) + ((height * padding_above) - trim_padding) ) if font is terminalio.FONT: - self._y_position += (height * scale - trim_y) + ( + self._y_position += (height * scale - trim_y) + round( (height * padding_above) - trim_padding ) else: self._y_position += height * scale + 4 - def show_custom_badge(self): + def show_custom_badge(self) -> None: """Call ``pybadger.show_custom_badge()`` to display the custom badge elements. If ``show_custom_badge()`` is not called, the custom badge elements will not be displayed. """ if not self._created_background: self._create_badge_background() - self.display.show(self._background_group) + self.root_group = self._background_group - # pylint: disable=too-many-arguments def _create_label_group( self, - text, - font, - scale, - height_adjustment, - color=0xFFFFFF, - width_adjustment=2, - line_spacing=0.75, - ): + text: str, + font: Union[BuiltinFont, BDF, PCF], + scale: int, + height_adjustment: float, + background_color: Optional[int] = None, + color: int = 0xFFFFFF, + width_adjustment: float = 2, + line_spacing: float = 0.75, + ) -> displayio.Group: """Create a label group with the given text, font, and spacing.""" # If the given font is a string, treat it as a file path and try to load it if isinstance(font, str): font = load_font(font, text) create_label_group = displayio.Group(scale=scale) - create_label = self._label.Label(font, text=text, line_spacing=line_spacing) + create_label = self._label.Label( + font, + text=text, + line_spacing=line_spacing, + background_color=background_color, + ) _, _, width, _ = create_label.bounding_box create_label.x = (self.display.width // (width_adjustment * scale)) - width // 2 create_label.y = int(self.display.height * (height_adjustment / scale)) @@ -375,25 +385,22 @@ def _create_label_group( create_label_group.append(create_label) return create_label_group - def _check_for_movement(self, movement_threshold=10): + def _check_for_movement(self, movement_threshold: int = 10) -> bool: """Checks to see if board is moving. Used to auto-dim display when not moving.""" current_accelerometer = self.acceleration if self._last_accelerometer is None: self._last_accelerometer = current_accelerometer return False acceleration_delta = sum( - [ - abs(self._last_accelerometer[n] - current_accelerometer[n]) - for n in range(3) - ] + abs(self._last_accelerometer[n] - current_accelerometer[n]) for n in range(3) ) self._last_accelerometer = current_accelerometer return acceleration_delta > movement_threshold - def auto_dim_display(self, delay=5.0, movement_threshold=10): + def auto_dim_display(self, delay: float = 5.0, movement_threshold: int = 10): """Auto-dim the display when board is not moving. - :param int delay: Time in seconds before display auto-dims after movement has ceased. + :param float delay: Time in seconds before display auto-dims after movement has ceased. :param int movement_threshold: Threshold required for movement to be considered stopped. Change to increase or decrease sensitivity. @@ -404,58 +411,64 @@ def auto_dim_display(self, delay=5.0, movement_threshold=10): while True: pybadger.auto_dim_display(delay=10) """ - if not self._check_for_movement(movement_threshold=movement_threshold): - current_time = time.monotonic() - if current_time - self._start_time > delay: - self.display.brightness = 0.1 - self._start_time = current_time + if not hasattr(self.display, "brightness"): + return + current_time = time.monotonic() + if self._check_for_movement(movement_threshold=movement_threshold): + self.activity(current_time) + if current_time - self._start_time > delay: + self.display.brightness = 0.1 else: self.display.brightness = self._display_brightness + def activity(self, current_time=None): + """Turn postpone dimming of the screen""" + if not hasattr(self.display, "brightness"): + return + self.display.brightness = self._display_brightness + self._start_time = current_time or time.monotonic() + @property - def pixels(self): + def pixels(self) -> NeoPixel: """Sequence like object representing the NeoPixels on the board.""" return self._neopixels @property - def light(self): + def light(self) -> bool: """Light sensor data.""" return self._light_sensor.value @property - def acceleration(self): + def acceleration(self) -> tuple[int, int, int]: """Accelerometer data, +/- 2G sensitivity.""" - return ( - self._accelerometer.acceleration - if self._accelerometer is not None - else None - ) + return self._accelerometer.acceleration if self._accelerometer is not None else (0, 0, 0) @property - def brightness(self): + def brightness(self) -> float: """Display brightness. Must be a value between ``0`` and ``1``.""" return self.display.brightness @brightness.setter - def brightness(self, value): + def brightness(self, value: float) -> None: self._display_brightness = value self.display.brightness = value - # pylint: disable=too-many-locals def show_business_card( self, *, - image_name=None, - name_string=None, - name_scale=1, - name_font=terminalio.FONT, - email_string_one=None, - email_scale_one=1, - email_font_one=terminalio.FONT, - email_string_two=None, - email_scale_two=1, - email_font_two=terminalio.FONT - ): + image_name: Optional[str] = None, + name_string: Optional[str] = None, + name_scale: int = 1, + name_font: Union[BuiltinFont, BDF, PCF] = terminalio.FONT, + font_color: int = 0xFFFFFF, + font_background_color: Optional[int] = None, + email_string_one: Optional[str] = None, + email_scale_one: int = 1, + email_font_one: Union[BuiltinFont, BDF, PCF] = terminalio.FONT, + email_string_two: Optional[str] = None, + email_scale_two: int = 1, + email_font_two: Union[BuiltinFont, BDF, PCF] = terminalio.FONT, + ) -> None: """Display a bitmap image and a text string, such as a personal image and email address. :param str image_name: REQUIRED. The name of the bitmap image including .bmp, e.g. @@ -464,10 +477,15 @@ def show_business_card( ``"Blinka"``. :param int name_scale: The scale of ``name_string``. Defaults to 1. :param name_font: The font for the name string. Defaults to ``terminalio.FONT``. + :type name_font: ~BuiltinFont|~BDF|~PCF + :param int font_background_color: The color of the font background, default is None + (transparent) + :param int font_color: The font color, default is white :param str email_string_one: A string to display along the bottom of the display, e.g. ``"blinka@adafruit.com"``. :param int email_scale_one: The scale of ``email_string_one``. Defaults to 1. :param email_font_one: The font for the first email string. Defaults to ``terminalio.FONT``. + :type email_font_one: ~BuiltinFont|~BDF|~PCF :param str email_string_two: A second string to display along the bottom of the display. Use if your email address is longer than one line or to add more space between the name and email address, @@ -475,6 +493,7 @@ def show_business_card( :param int email_scale_two: The scale of ``email_string_two``. Defaults to 1. :param email_font_two: The font for the second email string. Defaults to ``terminalio.FONT``. + :type email_font_two: ~BuiltinFont|~BDF|~PCF .. code-block:: python @@ -491,80 +510,80 @@ def show_business_card( name_group = self._create_label_group( text=name_string, font=name_font, + color=font_color, scale=name_scale, height_adjustment=0.73, + background_color=font_background_color, ) business_card_label_groups.append(name_group) if email_string_one: email_one_group = self._create_label_group( text=email_string_one, font=email_font_one, + color=font_color, scale=email_scale_one, height_adjustment=0.84, + background_color=font_background_color, ) business_card_label_groups.append(email_one_group) if email_string_two: email_two_group = self._create_label_group( text=email_string_two, font=email_font_two, + color=font_color, scale=email_scale_two, height_adjustment=0.91, + background_color=font_background_color, ) business_card_label_groups.append(email_two_group) - business_card_splash = displayio.Group(max_size=4) - self.display.show(business_card_splash) - with open(image_name, "rb") as file_name: - on_disk_bitmap = displayio.OnDiskBitmap(file_name) - face_image = displayio.TileGrid( - on_disk_bitmap, pixel_shader=displayio.ColorConverter() - ) - business_card_splash.append(face_image) - for group in business_card_label_groups: - business_card_splash.append(group) - try: - # Refresh display in CircuitPython 5 - self.display.refresh() - except AttributeError: - # Refresh display in CircuitPython 4 - self.display.wait_for_frame() - - # pylint: disable=too-many-locals + business_card_splash = displayio.Group() + image_file = open(image_name, "rb") + on_disk_bitmap = displayio.OnDiskBitmap(image_file) + face_image = displayio.TileGrid(on_disk_bitmap, pixel_shader=on_disk_bitmap.pixel_shader) + business_card_splash.append(face_image) + for group in business_card_label_groups: + business_card_splash.append(group) + self.root_group = business_card_splash + def show_badge( self, *, - background_color=(255, 0, 0), - foreground_color=(255, 255, 255), - background_text_color=(255, 255, 255), - foreground_text_color=(0, 0, 0), - hello_font=terminalio.FONT, - hello_scale=1, - hello_string="HELLO", - my_name_is_font=terminalio.FONT, - my_name_is_scale=1, - my_name_is_string="MY NAME IS", - name_font=terminalio.FONT, - name_scale=1, - name_string="Blinka" - ): + background_color: tuple[int, int, int] = RED, + foreground_color: tuple[int, int, int] = WHITE, + background_text_color: tuple[int, int, int] = WHITE, + foreground_text_color: tuple[int, int, int] = BLACK, + hello_font: Union[BuiltinFont, BDF, PCF] = terminalio.FONT, + hello_scale: int = 1, + hello_string: str = "HELLO", + my_name_is_font: Union[BuiltinFont, BDF, PCF] = terminalio.FONT, + my_name_is_scale: int = 1, + my_name_is_string: str = "MY NAME IS", + name_font: Union[BuiltinFont, BDF, PCF] = terminalio.FONT, + name_scale: int = 1, + name_string: str = "Blinka", + ) -> None: """Create a "Hello My Name is"-style badge. - :param background_color: The color of the background. Defaults to ``(255, 0, 0)``. - :param foreground_color: The color of the foreground rectangle. Defaults to + :param tuple background_color: The color of the background. Defaults to ``(255, 0, 0)``. + :param tuple foreground_color: The color of the foreground rectangle. Defaults to ``(255, 255, 255)``. - :param background_text_color: The color of the "HELLO MY NAME IS" text. Defaults to + :param tuple background_text_color: The color of the "HELLO MY NAME IS" text. Defaults to ``(255, 255, 255)``. - :param foreground_text_color: The color of the name text. Defaults to ``(0, 0, 0)``. + :param tuple foreground_text_color: The color of the name text. Defaults to ``(0, 0, 0)``. :param hello_font: The font for the "HELLO" string. Defaults to ``terminalio.FONT``. - :param hello_scale: The size scale of the "HELLO" string. Defaults to 1. - :param hello_string: The first string of the badge. Defaults to "HELLO". + :type hello_font: ~BuiltinFont|~BDF|~PCF + :param int hello_scale: The size scale of the "HELLO" string. Defaults to 1. + :param str hello_string: The first string of the badge. Defaults to "HELLO". :param my_name_is_font: The font for the "MY NAME IS" string. Defaults to ``terminalio.FONT``. - :param my_name_is_scale: The size scale of the "MY NAME IS" string. Defaults to 1. - :param my_name_is_string: The second string of the badge. Defaults to "MY NAME IS". + :type my_name_is_font: ~BuiltinFont|~BDF|~PCF + :param int my_name_is_scale: The size scale of the "MY NAME IS" string. Defaults to 1. + :param str my_name_is_string: The second string of the badge. Defaults to "MY NAME IS". :param name_font: The font for the name string. Defaults to ``terminalio.FONT``. - :param name_scale: The size scale of the name string. Defaults to 1. - :param name_string: The third string of the badge - change to be your name. Defaults to + :type name_font: ~BuiltinFont|~BDF|~PCF + :param int name_scale: The size scale of the name string. Defaults to 1. + :param str name_string: The third string of the badge - change to be your name. Defaults to "Blinka". .. code-block:: python @@ -609,14 +628,28 @@ def show_badge( group.append(hello_group) group.append(my_name_is_group) group.append(name_group) - self.display.show(group) + self.root_group = group - def show_terminal(self): + @property + def root_group(self): + """The currently showing Group""" + return self.display.root_group + + @root_group.setter + def root_group(self, group): + """Show the given group, refreshing the screen immediately""" + self.activity() + self.display.auto_refresh = False + self.display.root_group = group + self.display.refresh() + self.display.auto_refresh = True + + def show_terminal(self) -> None: """Revert to terminalio screen.""" - self.display.show(None) + self.root_group = displayio.CIRCUITPYTHON_TERMINAL @staticmethod - def bitmap_qr(matrix): + def bitmap_qr(matrix: adafruit_miniqr.QRBitMatrix) -> displayio.Bitmap: """The QR code bitmap.""" border_pixels = 2 bitmap = displayio.Bitmap( @@ -630,10 +663,10 @@ def bitmap_qr(matrix): bitmap[x + border_pixels, y + border_pixels] = 0 return bitmap - def show_qr_code(self, data="https://circuitpython.org"): + def show_qr_code(self, data: str = "https://circuitpython.org") -> None: """Generate a QR code. - :param string data: A string of data for the QR code + :param str data: A string of data for the QR code .. code-block:: python @@ -654,45 +687,38 @@ def show_qr_code(self, data="https://circuitpython.org"): self.display.width // qr_bitmap.width, self.display.height // qr_bitmap.height, ) - qr_position_x = int( - ((self.display.width / qr_code_scale) - qr_bitmap.width) / 2 - ) - qr_position_y = int( - ((self.display.height / qr_code_scale) - qr_bitmap.height) / 2 - ) + qr_position_x = int(((self.display.width / qr_code_scale) - qr_bitmap.width) / 2) + qr_position_y = int(((self.display.height / qr_code_scale) - qr_bitmap.height) / 2) qr_img = displayio.TileGrid( qr_bitmap, pixel_shader=palette, x=qr_position_x, y=qr_position_y ) qr_code = displayio.Group(scale=qr_code_scale) qr_code.append(qr_img) - self.display.show(qr_code) + self.root_group = qr_code @staticmethod - def _sine_sample(length): - tone_volume = (2 ** 15) - 1 - shift = 2 ** 15 + def _sine_sample(length: int) -> Generator[int, None, None]: + 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) -> None: if AUDIO_ENABLED: if self._sample is not None: return self._sine_wave = array.array("H", PyBadgerBase._sine_sample(length)) - # pylint: disable=not-callable - self._sample = self._audio_out( - board.SPEAKER - ) # pylint: disable=not-callable + self._sample = self._audio_out(board.SPEAKER) self._sine_wave_sample = audiocore.RawSample(self._sine_wave) else: print("Required audio modules were missing") - def _enable_speaker(self, enable): + def _enable_speaker(self, enable: bool) -> None: if not hasattr(board, "SPEAKER_ENABLE"): return self._speaker_enable.value = enable - def play_tone(self, frequency, duration): + def play_tone(self, frequency: int, duration: float) -> None: """Produce a tone using the speaker. Try changing frequency to change the pitch of the tone. @@ -705,7 +731,7 @@ def play_tone(self, frequency, duration): time.sleep(duration) self.stop_tone() - def start_tone(self, frequency): + def start_tone(self, frequency: int) -> None: """Produce a tone using the speaker. Try changing frequency to change the pitch of the tone. Use ``stop_tone`` to stop the tone. @@ -722,7 +748,7 @@ def start_tone(self, frequency): if not self._sample.playing: self._sample.play(self._sine_wave_sample, loop=True) - def stop_tone(self): + def stop_tone(self) -> None: """Use with ``start_tone`` to stop the tone produced.""" # Stop playing any tones. if self._sample is not None and self._sample.playing: @@ -731,18 +757,61 @@ def stop_tone(self): self._sample = None self._enable_speaker(enable=False) - def play_file(self, file_name): + def play_file(self, file_name: str) -> None: """Play a .wav file using the onboard speaker. - :param file_name: The name of your .wav file in quotation marks including .wav + :param str file_name: The name of your .wav file in quotation marks including .wav """ # Play a specified file. self.stop_tone() self._enable_speaker(enable=True) - with self._audio_out(board.SPEAKER) as audio: # pylint: disable=not-callable + with self._audio_out(board.SPEAKER) as audio: wavefile = audiocore.WaveFile(open(file_name, "rb")) audio.play(wavefile) while audio.playing: pass self._enable_speaker(enable=True) + + +class KeyStates: + """Convert `keypad.Event` information from the given `keypad` scanner into key-pressed state. + + :param scanner: a `keypad` scanner, such as `keypad.Keys` + """ + + def __init__(self, scanner: Union[Keys, ShiftRegisterKeys]) -> None: + self._scanner = scanner + self._pressed = [False] * self._scanner.key_count + self.update() + + def update(self) -> None: + """Update key information based on pending scanner events.""" + + # If the event queue overflowed, discard any pending events, + # and assume all keys are now released. + if self._scanner.events.overflowed: + self._scanner.events.clear() + self._scanner.reset() + self._pressed = [False] * self._scanner.key_count + + self._was_pressed = self._pressed.copy() + + while True: + event = self._scanner.events.get() + if not event: + # Event queue is now empty. + break + self._pressed[event.key_number] = event.pressed + if event.pressed: + self._was_pressed[event.key_number] = True + + def was_pressed(self, key_number: int) -> bool: + """True if key was down at any time since the last `update()`, + even if it was later released. + """ + return self._was_pressed[key_number] + + def pressed(self, key_number: int) -> bool: + """True if key is currently pressed, as of the last `update()`.""" + return self._pressed[key_number] diff --git a/adafruit_pybadger/pygamer.py b/adafruit_pybadger/pygamer.py old mode 100755 new mode 100644 index d4d1759..c22d2c8 --- a/adafruit_pybadger/pygamer.py +++ b/adafruit_pybadger/pygamer.py @@ -26,16 +26,23 @@ """ from collections import namedtuple -import board + +import adafruit_lis3dh import analogio -import digitalio import audioio +import board +import digitalio +import keypad import neopixel -from gamepadshift import GamePadShift -import adafruit_lis3dh -from adafruit_pybadger.pybadger_base import PyBadgerBase -__version__ = "0.0.0-auto.0" +from adafruit_pybadger.pybadger_base import KeyStates, PyBadgerBase + +try: + from typing import Tuple +except ImportError: + pass + +__version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_PyBadger.git" Buttons = namedtuple("Buttons", "b a start select right down up left") @@ -47,16 +54,14 @@ class PyGamer(PyBadgerBase): _audio_out = audioio.AudioOut _neopixel_count = 5 - def __init__(self): + def __init__(self) -> None: super().__init__() i2c = board.I2C() int1 = digitalio.DigitalInOut(board.ACCELEROMETER_INTERRUPT) try: - self._accelerometer = adafruit_lis3dh.LIS3DH_I2C( - i2c, address=0x19, int1=int1 - ) + self._accelerometer = adafruit_lis3dh.LIS3DH_I2C(i2c, address=0x19, int1=int1) except ValueError: self._accelerometer = adafruit_lis3dh.LIS3DH_I2C(i2c, int1=int1) @@ -65,11 +70,14 @@ def __init__(self): board.NEOPIXEL, self._neopixel_count, brightness=1, pixel_order=neopixel.GRB ) - self._buttons = GamePadShift( - digitalio.DigitalInOut(board.BUTTON_CLOCK), - digitalio.DigitalInOut(board.BUTTON_OUT), - digitalio.DigitalInOut(board.BUTTON_LATCH), + self._keys = keypad.ShiftRegisterKeys( + clock=board.BUTTON_CLOCK, + data=board.BUTTON_OUT, + latch=board.BUTTON_LATCH, + key_count=4, + value_when_pressed=True, ) + self._buttons = KeyStates(self._keys) self._pygamer_joystick_x = analogio.AnalogIn(board.JOYSTICK_X) self._pygamer_joystick_y = analogio.AnalogIn(board.JOYSTICK_Y) @@ -77,7 +85,7 @@ def __init__(self): self._light_sensor = analogio.AnalogIn(board.A7) @property - def button(self): + def button(self) -> Buttons: """The buttons on the board. Example use: @@ -97,13 +105,14 @@ def button(self): print("Button select") """ - button_values = self._buttons.get_pressed() + self._buttons.update() + button_values = tuple(self._buttons.was_pressed(i) for i in range(self._keys.key_count)) x, y = self.joystick return Buttons( - button_values & PyBadgerBase.BUTTON_B, - button_values & PyBadgerBase.BUTTON_A, - button_values & PyBadgerBase.BUTTON_START, - button_values & PyBadgerBase.BUTTON_SELECT, + button_values[0], + button_values[1], + button_values[2], + button_values[3], x > 50000, # RIGHT y > 50000, # DOWN y < 15000, # UP @@ -111,12 +120,12 @@ def button(self): ) @property - def joystick(self): + def joystick(self) -> Tuple[int, int]: """The joystick on the PyGamer.""" x = self._pygamer_joystick_x.value y = self._pygamer_joystick_y.value return x, y -pygamer = PyGamer() # pylint: disable=invalid-name +pygamer = PyGamer() """Object that is automatically created on import.""" diff --git a/adafruit_pybadger/pyportal.py b/adafruit_pybadger/pyportal.py index 556fcbd..38790a0 100644 --- a/adafruit_pybadger/pyportal.py +++ b/adafruit_pybadger/pyportal.py @@ -24,13 +24,15 @@ https://github.com/adafruit/circuitpython/releases """ -import board + import analogio import audioio +import board import neopixel + from adafruit_pybadger.pybadger_base import PyBadgerBase -__version__ = "0.0.0-auto.0" +__version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_PyBadger.git" @@ -40,7 +42,7 @@ class PyPortal(PyBadgerBase): _audio_out = audioio.AudioOut _neopixel_count = 1 - def __init__(self): + def __init__(self) -> None: super().__init__() # NeoPixels @@ -62,5 +64,5 @@ def _unsupported(self): auto_dim_display = _unsupported -pyportal = PyPortal() # pylint: disable=invalid-name +pyportal = PyPortal() """Object that is automatically created on import.""" diff --git a/docs/api.rst b/docs/api.rst index c264f39..8db5080 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -4,14 +4,26 @@ .. 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_pybadger.pybadger_base :members: .. automodule:: adafruit_pybadger.clue :members: +.. automodule:: adafruit_pybadger.magtag + :members: + +.. automodule:: adafruit_pybadger.pewpewm4 + :members: + .. automodule:: adafruit_pybadger.pybadge :members: .. automodule:: adafruit_pybadger.pygamer :members: + +.. automodule:: adafruit_pybadger.pyportal + :members: diff --git a/docs/conf.py b/docs/conf.py index e22c24c..2892cc5 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,13 +1,13 @@ -# -*- coding: utf-8 -*- - # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # # SPDX-License-Identifier: MIT +import datetime import os import sys sys.path.insert(0, os.path.abspath("..")) +sys.path.insert(0, os.path.abspath("mocks")) # -- General configuration ------------------------------------------------ @@ -16,6 +16,7 @@ # ones. extensions = [ "sphinx.ext.autodoc", + "sphinxcontrib.jquery", "sphinx.ext.intersphinx", "sphinx.ext.napoleon", "sphinx.ext.todo", @@ -27,18 +28,13 @@ # autodoc module docs will fail to generate with a warning. autodoc_mock_imports = [ "audioio", + "bitmaptools", "displayio", - "gamepadshift", "neopixel", "analogio", - "adafruit_display_shapes", - "adafruit_display_text", "terminalio", - "adafruit_miniqr", "adafruit_lis3dh", - "adafruit_bitmap_font", "adafruit_lsm6ds", - "gamepad", "audiocore", "audiopwmio", "micropython", @@ -49,8 +45,8 @@ intersphinx_mapping = { - "python": ("https://docs.python.org/3.4", None), - "CircuitPython": ("https://circuitpython.readthedocs.io/en/latest/", None), + "python": ("https://docs.python.org/3", None), + "CircuitPython": ("https://docs.circuitpython.org/en/latest/", None), } # Add any paths that contain templates here, relative to this directory. @@ -63,7 +59,12 @@ # General information about the project. project = "Adafruit PyBadger Library" -copyright = "2019 Kattni Rembor" +creation_year = "2019" +current_year = str(datetime.datetime.now().year) +year_duration = ( + current_year if current_year == creation_year else creation_year + " - " + current_year +) +copyright = year_duration + " Kattni Rembor" author = "Kattni Rembor" # The version info for the project you're documenting, acts as replacement for @@ -80,7 +81,7 @@ # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. -language = None +language = "en" # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. @@ -112,19 +113,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/index.rst b/docs/index.rst index 98b65bb..817fe4a 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -31,8 +31,9 @@ Table of Contents .. toctree:: :caption: Other Links - Download - CircuitPython Reference Documentation + Download from GitHub + Download Library Bundle + CircuitPython Reference Documentation CircuitPython Support Forum Discord Chat Adafruit Learning System diff --git a/docs/mocks/keypad.py b/docs/mocks/keypad.py new file mode 100644 index 0000000..5226b76 --- /dev/null +++ b/docs/mocks/keypad.py @@ -0,0 +1,32 @@ +# SPDX-FileCopyrightText: 2021 Jeff Epler for Adafruit Industries +# +# SPDX-License-Identifier: MIT +class EventQueue: + def __init__(self): + self.overflowed = False + + def get(self): + return None + + +class Keys: + def __init__(self, pins, value_when_pressed, pull): + self.key_count = len(pins) + self.events = EventQueue() + + +class ShiftRegisterKeys: + def __init__( + self, + *, + clock, + data, + latch, + value_to_latch=True, + key_count, + value_when_pressed, + interval=0.020, + max_events=64, + ): + self.key_count = 123 + self.events = EventQueue() diff --git a/docs/requirements.txt b/docs/requirements.txt new file mode 100644 index 0000000..979f568 --- /dev/null +++ b/docs/requirements.txt @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: 2021 Kattni Rembor for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense + +sphinx +sphinxcontrib-jquery +sphinx-rtd-theme diff --git a/examples/QR_Blinka_CircuitPythonOrg.bmp b/examples/QR_Blinka_CircuitPythonOrg.bmp new file mode 100644 index 0000000..84d9e11 Binary files /dev/null and b/examples/QR_Blinka_CircuitPythonOrg.bmp differ diff --git a/examples/QR_Blinka_CircuitPythonOrg.bmp.license b/examples/QR_Blinka_CircuitPythonOrg.bmp.license new file mode 100644 index 0000000..1a8072c --- /dev/null +++ b/examples/QR_Blinka_CircuitPythonOrg.bmp.license @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# +# SPDX-License-Identifier: CC-BY-SA-4.0 diff --git a/examples/pybadger_button_debouncing.py b/examples/pybadger_button_debouncing.py index 9e13756..4617dee 100644 --- a/examples/pybadger_button_debouncing.py +++ b/examples/pybadger_button_debouncing.py @@ -2,6 +2,7 @@ # SPDX-License-Identifier: MIT from adafruit_debouncer import Debouncer + from adafruit_pybadger import pybadger b_btn = Debouncer(lambda: pybadger.button.b == 0) diff --git a/examples/pybadger_clue_custom_badge.py b/examples/pybadger_clue_custom_badge.py index 280555e..db16e69 100644 --- a/examples/pybadger_clue_custom_badge.py +++ b/examples/pybadger_clue_custom_badge.py @@ -2,6 +2,7 @@ # SPDX-License-Identifier: MIT """Custom badge example for Adafruit CLUE.""" + from adafruit_pybadger import pybadger pybadger.badge_background( @@ -11,16 +12,10 @@ rectangle_height=0.6, ) -pybadger.badge_line( - text="@circuitpython", color=pybadger.BLINKA_PURPLE, scale=2, padding_above=2 -) -pybadger.badge_line(text="Blinka", color=pybadger.WHITE, scale=5, padding_above=3) -pybadger.badge_line( - text="CircuitPythonista", color=pybadger.WHITE, scale=2, padding_above=2 -) -pybadger.badge_line( - text="she/her", color=pybadger.BLINKA_PINK, scale=4, padding_above=4 -) +pybadger.badge_line(text="@circuitpython", color=pybadger.BLINKA_PURPLE, scale=2, padding_above=2) +pybadger.badge_line(text="Blinka", color=pybadger.WHITE, scale=5, padding_above=6) +pybadger.badge_line(text="CircuitPythonista", color=pybadger.WHITE, scale=2, padding_above=2) +pybadger.badge_line(text="she/her", color=pybadger.BLINKA_PINK, scale=4, padding_above=7) pybadger.show_custom_badge() diff --git a/examples/pybadger_clue_custom_image_badge.py b/examples/pybadger_clue_custom_image_badge.py index c7bab34..777831d 100644 --- a/examples/pybadger_clue_custom_image_badge.py +++ b/examples/pybadger_clue_custom_image_badge.py @@ -2,15 +2,14 @@ # SPDX-License-Identifier: MIT """Custom image badge example for Adafruit CLUE.""" + from adafruit_pybadger import pybadger pybadger.image_background("Blinka_CLUE.bmp") pybadger.badge_line(text="@circuitpython", color=pybadger.SKY, scale=2, padding_above=2) pybadger.badge_line(text="Blinka", color=pybadger.WHITE, scale=5, padding_above=3) -pybadger.badge_line( - text="CircuitPythonista", color=pybadger.WHITE, scale=2, padding_above=2 -) +pybadger.badge_line(text="CircuitPythonista", color=pybadger.WHITE, scale=2, padding_above=2) pybadger.badge_line(text="she/her", color=pybadger.SKY, scale=4, padding_above=4) while True: diff --git a/examples/pybadger_custom_badge.py b/examples/pybadger_custom_badge.py index 070c191..1ccfed7 100644 --- a/examples/pybadger_custom_badge.py +++ b/examples/pybadger_custom_badge.py @@ -2,6 +2,7 @@ # SPDX-License-Identifier: MIT """Custom badge for PyBadge or PyGamer.""" + from adafruit_pybadger import pybadger pybadger.badge_background( @@ -11,16 +12,10 @@ rectangle_height=0.6, ) -pybadger.badge_line( - text="@circuitpython", color=pybadger.BLINKA_PURPLE, scale=1, padding_above=1 -) +pybadger.badge_line(text="@circuitpython", color=pybadger.BLINKA_PURPLE, scale=1, padding_above=1) pybadger.badge_line(text="Blinka", color=pybadger.WHITE, scale=3, padding_above=2) -pybadger.badge_line( - text="CircuitPythonista", color=pybadger.WHITE, scale=1, padding_above=1 -) -pybadger.badge_line( - text="she/her", color=pybadger.BLINKA_PINK, scale=2, padding_above=2 -) +pybadger.badge_line(text="CircuitPythonista", color=pybadger.WHITE, scale=1, padding_above=1) +pybadger.badge_line(text="she/her", color=pybadger.BLINKA_PINK, scale=2, padding_above=2) while True: pybadger.show_custom_badge() diff --git a/examples/pybadger_magtag_simpletest.py b/examples/pybadger_magtag_simpletest.py index afa0e51..a92db0f 100644 --- a/examples/pybadger_magtag_simpletest.py +++ b/examples/pybadger_magtag_simpletest.py @@ -2,10 +2,13 @@ # SPDX-License-Identifier: MIT """Simpletest example using the Mag Tag. - Use the A, B, and C buttons to change between examples.""" +Use the A, B, and C buttons to change between examples.""" + import time + import board import digitalio + from adafruit_pybadger import pybadger @@ -44,28 +47,21 @@ def try_refresh(): SHOWING = "badge" -pybadger.show_badge( - name_string="Blinka", hello_scale=2, my_name_is_scale=2, name_scale=3 -) +pybadger.show_badge(name_string="Blinka", hello_scale=2, my_name_is_scale=2, name_scale=3) try_refresh() print("after show, going to loop") -neopixel_pwr = digitalio.DigitalInOut(board.NEOPIXEL_POWER) -neopixel_pwr.direction = digitalio.Direction.OUTPUT -neopixel_pwr.value = False pybadger.pixels.fill(0x000022) while True: - cur_a = btn_a.value cur_b = btn_b.value cur_c = btn_c.value if prev_a and not cur_a: pybadger.pixels.fill(0x000000) - neopixel_pwr.value = True if SHOWING != "badge": print("changing to badge") SHOWING = "badge" @@ -76,7 +72,6 @@ def try_refresh(): if prev_b and not cur_b: pybadger.pixels.fill(0x000000) - neopixel_pwr.value = True if SHOWING != "qr": print("changing to qr") SHOWING = "qr" @@ -85,7 +80,6 @@ def try_refresh(): if prev_c and not cur_c: pybadger.pixels.fill(0x000000) - neopixel_pwr.value = True if SHOWING != "card": print("changing to card") SHOWING = "card" diff --git a/examples/pybadger_pewpewm4_simpletest.py b/examples/pybadger_pewpewm4_simpletest.py index 1094d42..0c71069 100644 --- a/examples/pybadger_pewpewm4_simpletest.py +++ b/examples/pybadger_pewpewm4_simpletest.py @@ -2,12 +2,11 @@ # SPDX-License-Identifier: MIT """Simpletest example using the Pew Pew M4. - Use the O, X, and Z buttons to change between examples.""" +Use the O, X, and Z buttons to change between examples.""" + from adafruit_pybadger import pybadger -pybadger.show_badge( - name_string="Blinka", hello_scale=3, my_name_is_scale=3, name_scale=4 -) +pybadger.show_badge(name_string="Blinka", hello_scale=3, my_name_is_scale=3, name_scale=4) while True: if pybadger.button.o: @@ -23,6 +22,4 @@ elif pybadger.button.x: pybadger.show_qr_code(data="https://circuitpython.org") elif pybadger.button.z: - pybadger.show_badge( - name_string="Blinka", hello_scale=3, my_name_is_scale=3, name_scale=4 - ) + pybadger.show_badge(name_string="Blinka", hello_scale=3, my_name_is_scale=3, name_scale=4) diff --git a/examples/pybadger_pygamer_asyncio.py b/examples/pybadger_pygamer_asyncio.py new file mode 100644 index 0000000..c3ac367 --- /dev/null +++ b/examples/pybadger_pygamer_asyncio.py @@ -0,0 +1,86 @@ +# SPDX-FileCopyrightText: 2022 Jeff Epler for Adafruit Industries +# SPDX-License-Identifier: MIT + + +import asyncio + +from displayio import Group, OnDiskBitmap, TileGrid +from rainbowio import colorwheel + +from adafruit_pybadger import pybadger + +# If you choose to enter a pronoun it's shown on the "business card" page +pronoun = "" +custom_line1 = "FIRST" +custom_line2 = "LAST" # also a great place to show a pronoun + +# Set up the custom image +qr_image = OnDiskBitmap(open("/QR_Blinka_CircuitPythonOrg.bmp", "rb")) +qr_tg = TileGrid(qr_image, pixel_shader=qr_image.pixel_shader) +qr_gp = Group() +qr_gp.append(qr_tg) + +pybadger.badge_background( + background_color=pybadger.WHITE, + rectangle_color=pybadger.PURPLE, + rectangle_drop=0.25, + rectangle_height=0.55, +) + +pybadger.badge_line(text="HELLO I'M", color=pybadger.BLINKA_PURPLE, scale=2, padding_above=1) +pybadger.badge_line(text=custom_line1, color=pybadger.WHITE, scale=6, padding_above=1) +pybadger.badge_line(text=custom_line2, color=pybadger.BLINKA_PURPLE, scale=2, padding_above=0.25) + +# Start with the custom badge page +pybadger.show_custom_badge() + + +# This task responds to buttons and changes the visible page +async def ui_task(): + while True: + if pybadger.button.a: + pybadger.show_business_card( + image_name="Blinka.bmp", + name_string="Jeff Epler", + name_scale=2, + email_string_one="jeff@adafruit.com", + email_string_two=pronoun, + ) + elif pybadger.button.b: + pybadger.root_group = qr_gp + elif pybadger.button.start: + pybadger.show_custom_badge() + elif pybadger.button.select: + pybadger.activity() + else: + pybadger.auto_dim_display( + delay=0.5 + ) # Remove or comment out this line if you have the PyBadge LC + await asyncio.sleep(0.02) + + +# This task animates the LEDs +async def led_task(): + pixels = pybadger.pixels + pixels.auto_write = False + num_pixels = len(pixels) + j = 0 + while True: + bright = pybadger.display.brightness > 0.5 + j = (j + (7 if bright else 3)) & 255 + b = 31 / 255.0 if bright else 5 / 255.0 + if pixels.brightness != b: + pixels.brightness = b + for i in range(num_pixels): + rc_index = i * 97 + j + pixels[i] = colorwheel(rc_index & 255) + pixels.show() + await asyncio.sleep(0.02) + + +# Run both tasks via asyncio! +async def main(): + await asyncio.gather(ui_task(), led_task()) + + +asyncio.run(main()) diff --git a/examples/pybadger_pyportal_touchscreen.py b/examples/pybadger_pyportal_touchscreen.py index 10ce9c4..7633b26 100644 --- a/examples/pybadger_pyportal_touchscreen.py +++ b/examples/pybadger_pyportal_touchscreen.py @@ -2,11 +2,11 @@ # SPDX-License-Identifier: MIT """Simpletest example using Adafruit PyPortal. Uses the touchscreen to advance between examples.""" -import board + import adafruit_touchscreen -from adafruit_pybadger import pybadger +import board -# pylint: disable=invalid-name +from adafruit_pybadger import pybadger # These pins are used as both analog and digital! XL, XR and YU must be analog # and digital capable. YD just need to be digital @@ -19,9 +19,7 @@ size=(320, 240), ) -pybadger.show_badge( - name_string="Blinka", hello_scale=2, my_name_is_scale=2, name_scale=3 -) +pybadger.show_badge(name_string="Blinka", hello_scale=2, my_name_is_scale=2, name_scale=3) cur_example = 0 prev_touch = None @@ -45,6 +43,4 @@ elif cur_example == 1: pybadger.show_qr_code(data="https://circuitpython.org") elif cur_example == 2: - pybadger.show_badge( - name_string="Blinka", hello_scale=2, my_name_is_scale=2, name_scale=3 - ) + pybadger.show_badge(name_string="Blinka", hello_scale=2, my_name_is_scale=2, name_scale=3) diff --git a/examples/pybadger_simpletest.py b/examples/pybadger_simpletest.py index a720208..dd3657b 100644 --- a/examples/pybadger_simpletest.py +++ b/examples/pybadger_simpletest.py @@ -3,9 +3,7 @@ from adafruit_pybadger import pybadger -pybadger.show_badge( - name_string="Blinka", hello_scale=2, my_name_is_scale=2, name_scale=3 -) +pybadger.show_badge(name_string="Blinka", hello_scale=2, my_name_is_scale=2, name_scale=3) while True: pybadger.auto_dim_display( @@ -22,6 +20,4 @@ elif pybadger.button.b: pybadger.show_qr_code(data="https://circuitpython.org") elif pybadger.button.start: - pybadger.show_badge( - name_string="Blinka", hello_scale=2, my_name_is_scale=2, name_scale=3 - ) + pybadger.show_badge(name_string="Blinka", hello_scale=2, my_name_is_scale=2, name_scale=3) diff --git a/optional_requirements.txt b/optional_requirements.txt new file mode 100644 index 0000000..d4e27c4 --- /dev/null +++ b/optional_requirements.txt @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022 Alec Delaney, for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..8d4a8b1 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,46 @@ +# SPDX-FileCopyrightText: 2022 Alec Delaney for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +[build-system] +requires = [ + "setuptools", + "wheel", + "setuptools-scm", +] + +[project] +name = "adafruit-circuitpython-pybadger" +description = "Badge-focused CircuitPython helper library for PyBadge, PyBadge LC, PyGamer and CLUE" +version = "0.0.0+auto.0" +readme = "README.rst" +authors = [ + {name = "Adafruit Industries", email = "circuitpython@adafruit.com"} +] +urls = {Homepage = "https://github.com/adafruit/Adafruit_CircuitPython_PyBadger"} +keywords = [ + "adafruit", + "pybadge", + "pygamer", + "clue", + "display", + "hardware", + "micropythoncircuitpython", +] +license = {text = "MIT"} +classifiers = [ + "Intended Audience :: Developers", + "Topic :: Software Development :: Libraries", + "Topic :: Software Development :: Embedded Systems", + "Topic :: System :: Hardware", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", +] +dynamic = ["dependencies", "optional-dependencies"] + +[tool.setuptools] +packages = ["adafruit_pybadger"] + +[tool.setuptools.dynamic] +dependencies = {file = ["requirements.txt"]} +optional-dependencies = {optional = {file = ["optional_requirements.txt"]}} diff --git a/requirements.txt b/requirements.txt index 17a850d..92bd3f5 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,5 +1,13 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-FileCopyrightText: 2022 Alec Delaney, for Adafruit Industries # # SPDX-License-Identifier: Unlicense Adafruit-Blinka +adafruit-circuitpython-bitmap-font +adafruit-circuitpython-lsm6ds +adafruit-circuitpython-display-text +adafruit-circuitpython-miniqr +adafruit-circuitpython-neopixel +adafruit-circuitpython-gizmo +adafruit-circuitpython-lis3dh +adafruit-circuitpython-display-shapes diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 0000000..b485fab --- /dev/null +++ b/ruff.toml @@ -0,0 +1,108 @@ +# 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 + "PLR6301", # could-be-static no-self-use + "PLC0415", # import outside toplevel + "UP007", # x | y type annotation +] + +[format] +line-ending = "lf" diff --git a/setup.py b/setup.py deleted file mode 100644 index e11c6cf..0000000 --- a/setup.py +++ /dev/null @@ -1,57 +0,0 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries -# -# SPDX-License-Identifier: MIT - -"""A setuptools based setup module. - -See: -https://packaging.python.org/en/latest/distributing.html -https://github.com/pypa/sampleproject -""" - -from setuptools import setup, find_packages - -# To use a consistent encoding -from codecs import open -from os import path - -here = path.abspath(path.dirname(__file__)) - -# Get the long description from the README file -with open(path.join(here, "README.rst"), encoding="utf-8") as f: - long_description = f.read() - -setup( - name="adafruit-circuitpython-pybadger", - use_scm_version=True, - setup_requires=["setuptools_scm"], - description="Badge-focused CircuitPython helper library for PyBadge and PyGamer.", - long_description=long_description, - long_description_content_type="text/x-rst", - # The project's main homepage. - url="https://github.com/adafruit/Adafruit_CircuitPython_PyBadger", - # Author details - author="Adafruit Industries", - author_email="circuitpython@adafruit.com", - install_requires=["Adafruit-Blinka"], - # Choose your license - license="MIT", - # See https://pypi.python.org/pypi?%3Aaction=list_classifiers - classifiers=[ - "Development Status :: 3 - Alpha", - "Intended Audience :: Developers", - "Topic :: Software Development :: Libraries", - "Topic :: System :: Hardware", - "License :: OSI Approved :: MIT License", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.4", - "Programming Language :: Python :: 3.5", - ], - # What does your project relate to? - keywords="adafruit blinka circuitpython micropython pybadger pybadge pygamer badge", - # You can just specify the packages manually here if your project is - # simple. Or you can use find_packages(). - # TODO: IF LIBRARY FILES ARE A PACKAGE FOLDER, - # CHANGE `py_modules=['...']` TO `packages=['...']` - packages=["adafruit_pybadger"], -)