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

Add functions to control the LED of an access point #261

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

theimo1221
Copy link

@theimo1221 theimo1221 commented Dec 15, 2024

Hello @jens-maus,

It's kinda funny to mostly see the same good people in Open-Source! Keep up the good work 👍

This PR adds some functionality to control the LED Brightness and color (e.g. for E7)

A npm release after this PR would be highly appreciated 😃

Best regards

Thiemo

Summary by CodeRabbit

  • New Features
    • Introduced new methods to manage LED settings on devices, including:
      • setLED: Override LED settings with color, brightness, and mode.
      • setLEDBrightness: Adjust the brightness of the LED.
      • setLEDColor: Change the LED color using hex format.

Copy link

coderabbitai bot commented Dec 15, 2024

Walkthrough

The changes introduce three new methods to the Controller class in unifi.js for managing device LED settings. These methods provide granular control over LED configurations, allowing users to modify device LED color, brightness, and overall settings through REST API calls. The new methods setLED, setLEDBrightness, and setLEDColor follow the existing pattern of API interaction within the UniFi controller interface.

Changes

File Change Summary
unifi.js Added three new methods to Controller class:
- setLED(): Override complete LED settings
- setLEDBrightness(): Modify LED brightness
- setLEDColor(): Set LED color

Sequence Diagram

sequenceDiagram
    participant User
    participant Controller
    participant UniFi API
    
    User->>Controller: setLED(device_id, color, brightness, mode)
    Controller->>UniFi API: REST API Request
    UniFi API-->>Controller: Update LED Settings
    Controller-->>User: Confirmation
Loading

Poem

🐰 Hop, hop, LED bright and bold,
Unifi's colors now under control!
Brightness dancing, colors so fine,
With just a method, devices now shine!
Rabbit's tech magic, LED delight! 🌈

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. This feature will be included in our Pro Plan when released.


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>, please review it.
    • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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.
    • @coderabbitai help me debug CodeRabbit configuration file.

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 using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration 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

@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: 0

🧹 Nitpick comments (4)
unifi.js (4)

2142-2162: Add input validation and improve documentation

The implementation looks good but could benefit from some improvements:

  1. Add parameter validation:

    • Validate device_id is a 24 char string
    • Validate override_color is a valid hex color code
    • Validate override_color_brightness is between 0-100
    • Validate override_mode is one of: 'off', 'on', 'default'
  2. Enhance JSDoc documentation with:

Here's a suggested implementation with the improvements:

  /**
   * Override LED settings for a device (using REST)
   *
+  * @param {string} device_id - 24 char string; value of _id for the device which can be obtained from the device list
+  * @param {string} override_color - Hex color code e.g. "#ff0000" for red
+  * @param {number} override_color_brightness - Value between 0-100 for LED brightness
+  * @param {('off'|'on'|'default')} override_mode - LED mode: 'off' disables LED, 'on' enables LED, 'default' uses site setting
+  * @throws {Error} If parameters are invalid
+  * @returns {Promise<boolean>} True on success
+  * @example
+  * // Set device LED to bright red
+  * await controller.setLED('5f1234567890abcdef123456', '#ff0000', 100, 'on')
   */
  setLED(device_id, override_color, override_color_brightness, override_mode) {
+    // Validate parameters
+    if (!/^[0-9a-f]{24}$/i.test(device_id)) {
+      throw new Error('Invalid device_id format');
+    }
+    if (!/^#[0-9a-f]{6}$/i.test(override_color)) {
+      throw new Error('Invalid override_color format');
+    }
+    if (!Number.isInteger(override_color_brightness) || 
+        override_color_brightness < 0 || 
+        override_color_brightness > 100) {
+      throw new Error('override_color_brightness must be between 0-100');
+    }
+    if (!['off', 'on', 'default'].includes(override_mode)) {
+      throw new Error('override_mode must be one of: off, on, default');
+    }

    return this._request(
      '/api/s/<SITE>/rest/device/' + device_id.trim(),
      {
        led_override: override_mode,
        led_override_color: override_color,
        led_override_color_brightness: override_color_brightness
      },
      'PUT'
    );
  }

2164-2172: Add input validation and improve documentation for brightness control

Similar improvements needed as the main setLED method:

  1. Add parameter validation
  2. Enhance JSDoc documentation
  3. Consider adding a brightness range constant

Here's a suggested implementation with the improvements:

+ /** @const {number} Maximum LED brightness value */
+ const MAX_LED_BRIGHTNESS = 100;

  /**
   * Override LED Brightness for a device (using REST)
   *
+  * @param {string} device_id - 24 char string; value of _id for the device which can be obtained from the device list
+  * @param {number} override_color_brightness - Value between 0-100 for LED brightness
+  * @throws {Error} If parameters are invalid
+  * @returns {Promise<boolean>} True on success
+  * @example
+  * // Set device LED to 50% brightness
+  * await controller.setLEDBrightness('5f1234567890abcdef123456', 50)
   */
  setLEDBrightness(device_id, override_color_brightness) {
+    // Validate parameters
+    if (!/^[0-9a-f]{24}$/i.test(device_id)) {
+      throw new Error('Invalid device_id format');
+    }
+    if (!Number.isInteger(override_color_brightness) || 
+        override_color_brightness < 0 || 
+        override_color_brightness > MAX_LED_BRIGHTNESS) {
+      throw new Error(`override_color_brightness must be between 0-${MAX_LED_BRIGHTNESS}`);
+    }

    return this._request(
      '/api/s/<SITE>/rest/device/' + device_id.trim(),
      {led_override_color_brightness: override_color_brightness},
      'PUT'
    );
  }

2174-2182: Add input validation and improve documentation for color control

Similar improvements needed as the other LED control methods:

  1. Add parameter validation
  2. Enhance JSDoc documentation
  3. Consider adding color constants for common values

Here's a suggested implementation with the improvements:

+ /** @const {Object.<string, string>} Common LED colors */
+ const LED_COLORS = {
+   RED: '#ff0000',
+   GREEN: '#00ff00',
+   BLUE: '#0000ff',
+   WHITE: '#ffffff',
+   OFF: '#000000'
+ };

  /**
   * Override LED Color for a device (using REST)
   *
+  * @param {string} device_id - 24 char string; value of _id for the device which can be obtained from the device list
+  * @param {string} override_color - Hex color code e.g. "#ff0000" for red
+  * @throws {Error} If parameters are invalid
+  * @returns {Promise<boolean>} True on success
+  * @example
+  * // Set device LED to red
+  * await controller.setLEDColor('5f1234567890abcdef123456', LED_COLORS.RED)
   */
  setLEDColor(device_id, override_color) {
+    // Validate parameters
+    if (!/^[0-9a-f]{24}$/i.test(device_id)) {
+      throw new Error('Invalid device_id format');
+    }
+    if (!/^#[0-9a-f]{6}$/i.test(override_color)) {
+      throw new Error('Invalid override_color format');
+    }

    return this._request(
      '/api/s/<SITE>/rest/device/' + device_id.trim(),
      {led_override_color: override_color},
      'PUT'
    );
  }

2142-2182: Consider architectural improvements for LED control

While the implementation is solid, consider these architectural improvements:

  1. Extract common validation logic into helper methods:

    _validateDeviceId(device_id)
    _validateColor(color)
    _validateBrightness(brightness)
  2. Add error handling for API responses specific to LED control failures

  3. Add unit tests to verify:

    • Parameter validation
    • API call formatting
    • Error handling
    • Success cases
  4. Consider adding a higher-level LED control interface that combines these operations:

    async configureLED(device_id, {color, brightness, mode}) {
      // Validate all parameters once
      // Make a single API call instead of multiple
    }

Would you like me to help create a new GitHub issue to track these improvements?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6ccbe86 and fed0de2.

📒 Files selected for processing (1)
  • unifi.js (1 hunks)

@theimo1221
Copy link
Author

Hello @jens-maus,

a quick review followed by a new release (as you have resolved CVE-2024-39338 with the axios patch) would be highly appreciated 👍

Best regards and happy new year

Thiemo

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.

1 participant