From 79eb6fcade1c883cf27867bc2c24a3de859087e9 Mon Sep 17 00:00:00 2001 From: Matt Land Date: Mon, 24 Apr 2023 15:43:13 -0600 Subject: [PATCH 01/31] initial typing support, mypy passes add missing copyright statements to .pre-commit-config.yaml, gitignore --- .gitignore | 3 + .pre-commit-config.yaml | 14 +++ adafruit_rgb_display/hx8353.py | 20 ++++- adafruit_rgb_display/hx8357.py | 30 ++++--- adafruit_rgb_display/ili9341.py | 34 +++++--- adafruit_rgb_display/rgb.py | 148 ++++++++++++++++++++------------ adafruit_rgb_display/s6d02a1.py | 31 ++++++- adafruit_rgb_display/ssd1331.py | 36 +++++--- adafruit_rgb_display/ssd1351.py | 38 ++++---- adafruit_rgb_display/st7735.py | 98 +++++++++++---------- adafruit_rgb_display/st7789.py | 39 +++++---- mypy.ini | 22 +++++ optional_requirements.txt | 5 ++ 13 files changed, 346 insertions(+), 172 deletions(-) create mode 100644 mypy.ini diff --git a/.gitignore b/.gitignore index 871d9a7..7d6346a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ # SPDX-FileCopyrightText: 2022 Kattni Rembor, written for Adafruit Industries +# SPDX-FileCopyrightText: 2023 Matt Land # # SPDX-License-Identifier: MIT @@ -47,3 +48,5 @@ _build .idea .vscode *~ + +.mypy_cache/ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 6996f9c..5cedefc 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,4 +1,5 @@ # SPDX-FileCopyrightText: 2020 Diego Elio Pettenò +# SPDX-FileCopyrightText: 2023 Matt Land # # SPDX-License-Identifier: Unlicense @@ -40,3 +41,16 @@ repos: files: "^tests/" args: - --disable=missing-docstring,consider-using-f-string,duplicate-code + - repo: local + hooks: + - id: mypy + name: mypy (library code) + entry: "mypy adafruit_rgb_display" + language: python + additional_dependencies: ["mypy==1.2.0"] + types: [python] + exclude: "^(docs/|examples/|tests/|setup.py$)" + # use require_serial so that script + # is only called once per commit + require_serial: true + pass_filenames: false diff --git a/adafruit_rgb_display/hx8353.py b/adafruit_rgb_display/hx8353.py index 69819a8..2aaf712 100644 --- a/adafruit_rgb_display/hx8353.py +++ b/adafruit_rgb_display/hx8353.py @@ -1,4 +1,5 @@ # SPDX-FileCopyrightText: 2017 Radomir Dopieralski for Adafruit Industries +# SPDX-FileCopyrightText: 2023 Matt Land # # SPDX-License-Identifier: MIT @@ -8,11 +9,17 @@ A simple driver for the HX8353-based displays. -* Author(s): Radomir Dopieralski, Michael McWethy +* Author(s): Radomir Dopieralski, Michael McWethy, Matt Land """ from micropython import const from adafruit_rgb_display.rgb import DisplaySPI +try: + from typing import Optional + import digitalio + import busio +except ImportError: + pass __version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RGB_Display.git" @@ -59,5 +66,14 @@ class HX8353(DisplaySPI): _ENCODE_POS = ">HH" # pylint: disable-msg=useless-super-delegation, too-many-arguments - def __init__(self, spi, dc, cs, rst=None, width=128, height=128, rotation=0): + def __init__( + self, + spi: busio.SPI, + dc: digitalio.DigitalInOut, + cs: digitalio.DigitalInOut, + rst: Optional[digitalio.DigitalInOut] = None, + width: int = 128, + height: int = 128, + rotation: int = 0, + ) -> None: super().__init__(spi, dc, cs, rst, width, height, rotation) diff --git a/adafruit_rgb_display/hx8357.py b/adafruit_rgb_display/hx8357.py index 556f107..dfb9e2f 100755 --- a/adafruit_rgb_display/hx8357.py +++ b/adafruit_rgb_display/hx8357.py @@ -1,4 +1,5 @@ # SPDX-FileCopyrightText: 2019 Melissa LeBlanc-Williams for Adafruit Industries +# SPDX-FileCopyrightText: 2023 Matt Land # # SPDX-License-Identifier: MIT @@ -8,11 +9,18 @@ A simple driver for the HX8357-based displays. -* Author(s): Melissa LeBlanc-Williams +* Author(s): Melissa LeBlanc-Williams, Matt Land """ from micropython import const from adafruit_rgb_display.rgb import DisplaySPI +try: + from typing import Optional + import digitalio + import busio +except ImportError: + pass + __version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RGB_Display.git" @@ -94,16 +102,16 @@ class HX8357(DisplaySPI): # pylint: disable-msg=useless-super-delegation, too-many-arguments def __init__( self, - spi, - dc, - cs, - rst=None, - width=480, - height=320, - baudrate=16000000, - polarity=0, - phase=0, - rotation=0, + spi: busio.SPI, + dc: digitalio.DigitalInOut, + cs: digitalio.DigitalInOut, + rst: Optional[digitalio.DigitalInOut] = None, + width: int = 480, + height: int = 320, + baudrate: int = 16000000, + polarity: int = 0, + phase: int = 0, + rotation: int = 0, ): super().__init__( spi, diff --git a/adafruit_rgb_display/ili9341.py b/adafruit_rgb_display/ili9341.py index a01c38b..bb90093 100644 --- a/adafruit_rgb_display/ili9341.py +++ b/adafruit_rgb_display/ili9341.py @@ -1,4 +1,5 @@ # SPDX-FileCopyrightText: 2017 Radomir Dopieralski for Adafruit Industries +# SPDX-FileCopyrightText: 2023 Matt Land # # SPDX-License-Identifier: MIT @@ -8,12 +9,19 @@ A simple driver for the ILI9341/ILI9340-based displays. -* Author(s): Radomir Dopieralski, Michael McWethy +* Author(s): Radomir Dopieralski, Michael McWethy, Matt Land """ import struct from adafruit_rgb_display.rgb import DisplaySPI +try: + from typing import Optional + import digitalio + import busio +except ImportError: + pass + __version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RGB_Display.git" @@ -74,16 +82,16 @@ class ILI9341(DisplaySPI): # pylint: disable-msg=too-many-arguments def __init__( self, - spi, - dc, - cs, - rst=None, - width=240, - height=320, - baudrate=16000000, - polarity=0, - phase=0, - rotation=0, + spi: busio.SPI, + dc: digitalio.DigitalInOut, + cs: digitalio.DigitalInOut, + rst: Optional[digitalio.DigitalInOut] = None, + width: int = 240, + height: int = 320, + baudrate: int = 16000000, + polarity: int = 0, + phase: int = 0, + rotation: int = 0, ): super().__init__( spi, @@ -101,7 +109,9 @@ def __init__( # pylint: enable-msg=too-many-arguments - def scroll(self, dy=None): # pylint: disable-msg=invalid-name + def scroll( + self, dy: Optional[int] = None # pylint: disable-msg=invalid-name + ) -> Optional[int]: """Scroll the display by delta y""" if dy is None: return self._scroll diff --git a/adafruit_rgb_display/rgb.py b/adafruit_rgb_display/rgb.py index 1486203..c9b3233 100644 --- a/adafruit_rgb_display/rgb.py +++ b/adafruit_rgb_display/rgb.py @@ -1,4 +1,5 @@ # SPDX-FileCopyrightText: 2017 Radomir Dopieralski for Adafruit Industries +# SPDX-FileCopyrightText: 2023 Matt Land # # SPDX-License-Identifier: MIT @@ -8,12 +9,21 @@ Base class for all RGB Display devices -* Author(s): Radomir Dopieralski, Michael McWethy +* Author(s): Radomir Dopieralski, Michael McWethy, Matt Land """ import struct import time +try: + from typing import Optional, Union, Tuple, List, Any, ByteString + import digitalio + import busio + + Image = Any # from PIL import Image +except ImportError: + pass + try: import numpy except ImportError: @@ -36,18 +46,22 @@ pass -def color565(r, g=0, b=0): +def color565( + r: Union[int, Tuple[int, int, int], List[int]], + g: int = 0, + b: int = 0, +) -> int: """Convert red, green and blue values (0-255) into a 16-bit 565 encoding. As a convenience this is also available in the parent adafruit_rgb_display package namespace.""" - try: - r, g, b = r # see if the first var is a tuple/list - except TypeError: - pass - return (r & 0xF8) << 8 | (g & 0xFC) << 3 | b >> 3 + if not isinstance(r, int): # see if the first var is a tuple/list + red, g, b = r + else: + red = r + return (red & 0xF8) << 8 | (g & 0xFC) << 3 | b >> 3 -def image_to_data(image): +def image_to_data(image: Image) -> Any: """Generator function to convert a PIL image to 16-bit 565 RGB bytes.""" # NumPy is much faster at doing this. NumPy code provided by: # Keith (https://www.blogger.com/profile/02555547344016007163) @@ -63,37 +77,39 @@ def image_to_data(image): class DummyPin: """Can be used in place of a ``DigitalInOut()`` when you don't want to skip it.""" - def deinit(self): + def deinit(self) -> None: """Dummy DigitalInOut deinit""" - def switch_to_output(self, *args, **kwargs): + def switch_to_output( + self, *, value: bool = False, drive_mode: Optional[digitalio.DriveMode] = None + ) -> None: """Dummy switch_to_output method""" - def switch_to_input(self, *args, **kwargs): + def switch_to_input(self, *, pull: Optional[digitalio.Pull] = None) -> None: """Dummy switch_to_input method""" @property - def value(self): + def value(self) -> digitalio.DigitalInOut: """Dummy value DigitalInOut property""" @value.setter - def value(self, val): + def value(self, val: digitalio.DigitalInOut) -> None: pass @property - def direction(self): + def direction(self) -> digitalio.Direction: """Dummy direction DigitalInOut property""" @direction.setter - def direction(self, val): + def direction(self, val: digitalio.Direction) -> None: pass @property - def pull(self): + def pull(self) -> digitalio.Pull: """Dummy pull DigitalInOut property""" @pull.setter - def pull(self, val): + def pull(self, val: digitalio.Pull) -> None: pass @@ -103,18 +119,18 @@ class Display: # pylint: disable-msg=no-member :param height: number of pixels high """ - _PAGE_SET = None - _COLUMN_SET = None - _RAM_WRITE = None - _RAM_READ = None + _PAGE_SET: Optional[int] = None + _COLUMN_SET: Optional[int] = None + _RAM_WRITE: Optional[int] = None + _RAM_READ: Optional[int] = None _X_START = 0 # pylint: disable=invalid-name _Y_START = 0 # pylint: disable=invalid-name - _INIT = () + _INIT: Tuple[Tuple[int, Union[ByteString, None]], ...] = () _ENCODE_PIXEL = ">H" _ENCODE_POS = ">HH" _DECODE_PIXEL = ">BBB" - def __init__(self, width, height, rotation): + def __init__(self, width: int, height: int, rotation: int) -> None: self.width = width self.height = height if rotation not in (0, 90, 180, 270): @@ -122,13 +138,25 @@ def __init__(self, width, height, rotation): self._rotation = rotation self.init() - def init(self): + def write( + self, command: Optional[int] = None, data: Optional[ByteString] = None + ) -> None: + """Abstract method""" + raise NotImplementedError() + + def read(self, command: Optional[int] = None, count: int = 0) -> ByteString: + """Abstract method""" + raise NotImplementedError() + + def init(self) -> None: """Run the initialization commands.""" for command, data in self._INIT: self.write(command, data) # pylint: disable-msg=invalid-name,too-many-arguments - def _block(self, x0, y0, x1, y1, data=None): + def _block( + self, x0: int, y0: int, x1: int, y1: int, data: Optional[ByteString] = None + ) -> Optional[ByteString]: """Read or write a block of data.""" self.write( self._COLUMN_SET, self._encode_pos(x0 + self._X_START, x1 + self._X_START) @@ -144,28 +172,34 @@ def _block(self, x0, y0, x1, y1, data=None): # pylint: enable-msg=invalid-name,too-many-arguments - def _encode_pos(self, x, y): - """Encode a postion into bytes.""" + def _encode_pos(self, x: int, y: int) -> bytes: + """Encode a position into bytes.""" return struct.pack(self._ENCODE_POS, x, y) - def _encode_pixel(self, color): + def _encode_pixel(self, color: Any) -> bytes: """Encode a pixel color into bytes.""" return struct.pack(self._ENCODE_PIXEL, color) - def _decode_pixel(self, data): + def _decode_pixel(self, data: Union[bytes, Union[bytearray, memoryview]]) -> int: """Decode bytes into a pixel color.""" return color565(*struct.unpack(self._DECODE_PIXEL, data)) - def pixel(self, x, y, color=None): + def pixel(self, x: int, y: int, color: Optional[Any] = None) -> Optional[int]: """Read or write a pixel at a given position.""" if color is None: - return self._decode_pixel(self._block(x, y, x, y)) + return self._decode_pixel(self._block(x, y, x, y)) # type: ignore[arg-type] if 0 <= x < self.width and 0 <= y < self.height: self._block(x, y, x, y, self._encode_pixel(color)) return None - def image(self, img, rotation=None, x=0, y=0): + def image( + self, + img: Image, + rotation: Optional[int] = None, + x: int = 0, + y: int = 0, + ) -> None: """Set buffer to value of Python Imaging Library image. The image should be in 1 bit mode and a size not exceeding the display size when drawn at the supplied origin.""" @@ -197,7 +231,9 @@ def image(self, img, rotation=None, x=0, y=0): self._block(x, y, x + imwidth - 1, y + imheight - 1, pixels) # pylint: disable-msg=too-many-arguments - def fill_rectangle(self, x, y, width, height, color): + def fill_rectangle( + self, x: int, y: int, width: int, height: int, color: Any + ) -> None: """Draw a rectangle at specified position with specified width and height, and fill it with the specified color.""" x = min(self.width - 1, max(0, x)) @@ -215,25 +251,25 @@ def fill_rectangle(self, x, y, width, height, color): # pylint: enable-msg=too-many-arguments - def fill(self, color=0): + def fill(self, color: Any = 0) -> None: """Fill the whole display with the specified color.""" self.fill_rectangle(0, 0, self.width, self.height, color) - def hline(self, x, y, width, color): + def hline(self, x: int, y: int, width: int, color: Any) -> None: """Draw a horizontal line.""" self.fill_rectangle(x, y, width, 1, color) - def vline(self, x, y, height, color): + def vline(self, x: int, y: int, height: int, color: Any) -> None: """Draw a vertical line.""" self.fill_rectangle(x, y, 1, height, color) @property - def rotation(self): + def rotation(self) -> int: """Set the default rotation""" return self._rotation @rotation.setter - def rotation(self, val): + def rotation(self, val: int) -> None: if val not in (0, 90, 180, 270): raise ValueError("Rotation must be 0/90/180/270") self._rotation = val @@ -245,19 +281,19 @@ class DisplaySPI(Display): # pylint: disable-msg=too-many-arguments def __init__( self, - spi, - dc, - cs, - rst=None, - width=1, - height=1, - baudrate=12000000, - polarity=0, - phase=0, + spi: busio.SPI, + dc: digitalio.DigitalInOut, + cs: digitalio.DigitalInOut, + rst: Optional[digitalio.DigitalInOut] = None, + width: int = 1, + height: int = 1, + baudrate: int = 12000000, + polarity: int = 0, + phase: int = 0, *, - x_offset=0, - y_offset=0, - rotation=0 + x_offset: int = 0, + y_offset: int = 0, + rotation: int = 0 ): self.spi_device = spi_device.SPIDevice( spi, cs, baudrate=baudrate, polarity=polarity, phase=phase @@ -274,15 +310,19 @@ def __init__( # pylint: enable-msg=too-many-arguments - def reset(self): + def reset(self) -> None: """Reset the device""" + if not self.rst: + raise RuntimeError("a reset pin was not provided") self.rst.value = 0 time.sleep(0.050) # 50 milliseconds self.rst.value = 1 time.sleep(0.050) # 50 milliseconds # pylint: disable=no-member - def write(self, command=None, data=None): + def write( + self, command: Optional[int] = None, data: Optional[ByteString] = None + ) -> None: """SPI write to the device: commands and data""" if command is not None: self.dc_pin.value = 0 @@ -293,13 +333,13 @@ def write(self, command=None, data=None): with self.spi_device as spi: spi.write(data) - def read(self, command=None, count=0): + def read(self, command: Optional[int] = None, count: int = 0) -> ByteString: """SPI read from device with optional command""" data = bytearray(count) self.dc_pin.value = 0 with self.spi_device as spi: if command is not None: - spi.write(bytearray([command])) + spi.write(bytearray([command])) # change to self.write() if count: spi.readinto(data) return data diff --git a/adafruit_rgb_display/s6d02a1.py b/adafruit_rgb_display/s6d02a1.py index 92cd2d1..568cdec 100644 --- a/adafruit_rgb_display/s6d02a1.py +++ b/adafruit_rgb_display/s6d02a1.py @@ -1,4 +1,5 @@ # SPDX-FileCopyrightText: 2017 Radomir Dopieralski for Adafruit Industries +# SPDX-FileCopyrightText: 2023 Matt Land # # SPDX-License-Identifier: MIT @@ -8,12 +9,19 @@ A simple driver for the S6D02A1-based displays. -* Author(s): Radomir Dopieralski, Michael McWethy +* Author(s): Radomir Dopieralski, Michael McWethy, Matt Land """ from micropython import const from adafruit_rgb_display.rgb import DisplaySPI +try: + from typing import Optional + import digitalio + import busio +except ImportError: + pass + __version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RGB_Display.git" @@ -59,5 +67,22 @@ class S6D02A1(DisplaySPI): _ENCODE_POS = ">HH" # pylint: disable-msg=useless-super-delegation, too-many-arguments - def __init__(self, spi, dc, cs, rst=None, width=128, height=160, rotation=0): - super().__init__(spi, dc, cs, rst, width, height, rotation) + def __init__( + self, + spi: busio.SPI, + dc: digitalio.DigitalInOut, + cs: digitalio.DigitalInOut, + rst: Optional[digitalio.DigitalInOut] = None, + width: int = 128, + height: int = 160, + rotation: int = 0, + ): + super().__init__( + spi=spi, + dc=dc, + cs=cs, + rst=rst, + width=width, + height=height, + rotation=rotation, + ) diff --git a/adafruit_rgb_display/ssd1331.py b/adafruit_rgb_display/ssd1331.py index 6fd0e90..167afe1 100644 --- a/adafruit_rgb_display/ssd1331.py +++ b/adafruit_rgb_display/ssd1331.py @@ -1,4 +1,5 @@ # SPDX-FileCopyrightText: 2017 Radomir Dopieralski for Adafruit Industries +# SPDX-FileCopyrightText: 2023 Matt Land # # SPDX-License-Identifier: MIT @@ -8,12 +9,19 @@ A simple driver for the SSD1331-based displays. -* Author(s): Radomir Dopieralski, Michael McWethy +* Author(s): Radomir Dopieralski, Michael McWethy, Matt Land """ from micropython import const from adafruit_rgb_display.rgb import DisplaySPI +try: + from typing import Optional, ByteString + import digitalio + import busio +except ImportError: + pass + __version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RGB_Display.git" @@ -107,18 +115,18 @@ class SSD1331(DisplaySPI): # super required to allow override of default values def __init__( self, - spi, - dc, - cs, - rst=None, - width=96, - height=64, - baudrate=16000000, - polarity=0, - phase=0, + spi: busio.SPI, + dc: digitalio.DigitalInOut, + cs: digitalio.DigitalInOut, + rst: Optional[digitalio.DigitalInOut] = None, + width: int = 96, + height: int = 64, + baudrate: int = 16000000, + polarity: int = 0, + phase: int = 0, *, - rotation=0 - ): + rotation: int = 0 + ) -> None: super().__init__( spi, dc, @@ -133,7 +141,9 @@ def __init__( ) # pylint: disable=no-member - def write(self, command=None, data=None): + def write( + self, command: Optional[int] = None, data: Optional[ByteString] = None + ) -> None: """write procedure specific to SSD1331""" self.dc_pin.value = command is None with self.spi_device as spi: diff --git a/adafruit_rgb_display/ssd1351.py b/adafruit_rgb_display/ssd1351.py index cc5e5b8..03e58ab 100644 --- a/adafruit_rgb_display/ssd1351.py +++ b/adafruit_rgb_display/ssd1351.py @@ -1,4 +1,5 @@ # SPDX-FileCopyrightText: 2017 Radomir Dopieralski for Adafruit Industries +# SPDX-FileCopyrightText: 2023 Matt Land # # SPDX-License-Identifier: MIT @@ -8,11 +9,18 @@ A simple driver for the SSD1351-based displays. -* Author(s): Radomir Dopieralski, Michael McWethy +* Author(s): Radomir Dopieralski, Michael McWethy, Matt Land """ from micropython import const from adafruit_rgb_display.rgb import DisplaySPI +try: + from typing import Optional + import digitalio + import busio +except ImportError: + pass + __version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RGB_Display.git" @@ -99,22 +107,20 @@ class SSD1351(DisplaySPI): # pylint: disable-msg=useless-super-delegation, too-many-arguments def __init__( self, - spi, - dc, - cs, - rst=None, - width=128, - height=128, - baudrate=16000000, - polarity=0, - phase=0, + spi: busio.SPI, + dc: digitalio.DigitalInOut, + cs: digitalio.DigitalInOut, + rst: Optional[digitalio.DigitalInOut] = None, + width: int = 128, + height: int = 128, + baudrate: int = 16000000, + polarity: int = 0, + phase: int = 0, *, - x_offset=0, - y_offset=0, - rotation=0 + x_offset: int = 0, + y_offset: int = 0, + rotation: int = 0 ): - baudrate = min(baudrate, 16000000) # Limit to Display Max Baudrate - super().__init__( spi, dc, @@ -122,7 +128,7 @@ def __init__( rst, width, height, - baudrate=baudrate, + baudrate=min(baudrate, 16000000), # Limit to Display Max Baudrate polarity=polarity, phase=phase, x_offset=x_offset, diff --git a/adafruit_rgb_display/st7735.py b/adafruit_rgb_display/st7735.py index ca86edc..daa5020 100644 --- a/adafruit_rgb_display/st7735.py +++ b/adafruit_rgb_display/st7735.py @@ -1,4 +1,5 @@ # SPDX-FileCopyrightText: 2017 Radomir Dopieralski for Adafruit Industries +# SPDX-FileCopyrightText: 2023 Matt Land # # SPDX-License-Identifier: MIT @@ -8,13 +9,20 @@ A simple driver for the ST7735-based displays. -* Author(s): Radomir Dopieralski, Michael McWethy +* Author(s): Radomir Dopieralski, Michael McWethy, Matt Land """ import struct from micropython import const from adafruit_rgb_display.rgb import DisplaySPI +try: + from typing import Optional, Tuple, ByteString, Union + import digitalio + import busio +except ImportError: + pass + __version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RGB_Display.git" @@ -113,27 +121,27 @@ class ST7735(DisplaySPI): (_RASET, b"\x00\x02\x00\x81"), # XSTART = 2, XEND = 129 (_NORON, None), (_DISPON, None), - ) + ) # type: Tuple[Tuple[int, Union[ByteString, None]], ...] _ENCODE_PIXEL = ">H" _ENCODE_POS = ">HH" # pylint: disable-msg=useless-super-delegation, too-many-arguments def __init__( self, - spi, - dc, - cs, - rst=None, - width=128, - height=128, - baudrate=16000000, - polarity=0, - phase=0, + spi: busio.SPI, + dc: digitalio.DigitalInOut, + cs: digitalio.DigitalInOut, + rst: Optional[digitalio.DigitalInOut] = None, + width: int = 128, + height: int = 128, + baudrate: int = 16000000, + polarity: int = 0, + phase: int = 0, *, - x_offset=0, - y_offset=0, - rotation=0, - ): + x_offset: int = 0, + y_offset: int = 0, + rotation: int = 0, + ) -> None: super().__init__( spi, dc, @@ -182,22 +190,22 @@ class ST7735R(ST7735): # pylint: disable-msg=useless-super-delegation, too-many-arguments def __init__( self, - spi, - dc, - cs, - rst=None, - width=128, - height=160, - baudrate=16000000, - polarity=0, - phase=0, + spi: busio.SPI, + dc: digitalio.DigitalInOut, + cs: digitalio.DigitalInOut, + rst: Optional[digitalio] = None, + width: int = 128, + height: int = 160, + baudrate: int = 16000000, + polarity: int = 0, + phase: int = 0, *, - x_offset=0, - y_offset=0, - rotation=0, - bgr=False, - invert=False, - ): + x_offset: int = 0, + y_offset: int = 0, + rotation: int = 0, + bgr: bool = False, + invert: bool = False, + ) -> None: self._bgr = bgr self._invert = invert super().__init__( @@ -215,7 +223,7 @@ def __init__( rotation=rotation, ) - def init(self): + def init(self) -> None: super().init() cols = struct.pack(">HH", 0, self.width - 1) rows = struct.pack(">HH", 0, self.height - 1) @@ -271,21 +279,21 @@ class ST7735S(ST7735): # pylint: disable-msg=useless-super-delegation, too-many-arguments def __init__( self, - spi, - dc, - cs, - bl, - rst=None, - width=128, - height=160, - baudrate=16000000, - polarity=0, - phase=0, + spi: busio.SPI, + dc: digitalio.DigitalInOut, + cs: digitalio.DigitalInOut, + bl: digitalio.DigitalInOut, # Backlight + rst: Optional[digitalio.DigitalInOut] = None, + width: int = 128, + height: int = 160, + baudrate: int = 16000000, + polarity: int = 0, + phase: int = 0, *, - x_offset=2, - y_offset=1, - rotation=0, - ): + x_offset: int = 2, + y_offset: int = 1, + rotation: int = 0, + ) -> None: self._bl = bl # Turn on backlight self._bl.switch_to_output(value=1) diff --git a/adafruit_rgb_display/st7789.py b/adafruit_rgb_display/st7789.py index af57686..3fcfc43 100644 --- a/adafruit_rgb_display/st7789.py +++ b/adafruit_rgb_display/st7789.py @@ -1,4 +1,5 @@ # SPDX-FileCopyrightText: 2019 Melissa LeBlanc-Williams for Adafruit Industries +# SPDX-FileCopyrightText: 2023 Matt Land # # SPDX-License-Identifier: MIT @@ -8,14 +9,21 @@ A simple driver for the ST7789-based displays. -* Author(s): Melissa LeBlanc-Williams +* Author(s): Melissa LeBlanc-Williams, Matt Land """ import struct +import busio +import digitalio from micropython import const from adafruit_rgb_display.rgb import DisplaySPI +try: + from typing import Optional +except ImportError: + pass + __version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RGB_Display.git" @@ -96,20 +104,20 @@ class ST7789(DisplaySPI): # pylint: disable-msg=useless-super-delegation, too-many-arguments def __init__( self, - spi, - dc, - cs, - rst=None, - width=240, - height=320, - baudrate=16000000, - polarity=0, - phase=0, + spi: busio.SPI, + dc: digitalio.DigitalInOut, + cs: digitalio.DigitalInOut, + rst: Optional[digitalio.DigitalInOut] = None, + width: int = 240, + height: int = 320, + baudrate: int = 16000000, + polarity: int = 0, + phase: int = 0, *, - x_offset=0, - y_offset=0, - rotation=0 - ): + x_offset: int = 0, + y_offset: int = 0, + rotation: int = 0 + ) -> None: super().__init__( spi, dc, @@ -125,8 +133,7 @@ def __init__( rotation=rotation, ) - def init(self): - + def init(self) -> None: super().init() cols = struct.pack(">HH", self._X_START, self.width + self._X_START) rows = struct.pack(">HH", self._Y_START, self.height + self._Y_START) diff --git a/mypy.ini b/mypy.ini new file mode 100644 index 0000000..8bf7236 --- /dev/null +++ b/mypy.ini @@ -0,0 +1,22 @@ +# SPDX-FileCopyrightText: 2023 Matt Land +# +# SPDX-License-Identifier: Unlicense +[mypy] +python_version = 3.7 +disallow_untyped_defs = True +exclude = (examples|tests|setup.py|docs) + +[mypy-digitalio] +ignore_missing_imports = True + +[mypy-busio] +ignore_missing_imports = True + +[mypy-numpy] +ignore_missing_imports = True + +[mypy-adafruit_bus_device] +ignore_missing_imports = True + +[mypy-micropython] +ignore_missing_imports = True diff --git a/optional_requirements.txt b/optional_requirements.txt index d4e27c4..595a870 100644 --- a/optional_requirements.txt +++ b/optional_requirements.txt @@ -1,3 +1,8 @@ # SPDX-FileCopyrightText: 2022 Alec Delaney, for Adafruit Industries +# SPDX-FileCopyrightText: 2023 Matt Land # # SPDX-License-Identifier: Unlicense + +#adafruit_bus_device +#numpy +#PIL From 5aa898f3e0e0f5674346c81324150128a0493871 Mon Sep 17 00:00:00 2001 From: Matt Land Date: Mon, 24 Apr 2023 17:25:13 -0600 Subject: [PATCH 02/31] Add Color Type, change Image type, remove mypy pre-commit hook, remove comment --- .pre-commit-config.yaml | 14 -------------- adafruit_rgb_display/rgb.py | 18 ++++++++++-------- 2 files changed, 10 insertions(+), 22 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 5cedefc..6996f9c 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,5 +1,4 @@ # SPDX-FileCopyrightText: 2020 Diego Elio Pettenò -# SPDX-FileCopyrightText: 2023 Matt Land # # SPDX-License-Identifier: Unlicense @@ -41,16 +40,3 @@ repos: files: "^tests/" args: - --disable=missing-docstring,consider-using-f-string,duplicate-code - - repo: local - hooks: - - id: mypy - name: mypy (library code) - entry: "mypy adafruit_rgb_display" - language: python - additional_dependencies: ["mypy==1.2.0"] - types: [python] - exclude: "^(docs/|examples/|tests/|setup.py$)" - # use require_serial so that script - # is only called once per commit - require_serial: true - pass_filenames: false diff --git a/adafruit_rgb_display/rgb.py b/adafruit_rgb_display/rgb.py index c9b3233..48710e5 100644 --- a/adafruit_rgb_display/rgb.py +++ b/adafruit_rgb_display/rgb.py @@ -20,7 +20,7 @@ import digitalio import busio - Image = Any # from PIL import Image + from circuitpython_typing.pil import Image except ImportError: pass @@ -176,7 +176,7 @@ def _encode_pos(self, x: int, y: int) -> bytes: """Encode a position into bytes.""" return struct.pack(self._ENCODE_POS, x, y) - def _encode_pixel(self, color: Any) -> bytes: + def _encode_pixel(self, color: Union[int, Tuple]) -> bytes: """Encode a pixel color into bytes.""" return struct.pack(self._ENCODE_PIXEL, color) @@ -184,7 +184,9 @@ def _decode_pixel(self, data: Union[bytes, Union[bytearray, memoryview]]) -> int """Decode bytes into a pixel color.""" return color565(*struct.unpack(self._DECODE_PIXEL, data)) - def pixel(self, x: int, y: int, color: Optional[Any] = None) -> Optional[int]: + def pixel( + self, x: int, y: int, color: Optional[Union[int, Tuple]] = None + ) -> Optional[int]: """Read or write a pixel at a given position.""" if color is None: return self._decode_pixel(self._block(x, y, x, y)) # type: ignore[arg-type] @@ -232,7 +234,7 @@ def image( # pylint: disable-msg=too-many-arguments def fill_rectangle( - self, x: int, y: int, width: int, height: int, color: Any + self, x: int, y: int, width: int, height: int, color: Union[int, Tuple] ) -> None: """Draw a rectangle at specified position with specified width and height, and fill it with the specified color.""" @@ -251,15 +253,15 @@ def fill_rectangle( # pylint: enable-msg=too-many-arguments - def fill(self, color: Any = 0) -> None: + def fill(self, color: Union[int, Tuple] = 0) -> None: """Fill the whole display with the specified color.""" self.fill_rectangle(0, 0, self.width, self.height, color) - def hline(self, x: int, y: int, width: int, color: Any) -> None: + def hline(self, x: int, y: int, width: int, color: Union[int, Tuple]) -> None: """Draw a horizontal line.""" self.fill_rectangle(x, y, width, 1, color) - def vline(self, x: int, y: int, height: int, color: Any) -> None: + def vline(self, x: int, y: int, height: int, color: Union[int, Tuple]) -> None: """Draw a vertical line.""" self.fill_rectangle(x, y, 1, height, color) @@ -339,7 +341,7 @@ def read(self, command: Optional[int] = None, count: int = 0) -> ByteString: self.dc_pin.value = 0 with self.spi_device as spi: if command is not None: - spi.write(bytearray([command])) # change to self.write() + spi.write(bytearray([command])) if count: spi.readinto(data) return data From 2c7e95d1dd53944ff458a6246cb681e4c8f36fbb Mon Sep 17 00:00:00 2001 From: Matt Land Date: Tue, 25 Apr 2023 08:13:04 -0600 Subject: [PATCH 03/31] requested changes, fix DummyPin::value return --- adafruit_rgb_display/rgb.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adafruit_rgb_display/rgb.py b/adafruit_rgb_display/rgb.py index 48710e5..5c906f7 100644 --- a/adafruit_rgb_display/rgb.py +++ b/adafruit_rgb_display/rgb.py @@ -89,7 +89,7 @@ def switch_to_input(self, *, pull: Optional[digitalio.Pull] = None) -> None: """Dummy switch_to_input method""" @property - def value(self) -> digitalio.DigitalInOut: + def value(self) -> bool: """Dummy value DigitalInOut property""" @value.setter From f29eb23984bf655900ae4a8bbcbb19cbfaffbf41 Mon Sep 17 00:00:00 2001 From: Alec Delaney <89490472+tekktrik@users.noreply.github.com> Date: Fri, 28 Apr 2023 08:26:43 -0400 Subject: [PATCH 04/31] Fix Optional type annotation --- adafruit_rgb_display/st7735.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adafruit_rgb_display/st7735.py b/adafruit_rgb_display/st7735.py index daa5020..0191a15 100644 --- a/adafruit_rgb_display/st7735.py +++ b/adafruit_rgb_display/st7735.py @@ -193,7 +193,7 @@ def __init__( spi: busio.SPI, dc: digitalio.DigitalInOut, cs: digitalio.DigitalInOut, - rst: Optional[digitalio] = None, + rst: Optional[digitalio.DigitalInOut] = None, width: int = 128, height: int = 160, baudrate: int = 16000000, From 46c3e46cbe9c4c6e2ea7b118be399e681ec9cb10 Mon Sep 17 00:00:00 2001 From: Tekktrik Date: Tue, 9 May 2023 20:26:25 -0400 Subject: [PATCH 05/31] Update pre-commit hooks Signed-off-by: Tekktrik --- .pre-commit-config.yaml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 6996f9c..179cf07 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -4,21 +4,21 @@ repos: - repo: https://github.com/python/black - rev: 22.3.0 + rev: 23.3.0 hooks: - id: black - repo: https://github.com/fsfe/reuse-tool - rev: v0.14.0 + rev: v1.1.2 hooks: - id: reuse - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.2.0 + rev: v4.4.0 hooks: - id: check-yaml - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/pycqa/pylint - rev: v2.15.5 + rev: v2.17.4 hooks: - id: pylint name: pylint (library code) From 3a313a3239067f9c7960d389bb21030f254e0848 Mon Sep 17 00:00:00 2001 From: Alec Delaney <89490472+tekktrik@users.noreply.github.com> Date: Tue, 23 May 2023 22:22:54 -0400 Subject: [PATCH 06/31] Update .pylintrc, fix jQuery for docs --- .pylintrc | 2 +- docs/conf.py | 1 + docs/requirements.txt | 1 + 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.pylintrc b/.pylintrc index 40208c3..f945e92 100644 --- a/.pylintrc +++ b/.pylintrc @@ -396,4 +396,4 @@ min-public-methods=1 # Exceptions that will emit a warning when being caught. Defaults to # "Exception" -overgeneral-exceptions=Exception +overgeneral-exceptions=builtins.Exception diff --git a/docs/conf.py b/docs/conf.py index 33a0204..4118015 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -17,6 +17,7 @@ # ones. extensions = [ "sphinx.ext.autodoc", + "sphinxcontrib.jquery", "sphinx.ext.intersphinx", "sphinx.ext.viewcode", ] diff --git a/docs/requirements.txt b/docs/requirements.txt index 88e6733..797aa04 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -3,3 +3,4 @@ # SPDX-License-Identifier: Unlicense sphinx>=4.0.0 +sphinxcontrib-jquery From 0603368370cd3c0852f39a67b5667228016ca18b Mon Sep 17 00:00:00 2001 From: Melissa LeBlanc-Williams Date: Wed, 5 Jul 2023 11:05:37 -0700 Subject: [PATCH 07/31] Update examples to work with Pillow 10.0.0 --- examples/rgb_display_pillow_animated_gif.py | 2 +- examples/rgb_display_pillow_image.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/rgb_display_pillow_animated_gif.py b/examples/rgb_display_pillow_animated_gif.py index a268a2b..cc3a628 100644 --- a/examples/rgb_display_pillow_animated_gif.py +++ b/examples/rgb_display_pillow_animated_gif.py @@ -124,7 +124,7 @@ def preload(self): frame_object.image = ImageOps.pad( # pylint: disable=no-member image.convert("RGB"), (self._width, self._height), - method=Image.Resampling.NEAREST, + method=Image.NEAREST, color=(0, 0, 0), centering=(0.5, 0.5), ) diff --git a/examples/rgb_display_pillow_image.py b/examples/rgb_display_pillow_image.py index 1eb641c..b463106 100644 --- a/examples/rgb_display_pillow_image.py +++ b/examples/rgb_display_pillow_image.py @@ -86,7 +86,7 @@ else: scaled_width = width scaled_height = image.height * width // image.width -image = image.resize((scaled_width, scaled_height), Image.Resampling.BICUBIC) +image = image.resize((scaled_width, scaled_height), Image.BICUBIC) # Crop and center the image x = scaled_width // 2 - width // 2 From 07e240f531f038e864ff01937ba5b2eac2be8a81 Mon Sep 17 00:00:00 2001 From: Kattni Rembor Date: Tue, 29 Aug 2023 18:45:32 -0400 Subject: [PATCH 08/31] Add EYESPI Beret GIF player demo. --- .../rgb_display_eyespi_beret_animated_gif.py | 215 ++++++++++++++++++ 1 file changed, 215 insertions(+) create mode 100644 examples/rgb_display_eyespi_beret_animated_gif.py diff --git a/examples/rgb_display_eyespi_beret_animated_gif.py b/examples/rgb_display_eyespi_beret_animated_gif.py new file mode 100644 index 0000000..2ac205b --- /dev/null +++ b/examples/rgb_display_eyespi_beret_animated_gif.py @@ -0,0 +1,215 @@ +# SPDX-FileCopyrightText: 2021 Melissa LeBlanc Williams for Adafruit Industries +# SPDX-License-Identifier: MIT + +""" +EYESPI Pi Beret GIF Player Demo + +Extracts the frames and other parameters from an animated gif +and then runs the animation on the display. + +Save this file as eyespi_beret_gif_player.py to your Raspberry Pi. + +Usage: +python3 eyespi_beret_gif_player.py + +This example is for use on Raspberry Pi that are using CPython with +Adafruit Blinka to support CircuitPython libraries. CircuitPython does +not support PIL/pillow (python imaging library)! + +Author(s): Melissa LeBlanc-Williams for Adafruit Industries + Mike Mallett +""" +import os +import time +import digitalio +import board +from PIL import Image, ImageOps +import numpy # pylint: disable=unused-import +from adafruit_rgb_display import ili9341 +from adafruit_rgb_display import st7789 # pylint: disable=unused-import +from adafruit_rgb_display import hx8357 # pylint: disable=unused-import +from adafruit_rgb_display import st7735 # pylint: disable=unused-import +from adafruit_rgb_display import ssd1351 # pylint: disable=unused-import +from adafruit_rgb_display import ssd1331 # pylint: disable=unused-import + +# Button pins for EYESPI Pi Beret +BUTTON_NEXT = board.D5 +BUTTON_PREVIOUS = board.D6 + +# CS and DC pins for EYEPSPI Pi Beret: +cs_pin = digitalio.DigitalInOut(board.CE0) +dc_pin = digitalio.DigitalInOut(board.D25) + +# Reset pin for EYESPI Pi Beret +reset_pin = digitalio.DigitalInOut(board.D27) + +# Backlight pin for Pi Beret +backlight = digitalio.DigitalInOut(board.D18) +backlight.switch_to_output() +backlight.value = True + +# Config for display baudrate (default max is 64mhz): +BAUDRATE = 64000000 + +# Setup SPI bus using hardware SPI: +spi = board.SPI() + +# pylint: disable=line-too-long +# fmt: off +# Create the display. +disp = ili9341.ILI9341(spi, rotation=90, # 2.2", 2.4", 2.8", 3.2" ILI9341 +# disp = st7789.ST7789(spi, rotation=90, # 2.0" ST7789 +# disp = st7789.ST7789(spi, height=240, y_offset=80, rotation=180, # 1.3", 1.54" ST7789 +# disp = st7789.ST7789(spi, rotation=90, width=135, height=240, x_offset=53, y_offset=40, # 1.14" ST7789 +# disp = st7789.ST7789(spi, rotation=90, width=172, height=320, x_offset=34, # 1.47" ST7789 +# disp = st7789.ST7789(spi, rotation=270, width=170, height=320, x_offset=35, # 1.9" ST7789 +# disp = hx8357.HX8357(spi, rotation=180, # 3.5" HX8357 +# disp = st7735.ST7735R(spi, rotation=90, # 1.8" ST7735R +# disp = st7735.ST7735R(spi, rotation=270, height=128, x_offset=2, y_offset=3, # 1.44" ST7735R +# disp = st7735.ST7735R(spi, rotation=90, bgr=True, width=80, # 0.96" MiniTFT Rev A ST7735R +# disp = st7735.ST7735R(spi, rotation=90, invert=True, width=80, x_offset=26, y_offset=1, # 0.96" MiniTFT Rev B ST7735R +# disp = ssd1351.SSD1351(spi, rotation=180, # 1.5" SSD1351 +# disp = ssd1351.SSD1351(spi, height=96, y_offset=32, rotation=180, # 1.27" SSD1351 +# disp = ssd1331.SSD1331(spi, rotation=180, # 0.96" SSD1331 + cs=cs_pin, + dc=dc_pin, + rst=reset_pin, + baudrate=BAUDRATE, + ) +# fmt: on +# pylint: enable=line-too-long + + +def init_button(pin): + button = digitalio.DigitalInOut(pin) + button.switch_to_input() + button.pull = digitalio.Pull.UP + return button + + +class Frame: # pylint: disable=too-few-public-methods + def __init__(self, duration=0): + self.duration = duration + self.image = None + + +class AnimatedGif: + def __init__(self, display, width=None, height=None, folder=None): + self._frame_count = 0 + self._loop = 0 + self._index = 0 + self._duration = 0 + self._gif_files = [] + self._frames = [] + + if width is not None: + self._width = width + else: + self._width = display.width + if height is not None: + self._height = height + else: + self._height = display.height + self.display = display + self.advance_button = init_button(BUTTON_NEXT) + self.back_button = init_button(BUTTON_PREVIOUS) + if folder is not None: + self.load_files(folder) + self.run() + + def advance(self): + self._index = (self._index + 1) % len(self._gif_files) + + def back(self): + self._index = (self._index - 1 + len(self._gif_files)) % len(self._gif_files) + + def load_files(self, folder): + gif_files = [f for f in os.listdir(folder) if f.endswith(".gif")] + for gif_file in gif_files: + gif_file = os.path.join(folder, gif_file) + image = Image.open(gif_file) + # Only add animated Gifs + if image.is_animated: + self._gif_files.append(gif_file) + + print("Found", self._gif_files) + if not self._gif_files: + print("No Gif files found in current folder") + exit() # pylint: disable=consider-using-sys-exit + + def preload(self): + image = Image.open(self._gif_files[self._index]) + print("Loading {}...".format(self._gif_files[self._index])) + if "duration" in image.info: + self._duration = image.info["duration"] + else: + self._duration = 0 + if "loop" in image.info: + self._loop = image.info["loop"] + else: + self._loop = 1 + self._frame_count = image.n_frames + self._frames.clear() + for frame in range(self._frame_count): + image.seek(frame) + # Create blank image for drawing. + # Make sure to create image with mode 'RGB' for full color. + frame_object = Frame(duration=self._duration) + if "duration" in image.info: + frame_object.duration = image.info["duration"] + frame_object.image = ImageOps.pad( # pylint: disable=no-member + image.convert("RGB"), + (self._width, self._height), + method=Image.NEAREST, + color=(0, 0, 0), + centering=(0.5, 0.5), + ) + self._frames.append(frame_object) + + def play(self): + self.preload() + + _prev_advance_btn_val = self.advance_button.value + _prev_back_btn_val = self.back_button.value + # Check if we have loaded any files first + if not self._gif_files: + print("There are no Gif Images loaded to Play") + return False + while True: + for frame_object in self._frames: + start_time = time.monotonic() + self.display.image(frame_object.image) + _cur_advance_btn_val = self.advance_button.value + _cur_back_btn_val = self.back_button.value + if not _cur_advance_btn_val and _prev_advance_btn_val: + self.advance() + return False + if not _cur_back_btn_val and _prev_back_btn_val: + self.back() + return False + + _prev_back_btn_val = _cur_back_btn_val + _prev_advance_btn_val = _cur_advance_btn_val + while time.monotonic() < (start_time + frame_object.duration / 1000): + pass + + if self._loop == 1: + return True + if self._loop > 0: + self._loop -= 1 + + def run(self): + while True: + auto_advance = self.play() + if auto_advance: + self.advance() + + +if disp.rotation % 180 == 90: + disp_height = disp.width # we swap height/width to rotate it to landscape! + disp_width = disp.height +else: + disp_width = disp.width + disp_height = disp.height + +gif_player = AnimatedGif(disp, width=disp_width, height=disp_height, folder=".") From 8cfb0db7d36eb46ef1e2a575b03f5e630bfc2c94 Mon Sep 17 00:00:00 2001 From: foamyguy Date: Mon, 18 Sep 2023 16:24:13 -0500 Subject: [PATCH 09/31] "fix rtd theme " --- docs/conf.py | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) diff --git a/docs/conf.py b/docs/conf.py index 4118015..7c87192 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -101,19 +101,10 @@ # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # -on_rtd = os.environ.get("READTHEDOCS", None) == "True" - -if not on_rtd: # only import and set the theme if we're building docs locally - try: - import sphinx_rtd_theme - - html_theme = "sphinx_rtd_theme" - html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), "."] - except: - html_theme = "default" - html_theme_path = ["."] -else: - html_theme_path = ["."] +import sphinx_rtd_theme + +html_theme = "sphinx_rtd_theme" +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 a85229e4d44541f5e46b2f385de3c82ad86cc944 Mon Sep 17 00:00:00 2001 From: Melissa LeBlanc-Williams Date: Mon, 27 Nov 2023 10:12:14 -0800 Subject: [PATCH 10/31] Fix typing for color565 function --- adafruit_rgb_display/rgb.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/adafruit_rgb_display/rgb.py b/adafruit_rgb_display/rgb.py index 5c906f7..26b6fe0 100644 --- a/adafruit_rgb_display/rgb.py +++ b/adafruit_rgb_display/rgb.py @@ -47,14 +47,14 @@ def color565( - r: Union[int, Tuple[int, int, int], List[int]], - g: int = 0, - b: int = 0, + r: Union[int, Tuple[int, int, int], List[int, int, int]], + g: Optional[int] = 0, + b: Optional[int] = 0, ) -> int: """Convert red, green and blue values (0-255) into a 16-bit 565 encoding. As a convenience this is also available in the parent adafruit_rgb_display package namespace.""" - if not isinstance(r, int): # see if the first var is a tuple/list + if isinstance(r, (tuple, list)): # see if the first var is a tuple/list red, g, b = r else: red = r From c89be83fbec7fb9ab852ea45e84f6dd12eca8065 Mon Sep 17 00:00:00 2001 From: Melissa LeBlanc-Williams Date: Mon, 27 Nov 2023 10:20:15 -0800 Subject: [PATCH 11/31] Update color565 to just make sure we get what we expect --- adafruit_rgb_display/rgb.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/adafruit_rgb_display/rgb.py b/adafruit_rgb_display/rgb.py index 26b6fe0..a874201 100644 --- a/adafruit_rgb_display/rgb.py +++ b/adafruit_rgb_display/rgb.py @@ -47,7 +47,7 @@ def color565( - r: Union[int, Tuple[int, int, int], List[int, int, int]], + r: Union[int, Tuple[int, int, int], List[int]], g: Optional[int] = 0, b: Optional[int] = 0, ) -> int: @@ -55,7 +55,12 @@ def color565( a convenience this is also available in the parent adafruit_rgb_display package namespace.""" if isinstance(r, (tuple, list)): # see if the first var is a tuple/list - red, g, b = r + if len(r) >= 3: + red, g, b = r + else: + raise ValueError( + "Not enough values to unpack (expected 3, got %d)" % len(r) + ) else: red = r return (red & 0xF8) << 8 | (g & 0xFC) << 3 | b >> 3 From 7ecfffe3deac982f8698e72da7033b836c07ecd5 Mon Sep 17 00:00:00 2001 From: foamyguy Date: Mon, 16 Oct 2023 14:30:31 -0500 Subject: [PATCH 12/31] 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 a4c6325cff64fd168738c83ae530d62c0b8d4a5d Mon Sep 17 00:00:00 2001 From: Reza Nasab <49108667+reza-n@users.noreply.github.com> Date: Wed, 27 Dec 2023 00:45:40 -0800 Subject: [PATCH 13/31] Update rgb.py fixing an issue when 4 values are returned instead of r/g/b --- adafruit_rgb_display/rgb.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adafruit_rgb_display/rgb.py b/adafruit_rgb_display/rgb.py index a874201..c039b34 100644 --- a/adafruit_rgb_display/rgb.py +++ b/adafruit_rgb_display/rgb.py @@ -56,7 +56,7 @@ def color565( package namespace.""" if isinstance(r, (tuple, list)): # see if the first var is a tuple/list if len(r) >= 3: - red, g, b = r + red, g, b = r[0:3] else: raise ValueError( "Not enough values to unpack (expected 3, got %d)" % len(r) From 8bac28cc9b58a9a92609f3060da73be10e2decac Mon Sep 17 00:00:00 2001 From: Simon Ludwig Date: Wed, 31 Jul 2024 19:56:04 +0200 Subject: [PATCH 14/31] removed print calls --- adafruit_rgb_display/ssd1331.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/adafruit_rgb_display/ssd1331.py b/adafruit_rgb_display/ssd1331.py index 167afe1..86e0cca 100644 --- a/adafruit_rgb_display/ssd1331.py +++ b/adafruit_rgb_display/ssd1331.py @@ -149,7 +149,5 @@ def write( with self.spi_device as spi: if command is not None: spi.write(bytearray([command])) - print(bytearray([command])) if data is not None: spi.write(data) - print(data) From 2c4d380e552a2cd560e36a500f6ac3f51c8085b0 Mon Sep 17 00:00:00 2001 From: foamyguy Date: Mon, 7 Oct 2024 09:24:05 -0500 Subject: [PATCH 15/31] 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 7c87192..1ec3924 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -104,7 +104,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 197da2c37ed9aacfb7fc7ffae7cb84618b31fc11 Mon Sep 17 00:00:00 2001 From: foamyguy Date: Tue, 14 Jan 2025 11:32:34 -0600 Subject: [PATCH 16/31] 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 b55666be6d3a52aacbad9107699eb7190ccb605a Mon Sep 17 00:00:00 2001 From: Liz Date: Mon, 10 Feb 2025 11:00:31 -0500 Subject: [PATCH 17/31] Create gc9a01a.py --- adafruit_rgb_display/gc9a01a.py | 145 ++++++++++++++++++++++++++++++++ 1 file changed, 145 insertions(+) create mode 100644 adafruit_rgb_display/gc9a01a.py diff --git a/adafruit_rgb_display/gc9a01a.py b/adafruit_rgb_display/gc9a01a.py new file mode 100644 index 0000000..33800f9 --- /dev/null +++ b/adafruit_rgb_display/gc9a01a.py @@ -0,0 +1,145 @@ +# SPDX-FileCopyrightText: 2025 Liz Clark for Adafruit Industries +# +# SPDX-License-Identifier: MIT +""" +`adafruit_rgb_display.gc9a01a` +==================================================== +A simple driver for the GC9A01A-based displays. + +* Author(s): Liz Clark + +Implementation Notes +-------------------- +Adapted from the CircuitPython GC9A01A driver for use with the RGB Display library. +""" +import struct +import busio +import digitalio +from micropython import const +from adafruit_rgb_display.rgb import DisplaySPI + +try: + from typing import Optional +except ImportError: + pass + +__version__ = "0.0.0+auto.0" +__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RGB_Display.git" + +# Command constants +_NOP = const(0x00) +_SWRESET = const(0x01) +_SLPIN = const(0x10) +_SLPOUT = const(0x11) +_PTLON = const(0x12) +_NORON = const(0x13) +_INVOFF = const(0x20) +_INVON = const(0x21) +_DISPOFF = const(0x28) +_DISPON = const(0x29) +_CASET = const(0x2A) +_RASET = const(0x2B) +_RAMWR = const(0x2C) +_RAMRD = const(0x2E) +_MADCTL = const(0x36) +_COLMOD = const(0x3A) +_TEON = const(0x35) + +# Extended command constants +_PWCTR1 = const(0xC3) +_PWCTR2 = const(0xC4) +_PWCTR3 = const(0xC9) +_GMCTRP1 = const(0xF0) +_GMCTRN1 = const(0xF1) +_GMCTRP2 = const(0xF2) +_GMCTRN2 = const(0xF3) + +class GC9A01A(DisplaySPI): + """ + A simple driver for the GC9A01A-based displays. + + >>> import busio + >>> import digitalio + >>> import board + >>> from adafruit_rgb_display import color565 + >>> import adafruit_rgb_display.gc9a01a as gc9a01a + >>> spi = busio.SPI(clock=board.SCK, MOSI=board.MOSI, MISO=board.MISO) + >>> display = gc9a01a.GC9A01A(spi, cs=digitalio.DigitalInOut(board.GPIO0), + ... dc=digitalio.DigitalInOut(board.GPIO15), rst=digitalio.DigitalInOut(board.GPIO16)) + >>> display.fill(0x7521) + >>> display.pixel(64, 64, 0) + """ + # pylint: disable=too-few-public-methods + + COLUMN_SET = _CASET + PAGE_SET = _RASET + RAM_WRITE = _RAMWR + RAM_READ = _RAMRD + + _INIT = ( + (_SWRESET, None), + (0xFE, None), # Inter Register Enable1 + (0xEF, None), # Inter Register Enable2 + (0xB6, b"\x00\x00"), # Display Function Control + (_MADCTL, b"\x48"), # Memory Access Control + (_COLMOD, b"\x05"), # Interface Pixel Format (16 bits/pixel) + (_PWCTR1, b"\x13"), # Power Control 2 + (_PWCTR2, b"\x13"), # Power Control 3 + (_PWCTR3, b"\x22"), # Power Control 4 + (_GMCTRP1, b"\x45\x09\x08\x08\x26\x2a"), # Set Gamma 1 + (_GMCTRN1, b"\x43\x70\x72\x36\x37\x6f"), # Set Gamma 2 + (_GMCTRP2, b"\x45\x09\x08\x08\x26\x2a"), # Set Gamma 3 + (_GMCTRN2, b"\x43\x70\x72\x36\x37\x6f"), # Set Gamma 4 + (0x66, b"\x3c\x00\xcd\x67\x45\x45\x10\x00\x00\x00"), + (0x67, b"\x00\x3c\x00\x00\x00\x01\x54\x10\x32\x98"), + (0x74, b"\x10\x85\x80\x00\x00\x4e\x00"), + (0x98, b"\x3e\x07"), + (_TEON, None), # Tearing Effect Line ON + (_INVON, None), # Display Inversion ON + (_SLPOUT, None), # Exit Sleep Mode + (_NORON, None), # Normal Display Mode ON + (_DISPON, None), # Display ON + ) + + def __init__( + self, + spi: busio.SPI, + dc: digitalio.DigitalInOut, + cs: digitalio.DigitalInOut, + rst: Optional[digitalio.DigitalInOut] = None, + width: int = 240, + height: int = 240, + baudrate: int = 16000000, + polarity: int = 0, + phase: int = 0, + *, + x_offset: int = 0, + y_offset: int = 0, + rotation: int = 0 + ) -> None: + super().__init__( + spi, + dc, + cs, + rst, + width, + height, + baudrate=baudrate, + polarity=polarity, + phase=phase, + x_offset=x_offset, + y_offset=y_offset, + rotation=rotation, + ) + + def init(self) -> None: + super().init() + cols = struct.pack(">HH", 0, self.width - 1) + rows = struct.pack(">HH", 0, self.height - 1) + + for command, data in ( + (_CASET, cols), + (_RASET, rows), + (_MADCTL, b"\xc0"), # Set rotation to 0 and use RGB + ): + self.write(command, data) From 7d5528f6c6aa45c9493d0c8bf65db4e33328a3e6 Mon Sep 17 00:00:00 2001 From: Liz Date: Mon, 10 Feb 2025 11:23:56 -0500 Subject: [PATCH 18/31] Update gc9a01a.py --- adafruit_rgb_display/gc9a01a.py | 41 ++++++++++++++++----------------- 1 file changed, 20 insertions(+), 21 deletions(-) diff --git a/adafruit_rgb_display/gc9a01a.py b/adafruit_rgb_display/gc9a01a.py index 33800f9..d556911 100644 --- a/adafruit_rgb_display/gc9a01a.py +++ b/adafruit_rgb_display/gc9a01a.py @@ -77,28 +77,26 @@ class GC9A01A(DisplaySPI): RAM_READ = _RAMRD _INIT = ( - (_SWRESET, None), - (0xFE, None), # Inter Register Enable1 - (0xEF, None), # Inter Register Enable2 - (0xB6, b"\x00\x00"), # Display Function Control - (_MADCTL, b"\x48"), # Memory Access Control - (_COLMOD, b"\x05"), # Interface Pixel Format (16 bits/pixel) - (_PWCTR1, b"\x13"), # Power Control 2 - (_PWCTR2, b"\x13"), # Power Control 3 + (0xFE, b"\x00"), # Inter Register Enable1 + (0xEF, b"\x00"), # Inter Register Enable2 + (0xB6, b"\x00\x00"), # Display Function Control [S1→S360 source, G1→G32 gate] + (_MADCTL, b"\x48"), # Memory Access Control [Invert Row order, invert vertical scan order] + (_COLMOD, b"\x05"), # COLMOD: Pixel Format Set [16 bits/pixel] + (_PWCTR1, b"\x13"), # Power Control 2 [VREG1A = 5.06, VREG1B = 0.68] + (_PWCTR2, b"\x13"), # Power Control 3 [VREG2A = -3.7, VREG2B = 0.68] (_PWCTR3, b"\x22"), # Power Control 4 - (_GMCTRP1, b"\x45\x09\x08\x08\x26\x2a"), # Set Gamma 1 - (_GMCTRN1, b"\x43\x70\x72\x36\x37\x6f"), # Set Gamma 2 - (_GMCTRP2, b"\x45\x09\x08\x08\x26\x2a"), # Set Gamma 3 - (_GMCTRN2, b"\x43\x70\x72\x36\x37\x6f"), # Set Gamma 4 + (_GMCTRP1, b"\x45\x09\x08\x08\x26\x2a"), # SET_GAMMA1 + (_GMCTRN1, b"\x43\x70\x72\x36\x37\x6f"), # SET_GAMMA2 + (_GMCTRP2, b"\x45\x09\x08\x08\x26\x2a"), # SET_GAMMA3 + (_GMCTRN2, b"\x43\x70\x72\x36\x37\x6f"), # SET_GAMMA4 (0x66, b"\x3c\x00\xcd\x67\x45\x45\x10\x00\x00\x00"), (0x67, b"\x00\x3c\x00\x00\x00\x01\x54\x10\x32\x98"), (0x74, b"\x10\x85\x80\x00\x00\x4e\x00"), (0x98, b"\x3e\x07"), - (_TEON, None), # Tearing Effect Line ON - (_INVON, None), # Display Inversion ON - (_SLPOUT, None), # Exit Sleep Mode - (_NORON, None), # Normal Display Mode ON - (_DISPON, None), # Display ON + (_TEON, b"\x00"), # Tearing Effect Line ON [both V-blanking and H-blanking] + (_INVON, b"\x00"), # Display Inversion ON + (_SLPOUT, None), # Sleep Out Mode (with 120ms delay) + (_DISPON, None), # Display ON (with 20ms delay) ) def __init__( @@ -134,12 +132,13 @@ def __init__( def init(self) -> None: super().init() - cols = struct.pack(">HH", 0, self.width - 1) - rows = struct.pack(">HH", 0, self.height - 1) + # Account for offsets in the column and row addressing + cols = struct.pack(">HH", self._X_START, self.width + self._X_START - 1) + rows = struct.pack(">HH", self._Y_START, self.height + self._Y_START - 1) for command, data in ( - (_CASET, cols), - (_RASET, rows), (_MADCTL, b"\xc0"), # Set rotation to 0 and use RGB + (_CASET, b"\x00\x00\x00\xef"), # Column Address Set [Start col = 0, end col = 239] + (_RASET, b"\x00\x00\x00\xef"), # Row Address Set [Start row = 0, end row = 239] ): self.write(command, data) From 67547fadb2e197e32aeaf8dd5bcbcaa21c177baf Mon Sep 17 00:00:00 2001 From: Liz Date: Mon, 10 Feb 2025 11:32:10 -0500 Subject: [PATCH 19/31] Update gc9a01a.py --- adafruit_rgb_display/gc9a01a.py | 35 ++++++++++++++++++++++----------- 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/adafruit_rgb_display/gc9a01a.py b/adafruit_rgb_display/gc9a01a.py index d556911..c882a95 100644 --- a/adafruit_rgb_display/gc9a01a.py +++ b/adafruit_rgb_display/gc9a01a.py @@ -26,11 +26,14 @@ __version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RGB_Display.git" -# Command constants -_NOP = const(0x00) -_SWRESET = const(0x01) -_SLPIN = const(0x10) -_SLPOUT = const(0x11) +# Constants for MADCTL +_MADCTL_MY = const(0x80) # Bottom to top +_MADCTL_MX = const(0x40) # Right to left +_MADCTL_MV = const(0x20) # Reverse Mode +_MADCTL_ML = const(0x10) # LCD refresh Bottom to top +_MADCTL_RGB = const(0x00) # Red-Green-Blue pixel order +_MADCTL_BGR = const(0x08) # Blue-Green-Red pixel order +_MADCTL_MH = const(0x04) # LCD refresh right to left _PTLON = const(0x12) _NORON = const(0x13) _INVOFF = const(0x20) @@ -136,9 +139,19 @@ def init(self) -> None: cols = struct.pack(">HH", self._X_START, self.width + self._X_START - 1) rows = struct.pack(">HH", self._Y_START, self.height + self._Y_START - 1) - for command, data in ( - (_MADCTL, b"\xc0"), # Set rotation to 0 and use RGB - (_CASET, b"\x00\x00\x00\xef"), # Column Address Set [Start col = 0, end col = 239] - (_RASET, b"\x00\x00\x00\xef"), # Row Address Set [Start row = 0, end row = 239] - ): - self.write(command, data) + def init(self) -> None: + """Initialize the display""" + super().init() + + # Initialize display + self.write(_SWRESET) + time.sleep(0.150) # 150ms delay after reset + + # Set addressing mode and color format + self.write(_MADCTL, bytes([_MADCTL_MX | _MADCTL_BGR])) + + # Set addressing windows + self.write(_CASET, b"\x00\x00\x00\xef") # Column Address Set [0-239] + self.write(_RASET, b"\x00\x00\x00\xef") # Row Address Set [0-239] + + time.sleep(0.150) # 150ms delay before turning on display \ No newline at end of file From 9f02995bbca0523adc6453aa2b547159aa262dd7 Mon Sep 17 00:00:00 2001 From: Liz Date: Mon, 10 Feb 2025 12:31:41 -0500 Subject: [PATCH 20/31] pre-commit, tested --- adafruit_rgb_display/gc9a01a.py | 107 ++++++++++++-------------------- 1 file changed, 39 insertions(+), 68 deletions(-) diff --git a/adafruit_rgb_display/gc9a01a.py b/adafruit_rgb_display/gc9a01a.py index c882a95..4b95604 100644 --- a/adafruit_rgb_display/gc9a01a.py +++ b/adafruit_rgb_display/gc9a01a.py @@ -8,11 +8,10 @@ * Author(s): Liz Clark -Implementation Notes --------------------- -Adapted from the CircuitPython GC9A01A driver for use with the RGB Display library. """ + import struct +import time import busio import digitalio from micropython import const @@ -26,15 +25,9 @@ __version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RGB_Display.git" -# Constants for MADCTL -_MADCTL_MY = const(0x80) # Bottom to top -_MADCTL_MX = const(0x40) # Right to left -_MADCTL_MV = const(0x20) # Reverse Mode -_MADCTL_ML = const(0x10) # LCD refresh Bottom to top -_MADCTL_RGB = const(0x00) # Red-Green-Blue pixel order -_MADCTL_BGR = const(0x08) # Blue-Green-Red pixel order -_MADCTL_MH = const(0x04) # LCD refresh right to left -_PTLON = const(0x12) +# Command constants +_SWRESET = const(0xFE) +_SLPOUT = const(0x11) _NORON = const(0x13) _INVOFF = const(0x20) _INVON = const(0x21) @@ -46,16 +39,7 @@ _RAMRD = const(0x2E) _MADCTL = const(0x36) _COLMOD = const(0x3A) -_TEON = const(0x35) -# Extended command constants -_PWCTR1 = const(0xC3) -_PWCTR2 = const(0xC4) -_PWCTR3 = const(0xC9) -_GMCTRP1 = const(0xF0) -_GMCTRN1 = const(0xF1) -_GMCTRP2 = const(0xF2) -_GMCTRN2 = const(0xF3) class GC9A01A(DisplaySPI): """ @@ -64,42 +48,40 @@ class GC9A01A(DisplaySPI): >>> import busio >>> import digitalio >>> import board - >>> from adafruit_rgb_display import color565 - >>> import adafruit_rgb_display.gc9a01a as gc9a01a + >>> from adafruit_rgb_display import gc9a01a >>> spi = busio.SPI(clock=board.SCK, MOSI=board.MOSI, MISO=board.MISO) - >>> display = gc9a01a.GC9A01A(spi, cs=digitalio.DigitalInOut(board.GPIO0), - ... dc=digitalio.DigitalInOut(board.GPIO15), rst=digitalio.DigitalInOut(board.GPIO16)) + >>> display = gc9a01a.GC9A01A(spi, cs=digitalio.DigitalInOut(board.CE0), + ... dc=digitalio.DigitalInOut(board.D25), rst=digitalio.DigitalInOut(board.D27)) >>> display.fill(0x7521) >>> display.pixel(64, 64, 0) """ - # pylint: disable=too-few-public-methods - - COLUMN_SET = _CASET - PAGE_SET = _RASET - RAM_WRITE = _RAMWR - RAM_READ = _RAMRD + _COLUMN_SET = _CASET + _PAGE_SET = _RASET + _RAM_WRITE = _RAMWR + _RAM_READ = _RAMRD _INIT = ( - (0xFE, b"\x00"), # Inter Register Enable1 - (0xEF, b"\x00"), # Inter Register Enable2 - (0xB6, b"\x00\x00"), # Display Function Control [S1→S360 source, G1→G32 gate] - (_MADCTL, b"\x48"), # Memory Access Control [Invert Row order, invert vertical scan order] - (_COLMOD, b"\x05"), # COLMOD: Pixel Format Set [16 bits/pixel] - (_PWCTR1, b"\x13"), # Power Control 2 [VREG1A = 5.06, VREG1B = 0.68] - (_PWCTR2, b"\x13"), # Power Control 3 [VREG2A = -3.7, VREG2B = 0.68] - (_PWCTR3, b"\x22"), # Power Control 4 - (_GMCTRP1, b"\x45\x09\x08\x08\x26\x2a"), # SET_GAMMA1 - (_GMCTRN1, b"\x43\x70\x72\x36\x37\x6f"), # SET_GAMMA2 - (_GMCTRP2, b"\x45\x09\x08\x08\x26\x2a"), # SET_GAMMA3 - (_GMCTRN2, b"\x43\x70\x72\x36\x37\x6f"), # SET_GAMMA4 + (_SWRESET, None), + (0xEF, None), # Inter Register Enable2 + (0xB6, b"\x00\x00"), # Display Function Control + (_MADCTL, b"\x48"), # Memory Access Control - Set to BGR color filter panel + (_COLMOD, b"\x05"), # Interface Pixel Format - 16 bits per pixel + (0xC3, b"\x13"), # Power Control 2 + (0xC4, b"\x13"), # Power Control 3 + (0xC9, b"\x22"), # Power Control 4 + (0xF0, b"\x45\x09\x08\x08\x26\x2a"), # SET_GAMMA1 + (0xF1, b"\x43\x70\x72\x36\x37\x6f"), # SET_GAMMA2 + (0xF2, b"\x45\x09\x08\x08\x26\x2a"), # SET_GAMMA3 + (0xF3, b"\x43\x70\x72\x36\x37\x6f"), # SET_GAMMA4 (0x66, b"\x3c\x00\xcd\x67\x45\x45\x10\x00\x00\x00"), (0x67, b"\x00\x3c\x00\x00\x00\x01\x54\x10\x32\x98"), (0x74, b"\x10\x85\x80\x00\x00\x4e\x00"), (0x98, b"\x3e\x07"), - (_TEON, b"\x00"), # Tearing Effect Line ON [both V-blanking and H-blanking] - (_INVON, b"\x00"), # Display Inversion ON - (_SLPOUT, None), # Sleep Out Mode (with 120ms delay) - (_DISPON, None), # Display ON (with 20ms delay) + (0x35, None), # Tearing Effect Line ON + (_INVON, None), # Display Inversion ON + (_SLPOUT, None), # Sleep Out Mode + (_NORON, None), # Normal Display Mode ON + (_DISPON, None), # Display ON ) def __init__( @@ -110,7 +92,7 @@ def __init__( rst: Optional[digitalio.DigitalInOut] = None, width: int = 240, height: int = 240, - baudrate: int = 16000000, + baudrate: int = 24000000, polarity: int = 0, phase: int = 0, *, @@ -134,24 +116,13 @@ def __init__( ) def init(self) -> None: + """Initialize the display.""" + if self.rst: + self.rst.value = 0 + time.sleep(0.05) + self.rst.value = 1 + time.sleep(0.05) + super().init() - # Account for offsets in the column and row addressing - cols = struct.pack(">HH", self._X_START, self.width + self._X_START - 1) - rows = struct.pack(">HH", self._Y_START, self.height + self._Y_START - 1) - - def init(self) -> None: - """Initialize the display""" - super().init() - - # Initialize display - self.write(_SWRESET) - time.sleep(0.150) # 150ms delay after reset - - # Set addressing mode and color format - self.write(_MADCTL, bytes([_MADCTL_MX | _MADCTL_BGR])) - - # Set addressing windows - self.write(_CASET, b"\x00\x00\x00\xef") # Column Address Set [0-239] - self.write(_RASET, b"\x00\x00\x00\xef") # Row Address Set [0-239] - - time.sleep(0.150) # 150ms delay before turning on display \ No newline at end of file + + self._block(0, 0, self.width - 1, self.height - 1) From 8ce10d5951aa86e722b301109c5a72c8c91075d3 Mon Sep 17 00:00:00 2001 From: Liz Date: Mon, 10 Feb 2025 12:34:06 -0500 Subject: [PATCH 21/31] lint --- adafruit_rgb_display/gc9a01a.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/adafruit_rgb_display/gc9a01a.py b/adafruit_rgb_display/gc9a01a.py index 4b95604..d7b28cb 100644 --- a/adafruit_rgb_display/gc9a01a.py +++ b/adafruit_rgb_display/gc9a01a.py @@ -10,7 +10,6 @@ """ -import struct import time import busio import digitalio @@ -83,7 +82,7 @@ class GC9A01A(DisplaySPI): (_NORON, None), # Normal Display Mode ON (_DISPON, None), # Display ON ) - + # pylint: disable-msg=useless-super-delegation, too-many-arguments def __init__( self, spi: busio.SPI, From 664dcd28144f05df5833a23003a73d2fc089b2a1 Mon Sep 17 00:00:00 2001 From: Liz Date: Mon, 10 Feb 2025 12:36:42 -0500 Subject: [PATCH 22/31] oy vey, black --- adafruit_rgb_display/gc9a01a.py | 1 + 1 file changed, 1 insertion(+) diff --git a/adafruit_rgb_display/gc9a01a.py b/adafruit_rgb_display/gc9a01a.py index d7b28cb..f360cc0 100644 --- a/adafruit_rgb_display/gc9a01a.py +++ b/adafruit_rgb_display/gc9a01a.py @@ -82,6 +82,7 @@ class GC9A01A(DisplaySPI): (_NORON, None), # Normal Display Mode ON (_DISPON, None), # Display ON ) + # pylint: disable-msg=useless-super-delegation, too-many-arguments def __init__( self, From f56a9eeb4d7fdc42787d1ecb3882e86155ac0d02 Mon Sep 17 00:00:00 2001 From: Liz Date: Mon, 10 Feb 2025 16:06:29 -0500 Subject: [PATCH 23/31] remove _block --- adafruit_rgb_display/gc9a01a.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/adafruit_rgb_display/gc9a01a.py b/adafruit_rgb_display/gc9a01a.py index f360cc0..613bc7a 100644 --- a/adafruit_rgb_display/gc9a01a.py +++ b/adafruit_rgb_display/gc9a01a.py @@ -124,5 +124,3 @@ def init(self) -> None: time.sleep(0.05) super().init() - - self._block(0, 0, self.width - 1, self.height - 1) From 8fb075c6b85699be49ab62ea8150dbd23652e420 Mon Sep 17 00:00:00 2001 From: foamyguy Date: Tue, 29 Apr 2025 17:32:07 -0500 Subject: [PATCH 24/31] use ruff --- .gitattributes | 11 + .pre-commit-config.yaml | 43 +- .pylintrc | 399 ------------------ README.rst | 6 +- adafruit_rgb_display/__init__.py | 1 + adafruit_rgb_display/gc9a01a.py | 4 +- adafruit_rgb_display/hx8353.py | 5 +- adafruit_rgb_display/hx8357.py | 17 +- adafruit_rgb_display/ili9341.py | 7 +- adafruit_rgb_display/rgb.py | 60 +-- adafruit_rgb_display/s6d02a1.py | 4 +- adafruit_rgb_display/ssd1331.py | 12 +- adafruit_rgb_display/ssd1351.py | 7 +- adafruit_rgb_display/st7735.py | 11 +- adafruit_rgb_display/st7789.py | 3 +- docs/api.rst | 3 + docs/conf.py | 10 +- .../rgb_display_eyespi_beret_animated_gif.py | 29 +- examples/rgb_display_fbcp.py | 22 +- examples/rgb_display_hx8357test.py | 11 +- examples/rgb_display_ili9341test.py | 12 +- examples/rgb_display_minipitftstats.py | 7 +- examples/rgb_display_minipitfttest.py | 4 +- examples/rgb_display_pillow_animated_gif.py | 27 +- examples/rgb_display_pillow_bonnet_buttons.py | 20 +- examples/rgb_display_pillow_demo.py | 21 +- examples/rgb_display_pillow_image.py | 17 +- examples/rgb_display_pillow_stats.py | 20 +- examples/rgb_display_simpletest.py | 11 +- ruff.toml | 105 +++++ 30 files changed, 303 insertions(+), 606 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 179cf07..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,duplicate-code - 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 9a7c211..63ce6e5 100644 --- a/README.rst +++ b/README.rst @@ -13,9 +13,9 @@ Introduction :target: https://github.com/adafruit/Adafruit_CircuitPython_RGB_Display/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 Port of display drivers from https://github.com/adafruit/micropython-adafruit-rgb-display to Adafruit CircuitPython for use on Adafruit's SAMD21-based and other CircuitPython boards. diff --git a/adafruit_rgb_display/__init__.py b/adafruit_rgb_display/__init__.py index 825637e..c69a8da 100644 --- a/adafruit_rgb_display/__init__.py +++ b/adafruit_rgb_display/__init__.py @@ -3,4 +3,5 @@ # SPDX-License-Identifier: MIT """Auto imports for Adafruit_CircuitPython_RGB_Display""" + from adafruit_rgb_display.rgb import color565 diff --git a/adafruit_rgb_display/gc9a01a.py b/adafruit_rgb_display/gc9a01a.py index 613bc7a..e899004 100644 --- a/adafruit_rgb_display/gc9a01a.py +++ b/adafruit_rgb_display/gc9a01a.py @@ -11,9 +11,11 @@ """ import time + import busio import digitalio from micropython import const + from adafruit_rgb_display.rgb import DisplaySPI try: @@ -98,7 +100,7 @@ def __init__( *, x_offset: int = 0, y_offset: int = 0, - rotation: int = 0 + rotation: int = 0, ) -> None: super().__init__( spi, diff --git a/adafruit_rgb_display/hx8353.py b/adafruit_rgb_display/hx8353.py index 2aaf712..d1da61c 100644 --- a/adafruit_rgb_display/hx8353.py +++ b/adafruit_rgb_display/hx8353.py @@ -11,13 +11,16 @@ * Author(s): Radomir Dopieralski, Michael McWethy, Matt Land """ + from micropython import const + from adafruit_rgb_display.rgb import DisplaySPI try: from typing import Optional - import digitalio + import busio + import digitalio except ImportError: pass diff --git a/adafruit_rgb_display/hx8357.py b/adafruit_rgb_display/hx8357.py index dfb9e2f..432705e 100755 --- a/adafruit_rgb_display/hx8357.py +++ b/adafruit_rgb_display/hx8357.py @@ -11,13 +11,16 @@ * Author(s): Melissa LeBlanc-Williams, Matt Land """ + from micropython import const + from adafruit_rgb_display.rgb import DisplaySPI try: from typing import Optional - import digitalio + import busio + import digitalio except ImportError: pass @@ -72,21 +75,21 @@ class HX8357(DisplaySPI): _RAM_READ = _RAMRD _INIT = ( (_SWRESET, None), - (_SETC, b"\xFF\x83\x57"), + (_SETC, b"\xff\x83\x57"), (_SETRGB, b"\x80\x00\x06\x06"), # 0x80 enables SDO pin (0x00 disables) (_SETCOM, b"\x25"), # -1.52V (_SETOSC, b"\x68"), # Normal mode 70Hz, Idle mode 55 Hz (_SETPANEL, b"\x05"), # BGR, Gate direction swapped - (_SETPWR1, b"\x00\x15\x1C\x1C\x83\xAA"), # Not deep standby BT VSPR VSNR AP - (_SETSTBA, b"\x50\x50\x01\x3C\x1E\x08"), # OPON normal OPON idle STBA GEN + (_SETPWR1, b"\x00\x15\x1c\x1c\x83\xaa"), # Not deep standby BT VSPR VSNR AP + (_SETSTBA, b"\x50\x50\x01\x3c\x1e\x08"), # OPON normal OPON idle STBA GEN ( _SETCYC, - b"\x02\x40\x00\x2A\x2A\x0D\x78", + b"\x02\x40\x00\x2a\x2a\x0d\x78", ), # NW 0x02 RTN DIV DUM DUM GDON GDOFF ( _SETGAMMA, - b"\x02\x0A\x11\x1d\x23\x35\x41\x4b\x4b\x42\x3A\x27\x1B\x08\x09\x03\x02" - b"\x0A\x11\x1d\x23\x35\x41\x4b\x4b\x42\x3A\x27\x1B\x08\x09\x03\x00\x01", + b"\x02\x0a\x11\x1d\x23\x35\x41\x4b\x4b\x42\x3a\x27\x1b\x08\x09\x03\x02" + b"\x0a\x11\x1d\x23\x35\x41\x4b\x4b\x42\x3a\x27\x1b\x08\x09\x03\x00\x01", ), (_COLMOD, b"\x55"), # 16 bit (_MADCTL, b"\xc0"), diff --git a/adafruit_rgb_display/ili9341.py b/adafruit_rgb_display/ili9341.py index bb90093..3e79787 100644 --- a/adafruit_rgb_display/ili9341.py +++ b/adafruit_rgb_display/ili9341.py @@ -11,14 +11,16 @@ * Author(s): Radomir Dopieralski, Michael McWethy, Matt Land """ + import struct from adafruit_rgb_display.rgb import DisplaySPI try: from typing import Optional - import digitalio + import busio + import digitalio except ImportError: pass @@ -110,7 +112,8 @@ def __init__( # pylint: enable-msg=too-many-arguments def scroll( - self, dy: Optional[int] = None # pylint: disable-msg=invalid-name + self, + dy: Optional[int] = None, # pylint: disable-msg=invalid-name ) -> Optional[int]: """Scroll the display by delta y""" if dy is None: diff --git a/adafruit_rgb_display/rgb.py b/adafruit_rgb_display/rgb.py index c039b34..62f53e3 100644 --- a/adafruit_rgb_display/rgb.py +++ b/adafruit_rgb_display/rgb.py @@ -16,10 +16,10 @@ import time try: - from typing import Optional, Union, Tuple, List, Any, ByteString - import digitalio - import busio + from typing import Any, ByteString, List, Optional, Tuple, Union + import busio + import digitalio from circuitpython_typing.pil import Image except ImportError: pass @@ -58,9 +58,7 @@ def color565( if len(r) >= 3: red, g, b = r[0:3] else: - raise ValueError( - "Not enough values to unpack (expected 3, got %d)" % len(r) - ) + raise ValueError("Not enough values to unpack (expected 3, got %d)" % len(r)) else: red = r return (red & 0xF8) << 8 | (g & 0xFC) << 3 | b >> 3 @@ -71,11 +69,7 @@ def image_to_data(image: Image) -> Any: # NumPy is much faster at doing this. NumPy code provided by: # Keith (https://www.blogger.com/profile/02555547344016007163) data = numpy.array(image.convert("RGB")).astype("uint16") - color = ( - ((data[:, :, 0] & 0xF8) << 8) - | ((data[:, :, 1] & 0xFC) << 3) - | (data[:, :, 2] >> 3) - ) + color = ((data[:, :, 0] & 0xF8) << 8) | ((data[:, :, 1] & 0xFC) << 3) | (data[:, :, 2] >> 3) return numpy.dstack(((color >> 8) & 0xFF, color & 0xFF)).flatten().tolist() @@ -138,14 +132,12 @@ class Display: # pylint: disable-msg=no-member def __init__(self, width: int, height: int, rotation: int) -> None: self.width = width self.height = height - if rotation not in (0, 90, 180, 270): + if rotation not in {0, 90, 180, 270}: raise ValueError("Rotation must be 0/90/180/270") self._rotation = rotation self.init() - def write( - self, command: Optional[int] = None, data: Optional[ByteString] = None - ) -> None: + def write(self, command: Optional[int] = None, data: Optional[ByteString] = None) -> None: """Abstract method""" raise NotImplementedError() @@ -163,12 +155,8 @@ def _block( self, x0: int, y0: int, x1: int, y1: int, data: Optional[ByteString] = None ) -> Optional[ByteString]: """Read or write a block of data.""" - self.write( - self._COLUMN_SET, self._encode_pos(x0 + self._X_START, x1 + self._X_START) - ) - self.write( - self._PAGE_SET, self._encode_pos(y0 + self._Y_START, y1 + self._Y_START) - ) + self.write(self._COLUMN_SET, self._encode_pos(x0 + self._X_START, x1 + self._X_START)) + self.write(self._PAGE_SET, self._encode_pos(y0 + self._Y_START, y1 + self._Y_START)) if data is None: size = struct.calcsize(self._DECODE_PIXEL) return self.read(self._RAM_READ, (x1 - x0 + 1) * (y1 - y0 + 1) * size) @@ -189,9 +177,7 @@ def _decode_pixel(self, data: Union[bytes, Union[bytearray, memoryview]]) -> int """Decode bytes into a pixel color.""" return color565(*struct.unpack(self._DECODE_PIXEL, data)) - def pixel( - self, x: int, y: int, color: Optional[Union[int, Tuple]] = None - ) -> Optional[int]: + def pixel(self, x: int, y: int, color: Optional[Union[int, Tuple]] = None) -> Optional[int]: """Read or write a pixel at a given position.""" if color is None: return self._decode_pixel(self._block(x, y, x, y)) # type: ignore[arg-type] @@ -212,19 +198,15 @@ def image( the supplied origin.""" if rotation is None: rotation = self.rotation - if not img.mode in ("RGB", "RGBA"): + if not img.mode in {"RGB", "RGBA"}: raise ValueError("Image must be in mode RGB or RGBA") - if rotation not in (0, 90, 180, 270): + if rotation not in {0, 90, 180, 270}: raise ValueError("Rotation must be 0/90/180/270") if rotation != 0: img = img.rotate(rotation, expand=True) imwidth, imheight = img.size if x + imwidth > self.width or y + imheight > self.height: - raise ValueError( - "Image must not exceed dimensions of display ({0}x{1}).".format( - self.width, self.height - ) - ) + raise ValueError(f"Image must not exceed dimensions of display ({self.width}x{self.height}).") if numpy: pixels = bytes(image_to_data(img)) else: @@ -238,9 +220,7 @@ def image( self._block(x, y, x + imwidth - 1, y + imheight - 1, pixels) # pylint: disable-msg=too-many-arguments - def fill_rectangle( - self, x: int, y: int, width: int, height: int, color: Union[int, Tuple] - ) -> None: + def fill_rectangle(self, x: int, y: int, width: int, height: int, color: Union[int, Tuple]) -> None: """Draw a rectangle at specified position with specified width and height, and fill it with the specified color.""" x = min(self.width - 1, max(0, x)) @@ -277,7 +257,7 @@ def rotation(self) -> int: @rotation.setter def rotation(self, val: int) -> None: - if val not in (0, 90, 180, 270): + if val not in {0, 90, 180, 270}: raise ValueError("Rotation must be 0/90/180/270") self._rotation = val @@ -300,11 +280,9 @@ def __init__( *, x_offset: int = 0, y_offset: int = 0, - rotation: int = 0 + rotation: int = 0, ): - self.spi_device = spi_device.SPIDevice( - spi, cs, baudrate=baudrate, polarity=polarity, phase=phase - ) + self.spi_device = spi_device.SPIDevice(spi, cs, baudrate=baudrate, polarity=polarity, phase=phase) self.dc_pin = dc self.rst = rst self.dc_pin.switch_to_output(value=0) @@ -327,9 +305,7 @@ def reset(self) -> None: time.sleep(0.050) # 50 milliseconds # pylint: disable=no-member - def write( - self, command: Optional[int] = None, data: Optional[ByteString] = None - ) -> None: + def write(self, command: Optional[int] = None, data: Optional[ByteString] = None) -> None: """SPI write to the device: commands and data""" if command is not None: self.dc_pin.value = 0 diff --git a/adafruit_rgb_display/s6d02a1.py b/adafruit_rgb_display/s6d02a1.py index 568cdec..06b1c3d 100644 --- a/adafruit_rgb_display/s6d02a1.py +++ b/adafruit_rgb_display/s6d02a1.py @@ -13,12 +13,14 @@ """ from micropython import const + from adafruit_rgb_display.rgb import DisplaySPI try: from typing import Optional - import digitalio + import busio + import digitalio except ImportError: pass diff --git a/adafruit_rgb_display/ssd1331.py b/adafruit_rgb_display/ssd1331.py index 86e0cca..8f90848 100644 --- a/adafruit_rgb_display/ssd1331.py +++ b/adafruit_rgb_display/ssd1331.py @@ -13,12 +13,14 @@ """ from micropython import const + from adafruit_rgb_display.rgb import DisplaySPI try: - from typing import Optional, ByteString - import digitalio + from typing import ByteString, Optional + import busio + import digitalio except ImportError: pass @@ -125,7 +127,7 @@ def __init__( polarity: int = 0, phase: int = 0, *, - rotation: int = 0 + rotation: int = 0, ) -> None: super().__init__( spi, @@ -141,9 +143,7 @@ def __init__( ) # pylint: disable=no-member - def write( - self, command: Optional[int] = None, data: Optional[ByteString] = None - ) -> None: + def write(self, command: Optional[int] = None, data: Optional[ByteString] = None) -> None: """write procedure specific to SSD1331""" self.dc_pin.value = command is None with self.spi_device as spi: diff --git a/adafruit_rgb_display/ssd1351.py b/adafruit_rgb_display/ssd1351.py index 03e58ab..3208289 100644 --- a/adafruit_rgb_display/ssd1351.py +++ b/adafruit_rgb_display/ssd1351.py @@ -11,13 +11,16 @@ * Author(s): Radomir Dopieralski, Michael McWethy, Matt Land """ + from micropython import const + from adafruit_rgb_display.rgb import DisplaySPI try: from typing import Optional - import digitalio + import busio + import digitalio except ImportError: pass @@ -119,7 +122,7 @@ def __init__( *, x_offset: int = 0, y_offset: int = 0, - rotation: int = 0 + rotation: int = 0, ): super().__init__( spi, diff --git a/adafruit_rgb_display/st7735.py b/adafruit_rgb_display/st7735.py index 0191a15..4582f91 100644 --- a/adafruit_rgb_display/st7735.py +++ b/adafruit_rgb_display/st7735.py @@ -11,15 +11,18 @@ * Author(s): Radomir Dopieralski, Michael McWethy, Matt Land """ + import struct from micropython import const + from adafruit_rgb_display.rgb import DisplaySPI try: - from typing import Optional, Tuple, ByteString, Union - import digitalio + from typing import ByteString, Optional, Tuple, Union + import busio + import digitalio except ImportError: pass @@ -179,11 +182,11 @@ class ST7735R(ST7735): (_INVOFF, None), ( _GMCTRP1, - b"\x02\x1c\x07\x12\x37\x32\x29\x2d" b"\x29\x25\x2B\x39\x00\x01\x03\x10", + b"\x02\x1c\x07\x12\x37\x32\x29\x2d" b"\x29\x25\x2b\x39\x00\x01\x03\x10", ), # Gamma ( _GMCTRN1, - b"\x03\x1d\x07\x06\x2E\x2C\x29\x2D" b"\x2E\x2E\x37\x3F\x00\x00\x02\x10", + b"\x03\x1d\x07\x06\x2e\x2c\x29\x2d" b"\x2e\x2e\x37\x3f\x00\x00\x02\x10", ), ) diff --git a/adafruit_rgb_display/st7789.py b/adafruit_rgb_display/st7789.py index 3fcfc43..75f300e 100644 --- a/adafruit_rgb_display/st7789.py +++ b/adafruit_rgb_display/st7789.py @@ -17,6 +17,7 @@ import busio import digitalio from micropython import const + from adafruit_rgb_display.rgb import DisplaySPI try: @@ -116,7 +117,7 @@ def __init__( *, x_offset: int = 0, y_offset: int = 0, - rotation: int = 0 + rotation: int = 0, ) -> None: super().__init__( spi, diff --git a/docs/api.rst b/docs/api.rst index f5219f6..0303cb6 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_rgb_display.rgb :members: diff --git a/docs/conf.py b/docs/conf.py index 1ec3924..6ad6c55 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("..")) @@ -48,11 +46,7 @@ project = "Adafruit RGB_Display Library" creation_year = "2017" current_year = str(datetime.datetime.now().year) -year_duration = ( - current_year - if current_year == creation_year - else creation_year + " - " + current_year -) +year_duration = current_year if current_year == creation_year else creation_year + " - " + current_year copyright = year_duration + " Michale McWethy" author = "Michale McWethy" diff --git a/examples/rgb_display_eyespi_beret_animated_gif.py b/examples/rgb_display_eyespi_beret_animated_gif.py index 2ac205b..b5cab34 100644 --- a/examples/rgb_display_eyespi_beret_animated_gif.py +++ b/examples/rgb_display_eyespi_beret_animated_gif.py @@ -19,18 +19,23 @@ Author(s): Melissa LeBlanc-Williams for Adafruit Industries Mike Mallett """ + import os import time -import digitalio + import board -from PIL import Image, ImageOps +import digitalio import numpy # pylint: disable=unused-import -from adafruit_rgb_display import ili9341 -from adafruit_rgb_display import st7789 # pylint: disable=unused-import -from adafruit_rgb_display import hx8357 # pylint: disable=unused-import -from adafruit_rgb_display import st7735 # pylint: disable=unused-import -from adafruit_rgb_display import ssd1351 # pylint: disable=unused-import -from adafruit_rgb_display import ssd1331 # pylint: disable=unused-import +from PIL import Image, ImageOps + +from adafruit_rgb_display import ( + hx8357, # pylint: disable=unused-import + ili9341, + ssd1331, # pylint: disable=unused-import + ssd1351, # pylint: disable=unused-import + st7735, # pylint: disable=unused-import + st7789, # pylint: disable=unused-import +) # Button pins for EYESPI Pi Beret BUTTON_NEXT = board.D5 @@ -67,7 +72,7 @@ # disp = st7735.ST7735R(spi, rotation=90, # 1.8" ST7735R # disp = st7735.ST7735R(spi, rotation=270, height=128, x_offset=2, y_offset=3, # 1.44" ST7735R # disp = st7735.ST7735R(spi, rotation=90, bgr=True, width=80, # 0.96" MiniTFT Rev A ST7735R -# disp = st7735.ST7735R(spi, rotation=90, invert=True, width=80, x_offset=26, y_offset=1, # 0.96" MiniTFT Rev B ST7735R +# disp = st7735.ST7735R(spi, rotation=90, invert=True, width=80, x_offset=26, y_offset=1, # 0.96" MiniTFT Rev B ST7735R # noqa: E501 # disp = ssd1351.SSD1351(spi, rotation=180, # 1.5" SSD1351 # disp = ssd1351.SSD1351(spi, height=96, y_offset=32, rotation=180, # 1.27" SSD1351 # disp = ssd1331.SSD1331(spi, rotation=180, # 0.96" SSD1331 @@ -126,7 +131,7 @@ def back(self): def load_files(self, folder): gif_files = [f for f in os.listdir(folder) if f.endswith(".gif")] for gif_file in gif_files: - gif_file = os.path.join(folder, gif_file) + gif_file = os.path.join(folder, gif_file) # noqa: PLW2901, loop var overwrite image = Image.open(gif_file) # Only add animated Gifs if image.is_animated: @@ -135,11 +140,11 @@ def load_files(self, folder): print("Found", self._gif_files) if not self._gif_files: print("No Gif files found in current folder") - exit() # pylint: disable=consider-using-sys-exit + exit() # noqa: PLR1722, use sys.exit def preload(self): image = Image.open(self._gif_files[self._index]) - print("Loading {}...".format(self._gif_files[self._index])) + print(f"Loading {self._gif_files[self._index]}...") if "duration" in image.info: self._duration = image.info["duration"] else: diff --git a/examples/rgb_display_fbcp.py b/examples/rgb_display_fbcp.py index 63b210e..910d31b 100644 --- a/examples/rgb_display_fbcp.py +++ b/examples/rgb_display_fbcp.py @@ -1,14 +1,16 @@ # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT -import time -import os import fcntl import mmap +import os import struct -import digitalio +import time + import board +import digitalio from PIL import Image, ImageDraw + from adafruit_rgb_display import st7789 # definitions from linux/fb.h @@ -52,16 +54,12 @@ def __init__(self, dev): "8I12I16I4I", fcntl.ioctl(self.fbfd, FBIOGET_VSCREENINFO, " " * ((8 + 12 + 16 + 4) * 4)), ) - finfo = struct.unpack( - "16cL4I3HI", fcntl.ioctl(self.fbfd, FBIOGET_FSCREENINFO, " " * 48) - ) + finfo = struct.unpack("16cL4I3HI", fcntl.ioctl(self.fbfd, FBIOGET_FSCREENINFO, " " * 48)) bytes_per_pixel = (vinfo[6] + 7) // 8 screensize = vinfo[0] * vinfo[1] * bytes_per_pixel - fbp = mmap.mmap( - self.fbfd, screensize, flags=mmap.MAP_SHARED, prot=mmap.PROT_READ - ) + fbp = mmap.mmap(self.fbfd, screensize, flags=mmap.MAP_SHARED, prot=mmap.PROT_READ) self.fbp = fbp self.xres = vinfo[0] @@ -93,7 +91,7 @@ def blank(self, blank): fcntl.ioctl(self.fbfd, FBIOBLANK, FB_BLANK_POWERDOWN) else: fcntl.ioctl(self.fbfd, FBIOBLANK, FB_BLANK_UNBLANK) - except IOError: + except OSError: pass def __str__(self): @@ -122,9 +120,9 @@ def __str__(self): type_name = type_list[self.type] return ( - 'mode "%sx%s"\n' % (self.xres, self.yres) + 'mode "%sx%s"\n' % (self.xres, self.yres) # noqa: UP031 + " nonstd %s\n" % self.nonstd - + " rgba %s/%s,%s/%s,%s/%s,%s/%s\n" + + " rgba %s/%s,%s/%s,%s/%s,%s/%s\n" # noqa: UP031 % ( self.red.length, self.red.offset, diff --git a/examples/rgb_display_hx8357test.py b/examples/rgb_display_hx8357test.py index 83036c8..12eca84 100644 --- a/examples/rgb_display_hx8357test.py +++ b/examples/rgb_display_hx8357test.py @@ -4,13 +4,14 @@ # Quick test of 3.5" TFT FeatherWing (HX8357) with Feather M0 or M4 # Will fill the TFT black and put a red pixel in the center, wait 2 seconds, # then fill the screen blue (with no pixel), wait 2 seconds, and repeat. -import time import random -import digitalio +import time + import board +import digitalio -from adafruit_rgb_display.rgb import color565 from adafruit_rgb_display import hx8357 +from adafruit_rgb_display.rgb import color565 # Configuration for CS and DC pins (these are TFT FeatherWing defaults): cs_pin = digitalio.DigitalInOut(board.D9) @@ -37,8 +38,6 @@ # Pause 2 seconds. time.sleep(2) # Clear the screen a random color - display.fill( - color565(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) - ) + display.fill(color565(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))) # Pause 2 seconds. time.sleep(2) diff --git a/examples/rgb_display_ili9341test.py b/examples/rgb_display_ili9341test.py index 38ba796..2fe3f0f 100644 --- a/examples/rgb_display_ili9341test.py +++ b/examples/rgb_display_ili9341test.py @@ -4,15 +4,15 @@ # Quick test of TFT FeatherWing (ILI9341) with Feather M0 or M4 # Will fill the TFT black and put a red pixel in the center, wait 2 seconds, # then fill the screen blue (with no pixel), wait 2 seconds, and repeat. -import time import random +import time + +import board import busio import digitalio -import board -from adafruit_rgb_display.rgb import color565 from adafruit_rgb_display import ili9341 - +from adafruit_rgb_display.rgb import color565 # Configuratoin for CS and DC pins (these are FeatherWing defaults on M0/M4): cs_pin = digitalio.DigitalInOut(board.D9) @@ -39,8 +39,6 @@ # Pause 2 seconds. time.sleep(2) # Clear the screen a random color - display.fill( - color565(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) - ) + display.fill(color565(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))) # Pause 2 seconds. time.sleep(2) diff --git a/examples/rgb_display_minipitftstats.py b/examples/rgb_display_minipitftstats.py index 1f625ed..48c480f 100644 --- a/examples/rgb_display_minipitftstats.py +++ b/examples/rgb_display_minipitftstats.py @@ -3,13 +3,14 @@ # -*- coding: utf-8 -*- -import time import subprocess -import digitalio +import time + import board +import digitalio from PIL import Image, ImageDraw, ImageFont -from adafruit_rgb_display import st7789 +from adafruit_rgb_display import st7789 # Configuration for CS and DC pins (these are FeatherWing defaults on M0/M4): cs_pin = digitalio.DigitalInOut(board.CE0) diff --git a/examples/rgb_display_minipitfttest.py b/examples/rgb_display_minipitfttest.py index c418229..eeaab5d 100644 --- a/examples/rgb_display_minipitfttest.py +++ b/examples/rgb_display_minipitfttest.py @@ -1,11 +1,11 @@ # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT -import digitalio import board +import digitalio -from adafruit_rgb_display.rgb import color565 from adafruit_rgb_display import st7789 +from adafruit_rgb_display.rgb import color565 # Configuration for CS and DC pins for Raspberry Pi cs_pin = digitalio.DigitalInOut(board.CE0) diff --git a/examples/rgb_display_pillow_animated_gif.py b/examples/rgb_display_pillow_animated_gif.py index cc3a628..701d762 100644 --- a/examples/rgb_display_pillow_animated_gif.py +++ b/examples/rgb_display_pillow_animated_gif.py @@ -15,18 +15,23 @@ Author(s): Melissa LeBlanc-Williams for Adafruit Industries Mike Mallett """ + import os import time -import digitalio + import board -from PIL import Image, ImageOps +import digitalio import numpy # pylint: disable=unused-import -from adafruit_rgb_display import ili9341 -from adafruit_rgb_display import st7789 # pylint: disable=unused-import -from adafruit_rgb_display import hx8357 # pylint: disable=unused-import -from adafruit_rgb_display import st7735 # pylint: disable=unused-import -from adafruit_rgb_display import ssd1351 # pylint: disable=unused-import -from adafruit_rgb_display import ssd1331 # pylint: disable=unused-import +from PIL import Image, ImageOps + +from adafruit_rgb_display import ( + hx8357, # pylint: disable=unused-import + ili9341, + ssd1331, # pylint: disable=unused-import + ssd1351, # pylint: disable=unused-import + st7735, # pylint: disable=unused-import + st7789, # pylint: disable=unused-import +) # Change to match your display BUTTON_NEXT = board.D17 @@ -90,7 +95,7 @@ def back(self): def load_files(self, folder): gif_files = [f for f in os.listdir(folder) if f.endswith(".gif")] for gif_file in gif_files: - gif_file = os.path.join(folder, gif_file) + gif_file = os.path.join(folder, gif_file) # noqa: PLW2901, loop var overwrite image = Image.open(gif_file) # Only add animated Gifs if image.is_animated: @@ -99,11 +104,11 @@ def load_files(self, folder): print("Found", self._gif_files) if not self._gif_files: print("No Gif files found in current folder") - exit() # pylint: disable=consider-using-sys-exit + exit() # noqa: PLR1722, sys.exit def preload(self): image = Image.open(self._gif_files[self._index]) - print("Loading {}...".format(self._gif_files[self._index])) + print(f"Loading {self._gif_files[self._index]}...") if "duration" in image.info: self._duration = image.info["duration"] else: diff --git a/examples/rgb_display_pillow_bonnet_buttons.py b/examples/rgb_display_pillow_bonnet_buttons.py index 91bb656..cac9d7e 100644 --- a/examples/rgb_display_pillow_bonnet_buttons.py +++ b/examples/rgb_display_pillow_bonnet_buttons.py @@ -32,12 +32,14 @@ not support PIL/pillow (python imaging library)! """ -import time import random +import time from colorsys import hsv_to_rgb + import board from digitalio import DigitalInOut, Direction from PIL import Image, ImageDraw, ImageFont + from adafruit_rgb_display import st7789 # Create the display @@ -115,30 +117,22 @@ up_fill = 0 if not button_U.value: # up pressed up_fill = udlr_fill - draw.polygon( - [(40, 40), (60, 4), (80, 40)], outline=udlr_outline, fill=up_fill - ) # Up + draw.polygon([(40, 40), (60, 4), (80, 40)], outline=udlr_outline, fill=up_fill) # Up down_fill = 0 if not button_D.value: # down pressed down_fill = udlr_fill - draw.polygon( - [(60, 120), (80, 84), (40, 84)], outline=udlr_outline, fill=down_fill - ) # down + draw.polygon([(60, 120), (80, 84), (40, 84)], outline=udlr_outline, fill=down_fill) # down left_fill = 0 if not button_L.value: # left pressed left_fill = udlr_fill - draw.polygon( - [(0, 60), (36, 42), (36, 81)], outline=udlr_outline, fill=left_fill - ) # left + draw.polygon([(0, 60), (36, 42), (36, 81)], outline=udlr_outline, fill=left_fill) # left right_fill = 0 if not button_R.value: # right pressed right_fill = udlr_fill - draw.polygon( - [(120, 60), (84, 42), (84, 82)], outline=udlr_outline, fill=right_fill - ) # right + draw.polygon([(120, 60), (84, 42), (84, 82)], outline=udlr_outline, fill=right_fill) # right center_fill = 0 if not button_C.value: # center pressed diff --git a/examples/rgb_display_pillow_demo.py b/examples/rgb_display_pillow_demo.py index dc6eb56..e85691b 100644 --- a/examples/rgb_display_pillow_demo.py +++ b/examples/rgb_display_pillow_demo.py @@ -12,15 +12,18 @@ Author(s): Melissa LeBlanc-Williams for Adafruit Industries """ -import digitalio import board +import digitalio from PIL import Image, ImageDraw, ImageFont -from adafruit_rgb_display import ili9341 -from adafruit_rgb_display import st7789 # pylint: disable=unused-import -from adafruit_rgb_display import hx8357 # pylint: disable=unused-import -from adafruit_rgb_display import st7735 # pylint: disable=unused-import -from adafruit_rgb_display import ssd1351 # pylint: disable=unused-import -from adafruit_rgb_display import ssd1331 # pylint: disable=unused-import + +from adafruit_rgb_display import ( + hx8357, # pylint: disable=unused-import + ili9341, + ssd1331, # pylint: disable=unused-import + ssd1351, # pylint: disable=unused-import + st7735, # pylint: disable=unused-import + st7789, # pylint: disable=unused-import +) # First define some constants to allow easy resizing of shapes. BORDER = 20 @@ -82,9 +85,7 @@ disp.image(image) # Draw a smaller inner purple rectangle -draw.rectangle( - (BORDER, BORDER, width - BORDER - 1, height - BORDER - 1), fill=(170, 0, 136) -) +draw.rectangle((BORDER, BORDER, width - BORDER - 1, height - BORDER - 1), fill=(170, 0, 136)) # Load a TTF Font font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", FONTSIZE) diff --git a/examples/rgb_display_pillow_image.py b/examples/rgb_display_pillow_image.py index b463106..61e7f13 100644 --- a/examples/rgb_display_pillow_image.py +++ b/examples/rgb_display_pillow_image.py @@ -11,15 +11,18 @@ Author(s): Melissa LeBlanc-Williams for Adafruit Industries """ -import digitalio import board +import digitalio from PIL import Image, ImageDraw -from adafruit_rgb_display import ili9341 -from adafruit_rgb_display import st7789 # pylint: disable=unused-import -from adafruit_rgb_display import hx8357 # pylint: disable=unused-import -from adafruit_rgb_display import st7735 # pylint: disable=unused-import -from adafruit_rgb_display import ssd1351 # pylint: disable=unused-import -from adafruit_rgb_display import ssd1331 # pylint: disable=unused-import + +from adafruit_rgb_display import ( + hx8357, # pylint: disable=unused-import + ili9341, + ssd1331, # pylint: disable=unused-import + ssd1351, # pylint: disable=unused-import + st7735, # pylint: disable=unused-import + st7789, # pylint: disable=unused-import +) # Configuration for CS and DC pins (these are PiTFT defaults): cs_pin = digitalio.DigitalInOut(board.CE0) diff --git a/examples/rgb_display_pillow_stats.py b/examples/rgb_display_pillow_stats.py index 748f2ca..4a6d668 100644 --- a/examples/rgb_display_pillow_stats.py +++ b/examples/rgb_display_pillow_stats.py @@ -11,17 +11,21 @@ not support PIL/pillow (python imaging library)! """ -import time import subprocess -import digitalio +import time + import board +import digitalio from PIL import Image, ImageDraw, ImageFont -from adafruit_rgb_display import ili9341 -from adafruit_rgb_display import st7789 # pylint: disable=unused-import -from adafruit_rgb_display import hx8357 # pylint: disable=unused-import -from adafruit_rgb_display import st7735 # pylint: disable=unused-import -from adafruit_rgb_display import ssd1351 # pylint: disable=unused-import -from adafruit_rgb_display import ssd1331 # pylint: disable=unused-import + +from adafruit_rgb_display import ( + hx8357, # pylint: disable=unused-import + ili9341, + ssd1331, # pylint: disable=unused-import + ssd1351, # pylint: disable=unused-import + st7735, # pylint: disable=unused-import + st7789, # pylint: disable=unused-import +) # Configuration for CS and DC pins (these are PiTFT defaults): cs_pin = digitalio.DigitalInOut(board.CE0) diff --git a/examples/rgb_display_simpletest.py b/examples/rgb_display_simpletest.py index 8f7f7f0..0546972 100644 --- a/examples/rgb_display_simpletest.py +++ b/examples/rgb_display_simpletest.py @@ -5,13 +5,14 @@ # This will work even on a device running displayio # Will fill the TFT black and put a red pixel in the center, wait 2 seconds, # then fill the screen blue (with no pixel), wait 2 seconds, and repeat. -import time import random -import digitalio +import time + import board +import digitalio -from adafruit_rgb_display.rgb import color565 from adafruit_rgb_display import st7789 +from adafruit_rgb_display.rgb import color565 # Configuratoin for CS and DC pins (these are FeatherWing defaults on M0/M4): cs_pin = digitalio.DigitalInOut(board.D5) @@ -39,8 +40,6 @@ # Pause 2 seconds. time.sleep(2) # Clear the screen a random color - display.fill( - color565(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) - ) + display.fill(color565(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))) # Pause 2 seconds. time.sleep(2) diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 0000000..04e88ad --- /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 = 110 + +[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 + "PLR0917", # too many positional arguments +# "", +# "", +# "", +# "", +] + +[format] +line-ending = "lf" From 864f1cf1ede975daad5e95fd3d95c1d101834cde Mon Sep 17 00:00:00 2001 From: foamyguy Date: Tue, 29 Apr 2025 17:39:11 -0500 Subject: [PATCH 25/31] remove pylint disable comments --- adafruit_rgb_display/gc9a01a.py | 1 - adafruit_rgb_display/hx8353.py | 1 - adafruit_rgb_display/hx8357.py | 1 - adafruit_rgb_display/ili9341.py | 5 +---- adafruit_rgb_display/rgb.py | 20 +++++-------------- adafruit_rgb_display/s6d02a1.py | 1 - adafruit_rgb_display/ssd1331.py | 3 --- adafruit_rgb_display/ssd1351.py | 1 - adafruit_rgb_display/st7735.py | 3 --- adafruit_rgb_display/st7789.py | 1 - .../rgb_display_eyespi_beret_animated_gif.py | 18 ++++++++--------- examples/rgb_display_fbcp.py | 4 ++-- examples/rgb_display_minipitftstats.py | 2 +- examples/rgb_display_pillow_animated_gif.py | 20 +++++++------------ examples/rgb_display_pillow_demo.py | 12 +++++------ examples/rgb_display_pillow_image.py | 13 ++++++------ examples/rgb_display_pillow_stats.py | 14 ++++++------- 17 files changed, 41 insertions(+), 79 deletions(-) diff --git a/adafruit_rgb_display/gc9a01a.py b/adafruit_rgb_display/gc9a01a.py index e899004..18f5809 100644 --- a/adafruit_rgb_display/gc9a01a.py +++ b/adafruit_rgb_display/gc9a01a.py @@ -85,7 +85,6 @@ class GC9A01A(DisplaySPI): (_DISPON, None), # Display ON ) - # pylint: disable-msg=useless-super-delegation, too-many-arguments def __init__( self, spi: busio.SPI, diff --git a/adafruit_rgb_display/hx8353.py b/adafruit_rgb_display/hx8353.py index d1da61c..2c7c8dc 100644 --- a/adafruit_rgb_display/hx8353.py +++ b/adafruit_rgb_display/hx8353.py @@ -68,7 +68,6 @@ class HX8353(DisplaySPI): _ENCODE_PIXEL = ">H" _ENCODE_POS = ">HH" - # pylint: disable-msg=useless-super-delegation, too-many-arguments def __init__( self, spi: busio.SPI, diff --git a/adafruit_rgb_display/hx8357.py b/adafruit_rgb_display/hx8357.py index 432705e..1a0feea 100755 --- a/adafruit_rgb_display/hx8357.py +++ b/adafruit_rgb_display/hx8357.py @@ -102,7 +102,6 @@ class HX8357(DisplaySPI): _ENCODE_PIXEL = ">H" _ENCODE_POS = ">HH" - # pylint: disable-msg=useless-super-delegation, too-many-arguments def __init__( self, spi: busio.SPI, diff --git a/adafruit_rgb_display/ili9341.py b/adafruit_rgb_display/ili9341.py index 3e79787..018b87d 100644 --- a/adafruit_rgb_display/ili9341.py +++ b/adafruit_rgb_display/ili9341.py @@ -81,7 +81,6 @@ class ILI9341(DisplaySPI): _ENCODE_POS = ">HH" _DECODE_PIXEL = ">BBB" - # pylint: disable-msg=too-many-arguments def __init__( self, spi: busio.SPI, @@ -109,11 +108,9 @@ def __init__( ) self._scroll = 0 - # pylint: enable-msg=too-many-arguments - def scroll( self, - dy: Optional[int] = None, # pylint: disable-msg=invalid-name + dy: Optional[int] = None, ) -> Optional[int]: """Scroll the display by delta y""" if dy is None: diff --git a/adafruit_rgb_display/rgb.py b/adafruit_rgb_display/rgb.py index 62f53e3..8cfa5c9 100644 --- a/adafruit_rgb_display/rgb.py +++ b/adafruit_rgb_display/rgb.py @@ -112,7 +112,7 @@ def pull(self, val: digitalio.Pull) -> None: pass -class Display: # pylint: disable-msg=no-member +class Display: """Base class for all RGB display devices :param width: number of pixels wide :param height: number of pixels high @@ -122,8 +122,8 @@ class Display: # pylint: disable-msg=no-member _COLUMN_SET: Optional[int] = None _RAM_WRITE: Optional[int] = None _RAM_READ: Optional[int] = None - _X_START = 0 # pylint: disable=invalid-name - _Y_START = 0 # pylint: disable=invalid-name + _X_START = 0 + _Y_START = 0 _INIT: Tuple[Tuple[int, Union[ByteString, None]], ...] = () _ENCODE_PIXEL = ">H" _ENCODE_POS = ">HH" @@ -150,7 +150,6 @@ def init(self) -> None: for command, data in self._INIT: self.write(command, data) - # pylint: disable-msg=invalid-name,too-many-arguments def _block( self, x0: int, y0: int, x1: int, y1: int, data: Optional[ByteString] = None ) -> Optional[ByteString]: @@ -163,8 +162,6 @@ def _block( self.write(self._RAM_WRITE, data) return None - # pylint: enable-msg=invalid-name,too-many-arguments - def _encode_pos(self, x: int, y: int) -> bytes: """Encode a position into bytes.""" return struct.pack(self._ENCODE_POS, x, y) @@ -219,7 +216,6 @@ def image( pixels[2 * (j * imwidth + i) + 1] = pix & 0xFF self._block(x, y, x + imwidth - 1, y + imheight - 1, pixels) - # pylint: disable-msg=too-many-arguments def fill_rectangle(self, x: int, y: int, width: int, height: int, color: Union[int, Tuple]) -> None: """Draw a rectangle at specified position with specified width and height, and fill it with the specified color.""" @@ -236,8 +232,6 @@ def fill_rectangle(self, x: int, y: int, width: int, height: int, color: Union[i self.write(None, data) self.write(None, pixel * rest) - # pylint: enable-msg=too-many-arguments - def fill(self, color: Union[int, Tuple] = 0) -> None: """Fill the whole display with the specified color.""" self.fill_rectangle(0, 0, self.width, self.height, color) @@ -265,7 +259,6 @@ def rotation(self, val: int) -> None: class DisplaySPI(Display): """Base class for SPI type devices""" - # pylint: disable-msg=too-many-arguments def __init__( self, spi: busio.SPI, @@ -289,12 +282,10 @@ def __init__( if self.rst: self.rst.switch_to_output(value=0) self.reset() - self._X_START = x_offset # pylint: disable=invalid-name - self._Y_START = y_offset # pylint: disable=invalid-name + self._X_START = x_offset + self._Y_START = y_offset super().__init__(width, height, rotation) - # pylint: enable-msg=too-many-arguments - def reset(self) -> None: """Reset the device""" if not self.rst: @@ -304,7 +295,6 @@ def reset(self) -> None: self.rst.value = 1 time.sleep(0.050) # 50 milliseconds - # pylint: disable=no-member def write(self, command: Optional[int] = None, data: Optional[ByteString] = None) -> None: """SPI write to the device: commands and data""" if command is not None: diff --git a/adafruit_rgb_display/s6d02a1.py b/adafruit_rgb_display/s6d02a1.py index 06b1c3d..9382988 100644 --- a/adafruit_rgb_display/s6d02a1.py +++ b/adafruit_rgb_display/s6d02a1.py @@ -68,7 +68,6 @@ class S6D02A1(DisplaySPI): _ENCODE_PIXEL = ">H" _ENCODE_POS = ">HH" - # pylint: disable-msg=useless-super-delegation, too-many-arguments def __init__( self, spi: busio.SPI, diff --git a/adafruit_rgb_display/ssd1331.py b/adafruit_rgb_display/ssd1331.py index 8f90848..6947c13 100644 --- a/adafruit_rgb_display/ssd1331.py +++ b/adafruit_rgb_display/ssd1331.py @@ -113,8 +113,6 @@ class SSD1331(DisplaySPI): _ENCODE_PIXEL = ">H" _ENCODE_POS = ">BB" - # pylint: disable-msg=useless-super-delegation, too-many-arguments - # super required to allow override of default values def __init__( self, spi: busio.SPI, @@ -142,7 +140,6 @@ def __init__( rotation=rotation, ) - # pylint: disable=no-member def write(self, command: Optional[int] = None, data: Optional[ByteString] = None) -> None: """write procedure specific to SSD1331""" self.dc_pin.value = command is None diff --git a/adafruit_rgb_display/ssd1351.py b/adafruit_rgb_display/ssd1351.py index 3208289..e2416a7 100644 --- a/adafruit_rgb_display/ssd1351.py +++ b/adafruit_rgb_display/ssd1351.py @@ -107,7 +107,6 @@ class SSD1351(DisplaySPI): _ENCODE_PIXEL = ">H" _ENCODE_POS = ">BB" - # pylint: disable-msg=useless-super-delegation, too-many-arguments def __init__( self, spi: busio.SPI, diff --git a/adafruit_rgb_display/st7735.py b/adafruit_rgb_display/st7735.py index 4582f91..e623a5d 100644 --- a/adafruit_rgb_display/st7735.py +++ b/adafruit_rgb_display/st7735.py @@ -128,7 +128,6 @@ class ST7735(DisplaySPI): _ENCODE_PIXEL = ">H" _ENCODE_POS = ">HH" - # pylint: disable-msg=useless-super-delegation, too-many-arguments def __init__( self, spi: busio.SPI, @@ -190,7 +189,6 @@ class ST7735R(ST7735): ), ) - # pylint: disable-msg=useless-super-delegation, too-many-arguments def __init__( self, spi: busio.SPI, @@ -279,7 +277,6 @@ class ST7735S(ST7735): (_DISPON, None), ) - # pylint: disable-msg=useless-super-delegation, too-many-arguments def __init__( self, spi: busio.SPI, diff --git a/adafruit_rgb_display/st7789.py b/adafruit_rgb_display/st7789.py index 75f300e..2148789 100644 --- a/adafruit_rgb_display/st7789.py +++ b/adafruit_rgb_display/st7789.py @@ -102,7 +102,6 @@ class ST7789(DisplaySPI): (_MADCTL, b"\x08"), ) - # pylint: disable-msg=useless-super-delegation, too-many-arguments def __init__( self, spi: busio.SPI, diff --git a/examples/rgb_display_eyespi_beret_animated_gif.py b/examples/rgb_display_eyespi_beret_animated_gif.py index b5cab34..92b354a 100644 --- a/examples/rgb_display_eyespi_beret_animated_gif.py +++ b/examples/rgb_display_eyespi_beret_animated_gif.py @@ -25,16 +25,16 @@ import board import digitalio -import numpy # pylint: disable=unused-import +import numpy from PIL import Image, ImageOps from adafruit_rgb_display import ( - hx8357, # pylint: disable=unused-import + hx8357, ili9341, - ssd1331, # pylint: disable=unused-import - ssd1351, # pylint: disable=unused-import - st7735, # pylint: disable=unused-import - st7789, # pylint: disable=unused-import + ssd1331, + ssd1351, + st7735, + st7789, ) # Button pins for EYESPI Pi Beret @@ -59,7 +59,6 @@ # Setup SPI bus using hardware SPI: spi = board.SPI() -# pylint: disable=line-too-long # fmt: off # Create the display. disp = ili9341.ILI9341(spi, rotation=90, # 2.2", 2.4", 2.8", 3.2" ILI9341 @@ -82,7 +81,6 @@ baudrate=BAUDRATE, ) # fmt: on -# pylint: enable=line-too-long def init_button(pin): @@ -92,7 +90,7 @@ def init_button(pin): return button -class Frame: # pylint: disable=too-few-public-methods +class Frame: def __init__(self, duration=0): self.duration = duration self.image = None @@ -162,7 +160,7 @@ def preload(self): frame_object = Frame(duration=self._duration) if "duration" in image.info: frame_object.duration = image.info["duration"] - frame_object.image = ImageOps.pad( # pylint: disable=no-member + frame_object.image = ImageOps.pad( image.convert("RGB"), (self._width, self._height), method=Image.NEAREST, diff --git a/examples/rgb_display_fbcp.py b/examples/rgb_display_fbcp.py index 910d31b..6e5f220 100644 --- a/examples/rgb_display_fbcp.py +++ b/examples/rgb_display_fbcp.py @@ -37,7 +37,7 @@ FB_BLANK_POWERDOWN = 4 -class Bitfield: # pylint: disable=too-few-public-methods +class Bitfield: def __init__(self, offset, length, msb_right): self.offset = offset self.length = length @@ -46,7 +46,7 @@ def __init__(self, offset, length, msb_right): # Kind of like a pygame Surface object, or not! # http://www.pygame.org/docs/ref/surface.html -class Framebuffer: # pylint: disable=too-many-instance-attributes +class Framebuffer: def __init__(self, dev): self.dev = dev self.fbfd = os.open(dev, os.O_RDWR) diff --git a/examples/rgb_display_minipitftstats.py b/examples/rgb_display_minipitftstats.py index 48c480f..b096c31 100644 --- a/examples/rgb_display_minipitftstats.py +++ b/examples/rgb_display_minipitftstats.py @@ -82,7 +82,7 @@ MemUsage = subprocess.check_output(cmd, shell=True).decode("utf-8") cmd = 'df -h | awk \'$NF=="/"{printf "Disk: %d/%d GB %s", $3,$2,$5}\'' Disk = subprocess.check_output(cmd, shell=True).decode("utf-8") - cmd = "cat /sys/class/thermal/thermal_zone0/temp | awk '{printf \"CPU Temp: %.1f C\", $(NF-0) / 1000}'" # pylint: disable=line-too-long + cmd = "cat /sys/class/thermal/thermal_zone0/temp | awk '{printf \"CPU Temp: %.1f C\", $(NF-0) / 1000}'" Temp = subprocess.check_output(cmd, shell=True).decode("utf-8") # Write four lines of text. diff --git a/examples/rgb_display_pillow_animated_gif.py b/examples/rgb_display_pillow_animated_gif.py index 701d762..b65361c 100644 --- a/examples/rgb_display_pillow_animated_gif.py +++ b/examples/rgb_display_pillow_animated_gif.py @@ -21,16 +21,16 @@ import board import digitalio -import numpy # pylint: disable=unused-import +import numpy from PIL import Image, ImageOps from adafruit_rgb_display import ( - hx8357, # pylint: disable=unused-import + hx8357, ili9341, - ssd1331, # pylint: disable=unused-import - ssd1351, # pylint: disable=unused-import - st7735, # pylint: disable=unused-import - st7789, # pylint: disable=unused-import + ssd1331, + ssd1351, + st7735, + st7789, ) # Change to match your display @@ -52,16 +52,12 @@ def init_button(pin): return button -# pylint: disable=too-few-public-methods class Frame: def __init__(self, duration=0): self.duration = duration self.image = None -# pylint: enable=too-few-public-methods - - class AnimatedGif: def __init__(self, display, width=None, height=None, folder=None): self._frame_count = 0 @@ -126,7 +122,7 @@ def preload(self): frame_object = Frame(duration=self._duration) if "duration" in image.info: frame_object.duration = image.info["duration"] - frame_object.image = ImageOps.pad( # pylint: disable=no-member + frame_object.image = ImageOps.pad( image.convert("RGB"), (self._width, self._height), method=Image.NEAREST, @@ -180,7 +176,6 @@ def run(self): # Setup SPI bus using hardware SPI: spi = board.SPI() -# pylint: disable=line-too-long # Create the display: # disp = st7789.ST7789(spi, rotation=90, # 2.0" ST7789 # disp = st7789.ST7789(spi, height=240, y_offset=80, rotation=180, # 1.3", 1.54" ST7789 @@ -204,7 +199,6 @@ def run(self): rst=reset_pin, baudrate=BAUDRATE, ) -# pylint: enable=line-too-long if disp.rotation % 180 == 90: disp_height = disp.width # we swap height/width to rotate it to landscape! diff --git a/examples/rgb_display_pillow_demo.py b/examples/rgb_display_pillow_demo.py index e85691b..36f3961 100644 --- a/examples/rgb_display_pillow_demo.py +++ b/examples/rgb_display_pillow_demo.py @@ -17,12 +17,12 @@ from PIL import Image, ImageDraw, ImageFont from adafruit_rgb_display import ( - hx8357, # pylint: disable=unused-import + hx8357, ili9341, - ssd1331, # pylint: disable=unused-import - ssd1351, # pylint: disable=unused-import - st7735, # pylint: disable=unused-import - st7789, # pylint: disable=unused-import + ssd1331, + ssd1351, + st7735, + st7789, ) # First define some constants to allow easy resizing of shapes. @@ -40,7 +40,6 @@ # Setup SPI bus using hardware SPI: spi = board.SPI() -# pylint: disable=line-too-long # Create the display: # disp = st7789.ST7789(spi, rotation=90, # 2.0" ST7789 # disp = st7789.ST7789(spi, height=240, y_offset=80, rotation=180, # 1.3", 1.54" ST7789 @@ -64,7 +63,6 @@ rst=reset_pin, baudrate=BAUDRATE, ) -# pylint: enable=line-too-long # Create blank image for drawing. # Make sure to create image with mode 'RGB' for full color. diff --git a/examples/rgb_display_pillow_image.py b/examples/rgb_display_pillow_image.py index 61e7f13..c90f5e7 100644 --- a/examples/rgb_display_pillow_image.py +++ b/examples/rgb_display_pillow_image.py @@ -16,12 +16,12 @@ from PIL import Image, ImageDraw from adafruit_rgb_display import ( - hx8357, # pylint: disable=unused-import + hx8357, ili9341, - ssd1331, # pylint: disable=unused-import - ssd1351, # pylint: disable=unused-import - st7735, # pylint: disable=unused-import - st7789, # pylint: disable=unused-import + ssd1331, + ssd1351, + st7735, + st7789, ) # Configuration for CS and DC pins (these are PiTFT defaults): @@ -35,7 +35,7 @@ # Setup SPI bus using hardware SPI: spi = board.SPI() -# pylint: disable=line-too-long + # Create the display: # disp = st7789.ST7789(spi, rotation=90, # 2.0" ST7789 # disp = st7789.ST7789(spi, height=240, y_offset=80, rotation=180, # 1.3", 1.54" ST7789 @@ -59,7 +59,6 @@ rst=reset_pin, baudrate=BAUDRATE, ) -# pylint: enable=line-too-long # Create blank image for drawing. # Make sure to create image with mode 'RGB' for full color. diff --git a/examples/rgb_display_pillow_stats.py b/examples/rgb_display_pillow_stats.py index 4a6d668..673a032 100644 --- a/examples/rgb_display_pillow_stats.py +++ b/examples/rgb_display_pillow_stats.py @@ -19,12 +19,12 @@ from PIL import Image, ImageDraw, ImageFont from adafruit_rgb_display import ( - hx8357, # pylint: disable=unused-import + hx8357, ili9341, - ssd1331, # pylint: disable=unused-import - ssd1351, # pylint: disable=unused-import - st7735, # pylint: disable=unused-import - st7789, # pylint: disable=unused-import + ssd1331, + ssd1351, + st7735, + st7789, ) # Configuration for CS and DC pins (these are PiTFT defaults): @@ -38,7 +38,6 @@ # Setup SPI bus using hardware SPI: spi = board.SPI() -# pylint: disable=line-too-long # Create the display: # disp = st7789.ST7789(spi, rotation=90, # 2.0" ST7789 # disp = st7789.ST7789(spi, height=240, y_offset=80, rotation=180, # 1.3", 1.54" ST7789 @@ -62,7 +61,6 @@ rst=reset_pin, baudrate=BAUDRATE, ) -# pylint: enable=line-too-long # Create blank image for drawing. # Make sure to create image with mode 'RGB' for full color. @@ -105,7 +103,7 @@ MemUsage = subprocess.check_output(cmd, shell=True).decode("utf-8") cmd = 'df -h | awk \'$NF=="/"{printf "Disk: %d/%d GB %s", $3,$2,$5}\'' Disk = subprocess.check_output(cmd, shell=True).decode("utf-8") - cmd = "cat /sys/class/thermal/thermal_zone0/temp | awk '{printf \"CPU Temp: %.1f C\", $(NF-0) / 1000}'" # pylint: disable=line-too-long + cmd = "cat /sys/class/thermal/thermal_zone0/temp | awk '{printf \"CPU Temp: %.1f C\", $(NF-0) / 1000}'" Temp = subprocess.check_output(cmd, shell=True).decode("utf-8") # Write four lines of text. From c3c8bc658204f8a558d072f3a392b756fa3bee76 Mon Sep 17 00:00:00 2001 From: foamyguy Date: Tue, 29 Apr 2025 17:40:07 -0500 Subject: [PATCH 26/31] remove unused string comments --- ruff.toml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/ruff.toml b/ruff.toml index 04e88ad..6818392 100644 --- a/ruff.toml +++ b/ruff.toml @@ -95,10 +95,6 @@ ignore = [ "PLW1514", # unspecified-encoding "PLR0913", # too many arguments "PLR0917", # too many positional arguments -# "", -# "", -# "", -# "", ] [format] From b089f40c360af158c409f38e46b3e55c7c1de7ee Mon Sep 17 00:00:00 2001 From: foamyguy Date: Wed, 4 Jun 2025 10:00:20 -0500 Subject: [PATCH 27/31] update rtd.yml file Signed-off-by: foamyguy --- .readthedocs.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.readthedocs.yaml b/.readthedocs.yaml index 88bca9f..255dafd 100644 --- a/.readthedocs.yaml +++ b/.readthedocs.yaml @@ -12,7 +12,7 @@ sphinx: configuration: docs/conf.py build: - os: ubuntu-20.04 + os: ubuntu-lts-latest tools: python: "3" From b413eaa2ffc18d274fc07e017e47053ac6fcd77a Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Mon, 15 Sep 2025 10:53:47 -0700 Subject: [PATCH 28/31] Implement placeholder root_group property It throws an error on access to point to displayio --- adafruit_rgb_display/rgb.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/adafruit_rgb_display/rgb.py b/adafruit_rgb_display/rgb.py index 8cfa5c9..bbf93bb 100644 --- a/adafruit_rgb_display/rgb.py +++ b/adafruit_rgb_display/rgb.py @@ -255,6 +255,16 @@ def rotation(self, val: int) -> None: raise ValueError("Rotation must be 0/90/180/270") self._rotation = val + @property + def root_group(self) -> None: + """Placeholder attribute to catch displayio use""" + raise NotImplementedError("Please use a displayio driver for the display. This is the pixel-level driver.") + + @root_group.setter + def root_group(self, val) -> None: + raise NotImplementedError("Please use a displayio driver for the display. This is the pixel-level driver.") + + class DisplaySPI(Display): """Base class for SPI type devices""" From d1a842232955958b65820dabc2e5be1b6951e6d4 Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Mon, 15 Sep 2025 11:16:10 -0700 Subject: [PATCH 29/31] ruff format --- adafruit_rgb_display/rgb.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/adafruit_rgb_display/rgb.py b/adafruit_rgb_display/rgb.py index bbf93bb..777e9eb 100644 --- a/adafruit_rgb_display/rgb.py +++ b/adafruit_rgb_display/rgb.py @@ -258,11 +258,15 @@ def rotation(self, val: int) -> None: @property def root_group(self) -> None: """Placeholder attribute to catch displayio use""" - raise NotImplementedError("Please use a displayio driver for the display. This is the pixel-level driver.") + raise NotImplementedError( + "Please use a displayio driver for the display. This is the pixel-level driver." + ) @root_group.setter def root_group(self, val) -> None: - raise NotImplementedError("Please use a displayio driver for the display. This is the pixel-level driver.") + raise NotImplementedError( + "Please use a displayio driver for the display. This is the pixel-level driver." + ) From 9b93d2284e2ba4149bb445add48f09409f244cbe Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Wed, 17 Sep 2025 10:38:38 -0700 Subject: [PATCH 30/31] Remove extra line --- adafruit_rgb_display/rgb.py | 1 - 1 file changed, 1 deletion(-) diff --git a/adafruit_rgb_display/rgb.py b/adafruit_rgb_display/rgb.py index 777e9eb..0227cce 100644 --- a/adafruit_rgb_display/rgb.py +++ b/adafruit_rgb_display/rgb.py @@ -267,7 +267,6 @@ def root_group(self, val) -> None: raise NotImplementedError( "Please use a displayio driver for the display. This is the pixel-level driver." ) - class DisplaySPI(Display): From 54a63d453d3527561333454d10633e68cb6260da Mon Sep 17 00:00:00 2001 From: foamyguy Date: Fri, 10 Oct 2025 16:18:40 -0500 Subject: [PATCH 31/31] remove deprecated ruff rule, workaround RTD theme property inline issue. Signed-off-by: foamyguy --- docs/_static/custom.css | 8 ++++++++ docs/conf.py | 3 +++ ruff.toml | 1 - 3 files changed, 11 insertions(+), 1 deletion(-) create mode 100644 docs/_static/custom.css diff --git a/docs/_static/custom.css b/docs/_static/custom.css new file mode 100644 index 0000000..d60cf4b --- /dev/null +++ b/docs/_static/custom.css @@ -0,0 +1,8 @@ +/* SPDX-FileCopyrightText: 2025 Sam Blenny + * SPDX-License-Identifier: MIT + */ + +/* Monkey patch the rtd theme to prevent horizontal stacking of short items + * see https://github.com/readthedocs/sphinx_rtd_theme/issues/1301 + */ +.py.property{display: block !important;} diff --git a/docs/conf.py b/docs/conf.py index 6ad6c55..6b33eca 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -104,6 +104,9 @@ # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"] +# Include extra css to work around rtd theme glitches +html_css_files = ["custom.css"] + # The name of an image file (relative to this directory) to use as a favicon of # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. diff --git a/ruff.toml b/ruff.toml index 6818392..bd41569 100644 --- a/ruff.toml +++ b/ruff.toml @@ -17,7 +17,6 @@ extend-select = [ "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