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 index 71ef8f8..8de294e 100644 --- a/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md +++ b/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md @@ -4,7 +4,7 @@ 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://circuitpython.readthedocs.io/en/latest/docs/design_guide.html +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 diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index a9516b8..041a337 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -10,71 +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.7 - uses: actions/setup-python@v1 - with: - python-version: 3.7 - - 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: Setup problem matchers - uses: adafruit/circuitpython-action-library-ci-problem-matchers@v1 - - name: Pre-commit hooks - run: | - pre-commit run --all-files - - name: Build assets - run: circuitpython-build-bundles --filename_prefix ${{ steps.repo-name.outputs.repo-name }} --library_location . - - name: Archive bundles - uses: actions/upload-artifact@v2 - with: - name: bundles - path: ${{ github.workspace }}/bundles/ - - name: Check For docs folder - id: need-docs - run: | - echo ::set-output name=docs::$( find . -wholename './docs' ) - - name: Build docs - if: contains(steps.need-docs.outputs.docs, '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/release.yml b/.github/workflows/release.yml deleted file mode 100644 index 89f86fd..0000000 --- a/.github/workflows/release.yml +++ /dev/null @@ -1,99 +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 - # After the dist file is packaged, extract it, update the __version__ - # lines and repackage it. - cd dist - ZIP_FILE=`ls | sed -e "s/\.tar\.gz$//"` - echo "ZIP FILE = ${ZIP_FILE}" - tar xzf "${ZIP_FILE}.tar.gz" - echo The latest release version is \"${{github.event.release.tag_name}}\". - # Don't descend into ./.env, ./.eggs, or ./docs - for file in $(find -not -path "./.*" -not -path "./docs*" -name "*.py"); do - sed -i -e "s/0.0.0-auto.0/${{github.event.release.tag_name}}/" $file; - done; - tar czf "${ZIP_FILE}.tar.gz" "${ZIP_FILE}" - rm -rf "${ZIP_FILE}" - cd .. - 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 2c6ddfd..db3d538 100644 --- a/.gitignore +++ b/.gitignore @@ -1,18 +1,48 @@ -# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written 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 -.python-version -build*/ -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 13d4273..ff19dde 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,40 +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: 20.8b1 + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.5.0 hooks: - - id: black -- repo: https://github.com/fsfe/reuse-tool - rev: v0.12.1 + - 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 -- repo: https://github.com/pycqa/pylint - rev: pylint-2.7.1 - hooks: - - id: pylint - name: pylint (library code) - types: [python] - exclude: "^(docs/|examples/|tests/|setup.py$)" -- repo: local - hooks: - - id: pylint_examples - name: pylint (examples code) - description: Run pylint rules on "examples/*.py" files - entry: /usr/bin/env bash -c - args: ['([[ ! -d "examples" ]] || for example in $(find . -path "./examples/*.py"); do pylint --disable=missing-docstring,invalid-name,consider-using-f-string $example; done)'] - language: system - - id: pylint_tests - name: pylint (tests code) - description: Run pylint rules on "tests/*.py" files - entry: /usr/bin/env bash -c - args: ['([[ ! -d "tests" ]] || for test in $(find . -path "./tests/*.py"); do pylint --disable=missing-docstring,consider-using-f-string $test; done)'] - language: system + - id: reuse diff --git a/.pylintrc b/.pylintrc deleted file mode 100644 index 79bcfb7..0000000 --- a/.pylintrc +++ /dev/null @@ -1,436 +0,0 @@ -# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries -# -# SPDX-License-Identifier: Unlicense - -[MASTER] - -# A comma-separated list of package or module names from where C extensions may -# be loaded. Extensions are loading into the active Python interpreter and may -# run arbitrary code -extension-pkg-whitelist= - -# Add files or directories to the ignore-list. They should be base names, not -# paths. -ignore=CVS - -# Add files or directories matching the regex patterns to the ignore-list. The -# regex matches against base names, not paths. -ignore-patterns= - -# Python code to execute, usually for sys.path manipulation such as -# pygtk.require(). -#init-hook= - -# Use multiple processes to speed up Pylint. -jobs=1 - -# List of plugins (as comma separated values of python modules names) to load, -# usually to register additional checkers. -load-plugins= - -# Pickle collected data for later comparisons. -persistent=yes - -# Specify a configuration file. -#rcfile= - -# Allow loading of arbitrary C extensions. Extensions are imported into the -# active Python interpreter and may run arbitrary code. -unsafe-load-any-extension=no - - -[MESSAGES CONTROL] - -# Only show warnings with the listed confidence levels. Leave empty to show -# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED -confidence= - -# Disable the message, report, category or checker with the given id(s). You -# can either give multiple identifiers separated by comma (,) or put this -# option multiple times (only on the command line, not in the configuration -# file where it should appear only once).You can also use "--disable=all" to -# disable everything first and then reenable specific checks. For example, if -# you want to run only the similarities checker, you can use "--disable=all -# --enable=similarities". If you want to run only the classes checker, but have -# no Warning level messages displayed, use"--disable=all --enable=classes -# --disable=W" -# disable=import-error,print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call -disable=print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call,import-error,bad-continuation,pointless-string-statement - -# Enable the message, report, category or checker with the given id(s). You can -# either give multiple identifier separated by comma (,) or put this option -# multiple time (only on the command line, not in the configuration file where -# it should appear only once). See also the "--disable" option for examples. -enable= - - -[REPORTS] - -# Python expression which should return a note less than 10 (10 is the highest -# note). You have access to the variables errors warning, statement which -# respectively contain the number of errors / warnings messages and the total -# number of statements analyzed. This is used by the global evaluation report -# (RP0004). -evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) - -# Template used to display messages. This is a python new-style format string -# used to format the message information. See doc for all details -#msg-template= - -# Set the output format. Available formats are text, parseable, colorized, json -# and msvs (visual studio).You can also give a reporter class, eg -# mypackage.mymodule.MyReporterClass. -output-format=text - -# Tells whether to display a full report or only the messages -reports=no - -# Activate the evaluation score. -score=yes - - -[REFACTORING] - -# Maximum number of nested blocks for function / method body -max-nested-blocks=5 - - -[LOGGING] - -# Logging modules to check that the string format arguments are in logging -# function parameter format -logging-modules=logging - - -[SPELLING] - -# Spelling dictionary name. Available dictionaries: none. To make it working -# install python-enchant package. -spelling-dict= - -# List of comma separated words that should not be checked. -spelling-ignore-words= - -# A path to a file that contains private dictionary; one word per line. -spelling-private-dict-file= - -# Tells whether to store unknown words to indicated private dictionary in -# --spelling-private-dict-file option instead of raising a message. -spelling-store-unknown-words=no - - -[MISCELLANEOUS] - -# List of note tags to take in consideration, separated by a comma. -# notes=FIXME,XXX,TODO -notes=FIXME,XXX - - -[TYPECHECK] - -# List of decorators that produce context managers, such as -# contextlib.contextmanager. Add to this list to register other decorators that -# produce valid context managers. -contextmanager-decorators=contextlib.contextmanager - -# List of members which are set dynamically and missed by pylint inference -# system, and so shouldn't trigger E1101 when accessed. Python regular -# expressions are accepted. -generated-members= - -# Tells whether missing members accessed in mixin class should be ignored. A -# mixin class is detected if its name ends with "mixin" (case insensitive). -ignore-mixin-members=yes - -# This flag controls whether pylint should warn about no-member and similar -# checks whenever an opaque object is returned when inferring. The inference -# can return multiple potential results while evaluating a Python object, but -# some branches might not be evaluated, which results in partial inference. In -# that case, it might be useful to still emit no-member and other checks for -# the rest of the inferred objects. -ignore-on-opaque-inference=yes - -# List of class names for which member attributes should not be checked (useful -# for classes with dynamically set attributes). This supports the use of -# qualified names. -ignored-classes=optparse.Values,thread._local,_thread._local - -# List of module names for which member attributes should not be checked -# (useful for modules/projects where namespaces are manipulated during runtime -# and thus existing member attributes cannot be deduced by static analysis. It -# supports qualified module names, as well as Unix pattern matching. -ignored-modules=board - -# Show a hint with possible names when a member name was not found. The aspect -# of finding the hint is based on edit distance. -missing-member-hint=yes - -# The minimum edit distance a name should have in order to be considered a -# similar match for a missing member name. -missing-member-hint-distance=1 - -# The total number of similar names that should be taken in consideration when -# showing a hint for a missing member. -missing-member-max-choices=1 - - -[VARIABLES] - -# List of additional names supposed to be defined in builtins. Remember that -# you should avoid to define new builtins when possible. -additional-builtins= - -# Tells whether unused global variables should be treated as a violation. -allow-global-unused-variables=yes - -# List of strings which can identify a callback function by name. A callback -# name must start or end with one of those strings. -callbacks=cb_,_cb - -# A regular expression matching the name of dummy variables (i.e. expectedly -# not used). -dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ - -# Argument names that match this expression will be ignored. Default to name -# with leading underscore -ignored-argument-names=_.*|^ignored_|^unused_ - -# Tells whether we should check for unused import in __init__ files. -init-import=no - -# List of qualified module names which can have objects that can redefine -# builtins. -redefining-builtins-modules=six.moves,future.builtins - - -[FORMAT] - -# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. -# expected-line-ending-format= -expected-line-ending-format=LF - -# Regexp for a line that is allowed to be longer than the limit. -ignore-long-lines=^\s*(# )??$ - -# Number of spaces of indent required inside a hanging or continued line. -indent-after-paren=4 - -# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 -# tab). -indent-string=' ' - -# Maximum number of characters on a single line. -max-line-length=100 - -# Maximum number of lines in a module -max-module-lines=1000 - -# List of optional constructs for which whitespace checking is disabled. `dict- -# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. -# `trailing-comma` allows a space between comma and closing bracket: (a, ). -# `empty-line` allows space-only lines. -no-space-check=trailing-comma,dict-separator - -# Allow the body of a class to be on the same line as the declaration if body -# contains single statement. -single-line-class-stmt=no - -# Allow the body of an if to be on the same line as the test if there is no -# else. -single-line-if-stmt=no - - -[SIMILARITIES] - -# Ignore comments when computing similarities. -ignore-comments=yes - -# Ignore docstrings when computing similarities. -ignore-docstrings=yes - -# Ignore imports when computing similarities. -ignore-imports=yes - -# Minimum lines number of a similarity. -min-similarity-lines=12 - - -[BASIC] - -# Naming hint for argument names -argument-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Regular expression matching correct argument names -argument-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Naming hint for attribute names -attr-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Regular expression matching correct attribute names -attr-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Bad variable names which should always be refused, separated by a comma -bad-names=foo,bar,baz,toto,tutu,tata - -# Naming hint for class attribute names -class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ - -# Regular expression matching correct class attribute names -class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ - -# Naming hint for class names -# class-name-hint=[A-Z_][a-zA-Z0-9]+$ -class-name-hint=[A-Z_][a-zA-Z0-9_]+$ - -# Regular expression matching correct class names -# class-rgx=[A-Z_][a-zA-Z0-9]+$ -class-rgx=[A-Z_][a-zA-Z0-9_]+$ - -# Naming hint for constant names -const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$ - -# Regular expression matching correct constant names -const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ - -# Minimum line length for functions/classes that require docstrings, shorter -# ones are exempt. -docstring-min-length=-1 - -# Naming hint for function names -function-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Regular expression matching correct function names -function-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Good variable names which should always be accepted, separated by a comma -# good-names=i,j,k,ex,Run,_ -good-names=r,g,b,w,i,j,k,n,x,y,z,ex,ok,Run,_ - -# Include a hint for the correct naming format with invalid-name -include-naming-hint=no - -# Naming hint for inline iteration names -inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$ - -# Regular expression matching correct inline iteration names -inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ - -# Naming hint for method names -method-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Regular expression matching correct method names -method-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Naming hint for module names -module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ - -# Regular expression matching correct module names -module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ - -# Colon-delimited sets of names that determine each other's naming style when -# the name regexes allow several styles. -name-group= - -# Regular expression which should only match function or class names that do -# not require a docstring. -no-docstring-rgx=^_ - -# List of decorators that produce properties, such as abc.abstractproperty. Add -# to this list to register other decorators that produce valid properties. -property-classes=abc.abstractproperty - -# Naming hint for variable names -variable-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Regular expression matching correct variable names -variable-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - - -[IMPORTS] - -# Allow wildcard imports from modules that define __all__. -allow-wildcard-with-all=no - -# Analyse import fallback blocks. This can be used to support both Python 2 and -# 3 compatible code, which means that the block might have code that exists -# only in one or another interpreter, leading to false positives when analysed. -analyse-fallback-blocks=no - -# Deprecated modules which should not be used, separated by a comma -deprecated-modules=optparse,tkinter.tix - -# Create a graph of external dependencies in the given file (report RP0402 must -# not be disabled) -ext-import-graph= - -# Create a graph of every (i.e. internal and external) dependencies in the -# given file (report RP0402 must not be disabled) -import-graph= - -# Create a graph of internal dependencies in the given file (report RP0402 must -# not be disabled) -int-import-graph= - -# Force import order to recognize a module as part of the standard -# compatibility libraries. -known-standard-library= - -# Force import order to recognize a module as part of a third party library. -known-third-party=enchant - - -[CLASSES] - -# List of method names used to declare (i.e. assign) instance attributes. -defining-attr-methods=__init__,__new__,setUp - -# List of member names, which should be excluded from the protected access -# warning. -exclude-protected=_asdict,_fields,_replace,_source,_make - -# List of valid names for the first argument in a class method. -valid-classmethod-first-arg=cls - -# List of valid names for the first argument in a metaclass class method. -valid-metaclass-classmethod-first-arg=mcs - - -[DESIGN] - -# Maximum number of arguments for function / method -max-args=5 - -# Maximum number of attributes for a class (see R0902). -# max-attributes=7 -max-attributes=11 - -# Maximum number of boolean expressions in a if statement -max-bool-expr=5 - -# Maximum number of branch for function / method body -max-branches=12 - -# Maximum number of locals for function / method body -max-locals=15 - -# Maximum number of parents for a class (see R0901). -max-parents=7 - -# Maximum number of public methods for a class (see R0904). -max-public-methods=20 - -# Maximum number of return / yield for function / method body -max-returns=6 - -# Maximum number of statements in function / method body -max-statements=50 - -# Minimum number of public methods for a class (see R0903). -min-public-methods=1 - - -[EXCEPTIONS] - -# Exceptions that will emit a warning when being caught. Defaults to -# "Exception" -overgeneral-exceptions=Exception diff --git a/.readthedocs.yaml b/.readthedocs.yaml new file mode 100644 index 0000000..88bca9f --- /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-20.04 + 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 a1e2575..0000000 --- a/.readthedocs.yml +++ /dev/null @@ -1,7 +0,0 @@ -# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries -# -# SPDX-License-Identifier: Unlicense - -python: - version: 3 -requirements_file: requirements.txt diff --git a/README.rst b/README.rst index 7519576..44bf2b1 100644 --- a/README.rst +++ b/README.rst @@ -3,11 +3,11 @@ Introduction .. image:: https://readthedocs.org/projects/adafruit-circuitpython-macropad/badge/?version=latest - :target: https://circuitpython.readthedocs.io/projects/macropad/en/latest/ + :target: https://docs.circuitpython.org/projects/macropad/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 @@ -17,9 +17,9 @@ Introduction :alt: Build Status -.. image:: https://img.shields.io/badge/code%20style-black-000000.svg - :target: https://github.com/psf/black - :alt: Code Style: Black +.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json + :target: https://github.com/astral-sh/ruff + :alt: Code Style: Ruff A helper library for the Adafruit MacroPad RP2040. @@ -48,6 +48,10 @@ This driver depends on: * `Adafruit's CircuitPython Debouncer library `_ +* `Adafruit's CircuitPython Ticks library + `_ + + Please ensure all dependencies are available on the CircuitPython filesystem. This is easily achieved by downloading `the Adafruit library and driver bundle `_ @@ -103,15 +107,16 @@ state of the rotary encoder switch. print("Encoder switch: {}".format(macropad.encoder_switch)) time.sleep(0.4) +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_macropad.py b/adafruit_macropad.py old mode 100755 new mode 100644 index a1b33fa..ef959d0 --- a/adafruit_macropad.py +++ b/adafruit_macropad.py @@ -41,41 +41,134 @@ * Adafruit's CircuitPython Debouncer library: https://github.com/adafruit/Adafruit_CircuitPython_Debouncer +* Adafruit's CircuitPython Ticks library + https://github.com/adafruit/Adafruit_CircuitPython_Ticks + """ import array import math import time + +import adafruit_midi +import audiocore +import audiomp3 +import audiopwmio import board import digitalio -import rotaryio +import displayio import keypad import neopixel -import displayio -import audiopwmio -import audiocore -import audiomp3 +import rotaryio import usb_hid -from adafruit_hid.keyboard import Keyboard -from adafruit_hid.keycode import Keycode -from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS +import usb_midi +from adafruit_debouncer import Debouncer from adafruit_hid.consumer_control import ConsumerControl from adafruit_hid.consumer_control_code import ConsumerControlCode +from adafruit_hid.keyboard import Keyboard +from adafruit_hid.keyboard_layout_base import KeyboardLayoutBase +from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS +from adafruit_hid.keycode import Keycode from adafruit_hid.mouse import Mouse -import usb_midi -import adafruit_midi -from adafruit_midi.note_on import NoteOn +from adafruit_midi.control_change import ControlChange from adafruit_midi.note_off import NoteOff +from adafruit_midi.note_on import NoteOn from adafruit_midi.pitch_bend import PitchBend -from adafruit_midi.control_change import ControlChange from adafruit_midi.program_change import ProgramChange from adafruit_simple_text_display import SimpleTextDisplay -from adafruit_debouncer import Debouncer +try: + # Only used for typing + from typing import Iterator, Optional, Tuple, Union -__version__ = "0.0.0-auto.0" + import adafruit_hid + from keypad import Keys + from neopixel import NeoPixel +except ImportError: + pass + +__version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_MacroPad.git" +ROTATED_KEYMAP_0 = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) +ROTATED_KEYMAP_90 = (2, 5, 8, 11, 1, 4, 7, 10, 0, 3, 6, 9) +ROTATED_KEYMAP_180 = (11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0) +ROTATED_KEYMAP_270 = (9, 6, 3, 0, 10, 7, 4, 1, 11, 8, 5, 2) + +# See https://cdn-shop.adafruit.com/product-files/5228/5223-ds.pdf#page=13 +_DISPLAY_SLEEP_COMMAND = 0xAE +_DISPLAY_WAKE_COMMAND = 0xAF + +keycodes = Keycode +"""Module level Keycode class, to be changed when initing Macropad with a different language""" + + +class _PixelMapLite: + """Generate a pixel map based on a specified order. Designed to work with a set of 12 pixels, + e.g. the MacroPad keypad LEDs. + + :param pixels: The pixel object. + :param tuple order: The specified order of the pixels. Pixels are numbered 0-11. Defaults to + numerical order, ``0`` to ``11``. + """ + + def __init__( + self, + pixels: NeoPixel, + order: Tuple[int, int, int, int, int, int, int, int, int, int, int, int] = ROTATED_KEYMAP_0, + ): + self._pixels = pixels + self._order = order + self._num_pixels = len(pixels) + self.fill = pixels.fill + self.show = pixels.show + self.n = self._num_pixels + + def __setitem__(self, index: int, val: int) -> None: + if isinstance(index, slice): + for val_i, in_i in enumerate(range(*index.indices(self._num_pixels))): + self._pixels[self._order[in_i]] = val[val_i] + else: + self._pixels[self._order[index]] = val + + def __getitem__(self, index: int) -> int: + if isinstance(index, slice): + return [ + self._pixels[self._order[idx]] for idx in range(*index.indices(self._num_pixels)) + ] + if index < 0: + index += self._num_pixels + if index >= self._num_pixels or index < 0: + raise IndexError + return self._pixels[self._order[index]] + + def __repr__(self) -> str: + return self._pixels.__repr__() + + def __len__(self) -> int: + return len(self._pixels) + + @property + def auto_write(self) -> bool: + """ + True if the neopixels should immediately change when set. If False, ``show`` must be + called explicitly. + """ + return self._pixels.auto_write + + @auto_write.setter + def auto_write(self, value: bool) -> None: + self._pixels.auto_write = value + + @property + def brightness(self) -> float: + """Overall brightness of the pixel (0 to 1.0).""" + return self._pixels.brightness + + @brightness.setter + def brightness(self, value: float) -> None: + self._pixels.brightness = value + class MacroPad: """ @@ -95,6 +188,14 @@ class MacroPad: channels. Defaults to 1. :param int midi_out_channel: The MIDI output channel. Defaults to 1. + :param type[KeyboardLayoutBase] layout_class: Class for the keyboard layout, to setup an + international or alternative keyboard. Defaults + to KeyboardLayoutUS from adafruit_hid. + :param type[Keycode] keycode_class: Class used for the keycode names provided by + adafruit_macropad.Keycode. Defaults to the standard Keycode + from adafruit_hid. + + The following shows how to initialise the MacroPad library with the board rotated 90 degrees, and the MIDI channels both set to 1. @@ -105,44 +206,48 @@ class MacroPad: macropad = MacroPad(rotation=90, midi_in_channel=1, midi_out_channel=1) """ - # pylint: disable=invalid-name, too-many-instance-attributes, too-many-public-methods - def __init__(self, rotation=0, midi_in_channel=1, midi_out_channel=1): - if rotation not in (0, 90, 180, 270): - raise ValueError("Only 90 degree rotations are supported.") - - # Define LEDs: - self._pixels = neopixel.NeoPixel(board.NEOPIXEL, 12) - self._led = digitalio.DigitalInOut(board.LED) - self._led.switch_to_output() + Keycode = Keycode + """ + The contents of the Keycode module are available as a property of MacroPad. This includes all + keycode constants available within the Keycode module, which includes all the keys on a + regular PC or Mac keyboard. - # Define key and pixel maps based on rotation: - self._rotated_pixels = None - self._key_pins = None + Remember that keycodes are the names for key _positions_ on a US keyboard, and may not + correspond to the character that you mean to send if you want to emulate non-US keyboard. - def _keys_and_pixels(order=None): - """ - Generate key and pixel maps based on a specified order. - :param order: The order of the keys and pixels. - """ - if not order: - order = list(range(12)) - self._key_pins = [getattr(board, "KEY%d" % (num + 1)) for num in order] - self._rotated_pixels = _PixelMapLite(self._pixels, order=order) + For usage example, see the ``keyboard`` documentation in this library. + """ - if rotation == 0: - _keys_and_pixels() + ConsumerControlCode = ConsumerControlCode + """ + The contents of the ConsumerControlCode module are available as a property of MacroPad. + This includes the available USB HID Consumer Control Device constants. This list is not + exhaustive. - if rotation == 90: - _keys_and_pixels(order=(2, 5, 8, 11, 1, 4, 7, 10, 0, 3, 6, 9)) + For usage example, see the ``consumer_control`` documentation in this library. + """ - if rotation == 180: - _keys_and_pixels(order=(11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)) + Mouse = Mouse + """ + The contents of the Mouse module are available as a property of MacroPad. This includes the + ``LEFT_BUTTON``, ``MIDDLE_BUTTON``, and ``RIGHT_BUTTON`` constants. The rest of the + functionality of the ``Mouse`` module should be used through ``macropad.mouse``. - if rotation == 270: - _keys_and_pixels(order=(9, 6, 3, 0, 10, 7, 4, 1, 11, 8, 5, 2)) + For usage example, see the ``mouse`` documentation in this library. + """ - # Define keys: - self._keys = keypad.Keys(self._key_pins, value_when_pressed=False, pull=True) + def __init__( + self, + rotation: int = 0, + midi_in_channel: int = 1, + midi_out_channel: int = 1, + layout_class: type[KeyboardLayoutBase] = KeyboardLayoutUS, + keycode_class: type[Keycode] = Keycode, + ): + # Define LEDs: + self._pixels = neopixel.NeoPixel(board.NEOPIXEL, 12) + self._led = digitalio.DigitalInOut(board.LED) + self._led.switch_to_output() # Define rotary encoder and encoder switch: self._encoder = rotaryio.IncrementalEncoder(board.ROTA, board.ROTB) @@ -151,8 +256,16 @@ def _keys_and_pixels(order=None): self._debounced_switch = Debouncer(self._encoder_switch) # Define display: - self.display = board.DISPLAY - self.display.rotation = rotation + if not isinstance(board.DISPLAY, type(None)): + self.display = board.DISPLAY + self.display.bus.send(_DISPLAY_WAKE_COMMAND, b"") + self._display_sleep = False + + # Define key and pixel maps based on rotation: + self._rotated_pixels = None + self._key_pins = None + self._keys = None + self.rotate(rotation) # Define audio: self._speaker_enable = digitalio.DigitalInOut(board.SPEAKER_ENABLE) @@ -166,48 +279,108 @@ def _keys_and_pixels(order=None): self._keyboard_layout = None self._consumer_control = None self._mouse = None + self._layout_class = layout_class + self.Keycode = keycode_class + global keycodes + keycodes = keycode_class # Define MIDI: - self._midi = adafruit_midi.MIDI( - midi_in=usb_midi.ports[0], - # MIDI uses channels 1-16. CircuitPython uses 0-15. Ergo -1. - in_channel=midi_in_channel - 1, - midi_out=usb_midi.ports[1], - out_channel=midi_out_channel - 1, - ) + try: + self._midi = adafruit_midi.MIDI( + midi_in=usb_midi.ports[0], + # MIDI uses channels 1-16. CircuitPython uses 0-15. Ergo -1. + in_channel=midi_in_channel - 1, + midi_out=usb_midi.ports[1], + out_channel=midi_out_channel - 1, + ) + except IndexError: + # No MIDI ports available. + self._midi = None - Keycode = Keycode - """ - The contents of the Keycode module are available as a property of MacroPad. This includes all - keycode constants available within the Keycode module, which includes all the keys on a - regular PC or Mac keyboard. + def rotate(self, rotation): + """ + Set the display rotation + + :param int rotation: The rotational position of the MacroPad. Allows for rotating the + MacroPad in 90 degree increments to four different positions and + rotates the keypad layout and display orientation to match. Keypad + layout is always left to right, top to bottom, beginning with key + number 0 in the top left, and ending with key number 11 in the bottom + right. Supports ``0``, ``90``, ``180``, and ``270`` degree rotations. + ``0`` is when the USB port is at the top, ``90`` is when the USB port + is to the left, ``180`` is when the USB port is at the bottom, and + ``270`` is when the USB port is to the right. Defaults to ``0``. + """ + if rotation not in {0, 90, 180, 270}: + raise ValueError("Only 90 degree rotations are supported.") - Remember that keycodes are the names for key _positions_ on a US keyboard, and may not - correspond to the character that you mean to send if you want to emulate non-US keyboard. + self._rotation = rotation - For usage example, see the ``keyboard`` documentation in this library. - """ + def _keys_and_pixels( + order: Tuple[int, int, int, int, int, int, int, int, int, int, int, int], + ) -> None: + """ + Generate key and pixel maps based on a specified order. + :param order: Tuple containing the order of the keys and pixels. + """ + self._key_pins = [getattr(board, "KEY%d" % (num + 1)) for num in order] + self._rotated_pixels = _PixelMapLite(self._pixels, order=order) - ConsumerControlCode = ConsumerControlCode - """ - The contents of the ConsumerControlCode module are available as a property of MacroPad. - This includes the available USB HID Consumer Control Device constants. This list is not - exhaustive. + if rotation == 0: + _keys_and_pixels(order=ROTATED_KEYMAP_0) - For usage example, see the ``consumer_control`` documentation in this library. - """ + if rotation == 90: + _keys_and_pixels(order=ROTATED_KEYMAP_90) - Mouse = Mouse - """ - The contents of the Mouse module are available as a property of MacroPad. This includes the - ``LEFT_BUTTON``, ``MIDDLE_BUTTON``, and ``RIGHT_BUTTON`` constants. The rest of the - functionality of the ``Mouse`` module should be used through ``macropad.mouse``. + if rotation == 180: + _keys_and_pixels(order=ROTATED_KEYMAP_180) - For usage example, see the ``mouse`` documentation in this library. - """ + if rotation == 270: + _keys_and_pixels(order=ROTATED_KEYMAP_270) + + # Define keys: + if self._keys is not None: + self._keys.deinit() + self._keys = keypad.Keys(self._key_pins, value_when_pressed=False, pull=True) + + self.display.rotation = rotation + + @property + def rotation(self) -> int: + """ + The current rotation + """ + return self._rotation + + @rotation.setter + def rotation(self, new_rotation) -> None: + self.rotate(new_rotation) + + @property + def display_sleep(self) -> bool: + """The power saver mode of the display. Set it to put the display to + sleep or wake it up again. + + If the display is put to sleep, it stops the OLED drive and greatly + reduces its power usage. The display mode and current content of the + display are still kept in the memory of the displays microprocessor and + can be updated nevertheless. + """ + return self._display_sleep + + @display_sleep.setter + def display_sleep(self, sleep: bool) -> None: + if self._display_sleep == sleep: + return + if sleep: + command = _DISPLAY_SLEEP_COMMAND + else: + command = _DISPLAY_WAKE_COMMAND + self.display.bus.send(command, b"") + self._display_sleep = sleep @property - def pixels(self): + def pixels(self) -> Optional[_PixelMapLite]: """Sequence-like object representing the twelve NeoPixel LEDs in a 3 x 4 grid on the MacroPad. Each pixel is at a certain index in the sequence, numbered 0-11. Colors can be an RGB tuple like (255, 0, 0) where (R, G, B), or an RGB hex value like 0xFF0000 for red where @@ -245,7 +418,7 @@ def pixels(self): return self._rotated_pixels @property - def red_led(self): + def red_led(self) -> bool: """The red led next to the USB port. The following example blinks the red LED every 0.5 seconds. @@ -266,11 +439,11 @@ def red_led(self): return self._led.value @red_led.setter - def red_led(self, value): + def red_led(self, value: bool) -> None: self._led.value = value @property - def keys(self): + def keys(self) -> Keys: """ The keys on the MacroPad. Uses events to track key number and state, e.g. pressed or released. You must fetch the events using ``keys.events.get()`` and then the events are @@ -279,9 +452,9 @@ def keys(self): * ``key_number``: the number of the key that changed. Keys are numbered starting at 0. * ``pressed``: ``True`` if the event is a transition from released to pressed. * ``released``: ``True`` if the event is a transition from pressed to released. - ``released`` is always the opposite of ``pressed``; it's provided - for convenience and clarity, in case you want to test for - key-release events explicitly. + + ``released`` is always the opposite of ``pressed``; it's provided for convenience + and clarity, in case you want to test for key-release events explicitly. The following example prints the key press and release events to the serial console. @@ -299,7 +472,7 @@ def keys(self): return self._keys @property - def encoder(self): + def encoder(self) -> int: """ The rotary encoder relative rotation position. Always begins at 0 when the code is run, so the value returned is relative to the initial location. @@ -318,7 +491,7 @@ def encoder(self): return self._encoder.position * -1 @property - def encoder_switch(self): + def encoder_switch(self) -> bool: """ The rotary encoder switch. Returns ``True`` when pressed. @@ -336,7 +509,7 @@ def encoder_switch(self): return not self._encoder_switch.value @property - def encoder_switch_debounced(self): + def encoder_switch_debounced(self) -> Debouncer: """ The rotary encoder switch debounced. Allows for ``encoder_switch_debounced.pressed`` and ``encoder_switch_debounced.released``. Requires you to include @@ -363,7 +536,7 @@ def encoder_switch_debounced(self): return self._debounced_switch @property - def keyboard(self): + def keyboard(self) -> adafruit_hid.keyboard.Keyboard: """ A keyboard object used to send HID reports. For details, see the ``Keyboard`` documentation in CircuitPython HID: https://circuitpython.readthedocs.io/projects/hid/en/latest/index.html @@ -385,7 +558,7 @@ def keyboard(self): return self._keyboard @property - def keyboard_layout(self): + def keyboard_layout(self) -> adafruit_hid.keyboard_layout_base.KeyboardLayoutBase: """ Map ASCII characters to the appropriate key presses on a standard US PC keyboard. Non-ASCII characters and most control characters will raise an exception. Required to send @@ -406,11 +579,11 @@ def keyboard_layout(self): """ if self._keyboard_layout is None: # This will need to be updated if we add more layouts. Currently there is only US. - self._keyboard_layout = KeyboardLayoutUS(self.keyboard) + self._keyboard_layout = self._layout_class(self.keyboard) return self._keyboard_layout @property - def consumer_control(self): + def consumer_control(self) -> adafruit_hid.consumer_control.ConsumerControl: """ Send ConsumerControl code reports, used by multimedia keyboards, remote controls, etc. @@ -431,7 +604,7 @@ def consumer_control(self): return self._consumer_control @property - def mouse(self): + def mouse(self) -> adafruit_hid.mouse.Mouse: """ Send USB HID mouse reports. @@ -453,7 +626,7 @@ def mouse(self): return self._mouse @property - def midi(self): + def midi(self) -> adafruit_midi.MIDI: """ The MIDI object. Used to send and receive MIDI messages. For more details, see the ``adafruit_midi`` documentation in CircuitPython MIDI: @@ -491,7 +664,9 @@ def midi(self): return self._midi @staticmethod - def NoteOn(note, velocity=127, *, channel=None): + def NoteOn( + note: Union[int, str], velocity: int = 127, *, channel: Optional[int] = None + ) -> NoteOn: """ Note On Change MIDI message. For more details, see the ``adafruit_midi.note_on`` documentation in CircuitPython MIDI: @@ -541,7 +716,9 @@ def NoteOn(note, velocity=127, *, channel=None): return NoteOn(note=note, velocity=velocity, channel=channel) @staticmethod - def NoteOff(note, velocity=127, *, channel=None): + def NoteOff( + note: Union[int, str], velocity: int = 127, *, channel: Optional[int] = None + ) -> NoteOff: """ Note Off Change MIDI message. For more details, see the ``adafruit_midi.note_off`` documentation in CircuitPython MIDI: @@ -571,7 +748,7 @@ def NoteOff(note, velocity=127, *, channel=None): return NoteOff(note=note, velocity=velocity, channel=channel) @staticmethod - def PitchBend(pitch_bend, *, channel=None): + def PitchBend(pitch_bend: int, *, channel: Optional[int] = None) -> PitchBend: """ Pitch Bend Change MIDI message. For more details, see the ``adafruit_midi.pitch_bend`` documentation in CircuitPython MIDI: @@ -612,7 +789,7 @@ def PitchBend(pitch_bend, *, channel=None): return PitchBend(pitch_bend=pitch_bend, channel=channel) @staticmethod - def ControlChange(control, value, *, channel=None): + def ControlChange(control: int, value: int, *, channel: Optional[int] = None) -> ControlChange: """ Control Change MIDI message. For more details, see the ``adafruit_midi.control_change`` documentation in CircuitPython MIDI: @@ -655,7 +832,7 @@ def ControlChange(control, value, *, channel=None): return ControlChange(control=control, value=value, channel=channel) @staticmethod - def ProgramChange(patch, *, channel=None): + def ProgramChange(patch: int, *, channel: Optional[int] = None) -> ProgramChange: """ Program Change MIDI message. For more details, see the ``adafruit_midi.program_change`` documentation in CircuitPython MIDI: @@ -683,7 +860,11 @@ def ProgramChange(patch, *, channel=None): """ return ProgramChange(patch=patch, channel=channel) - def display_image(self, file_name=None, position=None): + def display_image( + self, + file_name: Optional[str] = None, + position: Optional[Tuple[int, int]] = None, + ) -> None: """ Display an image on the built-in display. @@ -710,7 +891,7 @@ def display_image(self, file_name=None, position=None): if not position: position = (0, 0) group = displayio.Group(scale=1) - self.display.show(group) + self.display.root_group = group with open(file_name, "rb") as image_file: background = displayio.OnDiskBitmap(image_file) sprite = displayio.TileGrid( @@ -724,8 +905,12 @@ def display_image(self, file_name=None, position=None): @staticmethod def display_text( - title=None, title_scale=1, title_length=80, text_scale=1, font=None - ): + title: Optional[str] = None, + title_scale: int = 1, + title_length: int = 80, + text_scale: int = 1, + font: Optional[str] = None, + ) -> SimpleTextDisplay: """ Display lines of text on the built-in display. Note that if you instantiate this without a title, it will display the first (``[0]``) line of text at the top of the display - use @@ -740,9 +925,9 @@ def display_text( Defaults to 80. :param int text_scale: Scale the size of the data lines. Scales the title as well. Defaults to 1. - :param font: The font or the path to the custom font file to use to display the text. - Defaults to the built-in ``terminalio.FONT``. Custom font files must be - provided as a string, e.g. ``"/Arial12.bdf"``. + :param ~FontProtocol|None font: The custom font to use to display the text. Defaults to the + built-in ``terminalio.FONT``. For more details, see: + https://docs.circuitpython.org/en/latest/shared-bindings/fontio/index.html The following example displays a title and lines of text indicating which key is pressed, the relative position of the rotary encoder, and whether the encoder switch is pressed. @@ -750,11 +935,14 @@ def display_text( .. code-block:: python + from adafruit_bitmap_font import bitmap_font from adafruit_macropad import MacroPad + from displayio import Bitmap macropad = MacroPad() - text_lines = macropad.display_text(title="MacroPad Info") + custom_font = bitmap_font.load_font("/Arial12.bdf", Bitmap) + text_lines = macropad.display_text(title="MacroPad Info", font=custom_font) while True: key_event = macropad.keys.events.get() @@ -776,20 +964,20 @@ def display_text( ) @staticmethod - def _sine_sample(length): - tone_volume = (2 ** 15) - 1 - shift = 2 ** 15 + def _sine_sample(length: int) -> Iterator[int]: + tone_volume = (2**15) - 1 + shift = 2**15 for i in range(length): yield int(tone_volume * math.sin(2 * math.pi * (i / length)) + shift) - def _generate_sample(self, length=100): + def _generate_sample(self, length: int = 100) -> None: if self._sample is not None: return self._sine_wave = array.array("H", self._sine_sample(length)) self._sample = audiopwmio.PWMAudioOut(board.SPEAKER) self._sine_wave_sample = audiocore.RawSample(self._sine_wave) - def play_tone(self, frequency, duration): + def play_tone(self, frequency: int, duration: float) -> None: """Produce a tone using the speaker at a specified hz for a specified duration in seconds. :param int frequency: The frequency of the tone in Hz @@ -812,7 +1000,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. Will continue playing until ``stop_tone`` is called. :param int frequency: The frequency of the tone in Hz @@ -841,7 +1029,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. See usage example in ``start_tone`` documentation.""" # Stop playing any tones. @@ -851,7 +1039,7 @@ def stop_tone(self): self._sample = None self._speaker_enable.value = False - def play_file(self, file_name): + def play_file(self, file_name: str) -> None: """Play a .wav or .mp3 file using the onboard speaker. :param file_name: The name of your .wav or .mp3 file in quotation marks including @@ -885,85 +1073,21 @@ def play_file(self, file_name): self.stop_tone() self._speaker_enable.value = True if file_name.lower().endswith(".wav"): - with audiopwmio.PWMAudioOut( - board.SPEAKER - ) as audio: # pylint: disable=not-callable - wavefile = audiocore.WaveFile(open(file_name, "rb")) + with audiopwmio.PWMAudioOut(board.SPEAKER) as audio, open( + file_name, "rb" + ) as audio_file: + wavefile = audiocore.WaveFile(audio_file) audio.play(wavefile) while audio.playing: pass elif file_name.lower().endswith(".mp3"): - with audiopwmio.PWMAudioOut( - board.SPEAKER - ) as audio: # pylint: disable=not-callable - mp3file = audiomp3.MP3Decoder(open(file_name, "rb")) + with audiopwmio.PWMAudioOut(board.SPEAKER) as audio, open( + file_name, "rb" + ) as audio_file: + mp3file = audiomp3.MP3Decoder(audio_file) audio.play(mp3file) while audio.playing: pass else: raise ValueError("Filetype must be wav or MP3.") self._speaker_enable.value = False - - -class _PixelMapLite: - """Generate a pixel map based on a specified order. Designed to work with a set of 12 pixels, - e.g. the MacroPad keypad LEDs. - - :param pixels: The pixel object. - :param tuple order: The specified order of the pixels. Pixels are numbered 0-11. Defaults to - numerical order, ``0`` to ``11``. - """ - - def __init__(self, pixels, order=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)): - self._pixels = pixels - self._order = order - self._num_pixels = len(pixels) - self.fill = pixels.fill - self.show = pixels.show - self.n = self._num_pixels - - def __setitem__(self, index, val): - if isinstance(index, slice): - for val_i, in_i in enumerate(range(*index.indices(self._num_pixels))): - self._pixels[self._order[in_i]] = val[val_i] - else: - self._pixels[self._order[index]] = val - - def __getitem__(self, index): - if isinstance(index, slice): - return [ - self._pixels[self._order[idx]] - for idx in range(*index.indices(self._num_pixels)) - ] - if index < 0: - index += self._num_pixels - if index >= self._num_pixels or index < 0: - raise IndexError - return self._pixels[self._order[index]] - - def __repr__(self): - return self._pixels.__repr__() - - def __len__(self): - return len(self._pixels) - - @property - def auto_write(self): - """ - True if the neopixels should immediately change when set. If False, ``show`` must be - called explicitly. - """ - return self._pixels.auto_write - - @auto_write.setter - def auto_write(self, value): - self._pixels.auto_write = value - - @property - def brightness(self): - """Overall brightness of the pixel (0 to 1.0).""" - return self._pixels.brightness - - @brightness.setter - def brightness(self, value): - self._pixels.brightness = value diff --git a/docs/api.rst b/docs/api.rst index 532b8c1..f1cf45b 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -4,11 +4,17 @@ .. 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_macropad :members: .. autoattribute:: MacroPad.Keycode + :noindex: .. autoattribute:: MacroPad.ConsumerControlCode + :noindex: .. autoattribute:: MacroPad.Mouse + :noindex: diff --git a/docs/conf.py b/docs/conf.py index e3d5574..89e71f8 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,9 +1,8 @@ -# -*- coding: utf-8 -*- - # SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries # # SPDX-License-Identifier: MIT +import datetime import os import sys @@ -16,6 +15,7 @@ # ones. extensions = [ "sphinx.ext.autodoc", + "sphinxcontrib.jquery", "sphinx.ext.intersphinx", "sphinx.ext.napoleon", "sphinx.ext.todo", @@ -45,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), } # Show the docstring from both the class and its __init__() method. @@ -62,7 +62,12 @@ # General information about the project. project = "Adafruit CircuitPython MacroPad Library" -copyright = "2021 Kattni Rembor" +creation_year = "2021" +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 @@ -79,7 +84,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. @@ -117,19 +122,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 7145b7e..f6fd1a9 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -34,8 +34,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/requirements.txt b/docs/requirements.txt new file mode 100644 index 0000000..e6ff49f --- /dev/null +++ b/docs/requirements.txt @@ -0,0 +1,8 @@ +# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries +# SPDX-FileCopyrightText: Copyright (c) 2021 Alec Delaney +# +# SPDX-License-Identifier: MIT + +sphinx +sphinxcontrib-jquery +sphinx-rtd-theme diff --git a/examples/macropad_display_image/macropad_display_image.py b/examples/macropad_display_image/macropad_display_image.py index d3fb46a..f189042 100644 --- a/examples/macropad_display_image/macropad_display_image.py +++ b/examples/macropad_display_image/macropad_display_image.py @@ -4,6 +4,7 @@ """ MacroPad display image demo. Displays a bitmap image on the built-in display. """ + from adafruit_macropad import MacroPad macropad = MacroPad() diff --git a/examples/macropad_grid_layout.py b/examples/macropad_grid_layout.py index 6f8f917..16d5d85 100644 --- a/examples/macropad_grid_layout.py +++ b/examples/macropad_grid_layout.py @@ -5,16 +5,18 @@ Grid layout demo for MacroPad. Displays the key pressed in a grid matching the key layout on the built-in display. """ + import displayio import terminalio from adafruit_display_text import bitmap_label as label from adafruit_displayio_layout.layouts.grid_layout import GridLayout + from adafruit_macropad import MacroPad macropad = MacroPad() main_group = displayio.Group() -macropad.display.show(main_group) +macropad.display.root_group = main_group title = label.Label( y=4, font=terminalio.FONT, @@ -39,6 +41,6 @@ key_event = macropad.keys.events.get() if key_event: if key_event.pressed: - labels[key_event.key_number].text = "KEY{}".format(key_event.key_number) + labels[key_event.key_number].text = f"KEY{key_event.key_number}" else: labels[key_event.key_number].text = "" diff --git a/examples/macropad_keyboard_layout.py b/examples/macropad_keyboard_layout.py new file mode 100644 index 0000000..c53b528 --- /dev/null +++ b/examples/macropad_keyboard_layout.py @@ -0,0 +1,47 @@ +# SPDX-FileCopyrightText: Copyright (c) 2021 Kattni Rembor for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense +""" +International layout demo for MacroPad. +""" + +import time + +from keyboard_layout_win_fr import KeyboardLayout +from keycode_win_fr import Keycode + +from adafruit_macropad import MacroPad + +macropad = MacroPad( + layout_class=KeyboardLayout, + keycode_class=Keycode, +) + +keycodes = [ + "https://adafruit.com/", + "https://adafru.it/discord", + "https://circuitpython.org", + Keycode.A, + Keycode.D, + Keycode.A, + Keycode.F, + Keycode.R, + Keycode.U, + Keycode.I, + Keycode.T, + Keycode.PERIOD, + # Keycode.C, Keycode.O, Keycode.M, +] + +while True: + key_event = macropad.keys.events.get() + if key_event: + keycode = keycodes[key_event.key_number] + if key_event.pressed: + if isinstance(keycode, int): + macropad.keyboard.press(keycode) + else: + macropad.keyboard_layout.write(keycode) + elif isinstance(keycode, int): + macropad.keyboard.release(keycode) + time.sleep(0.05) diff --git a/examples/macropad_keyboard_mouse.py b/examples/macropad_keyboard_mouse.py index 4900acf..ad76579 100755 --- a/examples/macropad_keyboard_mouse.py +++ b/examples/macropad_keyboard_mouse.py @@ -8,6 +8,7 @@ pressed. Finally, it moves the mouse left and right when the rotary encoder is rotated counterclockwise and clockwise respectively. """ + from adafruit_macropad import MacroPad macropad = MacroPad() @@ -26,9 +27,7 @@ if key_event.key_number == 2: macropad.keyboard_layout.write("Hello, World!") if key_event.key_number == 3: - macropad.consumer_control.send( - macropad.ConsumerControlCode.VOLUME_DECREMENT - ) + macropad.consumer_control.send(macropad.ConsumerControlCode.VOLUME_DECREMENT) macropad.encoder_switch_debounced.update() diff --git a/examples/macropad_led_animation_example.py b/examples/macropad_led_animation_example.py index bc0c5be..fe7e539 100644 --- a/examples/macropad_led_animation_example.py +++ b/examples/macropad_led_animation_example.py @@ -5,8 +5,10 @@ This simpletest example displays the Blink animation on the MacroPad neopixels """ + from adafruit_led_animation.animation.blink import Blink from adafruit_led_animation.color import BLUE + from adafruit_macropad import MacroPad macropad = MacroPad() diff --git a/examples/macropad_mp3/macropad_mp3.py b/examples/macropad_mp3/macropad_mp3.py index d85ccb6..494d9cc 100644 --- a/examples/macropad_mp3/macropad_mp3.py +++ b/examples/macropad_mp3/macropad_mp3.py @@ -6,7 +6,9 @@ is pressed. All keys light up a color of the rainbow when pressed, but no audio is played for the rest of the keys. """ + from rainbowio import colorwheel + from adafruit_macropad import MacroPad macropad = MacroPad() @@ -20,9 +22,7 @@ if key_event: if key_event.pressed: - macropad.pixels[key_event.key_number] = colorwheel( - int(255 / 12) * key_event.key_number - ) + macropad.pixels[key_event.key_number] = colorwheel(int(255 / 12) * key_event.key_number) if key_event.key_number < len(audio_files): macropad.play_file(audio_files[key_event.key_number]) diff --git a/examples/macropad_rainbow_keys.py b/examples/macropad_rainbow_keys.py index e3e2a1b..459611e 100644 --- a/examples/macropad_rainbow_keys.py +++ b/examples/macropad_rainbow_keys.py @@ -6,17 +6,19 @@ layout on the built-in display, and animates a rainbow the first time you press a key and turns it off on the next press. """ + import displayio import terminalio -from rainbowio import colorwheel from adafruit_display_text import bitmap_label as label from adafruit_displayio_layout.layouts.grid_layout import GridLayout +from rainbowio import colorwheel + from adafruit_macropad import MacroPad macropad = MacroPad() main_group = displayio.Group() -macropad.display.show(main_group) +macropad.display.root_group = main_group title = label.Label( y=4, font=terminalio.FONT, @@ -43,7 +45,7 @@ key_event = macropad.keys.events.get() if key_event: if key_event.pressed: - labels[key_event.key_number].text = "KEY{}".format(key_event.key_number) + labels[key_event.key_number].text = f"KEY{key_event.key_number}" # Turn the LED on with the first press, and off with the second press. lit_keys[key_event.key_number] = not lit_keys[key_event.key_number] else: diff --git a/examples/macropad_rotation.py b/examples/macropad_rotation.py index 136c677..744b3d9 100644 --- a/examples/macropad_rotation.py +++ b/examples/macropad_rotation.py @@ -6,7 +6,9 @@ Lights up the associated pixel when the key is pressed. Displays the key number pressed and the rotary encoder relative position on the display. """ + from rainbowio import colorwheel + from adafruit_macropad import MacroPad macropad = MacroPad(rotation=90) @@ -17,11 +19,9 @@ key_event = macropad.keys.events.get() if key_event: if key_event.pressed: - text_lines[1].text = "Key {}!".format(key_event.key_number) - macropad.pixels[key_event.key_number] = colorwheel( - int(255 / 12) * key_event.key_number - ) + text_lines[1].text = f"Key {key_event.key_number}!" + macropad.pixels[key_event.key_number] = colorwheel(int(255 / 12) * key_event.key_number) else: macropad.pixels.fill((0, 0, 0)) - text_lines[2].text = "Encoder {}".format(macropad.encoder) + text_lines[2].text = f"Encoder {macropad.encoder}" text_lines.show() diff --git a/examples/macropad_simpletest.py b/examples/macropad_simpletest.py index 64441bc..609b925 100644 --- a/examples/macropad_simpletest.py +++ b/examples/macropad_simpletest.py @@ -5,7 +5,9 @@ Simpletest demo for MacroPad. Prints the key pressed, the relative position of the rotary encoder, and the state of the rotary encoder switch to the serial console. """ + import time + from adafruit_macropad import MacroPad macropad = MacroPad() @@ -13,7 +15,7 @@ while True: key_event = macropad.keys.events.get() if key_event and key_event.pressed: - print("Key pressed: {}".format(key_event.key_number)) - print("Encoder: {}".format(macropad.encoder)) - print("Encoder switch: {}".format(macropad.encoder_switch)) + print(f"Key pressed: {key_event.key_number}") + print(f"Encoder: {macropad.encoder}") + print(f"Encoder switch: {macropad.encoder_switch}") time.sleep(0.4) diff --git a/examples/macropad_simpletest_display.py b/examples/macropad_simpletest_display.py index 65cd83a..faea058 100644 --- a/examples/macropad_simpletest_display.py +++ b/examples/macropad_simpletest_display.py @@ -6,6 +6,7 @@ encoder, and the state of the rotary encoder switch to the built-in display. Note that the key pressed line does not appear until a key is pressed. """ + from adafruit_macropad import MacroPad macropad = MacroPad() @@ -15,7 +16,7 @@ while True: key_event = macropad.keys.events.get() if key_event and key_event.pressed: - text_lines[0].text = "Key {} pressed!".format(key_event.key_number) - text_lines[1].text = "Rotary encoder {}".format(macropad.encoder) - text_lines[2].text = "Encoder switch: {}".format(macropad.encoder_switch) + text_lines[0].text = f"Key {key_event.key_number} pressed!" + text_lines[1].text = f"Rotary encoder {macropad.encoder}" + text_lines[2].text = f"Encoder switch: {macropad.encoder_switch}" text_lines.show() diff --git a/examples/macropad_tone_keypad.py b/examples/macropad_tone_keypad.py index 2c25205..d8046da 100644 --- a/examples/macropad_tone_keypad.py +++ b/examples/macropad_tone_keypad.py @@ -5,7 +5,9 @@ MacroPad tone demo. Plays a different tone for each key pressed and lights up each key a different color while the key is pressed. """ + from rainbowio import colorwheel + from adafruit_macropad import MacroPad macropad = MacroPad() @@ -17,9 +19,7 @@ if key_event: if key_event.pressed: - macropad.pixels[key_event.key_number] = colorwheel( - int(255 / 12) * key_event.key_number - ) + macropad.pixels[key_event.key_number] = colorwheel(int(255 / 12) * key_event.key_number) macropad.start_tone(tones[key_event.key_number]) else: diff --git a/examples/macropad_tone_keypad_extended.py b/examples/macropad_tone_keypad_extended.py index 21d095f..68c0c3a 100755 --- a/examples/macropad_tone_keypad_extended.py +++ b/examples/macropad_tone_keypad_extended.py @@ -9,6 +9,7 @@ """ from rainbowio import colorwheel + from adafruit_macropad import MacroPad macropad = MacroPad() @@ -28,6 +29,7 @@ # be the index of the currently playing note. playing_index = None + # Helper to convert an integer to an rgb value. def rgb_from_int(rgb): blue = rgb & 255 @@ -78,11 +80,9 @@ def rgb_from_int(rgb): playing_index = top_index # There are no keys pressed. - else: - # If a tone was playing, stop it. - if playing_index is not None: - macropad.stop_tone() - playing_index = None + elif playing_index is not None: + macropad.stop_tone() + playing_index = None # If a key was pressed or released, update the pixels for the pressed keys. if update_pixels: 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 index f3c35ae..40b4006 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,47 @@ -# SPDX-FileCopyrightText: 2020 Diego Elio Pettenò +# SPDX-FileCopyrightText: 2022 Alec Delaney for Adafruit Industries # -# SPDX-License-Identifier: Unlicense +# SPDX-License-Identifier: MIT -[tool.black] -target-version = ['py35'] +[build-system] +requires = [ + "setuptools", + "wheel", + "setuptools-scm", +] + +[project] +name = "adafruit-circuitpython-macropad" +description = "A helper library for the Adafruit MacroPad RP2040" +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_MacroPad"} +keywords = [ + "adafruit", + "macropad", + "rp2040", + "mechanical", + "keyboard", + "breakout", + "hardwaremicropython", + "circuitpython", +] +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] +py-modules = ["adafruit_macropad"] + +[tool.setuptools.dynamic] +dependencies = {file = ["requirements.txt"]} +optional-dependencies = {optional = {file = ["optional_requirements.txt"]}} diff --git a/requirements.txt b/requirements.txt index f5d71b5..a153564 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,12 +1,11 @@ -# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries -# SPDX-FileCopyrightText: Copyright (c) 2021 Kattni Rembor for Adafruit Industries +# SPDX-FileCopyrightText: 2022 Alec Delaney, for Adafruit Industries # -# SPDX-License-Identifier: MIT +# SPDX-License-Identifier: Unlicense Adafruit-Blinka adafruit-circuitpython-hid adafruit-circuitpython-midi -adafruit-circuitpython-neopixel adafruit-circuitpython-display-text -adafruit-circuitpython-simple-text-display adafruit-circuitpython-debouncer +adafruit-circuitpython-simple-text-display +adafruit-circuitpython-neopixel diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 0000000..d4a4777 --- /dev/null +++ b/ruff.toml @@ -0,0 +1,109 @@ +# 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 + "PLC2701", # private import + "PLW0603", # global statement +] + +[format] +line-ending = "lf" diff --git a/setup.py.disabled b/setup.py.disabled deleted file mode 100644 index 8eef2e8..0000000 --- a/setup.py.disabled +++ /dev/null @@ -1,9 +0,0 @@ -# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries -# SPDX-FileCopyrightText: Copyright (c) 2021 Kattni Rembor for Adafruit Industries -# -# SPDX-License-Identifier: MIT - -""" -This library is not deployed to PyPI. It is either a board-specific helper library, or -does not make sense for use on or is incompatible with single board computers and Linux. -"""