Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Devices for WS281x strip control over SPI #919

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open

Conversation

bbbergh
Copy link

@bbbergh bbbergh commented Apr 23, 2024

This adds two devices to control WS281x neopixel LED strips via the kernel SPI driver (through the spidev python package),
one for RGB strips and one for RGBW strips.

Highlights:

  • All data manipulation done in numpy, no python lists
  • Should work on all raspberry pis (including Pi 5, where all the other PWM based methods are currently broken), tested myself on Pi 3B+ and Pi5
  • Supports all color orders
  • White channel calculation can be configured to either replace the white proportion of the RGB channels or be added to it

The spidev package is added trough a new "spi" extra in poetry.

Current issues:

  • Somehow the descriptions of the newly added configuration fields don't show up in the frontend. Do I have to recompile the frontend somehow for them to be included?

Summary by CodeRabbit

  • New Features
    • Introduced support for controlling WS281X and RGBW LEDs via SPI on Raspberry Pi 5, including customization for white channel behavior and color order preferences.
    • Added spidev as an optional dependency to enhance SPI functionalities.

Copy link
Contributor

coderabbitai bot commented Apr 23, 2024

Walkthrough

This update enhances support for WS281X and RGBW LED strips through SPI on Raspberry Pi 5. It introduces new classes for managing these LEDs, offering functionalities like SPI connection initialization, LED data management, and customization of white channel behavior. Moreover, the optional dependency on the spidev library facilitates SPI communication.

Changes

File Summary
.../spi_ws281x.py Introduces SPI_WS281X class for WS281X LED control via SPI.
.../spi_ws281x_rgbw.py Adds SPI_WS281X_RBGW subclass for RGBW LEDs, including WhiteMode enum and color ordering.
pyproject.toml Updates dependencies, adding spidev >=3.5.0 under tool.poetry.extras for SPI support.

Recent Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 9d91906 and ed490cb.
Files selected for processing (1)
  • ledfx/devices/spi_ws281x.py (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • ledfx/devices/spi_ws281x.py

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Out of diff range and nitpick comments (1)
ledfx/devices/spi_ws281x_rgbw.py (1)

18-34: Ensure the description in the CONFIG_SCHEMA is clear and concise.

Consider simplifying the description for the white_mode field to enhance clarity and readability.

ledfx/devices/spi_ws281x_rgbw.py Show resolved Hide resolved
Comment on lines 43 to 61
def activate(self):
try:
import spidev
except ImportError as e:
described = ImportError("Unable to load spidev module. If you are on a raspberry pi, or another SPI capable linux device, "
"you can install spidev with 'pip install spidev' inside the ledfx venv.")
_LOGGER.error(described)
self.deactivate()
raise described from e

self.spi = spidev.SpiDev()
try:
self.spi.open(self._config["spi_bus"], self.SPI_DEVICE)
except OSError as e:
described = OSError("Unable to open SPI device. If you are on a raspberry pi, "
"you may need to enable SPI in 'sudo raspi-config'. Otherwise make sure the device is not used by another process.")
_LOGGER.error(described)
self.deactivate()
raise described from e
Copy link
Contributor

@coderabbitai coderabbitai bot Apr 23, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Improve error handling in the activate method.

-            described = ImportError("Unable to load spidev module. If you are on a raspberry pi, or another SPI capable linux device, "
-                                    "you can install spidev with 'pip install spidev' inside the ledfx venv.")
-            _LOGGER.error(described)
-            self.deactivate()
-            raise described from e
+            _LOGGER.error("Unable to load spidev module. If you are on a raspberry pi, or another SPI capable linux device, "
+                          "you can install spidev with 'pip install spidev' inside the ledfx venv.")
+            self.deactivate()
+            raise ImportError("Unable to load spidev module.") from e

Refactor to separate the logging and exception raising for clarity and maintainability.


Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
def activate(self):
try:
import spidev
except ImportError as e:
described = ImportError("Unable to load spidev module. If you are on a raspberry pi, or another SPI capable linux device, "
"you can install spidev with 'pip install spidev' inside the ledfx venv.")
_LOGGER.error(described)
self.deactivate()
raise described from e
self.spi = spidev.SpiDev()
try:
self.spi.open(self._config["spi_bus"], self.SPI_DEVICE)
except OSError as e:
described = OSError("Unable to open SPI device. If you are on a raspberry pi, "
"you may need to enable SPI in 'sudo raspi-config'. Otherwise make sure the device is not used by another process.")
_LOGGER.error(described)
self.deactivate()
raise described from e
def activate(self):
try:
import spidev
except ImportError as e:
_LOGGER.error("Unable to load spidev module. If you are on a raspberry pi, or another SPI capable linux device, "
"you can install spidev with 'pip install spidev' inside the ledfx venv.")
self.deactivate()
raise ImportError("Unable to load spidev module.") from e
self.spi = spidev.SpiDev()
try:
self.spi.open(self._config["spi_bus"], self.SPI_DEVICE)
except OSError as e:
described = OSError("Unable to open SPI device. If you are on a raspberry pi, "
"you may need to enable SPI in 'sudo raspi-config'. Otherwise make sure the device is not used by another process.")
_LOGGER.error(described)
self.deactivate()
raise described from e

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The point of doing it as committed was to display the verbose error message also in the react frontend (which prints the argument of the exception).

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bbbergh, thank you for clarifying the intention behind the current implementation of error handling. It's important that the frontend receives detailed error messages for better user feedback.

Considering your goal, we can still refactor the error handling to separate the concerns of logging and raising exceptions while ensuring that the verbose error messages are preserved for the frontend. Here's a suggested approach:

def activate(self):
    try:
        import spidev
    except ImportError as e:
        error_message = "Unable to load spidev module. If you are on a raspberry pi, or another SPI capable linux device, " \
                        "you can install spidev with 'pip install spidev' inside the ledfx venv."
        _LOGGER.error(error_message)
        self.deactivate()
        raise ImportError(error_message) from e

    self.spi = spidev.SpiDev()
    try:
        self.spi.open(self._config["spi_bus"], self.SPI_DEVICE)
    except OSError as e:
        error_message = "Unable to open SPI device. If you are on a raspberry pi, " \
                        "you may need to enable SPI in 'sudo raspi-config'. Otherwise make sure the device is not used by another process."
        _LOGGER.error(error_message)
        self.deactivate()
        raise OSError(error_message) from e

This refactoring maintains the detailed error messages for the frontend and separates the logging from the exception raising, enhancing the maintainability of the code. Let me know if this aligns with your requirements!


New Learnings Added
User: bbbergh
PR: LedFx/LedFx#919
File: ledfx/devices/spi_ws281x.py:0-0
Timestamp: 2024-04-23T14:51:09.775Z
Learning: The frontend of the LedFx project displays the argument of exceptions, which is used for showing verbose error messages to the user.

Note: Learnings are effective only in the context of specific code segments. To apply general coding guidelines, please configure review instructions.

ledfx/devices/spi_ws281x.py Outdated Show resolved Hide resolved
@shauneccles
Copy link
Member

Love it.

Any thoughts as to creating a single device and having RGB or rgbw as an option for the device?

And should we remove the ws281x device type at the same time as merging this you think?

@bbbergh
Copy link
Author

bbbergh commented Apr 26, 2024

Any thoughts as to creating a single device and having RGB or rgbw as an option for the device?

This is definitely possible, I just found splitting it into two device types a lot cleaner (theres different config options for white mode calculation and the color order selection, and the RGBW inherits from the RGB one, so theres no code duplication and the code paths are nicely separated). But if you prefer keeping the device type list short I can merge them together.

And should we remove the ws281x device type at the same time as merging this you think?

The ws281x device is currently completely broken (activate() never calls super().activate() and so the device never switches on), so I don't think anybody is actually using it. If we fix it, the only real reason someone might potentially want to use it is that it allows to use different pins, but I don't think thats enough of a reason to keep it around (it's also a lot slower, and some aspects of that are quite hard to change).

Also, can you have a quick look if I'm doing anything wrong the the descriptions of the config options, because I really have no idea why they don't show up in the frontend.

@shauneccles
Copy link
Member

I think I'd prefer a single device with an option for RGB or RGBW just to remove duplication.

I'll have a gander at the frontend, sorry I've been very busy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants