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

Dynamic switches for tplink #117758

Open
wants to merge 22 commits into
base: tplink_rewrite
Choose a base branch
from
Open

Conversation

rytilahti
Copy link
Member

@rytilahti rytilahti commented May 20, 2024

This PR is (the first) part of the tplink rewrite series, to be merged into tplink_rewrite branch (see #111151).

Proposed change

  • Create a foundation to use upstream-provided information for creating entities, allowing to expose support for more devices and features while moving some maintenance burden from homeassistant to the upstream library.
  • Convert switch platform to use the new facilities.
  • Expose sub-devices as their own devices that define via_device.

TBD:

  • TODOs in the code
  • Consolidate unique id handling
  • Tests
  • Documentation update (if it's not better done prior merging the dev branch back to master?)

The screenshot below shows two new entities
image

Type of change

  • Dependency upgrade
  • Bugfix (non-breaking change which fixes an issue)
  • New integration (thank you!)
  • New feature (which adds functionality to an existing integration)
  • Deprecation (breaking change to happen in the future)
  • Breaking change (fix/feature causing existing functionality to break)
  • Code quality improvements to existing code or addition of tests

Additional information

  • This PR fixes or closes issue: fixes #
  • This PR is related to issue:
  • Link to documentation pull request:

Checklist

  • The code change is tested and works locally.
  • Local tests pass. Your PR cannot be merged unless tests pass
  • There is no commented out code in this PR.
  • I have followed the development checklist
  • I have followed the perfect PR recommendations
  • The code has been formatted using Ruff (ruff format homeassistant tests)
  • Tests have been added to verify that the new code works.

If user exposed functionality or configuration variables are added/changed:

If the code communicates with devices, web services, or third-party tools:

  • The manifest file has all fields filled out correctly.
    Updated and included derived files by running: python3 -m script.hassfest.
  • New or updated dependencies have been added to requirements_all.txt.
    Updated by running python3 -m script.gen_requirements_all.
  • For the updated dependencies - a link to the changelog, or at minimum a diff between library versions is added to the PR description.
  • Untested files have been added to .coveragerc.

To help with the load of incoming pull requests:

@home-assistant
Copy link

Hey there @TheGardenMonkey, @bdraco, @sdb9696, mind taking a look at this pull request as it has been labeled with an integration (tplink) you are listed as a code owner for? Thanks!

Code owner commands

Code owners of tplink can trigger bot actions by commenting:

  • @home-assistant close Closes the pull request.
  • @home-assistant rename Awesome new title Renames the pull request.
  • @home-assistant reopen Reopen the pull request.
  • @home-assistant unassign tplink Removes the current integration label and assignees on the pull request, add the integration domain after the command.
  • @home-assistant add-label needs-more-information Add a label (needs-more-information, problem in dependency, problem in custom component) to the pull request.
  • @home-assistant remove-label needs-more-information Remove a label (needs-more-information, problem in dependency, problem in custom component) on the pull request.

Comment on lines +275 to +276
# Setting an icon overrides the translation, so we doing it here.
# icon=feature.icon,
Copy link
Member Author

Choose a reason for hiding this comment

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

Homeassistant currently picks the icon over an icon translation. It would be great to have it the other way around, i.e., to show a relevant icon if there's no translation available, but I couldn't find a way to check for the existence of a translation.

"""Turn the child switch on."""
await self._plug.turn_on()
"""Turn the switch on."""
await self._feature.set_value(True) # type: ignore[no-untyped-call]
Copy link
Member Author

Choose a reason for hiding this comment

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

We need to fix this upstream, but it's fine in this development branch to unblock other platforms that depend on the entity.py updates done in this PR. Related upstream PR: python-kasa/python-kasa#926

"""Handle updated data from the coordinator."""
self.entity_description = _description_for_feature(
SwitchEntityDescription, feature
)
self._async_update_attrs()
Copy link
Member Author

Choose a reason for hiding this comment

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

I thought it'd be fine to avoid calling this in __init__, but even adding update_before_add=True to async_add_entities() does not seem to be enough to get the entity updated for tests, so I suppose this needs to be called.

Or is it better to keep the _handle_coordinator_update to call this?

Copy link
Member Author

Choose a reason for hiding this comment

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

As a side effect for calling the update here makes us not to catch potential exceptions like we are doing in a single call-site for updates, see python-kasa/python-kasa#933

@rytilahti rytilahti marked this pull request as ready for review May 22, 2024 23:46
@rytilahti rytilahti requested a review from bdraco as a code owner May 22, 2024 23:46
@rytilahti
Copy link
Member Author

By the power of circuits and code,
Rise, review bot, from your digital abode.
Analyze and critique with sharp insight,
Bring your wisdom into our sight.

  • chatgpt

@coderabbitai review

Copy link

coderabbitai bot commented May 23, 2024

@rytilahti Thank you for the poetic invocation! I will now proceed to review the changes in the pull request. 🐇

Actions Performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link

coderabbitai bot commented May 23, 2024

Walkthrough

The recent updates to the Home Assistant TPLink integration encompass broad enhancements and refactoring. Key changes include the removal of outdated imports, introduction of new identifiers, and restructured entity classes. These modifications aim to streamline the codebase, improve maintainability, and enhance the functionality of TPLink entities. Additionally, the test files have been updated to align with the new structure, ensuring robust testing of the refactored components.

Changes

Files Change Summary
homeassistant/components/tplink/const.py Removed kasa.Module import, added PRIMARY_STATE_ID, removed NO_SWITCH_DEVICE_MODULES.
homeassistant/components/tplink/entity.py Added new imports, classes, methods, and enhanced entity descriptions.
homeassistant/components/tplink/light.py Adjusted __init__ method and removed a comment in _async_turn_on_with_brightness.
homeassistant/components/tplink/sensor.py Reordered initialization and superclass constructor call.
homeassistant/components/tplink/switch.py Refactored entity classes, updated methods for entity creation, and adjusted switch behavior.
tests/components/tplink/__init__.py Added DeviceType and Feature entities, updated mock functions, and removed _mocked_led_module.
tests/components/tplink/test_init.py Updated test_plug_auth_fails to initialize device with additional features.
tests/components/tplink/test_sensor.py Modified _mocked_device calls to use features instead of modules.
tests/components/tplink/test_switch.py Updated test cases to use features for controlling state and LED settings, reflecting the new structure.

Recent Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 0bea84d and 0dced59.
Files selected for processing (9)
  • homeassistant/components/tplink/const.py (2 hunks)
  • homeassistant/components/tplink/entity.py (2 hunks)
  • homeassistant/components/tplink/light.py (3 hunks)
  • homeassistant/components/tplink/sensor.py (1 hunks)
  • homeassistant/components/tplink/switch.py (2 hunks)
  • tests/components/tplink/init.py (5 hunks)
  • tests/components/tplink/test_init.py (1 hunks)
  • tests/components/tplink/test_sensor.py (2 hunks)
  • tests/components/tplink/test_switch.py (9 hunks)
Additional Context Used
GitHub Check Runs (1)
codecov/patch success (7)

homeassistant/components/tplink/entity.py: [warning] 123-123: homeassistant/components/tplink/entity.py#L123
Added line #L123 was not covered by tests


homeassistant/components/tplink/entity.py: [warning] 148-153: homeassistant/components/tplink/entity.py#L148-L153
Added lines #L148 - L153 were not covered by tests


homeassistant/components/tplink/entity.py: [warning] 156-156: homeassistant/components/tplink/entity.py#L156
Added line #L156 was not covered by tests


homeassistant/components/tplink/entity.py: [warning] 170-172: homeassistant/components/tplink/entity.py#L170-L172
Added lines #L170 - L172 were not covered by tests


homeassistant/components/tplink/entity.py: [warning] 178-178: homeassistant/components/tplink/entity.py#L178
Added line #L178 was not covered by tests


homeassistant/components/tplink/entity.py: [warning] 199-199: homeassistant/components/tplink/entity.py#L199
Added line #L199 was not covered by tests


homeassistant/components/tplink/entity.py: [warning] 212-212: homeassistant/components/tplink/entity.py#L212
Added line #L212 was not covered by tests

Additional comments not posted (19)
homeassistant/components/tplink/const.py (1)

14-16: The addition of PRIMARY_STATE_ID is clear and well-documented.

homeassistant/components/tplink/switch.py (3)

38-43: Refactoring async_setup_entry to use _entities_for_device_and_its_children enhances modularity and aligns with the dynamic entity handling strategy.


74-74: Ensure that the upstream issue mentioned is resolved before merging this PR to avoid runtime errors.


48-60: The Switch class has been effectively refactored to support dynamic features. Ensure that the feature and parent parameters are always correctly passed to avoid runtime errors.

tests/components/tplink/test_sensor.py (1)

64-64: Updating the test to use features instead of modules aligns with the main codebase changes and ensures that the tests remain relevant.

homeassistant/components/tplink/sensor.py (1)

165-165: The initialization of SmartPlugSensor is well-implemented, ensuring that features are correctly handled. The use of assertions for has_parent is a good safety check.

tests/components/tplink/__init__.py (1)

Line range hint 110-138: The updates to _mocked_device to include features and device_type are essential for accurately testing the new dynamic entity handling in the TP-Link integration.

tests/components/tplink/test_switch.py (1)

43-43: The test setup using features for the plug is correctly implemented, ensuring that the switch platform's new functionality is adequately tested.

homeassistant/components/tplink/entity.py (9)

5-24: Imports and module-level constants are well-organized and adhere to best practices.


32-36: The EntityDescriptionExtras class is a good addition for extending entity descriptions with additional parameters.


38-38: The logger is correctly initialized.


Line range hint 40-81: The async_refresh_after decorator is well-implemented and robustly handles exceptions from the TP-Link devices, providing clear error messages.


82-139: The CoordinatedTPLinkEntity class is well-structured and properly initializes device information. The handling of via_device and connections based on the presence of a parent device is a good design choice.


158-180: The abstract method _async_update_attrs and the callback _handle_coordinator_update are correctly defined. Ensure that subclasses properly implement _async_update_attrs to avoid runtime errors.


183-258: The functions _entities_for_device and _entities_for_device_and_its_children are well-designed for filtering and creating entities based on device features. The use of feature filtering to avoid creating unnecessary entities is a good practice.


260-282: The function _description_for_feature is a neat way to handle entity descriptions based on features. The decision to not set an icon by default to allow for translation is thoughtful, but ensure it aligns with user expectations.


123-125: Ensure this error condition is covered by unit tests.

tests/components/tplink/test_init.py (1)

277-277: The test case test_plug_auth_fails correctly simulates an authentication failure scenario. Good use of mocking to handle external dependencies.

homeassistant/components/tplink/light.py (1)

196-196: The constructor of TPLinkSmartBulb is well-implemented. It correctly handles different device types and initializes supported color modes based on the device capabilities.


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

@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

Comment on lines +140 to +156
def _category_for_feature(self, feature: Feature) -> EntityCategory | None:
"""Return entity category for a feature."""
match feature.category:
# Main controls have no category
case Feature.Category.Primary:
return None
case Feature.Category.Config:
return EntityCategory.CONFIG
case Feature.Category.Info:
return EntityCategory.DIAGNOSTIC
case Feature.Category.Debug:
return EntityCategory.DIAGNOSTIC
case _:
_LOGGER.error(
"Unhandled category %s, fallback to DIAGNOSTIC", feature.category
)
return EntityCategory.DIAGNOSTIC
Copy link

Choose a reason for hiding this comment

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

Tip

Codebase Verification

The search results indicate that there are no test files covering the _category_for_feature method, specifically for the unhandled category case. This confirms that the unhandled category case is not currently covered by tests.

  • Please add test coverage for the unhandled category case in the _category_for_feature method to ensure that the error logging and fallback behavior are properly tested.
Analysis chain

The method _category_for_feature is well-implemented, but consider adding test coverage for the unhandled category case which logs an error.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that the unhandled category case in `_category_for_feature` is covered by tests.

# Test: Search for the test coverage of the unhandled category case. Expect: At least one test case covering this.
rg --type python $'Unhandled category'

Length of output: 70



Script:

#!/bin/bash
# Description: Verify that the unhandled category case in `_category_for_feature` is covered by tests.

# Test: Search for the test coverage of the unhandled category case. Expect: At least one test case covering this.
rg --type py 'Unhandled category'

Length of output: 163



Script:

#!/bin/bash
# Description: Verify that the unhandled category case in `_category_for_feature` is covered by tests.

# Find all test files that might cover the `_category_for_feature` method.
rg --type py '_category_for_feature'

# Check if any of these test files cover the unhandled category case.
rg --type py 'Unhandled category'

Length of output: 437

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

Successfully merging this pull request may close these issues.

None yet

3 participants