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

Update range of characteristic if out of range numeric value is received #985

Merged

Conversation

itavero
Copy link
Owner

@itavero itavero commented Jan 4, 2025

Summary by CodeRabbit

Summary by CodeRabbit

  • Changelog Updates

    • Enhanced handling of numeric characteristics with automatic range updates
    • Updated changelog for version 1.11.0-beta.7 to reflect previous changes
  • Logging Improvements

    • Added logging capabilities across multiple sensor and device handlers
    • Improved state update logging for various device types (switches, locks, lights, climate controls)
  • Error Handling

    • Added more robust error handling for unsupported device state changes
    • Implemented better logging for characteristic value updates

Copy link

coderabbitai bot commented Jan 4, 2025

Walkthrough

This pull request introduces a comprehensive update to logging and characteristic handling across multiple converter classes. The changes primarily focus on enhancing logging capabilities by passing the accessory's log object to monitor callbacks. Additionally, the code now includes a mechanism to automatically update numeric characteristic ranges when out-of-range values are received from Zigbee2MQTT. The modifications span various sensor and device handler classes, including switches, locks, lights, climate controls, and battery handlers.

Changes

File Change Summary
CHANGELOG.md Updated to include changes in numeric characteristic range handling and beta version updates.
src/converters/action.ts Added logging capability to StatelessProgrammableSwitchHandler.
src/converters/basic_sensors/basic.ts Added log property to BasicSensorHandler.
src/converters/battery.ts Updated updateState to include logging in monitor callbacks.
src/converters/climate.ts Enhanced logging and error handling in ThermostatHandler.
src/converters/cover.ts Added logging parameter to monitor callbacks.
src/converters/light.ts Modified monitor callback signatures to include logging.
src/converters/lock.ts Updated updateState with logging capabilities.
src/converters/monitor.ts Introduced updateRangeIfNeeded method and updated monitor interfaces to support logging.
src/converters/switch.ts Added logging parameter to monitor callback.
.release-it.yml Removed addUnreleased option from changelog generation settings.

Possibly related PRs

Poem

🐰 Logging leaps through code so bright,
Monitors dance with logger's might!
Numeric ranges stretch and grow,
With Zigbee's data ebb and flow.
A rabbit's code, now smart and light! 🌟


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7afb420 and b8e3bb9.

📒 Files selected for processing (1)
  • .release-it.yml (0 hunks)
💤 Files with no reviewable changes (1)
  • .release-it.yml

🪧 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 (2)
src/converters/battery.ts (1)

144-144: Enhance error handling or gracefully handle exceptions in monitors
Passing the logger to each monitor is helpful for debugging. However, consider whether any monitor could throw an exception within its callback; if so, you might want to wrap calls in a try/catch block to gracefully log errors.

CHANGELOG.md (1)

10-13: Clarify the behavior for out-of-range automatic updates.
Great addition describing automatic range updates. Consider explicitly stating how the new range gets recalculated (e.g., is it set to the min/max boundary or extended beyond the defined limit?).

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between adc5b99 and 7afb420.

📒 Files selected for processing (10)
  • CHANGELOG.md (1 hunks)
  • src/converters/action.ts (3 hunks)
  • src/converters/basic_sensors/basic.ts (3 hunks)
  • src/converters/battery.ts (1 hunks)
  • src/converters/climate.ts (1 hunks)
  • src/converters/cover.ts (1 hunks)
  • src/converters/light.ts (1 hunks)
  • src/converters/lock.ts (1 hunks)
  • src/converters/monitor.ts (3 hunks)
  • src/converters/switch.ts (1 hunks)
🔇 Additional comments (18)
src/converters/basic_sensors/basic.ts (4)

7-7: Good addition of the logger import.
Importing BasicLogger is consistent with the new logging enhancements.


14-14: Appropriate addition of the log property.
Having a dedicated logger at the handler level is beneficial for debugging sensor state updates.


30-30: Verify the presence of a valid logger instance.
While assigning this.log = accessory.log is straightforward, ensure that accessory.log is properly defined and not undefined in edge cases.


98-98: Enhanced logging within the update flow.
Passing the logger to each monitor’s callback is a convenient way to centralize debugging information. Looks good.

src/converters/switch.ts (1)

119-119: Effective logging parameter for monitor callbacks.
Forwarding this.accessory.log to the callback helps maintain consistent logging across different state updates.

src/converters/action.ts (4)

9-9: Consistent logger import for unified logging.
This import matches the approach used in other handlers, enabling uniform logging features.


58-58: Clear introduction of the log property.
Defining a private readonly log ensures consistent use of the same logger instance throughout the handler.


66-66: Proper assignment of the logger instance.
Makes all logging calls easy to maintain and read.


119-119: Logging support in state updates.
Passing this.log to the monitor’s callback improves visibility and debugging for action triggers.

src/converters/lock.ts (1)

130-130: Consistent lock-state logging approach.
Including this.accessory.log in the callbacks ensures the lock’s state transitions can be clearly traced.

src/converters/monitor.ts (5)

2-2: Validate the necessity of the BasicLogger import
The added import for BasicLogger is appropriate since we are now leveraging this type in the monitor callbacks. No issues here.


7-7: Updated interface signature
Adding the logger: BasicLogger parameter to the monitor’s callback function broadens logging capabilities across different monitors. This interface change looks consistent with the rest of the PR.


19-26: Potential validation of transformed value
Within callback, the transformed value is passed to updateCharacteristic. Consider handling unexpected numeric ranges or invalid string conversions by applying further checks or catching thrown errors in transformValueFromMqtt.


32-52: Checks and updates for numeric-in-range
This new updateRangeIfNeeded method ensures characteristics adapt dynamically to unexpected out-of-range values. This is valuable for robust device handling. However, be mindful of how frequent range changes can shape user experience in HomeKit, as it might confuse users if min/max are constantly changing.


65-65: Nested monitor callbacks
The nested callback forwarding of the logger is consistent with the new interface. This design preserves the logging context across deeper or compound monitors.

src/converters/climate.ts (1)

271-271: Consistent logging enhancement
Forwarding the accessory’s log to each monitor standardizes debugging output and ensures consistent logging across climate-related monitors. No issues noted.

src/converters/cover.ts (1)

203-203: Uniform logging approach
Similar to the other handlers, passing this.accessory.log to each monitor ensures consistent logging and helps in diagnosing cover position updates or related issues. This change appears coherent with the rest of the system updates.

src/converters/light.ts (1)

227-227: Ensure all monitors accept the log argument.
This line passes this.accessory.log as a second argument to each monitor’s callback. Please confirm that all CharacteristicMonitor implementations are updated to handle two arguments, to avoid runtime errors.

Run this script to search for callback( signatures in the codebase and review if they all declare the second parameter:

✅ Verification successful

Let me try a different search strategy to find monitor callback implementations.


Let me fix the regex syntax and try another search approach.


All monitor callbacks correctly handle the logger parameter

Based on the search results, I can verify that all CharacteristicMonitor implementations are safe. Here's why:

  1. The CharacteristicMonitor interface in src/converters/monitor.ts explicitly defines the callback signature with both parameters:
export interface CharacteristicMonitor {
  callback(state: Record<string, unknown>, logger: BasicLogger): void;
}
  1. All monitor implementations extend either BaseCharacteristicMonitor or directly implement CharacteristicMonitor:
  • BaseCharacteristicMonitor (abstract base class)
  • NestedCharacteristicMonitor
  • PassthroughCharacteristicMonitor
  • MappingCharacteristicMonitor
  • BinaryConditionCharacteristicMonitor
  • NumericCharacteristicMonitor
  • ColorTemperatureToHueSatMonitor
  • ColorXyCharacteristicMonitor

Since TypeScript enforces interface compliance, all these implementations must correctly handle both parameters of the callback method, including the logger parameter.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that monitors accept the second parameter (logger).

ast-grep --pattern $'function callback($_, $_) {
  $$$
}' 

Length of output: 58


Script:

#!/bin/bash
# Search for class implementations containing 'callback'
ast-grep --pattern 'class $_ implements CharacteristicMonitor {
  $$$
  callback($$$) {
    $$$
  }
  $$$
}'

# Also search for direct callback implementations
rg "callback.*\(.*\).*{" -A 2

Length of output: 244


Script:

#!/bin/bash
# Search for callback implementations
rg "callback\s*\([^)]*\)\s*{" -A 2

# Also search for CharacteristicMonitor interface/type definition
rg "CharacteristicMonitor" -A 5

Length of output: 29889

Copy link
Contributor

github-actions bot commented Jan 4, 2025

🆗 Published SonarCloud and code coverage data.

@itavero itavero merged commit 1726609 into master Jan 4, 2025
4 checks passed
@itavero
Copy link
Owner Author

itavero commented Jan 4, 2025

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

@coderabbitai coderabbitai bot mentioned this pull request Jan 6, 2025
4 tasks
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