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 374676d..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: v3.3.1 + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.3.4 hooks: - - id: pylint - name: pylint (library code) - types: [python] - args: - - --disable=consider-using-f-string - exclude: "^(docs/|examples/|tests/|setup.py$)" - - id: pylint - name: pylint (example code) - description: Run pylint rules on "examples/*.py" files - types: [python] - files: "^examples/" - args: - - --disable=missing-docstring,invalid-name,consider-using-f-string,duplicate-code - - id: pylint - name: pylint (test code) - description: Run pylint rules on "tests/*.py" files - types: [python] - files: "^tests/" - args: - - --disable=missing-docstring,consider-using-f-string,duplicate-code + - id: ruff-format + - id: ruff + args: ["--fix"] + - repo: https://github.com/fsfe/reuse-tool + rev: v3.0.1 + hooks: + - id: reuse diff --git a/.pylintrc b/.pylintrc deleted file mode 100644 index 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 48e9ca9..c674acc 100644 --- a/README.rst +++ b/README.rst @@ -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 Library for the Adafruit PyCamera diff --git a/adafruit_pycamera/__init__.py b/adafruit_pycamera/__init__.py index 1ef4c94..e6d63ac 100644 --- a/adafruit_pycamera/__init__.py +++ b/adafruit_pycamera/__init__.py @@ -4,7 +4,6 @@ # SPDX-License-Identifier: MIT """Library for the Adafruit PyCamera with OV5640 autofocus module""" -# pylint: disable=too-many-lines import gc import os import struct @@ -19,10 +18,10 @@ import adafruit_lis3dh import bitmaptools import board -import displayio -import fourwire import busdisplay +import displayio import espcamera +import fourwire import microcontroller import neopixel import pwmio @@ -80,7 +79,7 @@ _NVM_TIMELAPSE_SUBMODE = const(5) -class PyCameraBase: # pylint: disable=too-many-instance-attributes,too-many-public-methods +class PyCameraBase: """Base class for PyCamera hardware Wrapper class for the PyCamera hardware with lots of smarts @@ -201,14 +200,14 @@ class PyCameraBase: # pylint: disable=too-many-instance-attributes,too-many-pub _INIT_SEQUENCE = ( b"\x01\x80\x78" # _SWRESET and Delay 120ms b"\x11\x80\x05" # _SLPOUT and Delay 5ms - b"\x3A\x01\x55" # _COLMOD + b"\x3a\x01\x55" # _COLMOD b"\x21\x00" # _INVON Hack b"\x13\x00" # _NORON - b"\x36\x01\xA0" # _MADCTL + b"\x36\x01\xa0" # _MADCTL b"\x29\x80\x05" # _DISPON and Delay 5ms ) - def __init__(self) -> None: # pylint: disable=too-many-statements + def __init__(self) -> None: displayio.release_displays() self._i2c = board.I2C() self._spi = board.SPI() @@ -273,7 +272,7 @@ def make_debounced_expander_pin(pin_no): pin.switch_to_input() return Debouncer(make_expander_input(pin_no)) - self.up = make_debounced_expander_pin(_AW_UP) # pylint: disable=invalid-name + self.up = make_debounced_expander_pin(_AW_UP) self.left = make_debounced_expander_pin(_AW_LEFT) self.right = make_debounced_expander_pin(_AW_RIGHT) self.down = make_debounced_expander_pin(_AW_DOWN) @@ -313,9 +312,7 @@ def check_for_update_needed(self): def make_camera_ui(self): """Create displayio widgets for the standard camera UI""" - self._sd_label = label.Label( - terminalio.FONT, text="SD ??", color=0x0, x=170, y=10, scale=2 - ) + self._sd_label = label.Label(terminalio.FONT, text="SD ??", color=0x0, x=170, y=10, scale=2) self._effect_label = label.Label( terminalio.FONT, text="EFFECT", color=0xFFFFFF, x=4, y=10, scale=2 ) @@ -323,9 +320,7 @@ def make_camera_ui(self): terminalio.FONT, text="MODE", color=0xFFFFFF, x=170, y=10, scale=2 ) self._topbar = displayio.Group() - self._res_label = label.Label( - terminalio.FONT, text="", color=0xFFFFFF, x=0, y=10, scale=2 - ) + self._res_label = label.Label(terminalio.FONT, text="", color=0xFFFFFF, x=0, y=10, scale=2) self._topbar.append(self._res_label) self._topbar.append(self._sd_label) @@ -365,9 +360,7 @@ def init_neopixel(self): neopix.deinit() # front bezel neopixels - self.pixels = neopixel.NeoPixel( - board.A1, 8, brightness=0.1, pixel_order=neopixel.RGBW - ) + self.pixels = neopixel.NeoPixel(board.A1, 8, brightness=0.1, pixel_order=neopixel.RGBW) self.pixels.fill(0) def init_camera(self, init_autofocus=True) -> None: @@ -470,9 +463,7 @@ def autofocus_init_from_bitstream(self, firmware: bytes): reg = offset + 0x8000 arr[0] = reg >> 8 arr[1] = reg & 0xFF - arr[2 : 2 + num_firmware_bytes] = firmware[ - offset : offset + num_firmware_bytes - ] + arr[2 : 2 + num_firmware_bytes] = firmware[offset : offset + num_firmware_bytes] i2c.write(arr, end=2 + num_firmware_bytes) self.write_camera_list(self._finalize_firmware_load) @@ -486,9 +477,7 @@ def autofocus_init_from_bitstream(self, firmware: bytes): def autofocus_init(self): """Initialize the autofocus engine from ov5640_autofocus.bin""" if "/" in __file__: - binfile = ( - __file__.rsplit("/", 1)[0].rsplit(".", 1)[0] + "/ov5640_autofocus.bin" - ) + binfile = __file__.rsplit("/", 1)[0].rsplit(".", 1)[0] + "/ov5640_autofocus.bin" else: binfile = "ov5640_autofocus.bin" print(binfile) @@ -499,7 +488,7 @@ def autofocus_status(self): """Read the camera autofocus status register""" return self.read_camera_register(_OV5640_CMD_FW_STATUS) - def _send_autofocus_command(self, command, msg): # pylint: disable=unused-argument + def _send_autofocus_command(self, command, msg): self.write_camera_register(_OV5640_CMD_ACK, 0x01) # clear command ack self.write_camera_register(_OV5640_CMD_MAIN, command) # send command for _ in range(100): @@ -519,18 +508,14 @@ def autofocus(self) -> list[int]: return [False] * 5 if not self._send_autofocus_command(_OV5640_CMD_TRIGGER_AUTOFOCUS, "autofocus"): return [False] * 5 - zone_focus = [ - self.read_camera_register(_OV5640_CMD_PARA0 + i) for i in range(5) - ] + zone_focus = [self.read_camera_register(_OV5640_CMD_PARA0 + i) for i in range(5)] print(f"zones focused: {zone_focus}") return zone_focus @property def autofocus_vcm_step(self): """Get the voice coil motor step location""" - if not self._send_autofocus_command( - _OV5640_CMD_AF_GET_VCM_STEP, "get vcm step" - ): + if not self._send_autofocus_command(_OV5640_CMD_AF_GET_VCM_STEP, "get vcm step"): return None return self.read_camera_register(_OV5640_CMD_PARA4) @@ -549,7 +534,7 @@ def select_setting(self, setting_name): self._effect_label.background_color = 0x0 self._res_label.color = 0xFFFFFF self._res_label.background_color = 0x0 - if self.mode_text in ("GIF", "GBOY"): + if self.mode_text in {"GIF", "GBOY"}: self._res_label.text = "" else: self._res_label.text = self.resolutions[self._resolution] @@ -601,7 +586,7 @@ def mode(self, setting): self._mode_label.text = self.modes[setting] if self.modes[setting] == "STOP": self.stop_motion_frame = 0 - if self.modes[setting] in ("GIF", "GBOY"): + if self.modes[setting] in {"GIF", "GBOY"}: self._res_label.text = "" else: self.resolution = self.resolution # kick it to reset the display @@ -656,9 +641,7 @@ def timelapse_rate(self, setting): if self.timelapse_rates[setting] < 60: self.timelapse_rate_label.text = "%d S" % self.timelapse_rates[setting] else: - self.timelapse_rate_label.text = "%d M" % ( - self.timelapse_rates[setting] / 60 - ) + self.timelapse_rate_label.text = "%d M" % (self.timelapse_rates[setting] / 60) microcontroller.nvm[_NVM_TIMELAPSE_RATE] = setting self.display.refresh() @@ -669,13 +652,9 @@ def timelapse_submode(self): @timelapse_submode.setter def timelapse_submode(self, setting): - setting = (setting + len(self.timelapse_submodes)) % len( - self.timelapse_submodes - ) + setting = (setting + len(self.timelapse_submodes)) % len(self.timelapse_submodes) self._timelapse_submode = setting - self.timelapse_submode_label.text = self.timelapse_submodes[ - self._timelapse_submode - ] + self.timelapse_submode_label.text = self.timelapse_submodes[self._timelapse_submode] microcontroller.nvm[_NVM_TIMELAPSE_SUBMODE] = setting def init_display(self): @@ -800,9 +779,7 @@ def keys_debounce(self): def tone(self, frequency, duration=0.1): """Play a tone on the internal speaker""" - with pwmio.PWMOut( - board.SPEAKER, frequency=int(frequency), variable_frequency=False - ) as pwm: + with pwmio.PWMOut(board.SPEAKER, frequency=int(frequency), variable_frequency=False) as pwm: self.mute.value = True pwm.duty_cycle = 0x8000 time.sleep(duration) @@ -874,10 +851,9 @@ def overlay(self) -> str: @overlay.setter def overlay(self, new_overlay_file: str) -> None: - # pylint: disable=import-outside-toplevel - from displayio import ColorConverter, Colorspace - import ulab.numpy as np import adafruit_imageload + import ulab.numpy as np + from displayio import ColorConverter, Colorspace if self.overlay_bmp is not None: self.overlay_bmp.deinit() @@ -891,7 +867,6 @@ def overlay(self, new_overlay_file: str) -> None: del arr def _init_jpeg_decoder(self): - # pylint: disable=import-outside-toplevel from jpegio import JpegDecoder """ @@ -908,10 +883,7 @@ def blit_overlay_into_last_capture(self): in a separate but similarly named .bmp file on the SDCard. """ if self.overlay_bmp is None: - raise ValueError( - "Must set overlay before calling blit_overlay_into_last_capture" - ) - # pylint: disable=import-outside-toplevel + raise ValueError("Must set overlay before calling blit_overlay_into_last_capture") from adafruit_bitmapsaver import save_pixels from displayio import Bitmap, ColorConverter, Colorspace @@ -955,7 +927,7 @@ def last_saved_filename(self) -> str: def continuous_capture_start(self): """Switch the camera to continuous-capture mode""" - pass # pylint: disable=unnecessary-pass + pass def capture_into_jpeg(self): """Captures an image and returns it in JPEG format. @@ -997,7 +969,6 @@ def blit(self, bitmap, x_offset=0, y_offset=32): The default preview capture is 240x176, leaving 32 pixel rows at the top and bottom for status information. """ - # pylint: disable=import-outside-toplevel from displayio import Bitmap if self.overlay_bmp is not None: @@ -1025,9 +996,7 @@ def blit(self, bitmap, x_offset=0, y_offset=32): self._display_bus.send( 42, struct.pack(">hh", 80 + x_offset, 80 + x_offset + bitmap.width - 1) ) - self._display_bus.send( - 43, struct.pack(">hh", y_offset, y_offset + bitmap.height - 1) - ) + self._display_bus.send(43, struct.pack(">hh", y_offset, y_offset + bitmap.height - 1)) self._display_bus.send(44, bitmap) @property @@ -1066,8 +1035,7 @@ def get_camera_autosettings(self): + (self.read_camera_register(0x3502) >> 4) ) white_balance = [ - self.read_camera_register(x) - for x in (0x3400, 0x3401, 0x3402, 0x3403, 0x3404, 0x3405) + self.read_camera_register(x) for x in (0x3400, 0x3401, 0x3402, 0x3403, 0x3404, 0x3405) ] settings = { @@ -1147,6 +1115,6 @@ def __init__(self, init_autofocus=True): try: self.mount_sd_card() - except Exception as exc: # pylint: disable=broad-exception-caught + except Exception as exc: # No SD card inserted, it's OK print(exc) diff --git a/adafruit_pycamera/imageprocessing.py b/adafruit_pycamera/imageprocessing.py index 98932aa..f218f08 100644 --- a/adafruit_pycamera/imageprocessing.py +++ b/adafruit_pycamera/imageprocessing.py @@ -84,7 +84,6 @@ def ironbow(bitmap, mask=None): return bitmapfilter.false_color(bitmap, ironbow_palette, mask=mask) -# pylint: disable=invalid-name def alphablend_maker(frac, nfrac=None): """Create an alpha-blending function for a specific fractional value diff --git a/docs/api.rst b/docs/api.rst index 4e86a8c..ac61409 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -4,6 +4,9 @@ .. 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_pycamera :members: .. automodule:: adafruit_pycamera.imageprocessing diff --git a/docs/conf.py b/docs/conf.py index 9993665..2ea50a3 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries # # SPDX-License-Identifier: MIT @@ -75,9 +73,7 @@ creation_year = "2023" 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 + " Jeff Epler for Adafruit Industries" author = "Jeff Epler for Adafruit Industries" diff --git a/examples/basic_camera/code.py b/examples/basic_camera/code.py index a58b4a3..ef2fd87 100644 --- a/examples/basic_camera/code.py +++ b/examples/basic_camera/code.py @@ -1,10 +1,11 @@ # SPDX-FileCopyrightText: Copyright (c) 2023 john park for Adafruit Industries # # SPDX-License-Identifier: MIT -""" simple point-and-shoot camera example. No bells! Zero whistles! """ +"""simple point-and-shoot camera example. No bells! Zero whistles!""" import time -import adafruit_pycamera # pylint: disable=import-error + +import adafruit_pycamera pycam = adafruit_pycamera.PyCamera() pycam.mode = 0 # only mode 0 (JPEG) will work in this example @@ -36,11 +37,11 @@ pycam.display_message("snap", color=0x00DD00) pycam.capture_jpeg() pycam.live_preview_mode() - except TypeError as exception: + except TypeError: pycam.display_message("Failed", color=0xFF0000) time.sleep(0.5) pycam.live_preview_mode() - except RuntimeError as exception: + except RuntimeError: pycam.display_message("Error\nNo SD Card", color=0xFF0000) time.sleep(0.5) diff --git a/examples/camera/boot.py b/examples/camera/boot.py index 84e2250..4106fc6 100644 --- a/examples/camera/boot.py +++ b/examples/camera/boot.py @@ -6,6 +6,7 @@ """Automatically create the /sd mount point at boot time""" import os + import storage storage.remount("/", readonly=False) diff --git a/examples/camera/code.py b/examples/camera/code.py index a03ea64..8c89f35 100644 --- a/examples/camera/code.py +++ b/examples/camera/code.py @@ -2,18 +2,19 @@ # SPDX-FileCopyrightText: 2023 Limor Fried for Adafruit Industries # # SPDX-License-Identifier: Unlicense -import ssl import os +import ssl import time -import socketpool -import adafruit_requests -import rtc + import adafruit_ntp -import wifi +import adafruit_requests import bitmaptools import displayio import gifio +import rtc +import socketpool import ulab.numpy as np +import wifi import adafruit_pycamera @@ -31,9 +32,7 @@ PASSWORD = os.getenv("CIRCUITPY_WIFI_PASSWORD") if SSID and PASSWORD: - wifi.radio.connect( - os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD") - ) + wifi.radio.connect(os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD")) if wifi.radio.connected: print(f"Connected to {os.getenv('CIRCUITPY_WIFI_SSID')}!") print("My IP address is", wifi.radio.ipv4_address) @@ -46,9 +45,7 @@ UTC_OFFSET = response_as_json["raw_offset"] + response_as_json["dst_offset"] print(f"UTC_OFFSET: {UTC_OFFSET}") - ntp = adafruit_ntp.NTP( - pool, server="pool.ntp.org", tz_offset=UTC_OFFSET // 3600 - ) + ntp = adafruit_ntp.NTP(pool, server="pool.ntp.org", tz_offset=UTC_OFFSET // 3600) print(f"ntp time: {ntp.datetime}") rtc.RTC().datetime = ntp.datetime @@ -103,13 +100,9 @@ pycam.timelapse_submode_label.text = pycam.timelapse_submode_label.text # only in high power mode do we continuously preview - if (timelapse_remaining is None) or ( - pycam.timelapse_submode_label.text == "HiPwr" - ): + if (timelapse_remaining is None) or (pycam.timelapse_submode_label.text == "HiPwr"): pycam.blit(pycam.continuous_capture()) - if pycam.timelapse_submode_label.text == "LowPwr" and ( - timelapse_remaining is not None - ): + if pycam.timelapse_submode_label.text == "LowPwr" and (timelapse_remaining is not None): pycam.display.brightness = 0.05 else: pycam.display.brightness = 1 @@ -122,18 +115,16 @@ try: pycam.display_message("Snap!", color=0x0000FF) pycam.capture_jpeg() - except TypeError as e: + except TypeError: pycam.display_message("Failed", color=0xFF0000) time.sleep(0.5) - except RuntimeError as e: + except RuntimeError: pycam.display_message("Error\nNo SD Card", color=0xFF0000) time.sleep(0.5) pycam.live_preview_mode() pycam.display.refresh() pycam.blit(pycam.continuous_capture()) - timelapse_timestamp = ( - time.time() + pycam.timelapse_rates[pycam.timelapse_rate] + 1 - ) + timelapse_timestamp = time.time() + pycam.timelapse_rates[pycam.timelapse_rate] + 1 else: pycam.blit(pycam.continuous_capture()) # print("\t\t", capture_time, blit_time) @@ -153,10 +144,10 @@ try: pycam.display_message("Snap!", color=0x0000FF) pycam.capture_jpeg() - except TypeError as e: + except TypeError: pycam.display_message("Failed", color=0xFF0000) time.sleep(0.5) - except RuntimeError as e: + except RuntimeError: pycam.display_message("Error\nNo SD Card", color=0xFF0000) time.sleep(0.5) pycam.live_preview_mode() @@ -164,7 +155,7 @@ if pycam.mode_text == "GBOY": try: f = pycam.open_next_image("gif") - except RuntimeError as e: + except RuntimeError: pycam.display_message("Error\nNo SD Card", color=0xFF0000) time.sleep(0.5) continue @@ -181,13 +172,13 @@ if pycam.mode_text == "GIF": try: f = pycam.open_next_image("gif") - except RuntimeError as e: + except RuntimeError: pycam.display_message("Error\nNo SD Card", color=0xFF0000) time.sleep(0.5) continue i = 0 ft = [] - pycam._mode_label.text = "RECORDING" # pylint: disable=protected-access + pycam._mode_label.text = "RECORDING" pycam.display.refresh() with gifio.GifWriter( @@ -207,7 +198,7 @@ ft.append(1 / (t1 - t0)) print(end=".") t0 = t1 - pycam._mode_label.text = "GIF" # pylint: disable=protected-access + pycam._mode_label.text = "GIF" print(f"\nfinal size {f.tell()} for {i} frames") print(f"average framerate {i / (t1 - t00)}fps") print(f"best {max(ft)} worst {min(ft)} std. deviation {np.std(ft)}") @@ -220,11 +211,11 @@ pycam.display_message("Snap!", color=0x0000FF) pycam.capture_jpeg() pycam.live_preview_mode() - except TypeError as e: + except TypeError: pycam.display_message("Failed", color=0xFF0000) time.sleep(0.5) pycam.live_preview_mode() - except RuntimeError as e: + except RuntimeError: pycam.display_message("Error\nNo SD Card", color=0xFF0000) time.sleep(0.5) diff --git a/examples/filter/code.py b/examples/filter/code.py index 207b55f..aacf487 100644 --- a/examples/filter/code.py +++ b/examples/filter/code.py @@ -11,16 +11,14 @@ Otherwise, effects cycle every DISPLAY_INTERVAL milliseconds (default 2000 = 2 seconds) """ +import bitmapfilter import displayio -from jpegio import JpegDecoder from adafruit_display_text.label import Label -from adafruit_ticks import ticks_less, ticks_ms, ticks_add, ticks_diff +from adafruit_ticks import ticks_add, ticks_diff, ticks_less, ticks_ms from font_free_mono_bold_24 import FONT -import bitmapfilter - -from adafruit_pycamera import imageprocessing -from adafruit_pycamera import PyCameraBase +from jpegio import JpegDecoder +from adafruit_pycamera import PyCameraBase, imageprocessing blend_50_50 = bitmapfilter.blend_precompute(imageprocessing.alphablend_maker(0.5)) screen = bitmapfilter.blend_precompute(imageprocessing.screen_func) @@ -130,9 +128,7 @@ def sketch(b): ("solarize", bitmapfilter.solarize), ( "swap r/b", - lambda b: bitmapfilter.mix( - b, bitmapfilter.ChannelMixer(0, 0, 1, 0, 1, 0, 1, 0, 0) - ), + lambda b: bitmapfilter.mix(b, bitmapfilter.ChannelMixer(0, 0, 1, 0, 1, 0, 1, 0, 0)), ), ] diff --git a/examples/overlay/code_select.py b/examples/overlay/code_select.py index 665d4e2..6735c53 100644 --- a/examples/overlay/code_select.py +++ b/examples/overlay/code_select.py @@ -2,14 +2,16 @@ # SPDX-FileCopyrightText: Copyright (c) 2024 Tim Cocks for Adafruit Industries # # SPDX-License-Identifier: MIT -""" simple point-and-shoot camera example, with overly selecting using select button. +"""simple point-and-shoot camera example, with overly selecting using select button. Place all overlay files inside /sd/overlays/ directory. """ + import os import time import traceback -import adafruit_pycamera # pylint: disable=import-error + +import adafruit_pycamera MODE_POSITION = 0 MODE_SCALE = 1 @@ -57,19 +59,13 @@ if CURRENT_MODE == MODE_POSITION: if not pycam.down.value: - pycam.overlay_position[1] += 1 * ( - int(pycam.down.current_duration / 0.3) + 1 - ) + pycam.overlay_position[1] += 1 * (int(pycam.down.current_duration / 0.3) + 1) if not pycam.up.value: pycam.overlay_position[1] -= 1 * (int(pycam.up.current_duration / 0.3) + 1) if not pycam.left.value: - pycam.overlay_position[0] -= 1 * ( - int(pycam.left.current_duration / 0.3) + 1 - ) + pycam.overlay_position[0] -= 1 * (int(pycam.left.current_duration / 0.3) + 1) if not pycam.right.value: - pycam.overlay_position[0] += 1 * ( - int(pycam.right.current_duration / 0.3) + 1 - ) + pycam.overlay_position[0] += 1 * (int(pycam.right.current_duration / 0.3) + 1) if CURRENT_MODE == MODE_SCALE: if pycam.down.fell: int_scale -= 10 @@ -98,7 +94,7 @@ pycam.display_message("Failed", color=0xFF0000) time.sleep(0.5) pycam.live_preview_mode() - except RuntimeError as exception: + except RuntimeError: pycam.display_message("Error\nNo SD Card", color=0xFF0000) time.sleep(0.5) diff --git a/examples/overlay/code_simple.py b/examples/overlay/code_simple.py index ffcea6a..4bd821f 100644 --- a/examples/overlay/code_simple.py +++ b/examples/overlay/code_simple.py @@ -2,11 +2,12 @@ # SPDX-FileCopyrightText: Copyright (c) 2024 Tim Cocks for Adafruit Industries # # SPDX-License-Identifier: MIT -""" simple point-and-shoot camera example, with an overlay frame image. """ +"""simple point-and-shoot camera example, with an overlay frame image.""" import time import traceback -import adafruit_pycamera # pylint: disable=import-error + +import adafruit_pycamera pycam = adafruit_pycamera.PyCamera() pycam.mode = 0 # only mode 0 (JPEG) will work in this example @@ -47,7 +48,7 @@ pycam.display_message("Failed", color=0xFF0000) time.sleep(0.5) pycam.live_preview_mode() - except RuntimeError as exception: + except RuntimeError: pycam.display_message("Error\nNo SD Card", color=0xFF0000) time.sleep(0.5) diff --git a/examples/qrio/code.py b/examples/qrio/code.py index bc04fb3..026106f 100644 --- a/examples/qrio/code.py +++ b/examples/qrio/code.py @@ -14,8 +14,8 @@ from adafruit_pycamera import PyCamera pycam = PyCamera() -pycam._mode_label.text = "QR SCAN" # pylint: disable=protected-access -pycam._res_label.text = "" # pylint: disable=protected-access +pycam._mode_label.text = "QR SCAN" +pycam._res_label.text = "" pycam.effect = 0 pycam.camera.hmirror = False pycam.display.refresh() diff --git a/examples/timestamp_filename/code.py b/examples/timestamp_filename/code.py index 05c2a2e..3dfebcc 100644 --- a/examples/timestamp_filename/code.py +++ b/examples/timestamp_filename/code.py @@ -1,18 +1,20 @@ # SPDX-FileCopyrightText: Copyright (c) 2024 Tim Cocks for Adafruit Industries # # SPDX-License-Identifier: MIT -""" simple point-and-shoot camera example. With NTP and internal RTC to - add timestamp to photo filenames. Must install adafruit_ntp library! - Example code assumes WIFI credentials are properly setup and web workflow - enabled in settings.toml. If not, you'll need to add code to manually connect - to your network.""" +"""simple point-and-shoot camera example. With NTP and internal RTC to +add timestamp to photo filenames. Must install adafruit_ntp library! +Example code assumes WIFI credentials are properly setup and web workflow +enabled in settings.toml. If not, you'll need to add code to manually connect +to your network.""" import time -import wifi -import socketpool -import rtc + import adafruit_ntp -import adafruit_pycamera # pylint: disable=import-error +import rtc +import socketpool +import wifi + +import adafruit_pycamera pool = socketpool.SocketPool(wifi.radio) ntp = adafruit_ntp.NTP(pool, tz_offset=0) @@ -46,21 +48,14 @@ pycam.tone(1600, 0.05) try: pycam.display_message("snap", color=0x00DD00) - timestamp = "img_{}-{}-{}_{:02}-{:02}-{:02}_".format( - time.localtime().tm_year, - time.localtime().tm_mon, - time.localtime().tm_mday, - time.localtime().tm_hour, - time.localtime().tm_min, - time.localtime().tm_sec, - ) + timestamp = f"img_{time.localtime().tm_year}-{time.localtime().tm_mon}-{time.localtime().tm_mday}_{time.localtime().tm_hour:02}-{time.localtime().tm_min:02}-{time.localtime().tm_sec:02}_" # noqa: E501 pycam.capture_jpeg(filename_prefix=timestamp) pycam.live_preview_mode() - except TypeError as exception: + except TypeError: pycam.display_message("Failed", color=0xFF0000) time.sleep(0.5) pycam.live_preview_mode() - except RuntimeError as exception: + except RuntimeError: pycam.display_message("Error\nNo SD Card", color=0xFF0000) time.sleep(0.5) diff --git a/examples/viewer/code.py b/examples/viewer/code.py index 51abc6b..db7d387 100644 --- a/examples/viewer/code.py +++ b/examples/viewer/code.py @@ -12,11 +12,13 @@ Otherwise, images cycle every DISPLAY_INTERVAL milliseconds (default 8000 = 8 seconds) """ -import time import os +import time + import displayio +from adafruit_ticks import ticks_add, ticks_diff, ticks_less, ticks_ms from jpegio import JpegDecoder -from adafruit_ticks import ticks_less, ticks_ms, ticks_add, ticks_diff + from adafruit_pycamera import PyCameraBase DISPLAY_INTERVAL = 8000 # milliseconds @@ -83,9 +85,7 @@ def mount_sd(): pycam.display_message("SD Card\nFailed!", color=0xFF0000) time.sleep(0.5) all_images = [ - f"/sd/{filename}" - for filename in os.listdir("/sd") - if filename.lower().endswith(".jpg") + f"/sd/{filename}" for filename in os.listdir("/sd") if filename.lower().endswith(".jpg") ] pycam.display_message(f"Found {len(all_images)}\nimages", color=0xFFFFFF) time.sleep(0.5) @@ -143,7 +143,7 @@ def main(): image_counter = (image_counter + 1) % len(all_images) try: load_resized_image(bitmap, filename) - except Exception as e: # pylint: disable=broad-exception-caught + except Exception as e: pycam.display_message(f"Failed to read\n{filename}", color=0xFF0000) print(e) deadline = ticks_add(now, 500) diff --git a/examples/web_camera/code.py b/examples/web_camera/code.py index 55cc82b..4b0d777 100644 --- a/examples/web_camera/code.py +++ b/examples/web_camera/code.py @@ -51,8 +51,7 @@ def body(): request, body, headers={ - "Content-Type": "multipart/x-mixed-replace; boundary=%s" - % BOUNDARY.decode("ascii") + "Content-Type": "multipart/x-mixed-replace; boundary=%s" % BOUNDARY.decode("ascii") }, ) diff --git a/examples/web_settings_explorer/code.py b/examples/web_settings_explorer/code.py index 696e584..e6f3cd4 100644 --- a/examples/web_settings_explorer/code.py +++ b/examples/web_settings_explorer/code.py @@ -69,17 +69,13 @@ def lcd(request: Request) -> Response: def take_jpeg(request: Request) -> Response: pycam.camera.reconfigure( pixel_format=espcamera.PixelFormat.JPEG, - frame_size=pycam.resolution_to_frame_size[ - pycam._resolution # pylint: disable=protected-access - ], + frame_size=pycam.resolution_to_frame_size[pycam._resolution], ) try: jpeg = pycam.camera.take(1) if jpeg is not None: return Response(request, bytes(jpeg), content_type="image/jpeg") - return Response( - request, "", content_type="text/plain", status=INTERNAL_SERVER_ERROR_500 - ) + return Response(request, "", content_type="text/plain", status=INTERNAL_SERVER_ERROR_500) finally: pycam.live_preview_mode() @@ -109,13 +105,13 @@ def property_common(obj, request): try: current_value = getattr(obj, propname, None) return JSONResponse(request, current_value) - except Exception as exc: # pylint: disable=broad-exception-caught + except Exception as exc: return Response(request, {"error": str(exc)}, status=BAD_REQUEST_400) else: new_value = json.loads(value) setattr(obj, propname, new_value) return JSONResponse(request, {"status": "OK"}) - except Exception as exc: # pylint: disable=broad-exception-caught + except Exception as exc: return JSONResponse(request, {"error": str(exc)}, status=BAD_REQUEST_400) diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 0000000..73e9efc --- /dev/null +++ b/ruff.toml @@ -0,0 +1,108 @@ +# SPDX-FileCopyrightText: 2024 Tim Cocks for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +target-version = "py38" +line-length = 100 + +[lint] +preview = true +select = ["I", "PL", "UP"] + +extend-select = [ + "D419", # empty-docstring + "E501", # line-too-long + "W291", # trailing-whitespace + "PLC0414", # useless-import-alias + "PLC2401", # non-ascii-name + "PLC2801", # unnecessary-dunder-call + "PLC3002", # unnecessary-direct-lambda-call + "E999", # syntax-error + "PLE0101", # return-in-init + "F706", # return-outside-function + "F704", # yield-outside-function + "PLE0116", # continue-in-finally + "PLE0117", # nonlocal-without-binding + "PLE0241", # duplicate-bases + "PLE0302", # unexpected-special-method-signature + "PLE0604", # invalid-all-object + "PLE0605", # invalid-all-format + "PLE0643", # potential-index-error + "PLE0704", # misplaced-bare-raise + "PLE1141", # dict-iter-missing-items + "PLE1142", # await-outside-async + "PLE1205", # logging-too-many-args + "PLE1206", # logging-too-few-args + "PLE1307", # bad-string-format-type + "PLE1310", # bad-str-strip-call + "PLE1507", # invalid-envvar-value + "PLE2502", # bidirectional-unicode + "PLE2510", # invalid-character-backspace + "PLE2512", # invalid-character-sub + "PLE2513", # invalid-character-esc + "PLE2514", # invalid-character-nul + "PLE2515", # invalid-character-zero-width-space + "PLR0124", # comparison-with-itself + "PLR0202", # no-classmethod-decorator + "PLR0203", # no-staticmethod-decorator + "UP004", # useless-object-inheritance + "PLR0206", # property-with-parameters + "PLR0904", # too-many-public-methods + "PLR0911", # too-many-return-statements + "PLR0912", # too-many-branches + "PLR0913", # too-many-arguments + "PLR0914", # too-many-locals + "PLR0915", # too-many-statements + "PLR0916", # too-many-boolean-expressions + "PLR1702", # too-many-nested-blocks + "PLR1704", # redefined-argument-from-local + "PLR1711", # useless-return + "C416", # unnecessary-comprehension + "PLR1733", # unnecessary-dict-index-lookup + "PLR1736", # unnecessary-list-index-lookup + + # ruff reports this rule is unstable + #"PLR6301", # no-self-use + + "PLW0108", # unnecessary-lambda + "PLW0120", # useless-else-on-loop + "PLW0127", # self-assigning-variable + "PLW0129", # assert-on-string-literal + "B033", # duplicate-value + "PLW0131", # named-expr-without-context + "PLW0245", # super-without-brackets + "PLW0406", # import-self + "PLW0602", # global-variable-not-assigned + "PLW0603", # global-statement + "PLW0604", # global-at-module-level + + # fails on the try: import typing used by libraries + #"F401", # unused-import + + "F841", # unused-variable + "E722", # bare-except + "PLW0711", # binary-op-exception + "PLW1501", # bad-open-mode + "PLW1508", # invalid-envvar-default + "PLW1509", # subprocess-popen-preexec-fn + "PLW2101", # useless-with-lock + "PLW3301", # nested-min-max +] + +ignore = [ + "PLR2004", # magic-value-comparison + "UP030", # format literals + "PLW1514", # unspecified-encoding + "PLR0913", # too-many-arguments + "PLR0915", # too-many-statements + "PLR0917", # too-many-positional-arguments + "PLR0904", # too-many-public-methods + "PLR0912", # too-many-branches + "PLR0916", # too-many-boolean-expressions + "PLR6301", # could-be-static no-self-use + "PLC0415", # import outside toplevel + "PLC2701", # private import +] + +[format] +line-ending = "lf"