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

Do not request brightness of light by default #982

Merged
merged 3 commits into from
Jan 4, 2025

Conversation

itavero
Copy link
Owner

@itavero itavero commented Jan 4, 2025

Should prevent issue mentioned in #882

Summary by CodeRabbit

  • New Features

    • Added request_brightness configuration option for light converters.
    • Enhanced light sensor compatibility with Zigbee2MQTT v2.
  • Documentation

    • Updated documentation to explain new request_brightness option.
    • Clarified default brightness request behavior.
  • Bug Fixes

    • Improved light sensor functionality when illuminance_lux is unavailable.
    • Prevented potential issues with brightness requests when light is off.
  • Tests

    • Adjusted test cases to reflect changes in brightness handling and expected device characteristics.

Copy link

coderabbitai bot commented Jan 4, 2025

Walkthrough

This pull request introduces a new configuration option request_brightness for the light converter in Zigbee2MQTT. The change modifies how brightness is handled for light devices, making brightness requests optional by default. The implementation allows users to control whether brightness can be requested, with the default set to false to prevent potential issues when a light is turned off. Additionally, the code now supports using the illuminance property as a fallback when illuminance_lux is unavailable.

Changes

File Change Summary
CHANGELOG.md Updated to reflect light sensor and brightness handling changes
docs/light.md Added request_brightness configuration option documentation
src/converters/light.ts - Updated LightConfig interface with request_brightness option
- Modified LightHandler constructor to accept requestBrightness
- Updated getableKeys method to conditionally include brightness
.vscode/settings.json Added "cSpell.words" with values ["Elgato", "Zigbee"]
test/light.spec.ts - Updated expected getable keys in multiple test cases to exclude 'brightness'
- Modified test cases to reflect new configurations for light characteristics

Sequence Diagram

sequenceDiagram
    participant User
    participant LightConverter
    participant LightHandler
    
    User->>LightConverter: Configure light service
    User-->>LightConverter: Set request_brightness (optional)
    LightConverter->>LightHandler: Initialize with requestBrightness
    LightHandler-->>LightConverter: Conditionally handle brightness requests
Loading

Possibly related PRs

Poem

🐰 A Rabbit's Ode to Light Control 🌟

Brightness now dances to a new tune,
Requested only when the time is right,
No more forcing when the lamp's in gloom,
A config switch, a developer's delight!
Hop, hop, configuration's bright! 🌈


🪧 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 (5)
src/converters/light.ts (3)

78-83: Consider consolidating this logic using direct assignment for clarity.
Defining a local requestBrightness and then reassigning can be simplified if you want more concise code, though the current approach is also valid and explicit.

-let requestBrightness = false;
-if (converterConfig.request_brightness === true) {
-  requestBrightness = true;
-}
+const requestBrightness = !!converterConfig.request_brightness;
🧰 Tools
🪛 GitHub Actions: Verify

[warning] Low code coverage: Only 47.76% statement coverage, 32.75% branch coverage


92-92: Wrap handler creation in a more comprehensive error message.
While you already catch and log an error, adding the current value of requestBrightness to the error log can speed up troubleshooting if misconfiguration leads to unexpected behaviors.

-accessory.log.warn(`Failed to setup light for accessory ${accessory.displayName} from expose "${JSON.stringify(expose)}": ${error}`);
+accessory.log.warn(
+  `Failed to setup light for accessory ${accessory.displayName} from expose "${JSON.stringify(expose)}" with requestBrightness=${requestBrightness}: ${error}`
+);
🧰 Tools
🪛 GitHub Actions: Verify

[warning] Low code coverage: Only 47.76% statement coverage, 32.75% branch coverage


146-146: Explicit naming for the requestBrightness parameter.
Ensure future maintainers understand its purpose by adding a brief comment (where declared) about controlling brightness queries. This is optional but can enhance clarity.

🧰 Tools
🪛 GitHub Actions: Verify

[warning] Low code coverage: Only 47.76% statement coverage, 32.75% branch coverage

docs/light.md (1)

20-20: Hyphenate “converter-specific” for clarity.
When used as a compound modifier (“converter-specific configuration”), it is typically spelled with a hyphen.

-Old behavior can be restored using the `request_brightness` option in the converter specific configuration.
+Old behavior can be restored using the `request_brightness` option in the converter-specific configuration.
🧰 Tools
🪛 LanguageTool

[uncategorized] ~20-~20: Loose punctuation mark.
Context: ...will not be send. - request_brightness: Set to true to allow the brightness t...

(UNLIKELY_OPENING_PUNCTUATION)

CHANGELOG.md (1)

13-15: Apply minor grammar fix and highlight the hyphenation.
Similar to the docs, consider using “converter-specific configuration” for consistent clarity across the project.

-Old behavior can be restored using the `request_brightness` option in the converter specific configuration.
+Old behavior can be restored using the `request_brightness` option in the converter-specific configuration.
🧰 Tools
🪛 LanguageTool

[uncategorized] ~14-~14: When ‘converter-specific’ is used as a modifier, it is usually spelled with a hyphen.
Context: ... the request_brightness option in the converter specific configuration. (see [#882](https://gi...

(SPECIFIC_HYPHEN)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ec0771b and b6fe321.

📒 Files selected for processing (3)
  • CHANGELOG.md (1 hunks)
  • docs/light.md (2 hunks)
  • src/converters/light.ts (5 hunks)
🧰 Additional context used
🪛 LanguageTool
CHANGELOG.md

[uncategorized] ~14-~14: When ‘converter-specific’ is used as a modifier, it is usually spelled with a hyphen.
Context: ... the request_brightness option in the converter specific configuration. (see [#882](https://gi...

(SPECIFIC_HYPHEN)

docs/light.md

[uncategorized] ~20-~20: Loose punctuation mark.
Context: ...will not be send. - request_brightness: Set to true to allow the brightness t...

(UNLIKELY_OPENING_PUNCTUATION)

🪛 GitHub Actions: Verify
src/converters/light.ts

[warning] Low code coverage: Only 47.76% statement coverage, 32.75% branch coverage

🔇 Additional comments (2)
src/converters/light.ts (2)

39-39: Add unit tests to verify usage of the new property.
While introducing the optional request_brightness?: boolean; can help prevent unwanted brightness queries, ensure sufficient testing is in place to confirm the behavior is as expected, particularly for edge cases.

I can generate a new test file or an updated test suite to cover scenarios where request_brightness is toggled. Let me know if you'd like me to open a PR or supply a code snippet!

🧰 Tools
🪛 GitHub Actions: Verify

[warning] Low code coverage: Only 47.76% statement coverage, 32.75% branch coverage


191-191: Confirm brightness property remains in sync when toggling request_brightness.
This condition excludes brightness from getableKeys unless requestBrightness is set. Ensure external calls that rely on brightness updates gracefully handle a missing brightness property.

🧰 Tools
🪛 GitHub Actions: Verify

[warning] Low code coverage: Only 47.76% statement coverage, 32.75% branch coverage

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 (1)
CHANGELOG.md (1)

14-14: Apply a hyphen for ‘converter-specific’
Use a hyphen when ‘converter-specific’ modifies “configuration.”

-  Old behavior can be restored using the `request_brightness` option in the converter specific configuration.
+  Old behavior can be restored using the `request_brightness` option in the converter-specific configuration.
🧰 Tools
🪛 LanguageTool

[uncategorized] ~14-~14: When ‘converter-specific’ is used as a modifier, it is usually spelled with a hyphen.
Context: ... the request_brightness option in the converter specific configuration. (see [#882](https://gi...

(SPECIFIC_HYPHEN)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b6fe321 and 3e2b9f2.

📒 Files selected for processing (3)
  • .vscode/settings.json (1 hunks)
  • CHANGELOG.md (3 hunks)
  • test/light.spec.ts (7 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .vscode/settings.json
🧰 Additional context used
🪛 LanguageTool
CHANGELOG.md

[uncategorized] ~14-~14: When ‘converter-specific’ is used as a modifier, it is usually spelled with a hyphen.
Context: ... the request_brightness option in the converter specific configuration. (see [#882](https://gi...

(SPECIFIC_HYPHEN)

🔇 Additional comments (13)
test/light.spec.ts (9)

184-184: Consistent with removing brightness from default getable keys
The updated line aligns with the new default behavior of not requesting brightness.


510-510: Same approach as line 184
This line is functionally the same as the approach used previously for removing brightness from default getable keys.


560-560: New test block ensures configurability for brightness
This describes a scenario where brightness requests are explicitly allowed. Good to see coverage.


574-574: No changes to review
This appears to be an empty or whitespace-only line.


575-575: Possible mismatch between comment and code
The comment references enabling adaptive lighting, yet the next line sets request_brightness. Verify if it's intentional or a leftover reference.


576-576: Explicitly requesting brightness
This configuration is consistent with the test scenario’s need to request brightness. Looks good.


694-694: Same approach as line 184
Again removing brightness from the default getable keys matches the new behavior.


836-836: Only “state” is requested
This device is configured to ignore brightness and color temperature, which aligns with the device’s actual capabilities.


892-892: Only state and color_temp are gettable
This device uses adaptive lighting, but no direct brightness request. Confirmed alignment with new default.

CHANGELOG.md (4)

13-13: Aligned with the PR objective
This line describes the new default behavior of not requesting brightness, consistent with the PR's goal.


15-15: Reference to issue #882
No specific revision needed.


117-117: Documentation clarity
Describes added checks to prevent errors—no issues here.


464-464: Changelog improvements
These bullet points are informative clarifications; no changes suggested.

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: 1

🧹 Nitpick comments (1)
src/converters/light.ts (1)

144-144: Consider using parameter property syntax

You can simplify the code by using TypeScript's parameter property syntax.

-  private readonly requestBrightness: boolean,
+  private readonly requestBrightness: boolean
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3e2b9f2 and 524bd1a.

📒 Files selected for processing (3)
  • CHANGELOG.md (3 hunks)
  • docs/light.md (3 hunks)
  • src/converters/light.ts (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • CHANGELOG.md
🧰 Additional context used
🪛 LanguageTool
docs/light.md

[uncategorized] ~20-~20: Loose punctuation mark.
Context: ...will not be send. - request_brightness: Set to true to allow the brightness t...

(UNLIKELY_OPENING_PUNCTUATION)

🔇 Additional comments (4)
docs/light.md (1)

Line range hint 20-32: Documentation looks good!

The new configuration option is well-documented with a clear explanation of its purpose, default value, and rationale. The JSON example effectively demonstrates the usage.

src/converters/light.ts (3)

39-39: LGTM!

The interface addition follows TypeScript conventions for optional properties.


78-82: Implementation looks good!

The code safely handles the new configuration option with proper type checking and default value initialization.


Line range hint 353-367: Verify adaptive lighting with disabled brightness

The code requires brightness for adaptive lighting but doesn't consider the requestBrightness setting. This could lead to unexpected behavior when adaptive lighting is enabled but brightness requests are disabled.

Consider adding a check in tryCreateAdaptiveLighting:

  private tryCreateAdaptiveLighting(service: Service) {
    // Adaptive lighting is not enabled
    if (!this.adaptiveLightingEnabled) {
      return;
    }

    // Need at least brightness and color temperature to add Adaptive Lighting
-   if (this.brightnessExpose === undefined || this.colorTempExpose === undefined) {
+   if (this.brightnessExpose === undefined || !this.requestBrightness || this.colorTempExpose === undefined) {
      return;
    }

Comment on lines +189 to 191
if (this.brightnessExpose !== undefined && exposesCanBeGet(this.brightnessExpose) && this.requestBrightness) {
keys.push(this.brightnessExpose.property);
}
Copy link

@coderabbitai coderabbitai bot Jan 4, 2025

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider conditional brightness characteristic creation

Currently, the brightness characteristic is always created even when requestBrightness is false, but its value won't be updated. This might lead to stale or incorrect values being displayed.

Consider moving the requestBrightness check to the tryCreateBrightness method to prevent characteristic creation when not needed:

  private tryCreateBrightness(features: ExposesEntryWithProperty[], service: Service) {
    this.brightnessExpose = features.find(
      (e) => e.name === 'brightness' && exposesHasNumericRangeProperty(e) && exposesCanBeSet(e) && exposesIsPublished(e)
    ) as ExposesEntryWithNumericRangeProperty;
-   if (this.brightnessExpose !== undefined) {
+   if (this.brightnessExpose !== undefined && this.requestBrightness) {
      this.mainCharacteristics.push(
        getOrAddCharacteristic(service, hap.Characteristic.Brightness).on('set', this.handleSetBrightness.bind(this))
      );

Committable suggestion skipped: line range outside the PR's diff.

Copy link
Owner Author

@itavero itavero Jan 4, 2025

Choose a reason for hiding this comment

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

Even if we cannot "get" brightness, it will still be published (we check that when finding the exposes information if I recall correctly). So the characteristic should be created regardless of this new setting.

Copy link

Choose a reason for hiding this comment

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

@itavero, understood. Thank you for clarifying! The brightness characteristic might still hold value even when it isn’t actively polled, given that it will be published based on the device’s exposes. Let me know if there’s anything else I can help with.


✏️ Learnings added
Learnt from: itavero
PR: itavero/homebridge-z2m#982
File: src/converters/light.ts:189-191
Timestamp: 2025-01-04T19:37:24.409Z
Learning: Even if brightness isn't gettable (when requestBrightness is false), the brightness characteristic remains relevant since it is published by the device. This is reflected in src/converters/light.ts, where we retain the brightness characteristic creation logic.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

Copy link
Contributor

github-actions bot commented Jan 4, 2025

🆗 Published SonarCloud and code coverage data.

@itavero itavero merged commit 573ce1e into master Jan 4, 2025
4 checks passed
@itavero itavero deleted the fix/do-not-get-brightness-by-default branch January 4, 2025 19:39
@itavero
Copy link
Owner Author

itavero commented Jan 4, 2025

🚀 This pull request is included in v1.11.0-beta.7. See Release 1.11.0-beta.7 for release notes.

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