From 9c25878e0b7bf2ad2085190a3d8be78579006667 Mon Sep 17 00:00:00 2001 From: foamyguy Date: Mon, 16 Oct 2023 14:30:31 -0500 Subject: [PATCH 1/5] unpin sphinx and add sphinx-rtd-theme to docs reqs Signed-off-by: foamyguy --- docs/requirements.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/requirements.txt b/docs/requirements.txt index 797aa04..979f568 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -2,5 +2,6 @@ # # SPDX-License-Identifier: Unlicense -sphinx>=4.0.0 +sphinx sphinxcontrib-jquery +sphinx-rtd-theme From 5a1e7dbb77edf82607c221e33ca741903cfbc25d Mon Sep 17 00:00:00 2001 From: foamyguy Date: Mon, 7 Oct 2024 09:24:05 -0500 Subject: [PATCH 2/5] remove deprecated get_html_theme_path() call Signed-off-by: foamyguy --- docs/conf.py | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/conf.py b/docs/conf.py index 2f99c4f..75e4591 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -117,7 +117,6 @@ import sphinx_rtd_theme html_theme = "sphinx_rtd_theme" -html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), "."] # 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, From fa981a2a56d3ef4e42609e544a8cb47b443edaf8 Mon Sep 17 00:00:00 2001 From: foamyguy Date: Tue, 12 Nov 2024 16:20:43 -0600 Subject: [PATCH 3/5] rename _samples to _mic_samples and fix if condition --- adafruit_circuitplayground/bluefruit.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/adafruit_circuitplayground/bluefruit.py b/adafruit_circuitplayground/bluefruit.py index 5758267..7f36195 100755 --- a/adafruit_circuitplayground/bluefruit.py +++ b/adafruit_circuitplayground/bluefruit.py @@ -61,7 +61,7 @@ def __init__(self) -> None: sample_rate=16000, bit_depth=16, ) - self._samples = None + self._mic_samples = None @staticmethod def _normalized_rms(values) -> float: @@ -91,10 +91,10 @@ def sound_level(self) -> float: while True: print(cpb.sound_level) """ - if self._sample is None: - self._samples = array.array("H", [0] * 160) - self._mic.record(self._samples, len(self._samples)) - return self._normalized_rms(self._samples) + if self._mic_samples is None: + self._mic_samples = array.array("H", [0] * 160) + self._mic.record(self._mic_samples, len(self._mic_samples)) + return self._normalized_rms(self._mic_samples) def loud_sound(self, sound_threshold: int = 200) -> bool: """Utilise a loud sound as an input. From f4ee2000d0b3e036cf437c5879349cbc9bc2849f Mon Sep 17 00:00:00 2001 From: foamyguy Date: Tue, 14 Jan 2025 11:32:34 -0600 Subject: [PATCH 4/5] add sphinx configuration to rtd.yaml Signed-off-by: foamyguy --- .readthedocs.yaml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.readthedocs.yaml b/.readthedocs.yaml index 33c2a61..88bca9f 100644 --- a/.readthedocs.yaml +++ b/.readthedocs.yaml @@ -8,6 +8,9 @@ # Required version: 2 +sphinx: + configuration: docs/conf.py + build: os: ubuntu-20.04 tools: From 71ebdcc960a716464d8f226427444ad72bcc67fd Mon Sep 17 00:00:00 2001 From: foamyguy Date: Tue, 13 May 2025 21:32:42 +0000 Subject: [PATCH 5/5] change to ruff --- .gitattributes | 11 + .pre-commit-config.yaml | 43 +- .pylintrc | 399 ------------------ README.rst | 6 +- adafruit_circuitplayground/bluefruit.py | 23 +- .../circuit_playground_base.py | 64 ++- adafruit_circuitplayground/express.py | 14 +- docs/api.rst | 3 + docs/conf.py | 8 +- docs/mocks/keypad.py | 2 +- examples/circuitplayground_acceleration.py | 2 + ...ircuitplayground_acceleration_neopixels.py | 1 + ...ayground_acceleration_mapping_neopixels.py | 7 +- .../circuitplayground_gravity_pulls_pixel.py | 21 +- .../circuitplayground_tilting_arpeggios.py | 23 +- .../circuitplayground_bluefruit_loud_sound.py | 2 + ...ayground_bluefruit_loud_sound_threshold.py | 2 + .../circuitplayground_bluefruit_play_mp3.py | 1 + ...circuitplayground_bluefruit_sound_level.py | 2 + ...layground_bluefruit_sound_level_plotter.py | 2 + examples/circuitplayground_button_a.py | 1 + examples/circuitplayground_button_b.py | 4 +- .../circuitplayground_buttons_1_neopixel.py | 1 + .../circuitplayground_buttons_neopixels.py | 1 + examples/circuitplayground_ir_receive.py | 6 +- examples/circuitplayground_ir_transmit.py | 7 +- examples/circuitplayground_light.py | 2 + examples/circuitplayground_light_neopixels.py | 1 + examples/circuitplayground_light_plotter.py | 2 + examples/circuitplayground_neopixel_0.py | 1 + examples/circuitplayground_neopixel_0_1.py | 1 + examples/circuitplayground_neopixels_fill.py | 1 + .../circuitplayground_pixels_simpletest.py | 3 + examples/circuitplayground_play_file.py | 1 + .../circuitplayground_play_file_buttons.py | 1 + examples/circuitplayground_play_tone.py | 1 + .../circuitplayground_play_tone_buttons.py | 1 + examples/circuitplayground_red_led.py | 1 + examples/circuitplayground_red_led_blinky.py | 2 + .../circuitplayground_red_led_blnky_short.py | 2 + examples/circuitplayground_shake.py | 1 + examples/circuitplayground_shake_red_led.py | 1 + examples/circuitplayground_slide_switch.py | 2 + .../circuitplayground_slide_switch_red_led.py | 4 +- ...itplayground_slide_switch_red_led_short.py | 1 + examples/circuitplayground_sound_meter.py | 12 +- examples/circuitplayground_tap_red_led.py | 2 + examples/circuitplayground_tapdetect.py | 2 + ...rcuitplayground_tapdetect_single_double.py | 1 + examples/circuitplayground_temperature.py | 2 + ...circuitplayground_temperature_neopixels.py | 2 + .../circuitplayground_temperature_plotter.py | 2 + examples/circuitplayground_tone.py | 1 + examples/circuitplayground_touch_a1.py | 1 + examples/circuitplayground_touch_all.py | 4 +- ...cuitplayground_touch_pixel_fill_rainbow.py | 2 + .../circuitplayground_touch_pixel_rainbow.py | 2 + ruff.toml | 105 +++++ 58 files changed, 276 insertions(+), 547 deletions(-) create mode 100644 .gitattributes delete mode 100644 .pylintrc create mode 100644 ruff.toml diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..21c125c --- /dev/null +++ b/.gitattributes @@ -0,0 +1,11 @@ +# SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense + +.py text eol=lf +.rst text eol=lf +.txt text eol=lf +.yaml text eol=lf +.toml text eol=lf +.license text eol=lf +.md text eol=lf diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 70ade69..ff19dde 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,42 +1,21 @@ -# SPDX-FileCopyrightText: 2020 Diego Elio Pettenò +# SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries # # SPDX-License-Identifier: Unlicense repos: - - repo: https://github.com/python/black - rev: 23.3.0 - hooks: - - id: black - - repo: https://github.com/fsfe/reuse-tool - rev: v1.1.2 - hooks: - - id: reuse - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.4.0 + rev: v4.5.0 hooks: - id: check-yaml - id: end-of-file-fixer - id: trailing-whitespace - - repo: https://github.com/pycqa/pylint - rev: v2.17.4 + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.3.4 hooks: - - id: pylint - name: pylint (library code) - types: [python] - args: - - --disable=consider-using-f-string - exclude: "^(docs/|examples/|tests/|setup.py$)" - - id: pylint - name: pylint (example code) - description: Run pylint rules on "examples/*.py" files - types: [python] - files: "^examples/" - args: - - --disable=missing-docstring,invalid-name,consider-using-f-string,duplicate-code - - id: pylint - name: pylint (test code) - description: Run pylint rules on "tests/*.py" files - types: [python] - files: "^tests/" - args: - - --disable=missing-docstring,consider-using-f-string,duplicate-code + - id: ruff-format + - id: ruff + args: ["--fix"] + - repo: https://github.com/fsfe/reuse-tool + rev: v3.0.1 + hooks: + - id: reuse diff --git a/.pylintrc b/.pylintrc deleted file mode 100644 index f945e92..0000000 --- a/.pylintrc +++ /dev/null @@ -1,399 +0,0 @@ -# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries -# -# SPDX-License-Identifier: Unlicense - -[MASTER] - -# A comma-separated list of package or module names from where C extensions may -# be loaded. Extensions are loading into the active Python interpreter and may -# run arbitrary code -extension-pkg-whitelist= - -# Add files or directories to the ignore-list. They should be base names, not -# paths. -ignore=CVS - -# Add files or directories matching the regex patterns to the ignore-list. The -# regex matches against base names, not paths. -ignore-patterns= - -# Python code to execute, usually for sys.path manipulation such as -# pygtk.require(). -#init-hook= - -# Use multiple processes to speed up Pylint. -jobs=1 - -# List of plugins (as comma separated values of python modules names) to load, -# usually to register additional checkers. -load-plugins=pylint.extensions.no_self_use - -# Pickle collected data for later comparisons. -persistent=yes - -# Specify a configuration file. -#rcfile= - -# Allow loading of arbitrary C extensions. Extensions are imported into the -# active Python interpreter and may run arbitrary code. -unsafe-load-any-extension=no - - -[MESSAGES CONTROL] - -# Only show warnings with the listed confidence levels. Leave empty to show -# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED -confidence= - -# Disable the message, report, category or checker with the given id(s). You -# can either give multiple identifiers separated by comma (,) or put this -# option multiple times (only on the command line, not in the configuration -# file where it should appear only once).You can also use "--disable=all" to -# disable everything first and then reenable specific checks. For example, if -# you want to run only the similarities checker, you can use "--disable=all -# --enable=similarities". If you want to run only the classes checker, but have -# no Warning level messages displayed, use"--disable=all --enable=classes -# --disable=W" -# disable=import-error,raw-checker-failed,bad-inline-option,locally-disabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,deprecated-str-translate-call -disable=raw-checker-failed,bad-inline-option,locally-disabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,import-error,pointless-string-statement,unspecified-encoding - -# Enable the message, report, category or checker with the given id(s). You can -# either give multiple identifier separated by comma (,) or put this option -# multiple time (only on the command line, not in the configuration file where -# it should appear only once). See also the "--disable" option for examples. -enable= - - -[REPORTS] - -# Python expression which should return a note less than 10 (10 is the highest -# note). You have access to the variables errors warning, statement which -# respectively contain the number of errors / warnings messages and the total -# number of statements analyzed. This is used by the global evaluation report -# (RP0004). -evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) - -# Template used to display messages. This is a python new-style format string -# used to format the message information. See doc for all details -#msg-template= - -# Set the output format. Available formats are text, parseable, colorized, json -# and msvs (visual studio).You can also give a reporter class, eg -# mypackage.mymodule.MyReporterClass. -output-format=text - -# Tells whether to display a full report or only the messages -reports=no - -# Activate the evaluation score. -score=yes - - -[REFACTORING] - -# Maximum number of nested blocks for function / method body -max-nested-blocks=5 - - -[LOGGING] - -# Logging modules to check that the string format arguments are in logging -# function parameter format -logging-modules=logging - - -[SPELLING] - -# Spelling dictionary name. Available dictionaries: none. To make it working -# install python-enchant package. -spelling-dict= - -# List of comma separated words that should not be checked. -spelling-ignore-words= - -# A path to a file that contains private dictionary; one word per line. -spelling-private-dict-file= - -# Tells whether to store unknown words to indicated private dictionary in -# --spelling-private-dict-file option instead of raising a message. -spelling-store-unknown-words=no - - -[MISCELLANEOUS] - -# List of note tags to take in consideration, separated by a comma. -# notes=FIXME,XXX,TODO -notes=FIXME,XXX - - -[TYPECHECK] - -# List of decorators that produce context managers, such as -# contextlib.contextmanager. Add to this list to register other decorators that -# produce valid context managers. -contextmanager-decorators=contextlib.contextmanager - -# List of members which are set dynamically and missed by pylint inference -# system, and so shouldn't trigger E1101 when accessed. Python regular -# expressions are accepted. -generated-members= - -# Tells whether missing members accessed in mixin class should be ignored. A -# mixin class is detected if its name ends with "mixin" (case insensitive). -ignore-mixin-members=yes - -# This flag controls whether pylint should warn about no-member and similar -# checks whenever an opaque object is returned when inferring. The inference -# can return multiple potential results while evaluating a Python object, but -# some branches might not be evaluated, which results in partial inference. In -# that case, it might be useful to still emit no-member and other checks for -# the rest of the inferred objects. -ignore-on-opaque-inference=yes - -# List of class names for which member attributes should not be checked (useful -# for classes with dynamically set attributes). This supports the use of -# qualified names. -ignored-classes=optparse.Values,thread._local,_thread._local - -# List of module names for which member attributes should not be checked -# (useful for modules/projects where namespaces are manipulated during runtime -# and thus existing member attributes cannot be deduced by static analysis. It -# supports qualified module names, as well as Unix pattern matching. -ignored-modules=board - -# Show a hint with possible names when a member name was not found. The aspect -# of finding the hint is based on edit distance. -missing-member-hint=yes - -# The minimum edit distance a name should have in order to be considered a -# similar match for a missing member name. -missing-member-hint-distance=1 - -# The total number of similar names that should be taken in consideration when -# showing a hint for a missing member. -missing-member-max-choices=1 - - -[VARIABLES] - -# List of additional names supposed to be defined in builtins. Remember that -# you should avoid to define new builtins when possible. -additional-builtins= - -# Tells whether unused global variables should be treated as a violation. -allow-global-unused-variables=yes - -# List of strings which can identify a callback function by name. A callback -# name must start or end with one of those strings. -callbacks=cb_,_cb - -# A regular expression matching the name of dummy variables (i.e. expectedly -# not used). -dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ - -# Argument names that match this expression will be ignored. Default to name -# with leading underscore -ignored-argument-names=_.*|^ignored_|^unused_ - -# Tells whether we should check for unused import in __init__ files. -init-import=no - -# List of qualified module names which can have objects that can redefine -# builtins. -redefining-builtins-modules=six.moves,future.builtins - - -[FORMAT] - -# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. -# expected-line-ending-format= -expected-line-ending-format=LF - -# Regexp for a line that is allowed to be longer than the limit. -ignore-long-lines=^\s*(# )??$ - -# Number of spaces of indent required inside a hanging or continued line. -indent-after-paren=4 - -# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 -# tab). -indent-string=' ' - -# Maximum number of characters on a single line. -max-line-length=100 - -# Maximum number of lines in a module -max-module-lines=1000 - -# Allow the body of a class to be on the same line as the declaration if body -# contains single statement. -single-line-class-stmt=no - -# Allow the body of an if to be on the same line as the test if there is no -# else. -single-line-if-stmt=no - - -[SIMILARITIES] - -# Ignore comments when computing similarities. -ignore-comments=yes - -# Ignore docstrings when computing similarities. -ignore-docstrings=yes - -# Ignore imports when computing similarities. -ignore-imports=yes - -# Minimum lines number of a similarity. -min-similarity-lines=12 - - -[BASIC] - -# Regular expression matching correct argument names -argument-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Regular expression matching correct attribute names -attr-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Bad variable names which should always be refused, separated by a comma -bad-names=foo,bar,baz,toto,tutu,tata - -# Regular expression matching correct class attribute names -class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ - -# Regular expression matching correct class names -# class-rgx=[A-Z_][a-zA-Z0-9]+$ -class-rgx=[A-Z_][a-zA-Z0-9_]+$ - -# Regular expression matching correct constant names -const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ - -# Minimum line length for functions/classes that require docstrings, shorter -# ones are exempt. -docstring-min-length=-1 - -# Regular expression matching correct function names -function-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Good variable names which should always be accepted, separated by a comma -# good-names=i,j,k,ex,Run,_ -good-names=r,g,b,w,i,j,k,n,x,y,z,ex,ok,Run,_ - -# Include a hint for the correct naming format with invalid-name -include-naming-hint=no - -# Regular expression matching correct inline iteration names -inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ - -# Regular expression matching correct method names -method-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Regular expression matching correct module names -module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ - -# Colon-delimited sets of names that determine each other's naming style when -# the name regexes allow several styles. -name-group= - -# Regular expression which should only match function or class names that do -# not require a docstring. -no-docstring-rgx=^_ - -# List of decorators that produce properties, such as abc.abstractproperty. Add -# to this list to register other decorators that produce valid properties. -property-classes=abc.abstractproperty - -# Regular expression matching correct variable names -variable-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - - -[IMPORTS] - -# Allow wildcard imports from modules that define __all__. -allow-wildcard-with-all=no - -# Analyse import fallback blocks. This can be used to support both Python 2 and -# 3 compatible code, which means that the block might have code that exists -# only in one or another interpreter, leading to false positives when analysed. -analyse-fallback-blocks=no - -# Deprecated modules which should not be used, separated by a comma -deprecated-modules=optparse,tkinter.tix - -# Create a graph of external dependencies in the given file (report RP0402 must -# not be disabled) -ext-import-graph= - -# Create a graph of every (i.e. internal and external) dependencies in the -# given file (report RP0402 must not be disabled) -import-graph= - -# Create a graph of internal dependencies in the given file (report RP0402 must -# not be disabled) -int-import-graph= - -# Force import order to recognize a module as part of the standard -# compatibility libraries. -known-standard-library= - -# Force import order to recognize a module as part of a third party library. -known-third-party=enchant - - -[CLASSES] - -# List of method names used to declare (i.e. assign) instance attributes. -defining-attr-methods=__init__,__new__,setUp - -# List of member names, which should be excluded from the protected access -# warning. -exclude-protected=_asdict,_fields,_replace,_source,_make - -# List of valid names for the first argument in a class method. -valid-classmethod-first-arg=cls - -# List of valid names for the first argument in a metaclass class method. -valid-metaclass-classmethod-first-arg=mcs - - -[DESIGN] - -# Maximum number of arguments for function / method -max-args=5 - -# Maximum number of attributes for a class (see R0902). -# max-attributes=7 -max-attributes=11 - -# Maximum number of boolean expressions in a if statement -max-bool-expr=5 - -# Maximum number of branch for function / method body -max-branches=12 - -# Maximum number of locals for function / method body -max-locals=15 - -# Maximum number of parents for a class (see R0901). -max-parents=7 - -# Maximum number of public methods for a class (see R0904). -max-public-methods=20 - -# Maximum number of return / yield for function / method body -max-returns=6 - -# Maximum number of statements in function / method body -max-statements=50 - -# Minimum number of public methods for a class (see R0903). -min-public-methods=1 - - -[EXCEPTIONS] - -# Exceptions that will emit a warning when being caught. Defaults to -# "Exception" -overgeneral-exceptions=builtins.Exception diff --git a/README.rst b/README.rst index bbac9f3..73c8a25 100644 --- a/README.rst +++ b/README.rst @@ -14,9 +14,9 @@ Introduction :target: https://github.com/adafruit/Adafruit_CircuitPython_CircuitPlayground/actions/ :alt: Build Status -.. image:: https://img.shields.io/badge/code%20style-black-000000.svg - :target: https://github.com/psf/black - :alt: Code Style: Black +.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json + :target: https://github.com/astral-sh/ruff + :alt: Code Style: Ruff This high level library provides objects that represent Circuit Playground Express and Bluefruit hardware. diff --git a/adafruit_circuitplayground/bluefruit.py b/adafruit_circuitplayground/bluefruit.py index 7f36195..65c77d2 100755 --- a/adafruit_circuitplayground/bluefruit.py +++ b/adafruit_circuitplayground/bluefruit.py @@ -18,20 +18,22 @@ * `Circuit Playground Bluefruit `_ """ + try: - import typing # pylint: disable=unused-import + import typing except ImportError: pass import array import math -import digitalio -import board -import audiopwmio -import audiomp3 + import audiobusio -from adafruit_circuitplayground.circuit_playground_base import CircuitPlaygroundBase +import audiomp3 +import audiopwmio +import board +import digitalio +from adafruit_circuitplayground.circuit_playground_base import CircuitPlaygroundBase __version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_CircuitPlayground.git" @@ -67,10 +69,7 @@ def __init__(self) -> None: def _normalized_rms(values) -> float: mean_values = int(sum(values) / len(values)) return math.sqrt( - sum( - float(sample - mean_values) * (sample - mean_values) - for sample in values - ) + sum(float(sample - mean_values) * (sample - mean_values) for sample in values) / len(values) ) @@ -164,7 +163,7 @@ def play_mp3(self, file_name: str) -> None: self._speaker_enable.value = True with self._audio_out(board.SPEAKER) as audio, audiomp3.MP3Decoder( open(file_name, "rb") - ) as mp3file: # pylint: disable=not-callable + ) as mp3file: audio.play(mp3file) while audio.playing: pass @@ -173,7 +172,7 @@ def play_mp3(self, file_name: str) -> None: raise ValueError("Filetype must be mp3") -cpb = Bluefruit() # pylint: disable=invalid-name +cpb = Bluefruit() """Object that is automatically created on import. To use, simply import it from the module: diff --git a/adafruit_circuitplayground/circuit_playground_base.py b/adafruit_circuitplayground/circuit_playground_base.py index 5806ebf..ef72b67 100755 --- a/adafruit_circuitplayground/circuit_playground_base.py +++ b/adafruit_circuitplayground/circuit_playground_base.py @@ -5,7 +5,6 @@ # SPDX-License-Identifier: MIT # We have a lot of attributes for this complex library, as well as a lot of documentation. -# pylint: disable=too-many-instance-attributes, too-many-lines """ `adafruit_circuitplayground.circuit_playground_base` @@ -19,24 +18,26 @@ * Author(s): Kattni Rembor, Scott Shawcroft, Ryan Keith """ -import math import array -import time +import math import os -import audiocore +import time + +import adafruit_lis3dh +import adafruit_thermistor import analogio +import audiocore import board import busio import digitalio -import adafruit_lis3dh -import adafruit_thermistor import neopixel import touchio try: - from typing import Optional, Iterator, List - from typing_extensions import Literal + from typing import Iterator, List, Optional + from microcontroller import Pin + from typing_extensions import Literal except ImportError: pass @@ -47,7 +48,6 @@ class Photocell: """Simple driver for analog photocell on the Circuit Playground Express and Bluefruit.""" - # pylint: disable=too-few-public-methods def __init__(self, pin: Pin) -> None: self._photocell = analogio.AnalogIn(pin) @@ -58,7 +58,7 @@ def light(self) -> int: return self._photocell.value * 330 // (2**16) -class CircuitPlaygroundBase: # pylint: disable=too-many-public-methods +class CircuitPlaygroundBase: """Circuit Playground base class.""" _audio_out = None @@ -76,9 +76,7 @@ def __init__(self) -> None: self._pixels = neopixel.NeoPixel(board.NEOPIXEL, 10) # Define sensors: - self._temp = adafruit_thermistor.Thermistor( - board.TEMPERATURE, 10000, 10000, 25, 3950 - ) + self._temp = adafruit_thermistor.Thermistor(board.TEMPERATURE, 10000, 10000, 25, 3950) self._light = Photocell(board.LIGHT) # Define touch: @@ -94,9 +92,7 @@ def __init__(self) -> None: # Define acceleration: self._i2c = busio.I2C(board.ACCELEROMETER_SCL, board.ACCELEROMETER_SDA) self._int1 = digitalio.DigitalInOut(board.ACCELEROMETER_INTERRUPT) - self._lis3dh = adafruit_lis3dh.LIS3DH_I2C( - self._i2c, address=0x19, int1=self._int1 - ) + self._lis3dh = adafruit_lis3dh.LIS3DH_I2C(self._i2c, address=0x19, int1=self._int1) self._lis3dh.range = adafruit_lis3dh.RANGE_8_G # Define audio: @@ -137,9 +133,7 @@ def detect_taps(self) -> Literal[1, 2]: @staticmethod def _default_tap_threshold(tap: Literal[1, 2]) -> int: - if ( - "nRF52840" in os.uname().machine - ): # If we're on a CPB, use a higher tap threshold + if "nRF52840" in os.uname().machine: # If we're on a CPB, use a higher tap threshold return 100 if tap == 1 else 70 # If we're on a CPX @@ -165,7 +159,7 @@ def detect_taps(self, value: Literal[1, 2]) -> None: time_window=255, ) - def configure_tap( # pylint: disable-msg=too-many-arguments + def configure_tap( self, tap: Literal[0, 1, 2], accel_range: Literal[0, 1, 2, 3] = adafruit_lis3dh.RANGE_8_G, @@ -210,12 +204,12 @@ def configure_tap( # pylint: disable-msg=too-many-arguments self._detect_taps = tap - if accel_range not in [ + if accel_range not in { adafruit_lis3dh.RANGE_2_G, adafruit_lis3dh.RANGE_4_G, adafruit_lis3dh.RANGE_8_G, adafruit_lis3dh.RANGE_16_G, - ]: + }: accel_range = adafruit_lis3dh.RANGE_8_G self._lis3dh.range = accel_range @@ -363,7 +357,7 @@ def _touch(self, pin: Pin) -> bool: # lists and the capital A to match the pin name. The capitalization is not strictly Python # style, so everywhere we use these names, we whitelist the errors using: @property - def touch_A1(self) -> bool: # pylint: disable=invalid-name + def touch_A1(self) -> bool: """Detect touch on capacitive touch pad A1. .. image :: ../docs/_static/capacitive_touch_pad_A1.jpg @@ -382,7 +376,7 @@ def touch_A1(self) -> bool: # pylint: disable=invalid-name return self._touch(board.A1) @property - def touch_A2(self) -> bool: # pylint: disable=invalid-name + def touch_A2(self) -> bool: """Detect touch on capacitive touch pad A2. .. image :: ../docs/_static/capacitive_touch_pad_A2.jpg @@ -401,7 +395,7 @@ def touch_A2(self) -> bool: # pylint: disable=invalid-name return self._touch(board.A2) @property - def touch_A3(self) -> bool: # pylint: disable=invalid-name + def touch_A3(self) -> bool: """Detect touch on capacitive touch pad A3. .. image :: ../docs/_static/capacitive_touch_pad_A3.jpg @@ -420,7 +414,7 @@ def touch_A3(self) -> bool: # pylint: disable=invalid-name return self._touch(board.A3) @property - def touch_A4(self) -> bool: # pylint: disable=invalid-name + def touch_A4(self) -> bool: """Detect touch on capacitive touch pad A4. .. image :: ../docs/_static/capacitive_touch_pad_A4.jpg @@ -439,7 +433,7 @@ def touch_A4(self) -> bool: # pylint: disable=invalid-name return self._touch(board.A4) @property - def touch_A5(self) -> bool: # pylint: disable=invalid-name + def touch_A5(self) -> bool: """Detect touch on capacitive touch pad A5. .. image :: ../docs/_static/capacitive_touch_pad_A5.jpg @@ -458,7 +452,7 @@ def touch_A5(self) -> bool: # pylint: disable=invalid-name return self._touch(board.A5) @property - def touch_A6(self) -> bool: # pylint: disable=invalid-name + def touch_A6(self) -> bool: """Detect touch on capacitive touch pad A6. .. image :: ../docs/_static/capacitive_touch_pad_A6.jpg @@ -477,7 +471,7 @@ def touch_A6(self) -> bool: # pylint: disable=invalid-name return self._touch(board.A6) @property - def touch_TX(self) -> bool: # pylint: disable=invalid-name + def touch_TX(self) -> bool: """Detect touch on capacitive touch pad TX (also known as A7 on the Circuit Playground Express) Note: can be called as ``touch_A7`` on Circuit Playground Express. @@ -722,12 +716,10 @@ def _generate_sample(self, length: int = 100, waveform: int = SINE_WAVE) -> None self._wave = array.array("H", self._square_sample(length)) else: self._wave = array.array("H", self._sine_sample(length)) - self._sample = self._audio_out(board.SPEAKER) # pylint: disable=not-callable + self._sample = self._audio_out(board.SPEAKER) self._wave_sample = audiocore.RawSample(self._wave) - def play_tone( - self, frequency: int, duration: float, waveform: int = SINE_WAVE - ) -> None: + def play_tone(self, frequency: int, duration: float, waveform: int = SINE_WAVE) -> None: """Produce a tone using the speaker. Try changing frequency to change the pitch of the tone. @@ -839,9 +831,9 @@ def play_file(self, file_name: str) -> None: # Play a specified file. self.stop_tone() self._speaker_enable.value = True - with self._audio_out( # pylint: disable=not-callable - board.SPEAKER - ) as audio, audiocore.WaveFile(open(file_name, "rb")) as wavefile: + with self._audio_out(board.SPEAKER) as audio, audiocore.WaveFile( + open(file_name, "rb") + ) as wavefile: audio.play(wavefile) while audio.playing: pass diff --git a/adafruit_circuitplayground/express.py b/adafruit_circuitplayground/express.py index 4a2cb79..ef13839 100755 --- a/adafruit_circuitplayground/express.py +++ b/adafruit_circuitplayground/express.py @@ -17,22 +17,22 @@ """ import sys -import digitalio + import audioio +import digitalio try: - lib_index = sys.path.index("/lib") # pylint: disable=invalid-name + lib_index = sys.path.index("/lib") if lib_index < sys.path.index(".frozen"): # Prefer frozen modules over those in /lib. sys.path.insert(lib_index, ".frozen") except ValueError: # Don't change sys.path if it doesn't contain "lib" or ".frozen". pass -from adafruit_circuitplayground.circuit_playground_base import ( # pylint: disable=wrong-import-position +from adafruit_circuitplayground.circuit_playground_base import ( CircuitPlaygroundBase, ) - __version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_CircuitPlayground.git" @@ -60,9 +60,7 @@ def __init__(self): @property def _unsupported(self): """This feature is not supported on Circuit Playground Express.""" - raise NotImplementedError( - "This feature is not supported on Circuit Playground Express." - ) + raise NotImplementedError("This feature is not supported on Circuit Playground Express.") # The following is a list of the features available in other Circuit Playground modules but # not available for Circuit Playground Express. If called while using a Circuit Playground @@ -72,7 +70,7 @@ def _unsupported(self): play_mp3 = _unsupported -cpx = Express() # pylint: disable=invalid-name +cpx = Express() """Object that is automatically created on import. To use, simply import it from the module: diff --git a/docs/api.rst b/docs/api.rst index 88535f9..0e62c1d 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -1,6 +1,9 @@ .. If you created a package, create one automodule per module in the package. +API Reference +############# + .. automodule:: adafruit_circuitplayground.circuit_playground_base :members: diff --git a/docs/conf.py b/docs/conf.py index 75e4591..6e182ba 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,12 +1,10 @@ -# -*- coding: utf-8 -*- - # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # # SPDX-License-Identifier: MIT +import datetime import os import sys -import datetime sys.path.insert(0, os.path.abspath("..")) sys.path.insert(0, os.path.abspath("mocks")) @@ -62,9 +60,7 @@ creation_year = "2017" current_year = str(datetime.datetime.now().year) year_duration = ( - current_year - if current_year == creation_year - else creation_year + " - " + current_year + current_year if current_year == creation_year else creation_year + " - " + current_year ) copyright = year_duration + " Scott Shawcroft" author = "Scott Shawcroft" diff --git a/docs/mocks/keypad.py b/docs/mocks/keypad.py index d042ab5..114c04a 100644 --- a/docs/mocks/keypad.py +++ b/docs/mocks/keypad.py @@ -5,7 +5,7 @@ class EventQueue: def __init__(self): self.overflowed = False - def get(self): + def get(self): # noqa: PLR6301 return None diff --git a/examples/circuitplayground_acceleration.py b/examples/circuitplayground_acceleration.py index 839d945..a825141 100644 --- a/examples/circuitplayground_acceleration.py +++ b/examples/circuitplayground_acceleration.py @@ -5,7 +5,9 @@ This example uses the accelerometer on the Circuit Playground. It prints the values. Try moving the board to see the values change. If you're using Mu, open the plotter to see the values plotted. """ + import time + from adafruit_circuitplayground import cp while True: diff --git a/examples/circuitplayground_acceleration_neopixels.py b/examples/circuitplayground_acceleration_neopixels.py index d0efcf8..c7f3e31 100644 --- a/examples/circuitplayground_acceleration_neopixels.py +++ b/examples/circuitplayground_acceleration_neopixels.py @@ -5,6 +5,7 @@ left to see the NeoPixels light up in colors related to the accelerometer! The Circuit Playground has an accelerometer in the center that returns (x, y, z) acceleration values. This program uses those values to light up the NeoPixels based on those acceleration values.""" + from adafruit_circuitplayground import cp # Main loop gets x, y and z axis acceleration, prints the values, and turns on diff --git a/examples/circuitplayground_advanced_examples/circuitplayground_acceleration_mapping_neopixels.py b/examples/circuitplayground_advanced_examples/circuitplayground_acceleration_mapping_neopixels.py index bb32bf6..1ea046a 100644 --- a/examples/circuitplayground_advanced_examples/circuitplayground_acceleration_mapping_neopixels.py +++ b/examples/circuitplayground_advanced_examples/circuitplayground_acceleration_mapping_neopixels.py @@ -17,6 +17,7 @@ """ import time + from adafruit_circuitplayground import cp cp.pixels.brightness = 0.2 # Adjust overall brightness as desired, between 0 and 1 @@ -32,15 +33,15 @@ def color_amount(accel_component): def format_acceleration(): - return ", ".join(("{:>6.2f}".format(axis_value) for axis_value in acceleration)) + return ", ".join(f"{axis_value:>6.2f}" for axis_value in acceleration) def format_rgb(): - return ", ".join(("{:>3d}".format(rgb_amount) for rgb_amount in rgb_amounts)) + return ", ".join(f"{rgb_amount:>3d}" for rgb_amount in rgb_amounts) def log_values(): - print("({}) ==> ({})".format(format_acceleration(), format_rgb())) + print(f"({format_acceleration()}) ==> ({format_rgb()})") while True: diff --git a/examples/circuitplayground_advanced_examples/circuitplayground_gravity_pulls_pixel.py b/examples/circuitplayground_advanced_examples/circuitplayground_gravity_pulls_pixel.py index 357dda9..5f8a982 100644 --- a/examples/circuitplayground_advanced_examples/circuitplayground_gravity_pulls_pixel.py +++ b/examples/circuitplayground_advanced_examples/circuitplayground_gravity_pulls_pixel.py @@ -9,8 +9,10 @@ Flip the switch left (toward the notes) to turn on debugging messages and slow down the action. See a code walkthrough here: https://youtu.be/sZ4tNOUKRpw """ -import time + import math +import time + from adafruit_circuitplayground import cp PIXEL_SPACING_ANGLE = 30 @@ -31,9 +33,7 @@ def compute_pixel_angles(): accelerometer’s (x, y) values give an angle of 300°. Rotated clockwise 1/12 turn (30°), so that pixel 1 is at the bottom, the angle is 330°. """ - return [ - (300 + PIXEL_SPACING_ANGLE * n) % 360 for n in range(12) if n not in (5, 11) - ] + return [(300 + PIXEL_SPACING_ANGLE * n) % 360 for n in range(12) if n not in {5, 11}] def degrees_between(a1, a2): @@ -74,24 +74,19 @@ def positive_degrees(angle): down_angle = positive_degrees(angle_in_degrees(accel_x, accel_y)) magnitude_limit = STANDARD_GRAVITY normalized_magnitude = ( - min(math.sqrt(accel_x * accel_x + accel_y * accel_y), magnitude_limit) - / magnitude_limit + min(math.sqrt(accel_x * accel_x + accel_y * accel_y), magnitude_limit) / magnitude_limit ) pixels_lit = [] for i, pixel_position in enumerate(pixel_positions): - pe = pixel_brightness( - degrees_between(pixel_position, down_angle), normalized_magnitude - ) + pe = pixel_brightness(degrees_between(pixel_position, down_angle), normalized_magnitude) cp.pixels[i] = (pe, pe, pe) if pe else BACKGROUND_COLOR if pe: pixels_lit.append((i, pe)) if debug: - lit_formatted = ", ".join(("{}: {:>3d}".format(p, i) for p, i in pixels_lit)) + lit_formatted = ", ".join((f"{p}: {i:>3d}" for p, i in pixels_lit)) print( - "x: {:>6.2f}, y: {:>6.2f}, angle: {:>6.2f}, mag: {:>3.2f}, pixels: [{}]".format( - accel_x, accel_y, down_angle, normalized_magnitude, lit_formatted - ) + f"x: {accel_x:>6.2f}, y: {accel_y:>6.2f}, angle: {down_angle:>6.2f}, mag: {normalized_magnitude:>3.2f}, pixels: [{lit_formatted}]" # noqa: E501 ) time.sleep(0.5) diff --git a/examples/circuitplayground_advanced_examples/circuitplayground_tilting_arpeggios.py b/examples/circuitplayground_advanced_examples/circuitplayground_tilting_arpeggios.py index 71fbfd8..77c91d0 100644 --- a/examples/circuitplayground_advanced_examples/circuitplayground_tilting_arpeggios.py +++ b/examples/circuitplayground_advanced_examples/circuitplayground_tilting_arpeggios.py @@ -13,8 +13,8 @@ See a code walkthrough here: https://www.youtube.com/watch?v=cDhqyT3ZN0g """ -# pylint: disable=R0903 import time + from adafruit_circuitplayground import cp HS_OCT = 12 # Half-steps per octave @@ -37,25 +37,18 @@ def calc_freq(i): return STARTING_NOTE * 2 ** (i / HS_OCT) self.note_frequencies = [calc_freq(i) for i in range(num_freqs)] - self.arpeg_note_indexes = FrequencyMaker.create_arpeggios( - num_octaves_to_pre_compute - ) + self.arpeg_note_indexes = FrequencyMaker.create_arpeggios(num_octaves_to_pre_compute) self.circle_pos = 0 self.key_offset = 0 @staticmethod def create_arpeggios(num_octaves): """Create a list of arpeggios, where each one is a list of chromatic scale note indexes""" - return [ - FrequencyMaker.create_arpeggio(arpeggio, num_octaves) - for arpeggio in ARPEGGIOS - ] + return [FrequencyMaker.create_arpeggio(arpeggio, num_octaves) for arpeggio in ARPEGGIOS] @staticmethod def create_arpeggio(arpeggio, num_octaves): - return [ - octave * HS_OCT + note for octave in range(num_octaves) for note in arpeggio - ] + return [octave * HS_OCT + note for octave in range(num_octaves) for note in arpeggio] def advance(self, amount): """Advance forward or backward through the circle of fourths""" @@ -101,9 +94,7 @@ def run(self): while True: self.process_button_presses() if time.monotonic() >= self.next_freq_change_allowed_at: - self.next_freq_change_allowed_at = ( - time.monotonic() + MIN_NOTE_PLAY_SECONDS - ) + self.next_freq_change_allowed_at = time.monotonic() + MIN_NOTE_PLAY_SECONDS self.change_tone_if_needed() @staticmethod @@ -119,9 +110,7 @@ def update_pixel(circle_pos): @staticmethod def tilt(): """Normalize the Y-Axis Tilt""" - standard_gravity = ( - 9.81 # Acceleration (m/s²) due to gravity at the earth’s surface - ) + standard_gravity = 9.81 # Acceleration (m/s²) due to gravity at the earth’s surface constrained_accel = min(max(0.0, -cp.acceleration[1]), standard_gravity) return constrained_accel / standard_gravity diff --git a/examples/circuitplayground_bluefruit_loud_sound.py b/examples/circuitplayground_bluefruit_loud_sound.py index 20ea3b7..1c97e96 100644 --- a/examples/circuitplayground_bluefruit_loud_sound.py +++ b/examples/circuitplayground_bluefruit_loud_sound.py @@ -7,7 +7,9 @@ NOTE: This example does NOT support Circuit Playground Express. """ + import time + from adafruit_circuitplayground import cp while True: diff --git a/examples/circuitplayground_bluefruit_loud_sound_threshold.py b/examples/circuitplayground_bluefruit_loud_sound_threshold.py index 81e882a..c0b6d83 100644 --- a/examples/circuitplayground_bluefruit_loud_sound_threshold.py +++ b/examples/circuitplayground_bluefruit_loud_sound_threshold.py @@ -7,7 +7,9 @@ NOTE: This example does NOT support Circuit Playground Express. """ + import time + from adafruit_circuitplayground import cp while True: diff --git a/examples/circuitplayground_bluefruit_play_mp3.py b/examples/circuitplayground_bluefruit_play_mp3.py index 369fa69..3bea0c8 100644 --- a/examples/circuitplayground_bluefruit_play_mp3.py +++ b/examples/circuitplayground_bluefruit_play_mp3.py @@ -6,6 +6,7 @@ NOTE: This example does NOT support Circuit Playground Express. """ + from adafruit_circuitplayground import cp while True: diff --git a/examples/circuitplayground_bluefruit_sound_level.py b/examples/circuitplayground_bluefruit_sound_level.py index 280487a..5ad2693 100644 --- a/examples/circuitplayground_bluefruit_sound_level.py +++ b/examples/circuitplayground_bluefruit_sound_level.py @@ -7,7 +7,9 @@ NOTE: This example does NOT support Circuit Playground Express. """ + import time + from adafruit_circuitplayground import cp while True: diff --git a/examples/circuitplayground_bluefruit_sound_level_plotter.py b/examples/circuitplayground_bluefruit_sound_level_plotter.py index eb21ec7..070def9 100644 --- a/examples/circuitplayground_bluefruit_sound_level_plotter.py +++ b/examples/circuitplayground_bluefruit_sound_level_plotter.py @@ -8,7 +8,9 @@ NOTE: This example does NOT support Circuit Playground Express. """ + import time + from adafruit_circuitplayground import cp while True: diff --git a/examples/circuitplayground_button_a.py b/examples/circuitplayground_button_a.py index f12cf25..5d78320 100644 --- a/examples/circuitplayground_button_a.py +++ b/examples/circuitplayground_button_a.py @@ -2,6 +2,7 @@ # SPDX-License-Identifier: MIT """This example turns on the little red LED when button A is pressed.""" + from adafruit_circuitplayground import cp while True: diff --git a/examples/circuitplayground_button_b.py b/examples/circuitplayground_button_b.py index 2efab1c..65558ac 100644 --- a/examples/circuitplayground_button_b.py +++ b/examples/circuitplayground_button_b.py @@ -2,10 +2,8 @@ # SPDX-License-Identifier: MIT """This example turns the little red LED on only while button B is currently being pressed.""" -from adafruit_circuitplayground import cp -# This code is written to be readable versus being Pylint compliant. -# pylint: disable=simplifiable-if-statement +from adafruit_circuitplayground import cp while True: if cp.button_b: diff --git a/examples/circuitplayground_buttons_1_neopixel.py b/examples/circuitplayground_buttons_1_neopixel.py index 26a6108..057ab27 100644 --- a/examples/circuitplayground_buttons_1_neopixel.py +++ b/examples/circuitplayground_buttons_1_neopixel.py @@ -3,6 +3,7 @@ """This example lights up the third NeoPixel while button A is being pressed, and lights up the eighth NeoPixel while button B is being pressed.""" + from adafruit_circuitplayground import cp cp.pixels.brightness = 0.3 diff --git a/examples/circuitplayground_buttons_neopixels.py b/examples/circuitplayground_buttons_neopixels.py index d633186..dade4b1 100644 --- a/examples/circuitplayground_buttons_neopixels.py +++ b/examples/circuitplayground_buttons_neopixels.py @@ -3,6 +3,7 @@ """This example lights up half the NeoPixels red while button A is being pressed, and half the NeoPixels green while button B is being pressed.""" + from adafruit_circuitplayground import cp cp.pixels.brightness = 0.3 diff --git a/examples/circuitplayground_ir_receive.py b/examples/circuitplayground_ir_receive.py index cab9970..bca803e 100644 --- a/examples/circuitplayground_ir_receive.py +++ b/examples/circuitplayground_ir_receive.py @@ -9,9 +9,11 @@ This example uses the IR receiver found near the center of the board. Works with another Circuit Playground Express running the circuitplayground_ir_transmit.py example. The NeoPixels will light up when the buttons on the TRANSMITTING Circuit Playground Express are pressed!""" -import pulseio -import board + import adafruit_irremote +import board +import pulseio + from adafruit_circuitplayground import cp # Create a 'pulseio' input, to listen to infrared signals on the IR receiver diff --git a/examples/circuitplayground_ir_transmit.py b/examples/circuitplayground_ir_transmit.py index a516dfe..3bb8e90 100644 --- a/examples/circuitplayground_ir_transmit.py +++ b/examples/circuitplayground_ir_transmit.py @@ -9,10 +9,13 @@ This example uses the IR transmitter found near the center of the board. Works with another Circuit Playground Express running the circuitplayground_ir_receive.py example. Press the buttons to light up the NeoPixels on the RECEIVING Circuit Playground Express!""" + import time -import pulseio -import board + import adafruit_irremote +import board +import pulseio + from adafruit_circuitplayground import cp # Create a 'PulseOut' output, to send infrared signals from the IR transmitter diff --git a/examples/circuitplayground_light.py b/examples/circuitplayground_light.py index e626b35..3f9d98d 100644 --- a/examples/circuitplayground_light.py +++ b/examples/circuitplayground_light.py @@ -4,7 +4,9 @@ """This example uses the light sensor on your Circuit Playground, located next to the picture of the eye. Try shining a flashlight on your Circuit Playground, or covering the light sensor with your finger to see the values increase and decrease.""" + import time + from adafruit_circuitplayground import cp while True: diff --git a/examples/circuitplayground_light_neopixels.py b/examples/circuitplayground_light_neopixels.py index d2f9f7f..da6dad1 100644 --- a/examples/circuitplayground_light_neopixels.py +++ b/examples/circuitplayground_light_neopixels.py @@ -9,6 +9,7 @@ """ import time + from adafruit_circuitplayground import cp cp.pixels.auto_write = False diff --git a/examples/circuitplayground_light_plotter.py b/examples/circuitplayground_light_plotter.py index 920d95a..73d3600 100644 --- a/examples/circuitplayground_light_plotter.py +++ b/examples/circuitplayground_light_plotter.py @@ -4,7 +4,9 @@ """If you're using Mu, this example will plot the light levels from the light sensor (located next to the eye) on your Circuit Playground. Try shining a flashlight on your Circuit Playground, or covering the light sensor to see the plot increase and decrease.""" + import time + from adafruit_circuitplayground import cp while True: diff --git a/examples/circuitplayground_neopixel_0.py b/examples/circuitplayground_neopixel_0.py index ae16b93..b39557f 100644 --- a/examples/circuitplayground_neopixel_0.py +++ b/examples/circuitplayground_neopixel_0.py @@ -2,6 +2,7 @@ # SPDX-License-Identifier: MIT """This example lights up the first NeoPixel red.""" + from adafruit_circuitplayground import cp cp.pixels.brightness = 0.3 diff --git a/examples/circuitplayground_neopixel_0_1.py b/examples/circuitplayground_neopixel_0_1.py index 77ed331..af09aaf 100644 --- a/examples/circuitplayground_neopixel_0_1.py +++ b/examples/circuitplayground_neopixel_0_1.py @@ -2,6 +2,7 @@ # SPDX-License-Identifier: MIT """This example lights up the first and second NeoPixel, red and blue respectively.""" + from adafruit_circuitplayground import cp cp.pixels.brightness = 0.3 diff --git a/examples/circuitplayground_neopixels_fill.py b/examples/circuitplayground_neopixels_fill.py index fce738d..d6b48b7 100644 --- a/examples/circuitplayground_neopixels_fill.py +++ b/examples/circuitplayground_neopixels_fill.py @@ -2,6 +2,7 @@ # SPDX-License-Identifier: MIT """This example lights up all the NeoPixel LEDs red.""" + from adafruit_circuitplayground import cp while True: diff --git a/examples/circuitplayground_pixels_simpletest.py b/examples/circuitplayground_pixels_simpletest.py index 9e9da05..dcb1966 100644 --- a/examples/circuitplayground_pixels_simpletest.py +++ b/examples/circuitplayground_pixels_simpletest.py @@ -2,8 +2,11 @@ # SPDX-License-Identifier: MIT """This example lights up the NeoPixels with a rainbow swirl.""" + import time + from rainbowio import colorwheel + from adafruit_circuitplayground import cp diff --git a/examples/circuitplayground_play_file.py b/examples/circuitplayground_play_file.py index a5f8df2..cee8239 100644 --- a/examples/circuitplayground_play_file.py +++ b/examples/circuitplayground_play_file.py @@ -8,6 +8,7 @@ Copy the "dip.wav" file to your CIRCUITPY drive. Once the file is copied, this example plays a wav file!""" + from adafruit_circuitplayground import cp cp.play_file("dip.wav") diff --git a/examples/circuitplayground_play_file_buttons.py b/examples/circuitplayground_play_file_buttons.py index 0045ee3..8c2cae0 100644 --- a/examples/circuitplayground_play_file_buttons.py +++ b/examples/circuitplayground_play_file_buttons.py @@ -8,6 +8,7 @@ Copy the "dip.wav" and "rise.wav" files to your CIRCUITPY drive. Once the files are copied, this example plays a different wav file for each button pressed!""" + from adafruit_circuitplayground import cp while True: diff --git a/examples/circuitplayground_play_tone.py b/examples/circuitplayground_play_tone.py index 855ebe1..479fcf9 100644 --- a/examples/circuitplayground_play_tone.py +++ b/examples/circuitplayground_play_tone.py @@ -3,6 +3,7 @@ """This example plays two tones for 1 second each. Note that the tones are not in a loop - this is to prevent them from playing indefinitely!""" + from adafruit_circuitplayground import cp cp.play_tone(262, 1) diff --git a/examples/circuitplayground_play_tone_buttons.py b/examples/circuitplayground_play_tone_buttons.py index 3b29037..62f8e52 100644 --- a/examples/circuitplayground_play_tone_buttons.py +++ b/examples/circuitplayground_play_tone_buttons.py @@ -2,6 +2,7 @@ # SPDX-License-Identifier: MIT """This example plays a different tone for a duration of 1 second for each button pressed.""" + from adafruit_circuitplayground import cp while True: diff --git a/examples/circuitplayground_red_led.py b/examples/circuitplayground_red_led.py index d0594dd..bfcccab 100644 --- a/examples/circuitplayground_red_led.py +++ b/examples/circuitplayground_red_led.py @@ -2,6 +2,7 @@ # SPDX-License-Identifier: MIT """This example turns on the little red LED.""" + from adafruit_circuitplayground import cp while True: diff --git a/examples/circuitplayground_red_led_blinky.py b/examples/circuitplayground_red_led_blinky.py index 114a59f..1609839 100644 --- a/examples/circuitplayground_red_led_blinky.py +++ b/examples/circuitplayground_red_led_blinky.py @@ -3,7 +3,9 @@ """This is the "Hello, world!" of CircuitPython: Blinky! This example blinks the little red LED on and off!""" + import time + from adafruit_circuitplayground import cp while True: diff --git a/examples/circuitplayground_red_led_blnky_short.py b/examples/circuitplayground_red_led_blnky_short.py index d8af7bf..ae3f543 100644 --- a/examples/circuitplayground_red_led_blnky_short.py +++ b/examples/circuitplayground_red_led_blnky_short.py @@ -3,7 +3,9 @@ """This is the "Hello, world!" of CircuitPython: Blinky! This example blinks the little red LED on and off! It's a shorter version of the other Blinky example.""" + import time + from adafruit_circuitplayground import cp while True: diff --git a/examples/circuitplayground_shake.py b/examples/circuitplayground_shake.py index e2971e1..0cc7f5e 100644 --- a/examples/circuitplayground_shake.py +++ b/examples/circuitplayground_shake.py @@ -2,6 +2,7 @@ # SPDX-License-Identifier: MIT """This example prints to the serial console when the Circuit Playground is shaken.""" + from adafruit_circuitplayground import cp while True: diff --git a/examples/circuitplayground_shake_red_led.py b/examples/circuitplayground_shake_red_led.py index d82818a..53d4f30 100644 --- a/examples/circuitplayground_shake_red_led.py +++ b/examples/circuitplayground_shake_red_led.py @@ -2,6 +2,7 @@ # SPDX-License-Identifier: MIT """This example flashes the little red LED when the Circuit Playground is shaken.""" + from adafruit_circuitplayground import cp while True: diff --git a/examples/circuitplayground_slide_switch.py b/examples/circuitplayground_slide_switch.py index 3531a1c..a0e22f3 100644 --- a/examples/circuitplayground_slide_switch.py +++ b/examples/circuitplayground_slide_switch.py @@ -3,7 +3,9 @@ """This example prints the status of the slide switch. Try moving the switch back and forth to see what's printed to the serial console!""" + import time + from adafruit_circuitplayground import cp while True: diff --git a/examples/circuitplayground_slide_switch_red_led.py b/examples/circuitplayground_slide_switch_red_led.py index 8e50a04..99f0b62 100644 --- a/examples/circuitplayground_slide_switch_red_led.py +++ b/examples/circuitplayground_slide_switch_red_led.py @@ -2,10 +2,8 @@ # SPDX-License-Identifier: MIT """This example uses the slide switch to control the little red LED.""" -from adafruit_circuitplayground import cp -# This code is written to be readable versus being Pylint compliant. -# pylint: disable=simplifiable-if-statement +from adafruit_circuitplayground import cp while True: if cp.switch: diff --git a/examples/circuitplayground_slide_switch_red_led_short.py b/examples/circuitplayground_slide_switch_red_led_short.py index 52666dd..8542370 100644 --- a/examples/circuitplayground_slide_switch_red_led_short.py +++ b/examples/circuitplayground_slide_switch_red_led_short.py @@ -3,6 +3,7 @@ """This example uses the slide switch to control the little red LED. When the switch is to the right it returns False, and when it's to the left, it returns True.""" + from adafruit_circuitplayground import cp while True: diff --git a/examples/circuitplayground_sound_meter.py b/examples/circuitplayground_sound_meter.py index 2567d8d..f5fd5f3 100644 --- a/examples/circuitplayground_sound_meter.py +++ b/examples/circuitplayground_sound_meter.py @@ -4,10 +4,13 @@ """This example uses the sound sensor, located next to the picture of the ear on your board, to light up the NeoPixels as a sound meter. Try talking to your Circuit Playground or clapping, etc, to see the NeoPixels light up!""" + import array import math -import board + import audiobusio +import board + from adafruit_circuitplayground import cp @@ -17,16 +20,13 @@ def constrain(value, floor, ceiling): def log_scale(input_value, input_min, input_max, output_min, output_max): normalized_input_value = (input_value - input_min) / (input_max - input_min) - return output_min + math.pow(normalized_input_value, 0.630957) * ( - output_max - output_min - ) + return output_min + math.pow(normalized_input_value, 0.630957) * (output_max - output_min) def normalized_rms(values): minbuf = int(sum(values) / len(values)) return math.sqrt( - sum(float(sample - minbuf) * (sample - minbuf) for sample in values) - / len(values) + sum(float(sample - minbuf) * (sample - minbuf) for sample in values) / len(values) ) diff --git a/examples/circuitplayground_tap_red_led.py b/examples/circuitplayground_tap_red_led.py index d51185d..2ed54c6 100644 --- a/examples/circuitplayground_tap_red_led.py +++ b/examples/circuitplayground_tap_red_led.py @@ -3,7 +3,9 @@ """This example turns on the little red LED and prints to the serial console when you double-tap the Circuit Playground!""" + import time + from adafruit_circuitplayground import cp # Change to 1 for detecting a single-tap! diff --git a/examples/circuitplayground_tapdetect.py b/examples/circuitplayground_tapdetect.py index bc03909..669c61f 100644 --- a/examples/circuitplayground_tapdetect.py +++ b/examples/circuitplayground_tapdetect.py @@ -2,7 +2,9 @@ # SPDX-License-Identifier: MIT """This example prints to the serial console when the board is double-tapped.""" + import time + from adafruit_circuitplayground import cp # Change to 1 for single-tap detection. diff --git a/examples/circuitplayground_tapdetect_single_double.py b/examples/circuitplayground_tapdetect_single_double.py index 63e6994..7f872cc 100644 --- a/examples/circuitplayground_tapdetect_single_double.py +++ b/examples/circuitplayground_tapdetect_single_double.py @@ -3,6 +3,7 @@ """This example shows how you can use single-tap and double-tap together with a delay between. Single-tap the board twice and then double-tap the board twice to complete the program.""" + from adafruit_circuitplayground import cp # Set to check for single-taps. diff --git a/examples/circuitplayground_temperature.py b/examples/circuitplayground_temperature.py index ec5c945..dbc3469 100644 --- a/examples/circuitplayground_temperature.py +++ b/examples/circuitplayground_temperature.py @@ -4,7 +4,9 @@ """This example uses the temperature sensor on the Circuit Playground, located next to the image of a thermometer on the board. It prints the temperature in both C and F to the serial console. Try putting your finger over the sensor to see the numbers change!""" + import time + from adafruit_circuitplayground import cp while True: diff --git a/examples/circuitplayground_temperature_neopixels.py b/examples/circuitplayground_temperature_neopixels.py index 6f219ae..ab77c40 100644 --- a/examples/circuitplayground_temperature_neopixels.py +++ b/examples/circuitplayground_temperature_neopixels.py @@ -7,7 +7,9 @@ increase, or cooling it down to see the number decrease. You can set the min and max temperatures to make it more or less sensitive to temperature changes. """ + import time + from adafruit_circuitplayground import cp cp.pixels.auto_write = False diff --git a/examples/circuitplayground_temperature_plotter.py b/examples/circuitplayground_temperature_plotter.py index edb1627..52c854b 100644 --- a/examples/circuitplayground_temperature_plotter.py +++ b/examples/circuitplayground_temperature_plotter.py @@ -4,7 +4,9 @@ """If you're using Mu, this example will plot the temperature in C and F on the plotter! Click "Plotter" to open it, and place your finger over the sensor to see the numbers change. The sensor is located next to the picture of the thermometer on the CPX.""" + import time + from adafruit_circuitplayground import cp while True: diff --git a/examples/circuitplayground_tone.py b/examples/circuitplayground_tone.py index 97b6030..a6de24e 100644 --- a/examples/circuitplayground_tone.py +++ b/examples/circuitplayground_tone.py @@ -2,6 +2,7 @@ # SPDX-License-Identifier: MIT """This example plays a different tone for each button, while the button is pressed.""" + from adafruit_circuitplayground import cp while True: diff --git a/examples/circuitplayground_touch_a1.py b/examples/circuitplayground_touch_a1.py index b026e04..f256078 100644 --- a/examples/circuitplayground_touch_a1.py +++ b/examples/circuitplayground_touch_a1.py @@ -2,6 +2,7 @@ # SPDX-License-Identifier: MIT """This example prints to the serial console when you touch capacitive touch pad A1.""" + from adafruit_circuitplayground import cp while True: diff --git a/examples/circuitplayground_touch_all.py b/examples/circuitplayground_touch_all.py index 9d6203e..9cdc55c 100644 --- a/examples/circuitplayground_touch_all.py +++ b/examples/circuitplayground_touch_all.py @@ -2,10 +2,12 @@ # SPDX-License-Identifier: MIT """This example prints to the serial console when you touch the capacitive touch pads.""" + import time + import board -from adafruit_circuitplayground import cp +from adafruit_circuitplayground import cp # You'll need to first use the touchpads individually to register them as active touchpads # You don't have to use the result though diff --git a/examples/circuitplayground_touch_pixel_fill_rainbow.py b/examples/circuitplayground_touch_pixel_fill_rainbow.py index cef84ce..479b261 100644 --- a/examples/circuitplayground_touch_pixel_fill_rainbow.py +++ b/examples/circuitplayground_touch_pixel_fill_rainbow.py @@ -4,7 +4,9 @@ """This example uses the capacitive touch pads on the Circuit Playground. They are located around the outer edge of the board and are labeled A1-A6 and TX. (A0 is not a touch pad.) This example lights up all the NeoPixels a different color of the rainbow for each pad touched!""" + import time + from adafruit_circuitplayground import cp cp.pixels.brightness = 0.3 diff --git a/examples/circuitplayground_touch_pixel_rainbow.py b/examples/circuitplayground_touch_pixel_rainbow.py index daeb003..97f19bc 100644 --- a/examples/circuitplayground_touch_pixel_rainbow.py +++ b/examples/circuitplayground_touch_pixel_rainbow.py @@ -4,7 +4,9 @@ """This example uses the capacitive touch pads on the Circuit Playground. They are located around the outer edge of the board and are labeled A1-A6 and TX. (A0 is not a touch pad.) This example lights up the nearest NeoPixel to that pad a different color of the rainbow!""" + import time + from adafruit_circuitplayground import cp cp.pixels.brightness = 0.3 diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 0000000..36332ff --- /dev/null +++ b/ruff.toml @@ -0,0 +1,105 @@ +# SPDX-FileCopyrightText: 2024 Tim Cocks for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +target-version = "py38" +line-length = 100 + +[lint] +preview = true +select = ["I", "PL", "UP"] + +extend-select = [ + "D419", # empty-docstring + "E501", # line-too-long + "W291", # trailing-whitespace + "PLC0414", # useless-import-alias + "PLC2401", # non-ascii-name + "PLC2801", # unnecessary-dunder-call + "PLC3002", # unnecessary-direct-lambda-call + "E999", # syntax-error + "PLE0101", # return-in-init + "F706", # return-outside-function + "F704", # yield-outside-function + "PLE0116", # continue-in-finally + "PLE0117", # nonlocal-without-binding + "PLE0241", # duplicate-bases + "PLE0302", # unexpected-special-method-signature + "PLE0604", # invalid-all-object + "PLE0605", # invalid-all-format + "PLE0643", # potential-index-error + "PLE0704", # misplaced-bare-raise + "PLE1141", # dict-iter-missing-items + "PLE1142", # await-outside-async + "PLE1205", # logging-too-many-args + "PLE1206", # logging-too-few-args + "PLE1307", # bad-string-format-type + "PLE1310", # bad-str-strip-call + "PLE1507", # invalid-envvar-value + "PLE2502", # bidirectional-unicode + "PLE2510", # invalid-character-backspace + "PLE2512", # invalid-character-sub + "PLE2513", # invalid-character-esc + "PLE2514", # invalid-character-nul + "PLE2515", # invalid-character-zero-width-space + "PLR0124", # comparison-with-itself + "PLR0202", # no-classmethod-decorator + "PLR0203", # no-staticmethod-decorator + "UP004", # useless-object-inheritance + "PLR0206", # property-with-parameters + "PLR0904", # too-many-public-methods + "PLR0911", # too-many-return-statements + "PLR0912", # too-many-branches + "PLR0913", # too-many-arguments + "PLR0914", # too-many-locals + "PLR0915", # too-many-statements + "PLR0916", # too-many-boolean-expressions + "PLR1702", # too-many-nested-blocks + "PLR1704", # redefined-argument-from-local + "PLR1711", # useless-return + "C416", # unnecessary-comprehension + "PLR1733", # unnecessary-dict-index-lookup + "PLR1736", # unnecessary-list-index-lookup + + # ruff reports this rule is unstable + #"PLR6301", # no-self-use + + "PLW0108", # unnecessary-lambda + "PLW0120", # useless-else-on-loop + "PLW0127", # self-assigning-variable + "PLW0129", # assert-on-string-literal + "B033", # duplicate-value + "PLW0131", # named-expr-without-context + "PLW0245", # super-without-brackets + "PLW0406", # import-self + "PLW0602", # global-variable-not-assigned + "PLW0603", # global-statement + "PLW0604", # global-at-module-level + + # fails on the try: import typing used by libraries + #"F401", # unused-import + + "F841", # unused-variable + "E722", # bare-except + "PLW0711", # binary-op-exception + "PLW1501", # bad-open-mode + "PLW1508", # invalid-envvar-default + "PLW1509", # subprocess-popen-preexec-fn + "PLW2101", # useless-with-lock + "PLW3301", # nested-min-max +] + +ignore = [ + "PLR2004", # magic-value-comparison + "UP030", # format literals + "PLW1514", # unspecified-encoding + "PLR0913", # too-many-arguments + "PLR0915", # too-many-statements + "PLR0917", # too-many-positional-arguments + "PLR0904", # too-many-public-methods + "PLR0912", # too-many-branches + "PLR0916", # too-many-boolean-expressions +] + +[format] +line-ending = "lf"