Skip to content

Implement HA Core PR 138039#829

Merged
bouwew merged 3 commits intomainfrom
HA-138039
Feb 11, 2025
Merged

Implement HA Core PR 138039#829
bouwew merged 3 commits intomainfrom
HA-138039

Conversation

@bouwew
Copy link
Contributor

@bouwew bouwew commented Feb 11, 2025

Summary by CodeRabbit

  • Documentation
    • Introduced an "Ongoing" section in release notes to reflect current development progress.
  • New Features
    • Persistent notifications now provide clear, actionable alerts.
    • Improved device control enhancements streamline interactions with sensors, climate controls, numbers, and switches.
    • A new conditional reboot control is added for more convenient device management.
    • Enhanced configuration management for Plugwise integration improves stability and usability.

@bouwew bouwew requested a review from a team as a code owner February 11, 2025 18:23
@bouwew bouwew requested a review from CoMPaTech February 11, 2025 18:23
@bouwew bouwew added the downstreaming Things that are changed on HA-core side and to be applied to -beta label Feb 11, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 11, 2025

Walkthrough

This pull request introduces a new "Ongoing" section in the CHANGELOG to document current development work. Across the Plugwise integration, the type PlugwiseConfigEntry has been introduced and integrated into multiple modules. Updates include changes to the coordinator initialization, async setup functions, entity logging, migration handling, and notification management, all aimed at refining configuration entry handling and type clarity.

Changes

File(s) Summary of Changes
CHANGELOG.md Added a new Ongoing section with an entry for Home Assistant Core PR #138039.
custom_components/plugwise/__init__.py,
custom_components/plugwise/coordinator.py
Introduced the type alias PlugwiseConfigEntry, updated the PlugwiseDataUpdateCoordinator constructor and configuration handling, and revised migration functions and service registrations.
custom_components/plugwise/binary_sensor.py,
button.py, climate.py, number.py, select.py, sensor.py, switch.py,
diagnostics.py
Updated async_setup_entry signatures to accept PlugwiseConfigEntry; improved entity logging, notification management, and adjusted entity attributes such as HVAC mode handling and numeric boundaries.

Possibly related PRs

Suggested labels

enhancement, needs_upstreaming

Suggested reviewers

  • CoMPaTech

Poem

Oh, I’m a rabbit with coding delight,
Hopping through changes in the night.
Configs refined, entries so clear,
Logging and sensors now sing in cheer.
With each new line, my heart does hop —
A carrot for progress at every stop!
🐰🥕

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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 or @coderabbitai title 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
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: 0

🔭 Outside diff range comments (1)
custom_components/plugwise/__init__.py (1)

145-145: ⚠️ Potential issue

Fix missing import for ConfigEntry.

The ConfigEntry type is used but not imported, causing a pipeline failure.

Add the import to the existing imports from homeassistant.config_entries:

-from homeassistant.const import CONF_TIMEOUT, Platform
+from homeassistant.config_entries import ConfigEntry
+from homeassistant.const import CONF_TIMEOUT, Platform
🧰 Tools
🪛 Ruff (0.8.2)

145-145: Undefined name ConfigEntry

(F821)

🪛 GitHub Actions: Test PR against HA-core

[error] 145-145: Undefined name ConfigEntry.

🧹 Nitpick comments (10)
custom_components/plugwise/button.py (1)

29-33: Remove commented-out code.

The old implementation has been replaced and the comments can be safely removed.

-    # async_add_entities(
-    #     PlugwiseButtonEntity(coordinator, device_id)
-    #     for device_id in coordinator.data.devices
-    #     if device_id == gateway[GATEWAY_ID] and REBOOT in gateway
-    # )
custom_components/plugwise/switch.py (2)

87-93: Remove commented-out code.

The old implementation has been replaced and the comments can be safely removed.

-        # Upstream consts
-        # async_add_entities(
-        #     PlugwiseSwitchEntity(coordinator, device_id, description)
-        #     for device_id in coordinator.new_devices
-        #     if (switches := coordinator.data.devices[device_id].get(SWITCHES))
-        #     for description in PLUGWISE_SWITCHES
-        #     if description.key in switches
-        # )

95-107: Consider simplifying entity creation logic.

The current implementation could be simplified using list comprehension while maintaining the debug logging.

-        entities: list[PlugwiseSwitchEntity] = []
-        for device_id in coordinator.new_devices:
-            device = coordinator.data[device_id]
-            if not (switches := device.get(SWITCHES)):
-                continue
-            for description in PLUGWISE_SWITCHES:
-                if description.key not in switches:
-                    continue
-                entities.append(PlugwiseSwitchEntity(coordinator, device_id, description))
-                LOGGER.debug(
-                    "Add %s %s switch", device["name"], description.translation_key
-                )
+        entities = [
+            entity for device_id in coordinator.new_devices
+            if (device := coordinator.data[device_id])
+            and (switches := device.get(SWITCHES))
+            for description in PLUGWISE_SWITCHES
+            if description.key in switches
+            for entity in [PlugwiseSwitchEntity(coordinator, device_id, description)]
+            if (LOGGER.debug("Add %s %s switch", device["name"], description.translation_key) or True)
+        ]
custom_components/plugwise/select.py (2)

46-47: Address the TODO comment about renaming.

The comment suggests there might be an inconsistency in naming conventions. Consider prefixing the constant to maintain consistency.

Would you like me to help rename the SELECT_TYPES constant to follow the naming convention? Let me know and I can propose a specific name that aligns with the codebase.


89-94: Remove commented-out code.

The old implementation has been replaced and the comments can be safely removed.

-        # Upstream consts
-        # async_add_entities(
-        #     PlugwiseSelectEntity(coordinator, device_id, description)
-        #     for device_id in coordinator.new_devices
-        #     for description in SELECT_TYPES
-        #     if description.options_key in coordinator.data.devices[device_id]
-        # )
custom_components/plugwise/number.py (1)

85-90: Consider reverting to list comprehension after debugging.

The current implementation favors debugging with detailed logging over the more concise list comprehension approach. While this is helpful during development, consider reverting to the list comprehension once debugging is complete.

-        # async_add_entities(
-        #     PlugwiseNumberEntity(coordinator, device_id, description)
-        #     for device_id in coordinator.new_devices
-        #     for description in NUMBER_TYPES
-        #     if description.key in coordinator.data.devices[device_id]
-        # )
-
-        # pw-beta alternative for debugging
-        entities: list[PlugwiseNumberEntity] = []
-        for device_id in coordinator.new_devices:
-            device = coordinator.data[device_id]
-            for description in NUMBER_TYPES:
-                if description.key in device:
-                    entities.append(
-                        PlugwiseNumberEntity(coordinator, device_id, description)
-                    )
-                    LOGGER.debug(
-                        "Add %s %s number", device["name"], description.translation_key
-                    )
-
-        async_add_entities(entities)
+        async_add_entities(
+            PlugwiseNumberEntity(coordinator, device_id, description)
+            for device_id in coordinator.new_devices
+            for description in NUMBER_TYPES
+            if description.key in coordinator.data[device_id]
+        )

Also applies to: 92-105

custom_components/plugwise/__init__.py (1)

79-83: Document platform-specific service registration.

The delete_notification service is only registered when the binary_sensor platform is loaded. Consider documenting this limitation in the service description or README.

custom_components/plugwise/binary_sensor.py (1)

171-175: Consider limiting the number of persistent notifications.

Creating a persistent notification for each message could lead to notification overload. Consider:

  • Limiting the number of concurrent notifications
  • Combining related notifications
  • Adding a mechanism to automatically clear old notifications
custom_components/plugwise/climate.py (2)

111-111: Consider using a more descriptive type hint.

The type hint str | None could be more specific by using a literal union of possible HVAC modes.

-    _homekit_mode: str | None = None  # pw-beta homekit emulation + intentional unsort
+    _homekit_mode: HVACMode | None = None  # pw-beta homekit emulation + intentional unsort

294-302: Consider extracting HomeKit mode handling to a separate method.

The HomeKit mode handling logic is complex and could benefit from being extracted into a dedicated method for better maintainability.

+    async def _handle_homekit_mode(self, hvac_mode: HVACMode) -> None:
+        """Handle HomeKit specific mode changes."""
+        self._homekit_mode = hvac_mode
+        if self._homekit_mode == HVACMode.OFF:
+            await self.async_set_preset_mode(PRESET_AWAY)
+        if (
+            self._homekit_mode in [HVACMode.HEAT, HVACMode.HEAT_COOL]
+            and self.device[ACTIVE_PRESET] == PRESET_AWAY
+        ):
+            await self.async_set_preset_mode(PRESET_HOME)

     @plugwise_command
     async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None:
         """Set the hvac mode."""
         if hvac_mode not in self.hvac_modes:
             raise HomeAssistantError("Unsupported hvac_mode")

         if hvac_mode == self.hvac_mode:
             return

         if hvac_mode != HVACMode.OFF:
             await self.coordinator.api.set_schedule_state(
                 self._location,
                 STATE_ON if hvac_mode == HVACMode.AUTO else STATE_OFF,
             )

         if not self._homekit_enabled:
             if hvac_mode == HVACMode.OFF:
                 await self.coordinator.api.set_regulation_mode(hvac_mode)
             elif self.hvac_mode == HVACMode.OFF:
                 await self.coordinator.api.set_regulation_mode(self._previous_mode)
         else:
-            self._homekit_mode = hvac_mode
-            if self._homekit_mode == HVACMode.OFF:
-                await self.async_set_preset_mode(PRESET_AWAY)
-            if (
-                self._homekit_mode in [HVACMode.HEAT, HVACMode.HEAT_COOL]
-                and self.device[ACTIVE_PRESET] == PRESET_AWAY
-            ):
-                await self.async_set_preset_mode(PRESET_HOME)
+            await self._handle_homekit_mode(hvac_mode)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 677956c and 70fc491.

📒 Files selected for processing (11)
  • CHANGELOG.md (1 hunks)
  • custom_components/plugwise/__init__.py (2 hunks)
  • custom_components/plugwise/binary_sensor.py (1 hunks)
  • custom_components/plugwise/button.py (1 hunks)
  • custom_components/plugwise/climate.py (1 hunks)
  • custom_components/plugwise/coordinator.py (1 hunks)
  • custom_components/plugwise/diagnostics.py (1 hunks)
  • custom_components/plugwise/number.py (1 hunks)
  • custom_components/plugwise/select.py (1 hunks)
  • custom_components/plugwise/sensor.py (1 hunks)
  • custom_components/plugwise/switch.py (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • CHANGELOG.md
🧰 Additional context used
🪛 GitHub Actions: Test PR against HA-core
custom_components/plugwise/__init__.py

[error] 145-145: Undefined name ConfigEntry.

🔇 Additional comments (16)
custom_components/plugwise/diagnostics.py (1)

9-9: LGTM! Import change aligns with type centralization.

The change to import PlugwiseConfigEntry from .coordinator aligns with the effort to centralize type definitions.

custom_components/plugwise/button.py (2)

14-14: LGTM! Import change aligns with type centralization.

The addition of PlugwiseConfigEntry to imports aligns with the effort to centralize type definitions.


35-40: Verify data structure changes across the integration.

The change from coordinator.data.devices to coordinator.data.items() suggests a data structure change. Let's verify this change is consistent across the integration.

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Search for remaining uses of .devices attribute
rg "coordinator\.data\.devices" -A 2

Length of output: 1573


Data structure change is consistent in active code.

  • In custom_components/plugwise/button.py, the active code now iterates over coordinator.data.items().
  • All instances of coordinator.data.devices found in other files (binary_sensor, number, sensor, switch, select) appear only in commented-out sections, which implies they are legacy references not affecting current operation.
custom_components/plugwise/switch.py (1)

30-30: LGTM! Import change aligns with type centralization.

The addition of PlugwiseConfigEntry to imports aligns with the effort to centralize type definitions.

custom_components/plugwise/select.py (1)

31-31: LGTM! Import change aligns with type centralization.

The addition of PlugwiseConfigEntry to imports aligns with the effort to centralize type definitions.

custom_components/plugwise/number.py (2)

111-136: LGTM!

The implementation correctly handles:

  • Entity description initialization
  • Native max/min value configuration from device settings
  • Special case for temperature offset step value

137-149: LGTM!

The methods for getting and setting values are well-implemented with appropriate logging.

custom_components/plugwise/__init__.py (1)

97-164: LGTM!

The migration functions correctly handle:

  • Migration of old unique IDs for binary sensors and switches
  • Removal of CONF_TIMEOUT during downgrade
🧰 Tools
🪛 Ruff (0.8.2)

145-145: Undefined name ConfigEntry

(F821)

🪛 GitHub Actions: Test PR against HA-core

[error] 145-145: Undefined name ConfigEntry.

custom_components/plugwise/coordinator.py (1)

33-33: LGTM!

The introduction of PlugwiseConfigEntry type alias and its integration into the coordinator class improves type safety and clarity.

Also applies to: 41-41

custom_components/plugwise/binary_sensor.py (1)

185-207: LGTM!

The attribute handling implementation:

  • Effectively filters notifications by severity
  • Uses clear and descriptive attribute names
  • Properly organizes messages by type
custom_components/plugwise/climate.py (4)

51-51: LGTM!

The import statement correctly adds PlugwiseConfigEntry type from the coordinator module.


265-265: LGTM!

Good improvement: Removing input validation check as it's handled by the coordinator.


278-279: Good optimization!

Early return when the mode hasn't changed prevents unnecessary API calls.


207-208: Verify HomeKit mode handling.

The HomeKit mode handling overrides the actual HVAC mode. Ensure this behavior is intended and documented.

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Search for documentation or tests related to HomeKit mode handling
rg -A 5 "homekit.*mode" --type md

Length of output: 35


Below are additional shell scripts to collect more context around the HomeKit handling in the source file. We’ll review both the surrounding code and the inline comments to see if this behavior is further explained in the implementation.

Once these outputs are reviewed, we can determine if the overriding of the actual HVAC mode when HomeKit is enabled is intended behavior (albeit lacking external markdown documentation) or if it needs further clarification. Given that the initial markdown search returned no relevant documentation, manual verification and further review of the code’s intent might be necessary.

Please run the above commands and verify the surrounding context.


🏁 Script executed:

#!/bin/bash
# Display extended context for HomeKit-related logic in custom_components/plugwise/climate.py
rg -n "if self._homekit_enabled" --context 10 custom_components/plugwise/climate.py

Length of output: 963


🏁 Script executed:

#!/bin/bash
# Search for inline comments mentioning 'HomeKit' in the same file to check for documentation
rg -n "#.*HomeKit" custom_components/plugwise/climate.py

Length of output: 126


HomeKit Mode Handling Is Intentional in the Beta Emulation Implementation

  • The code intentionally forces the HVAC mode to OFF when HomeKit is enabled and its mode is OFF.
  • Inline comments (e.g., "pw-beta homekit emulation" and "pw-beta: feature request - mimic HomeKit behavior") confirm that overriding the HVAC mode is part of a beta feature to simulate HomeKit behavior.
  • Although no dedicated external documentation was found, the inline comments clearly indicate that the behavior is intentional.
custom_components/plugwise/sensor.py (2)

82-82: LGTM!

The import statement correctly adds PlugwiseConfigEntry type from the coordinator module.


482-495: Good addition of debug logging!

The alternative implementation with debug logging helps in troubleshooting sensor creation issues.

@sonarqubecloud
Copy link

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

🧹 Nitpick comments (1)
custom_components/plugwise/__init__.py (1)

151-156: Add safe handling when removing timeout configuration.

The current implementation might raise a KeyError if CONF_TIMEOUT is not present in the data.

Consider using dict.pop() with a default value:

-        new_data.pop(CONF_TIMEOUT)
+        new_data.pop(CONF_TIMEOUT, None)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 70fc491 and dcf3129.

📒 Files selected for processing (1)
  • custom_components/plugwise/__init__.py (3 hunks)
🔇 Additional comments (3)
custom_components/plugwise/__init__.py (3)

25-25: LGTM! Clean type import.

The import of PlugwiseConfigEntry and PlugwiseDataUpdateCoordinator from the coordinator module improves type clarity and follows good practices for type organization.


39-41: LGTM! Enhanced coordinator initialization.

The addition of the entry parameter to the coordinator constructor provides better access to configuration data. The type updates improve type safety.


79-83: LGTM! Well-scoped service registration.

The service registration is correctly limited to the BINARY_SENSOR platform, preventing duplicate registrations across platforms.

Copy link

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

Error while testing for Development HA-core:

⚠️ Warning: Incompatible while testing against dev HA-core.
Error: Incompatible while testing against released HA-core and required to pass.

@CoMPaTech CoMPaTech changed the title Implement HA Core PR #138039 Implement HA Core PR 138039 Feb 11, 2025
@CoMPaTech
Copy link
Member

Edited title not to contain # refs from other projects to save confusion

@CoMPaTech
Copy link
Member

Could you bump cache to figure out what's borking in release-check?

Copy link

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

Error while testing for Development HA-core:

⚠️ Warning: Incompatible while testing against dev HA-core.
✔️ Success: No problem with testing against released HA-core.

@bouwew bouwew merged commit 036fe88 into main Feb 11, 2025
10 checks passed
@bouwew bouwew deleted the HA-138039 branch February 11, 2025 18:55
@coderabbitai coderabbitai bot mentioned this pull request Sep 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

downstreaming Things that are changed on HA-core side and to be applied to -beta

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants