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

Fix for #288 and minor corrections #289

Merged
merged 4 commits into from
Nov 30, 2024
Merged

Fix for #288 and minor corrections #289

merged 4 commits into from
Nov 30, 2024

Conversation

sca075
Copy link
Owner

@sca075 sca075 commented Nov 30, 2024

As per comment in the commit config_flow fix for #288 and minor changes on robot error condition drawing and camera switch from test mode to normal mode

Summary by CodeRabbit

  • New Features

    • Enhanced camera functionality with improved error handling and logging for image updates.
    • Conditional snapshot taking based on vacuum state and image data availability.
  • Improvements

    • Renamed configuration options for clarity and consistency.
    • Updated color handling in the drawable representation of the robot based on its state.
    • Expanded method signatures to accommodate more flexible input options.
  • Bug Fixes

    • Refined handling of empty parsed JSON data to prevent errors and improve camera state management.

camera.py was in test mode, switched to normal mode.
drawable.py as discussed the robot icon is now draw in red 75% with outer at 100% in error condition

Signed-off-by: [email protected] <[email protected]>
@sca075 sca075 self-assigned this Nov 30, 2024
@sca075 sca075 added dependencies Pull requests that update a dependency file Fixes for issues labels Nov 30, 2024
Copy link

coderabbitai bot commented Nov 30, 2024

Walkthrough

This pull request introduces several modifications across multiple files in the mqtt_vacuum_camera component. Key changes include the removal of the test_mode parameter from the _process_parsed_json method in the MQTTCamera class, adjustments to error handling in the async_update method, and a renaming of the options attribute to camera_options within the configuration flow. Additionally, the robot method in the Drawable class has been updated to enhance color handling based on the robot's state, and its method signature has been adjusted to accept a None value for robot_state.

Changes

File Path Change Summary
custom_components/mqtt_vacuum_camera/camera.py - Removed test_mode from _process_parsed_json method.
- Updated error handling in async_update to raise ValueError for empty JSON data.
- Added logging in async_update for image updates.
- Updated _take_snapshot to conditionally take snapshots.
custom_components/mqtt_vacuum_camera/config_flow.py - Renamed options to camera_options in MQTTCameraFlowHandler and OptionsFlowHandler classes.
- Updated method signatures to use ConfigEntry directly.
custom_components/mqtt_vacuum_camera/utils/drawable.py - Adjusted robot method to set fixed colors when robot_state is "error".
- Updated robot method signature to accept None for robot_state.

Possibly related PRs

  • Adding event "valetudo_error" #280: The changes in this PR enhance error handling and introduce a new event for vacuum errors, which is related to the error handling improvements made in the async_update method of the MQTTCamera class in the main PR.
  • fix issue #282 AREA_SQUARE_METERS deprecated #283: Although primarily focused on updating constants for sensor types, this PR is related as it addresses the overall functionality of the vacuum system, which is also impacted by the changes in the main PR regarding the handling of vacuum data and states.

Suggested labels

enhancement


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 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.

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.

@sca075 sca075 linked an issue Nov 30, 2024 that may be closed by this pull request
2 tasks
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

🧹 Outside diff range and nitpick comments (7)
custom_components/mqtt_vacuum_camera/camera.py (1)

Line range hint 442-449: Consider making test data path configurable 🎯

The hardcoded test data path could cause issues if the directory structure changes. Consider making this configurable or using a relative path.

-            file_to_load="custom_components/mqtt_vacuum_camera/snapshots/test.json",
+            file_to_load=os.path.join(os.path.dirname(__file__), "snapshots", "test.json"),
custom_components/mqtt_vacuum_camera/utils/drawable.py (2)

429-430: Sweet color handling for error states! 🚨

The red color choice for error states makes the robot super visible when something's wrong. Nice touch making it semi-transparent with that 191 alpha value - keeps it noticeable without being too in-your-face.

Though, might want to consider extracting these magic color values into constants at the class level:

class Drawable:
+    # Robot state colors
+    ERROR_OUTLINE = (255, 0, 0, 255)  # Solid red
+    ERROR_FILL = (255, 0, 0, 191)     # Semi-transparent red

    @staticmethod
    async def robot(
        layers: NumpyArray,
        x: int,
        y: int,
        angle: float,
        fill: Color,
        robot_state: str | None = None,
    ) -> NumpyArray:
        if robot_state == "error":
-            outline = (255, 0, 0, 255)
-            fill = (255, 0, 0, 191)
+            outline = Drawable.ERROR_OUTLINE
+            fill = Drawable.ERROR_FILL

429-430: Level up the error state handling! 🎮

Consider expanding the error state handling to support different types of errors with distinct visual cues. For example:

    @staticmethod
    async def robot(
        layers: NumpyArray,
        x: int,
        y: int,
        angle: float,
        fill: Color,
        robot_state: str | None = None,
    ) -> NumpyArray:
-        if robot_state == "error":
+        if robot_state == "critical_error":
             outline = (255, 0, 0, 255)  # Red
             fill = (255, 0, 0, 191)
+        elif robot_state == "warning":
+            outline = (255, 165, 0, 255)  # Orange
+            fill = (255, 165, 0, 191)
+        elif robot_state == "stuck":
+            outline = (128, 0, 128, 255)  # Purple
+            fill = (128, 0, 128, 191)

This would give users more detailed visual feedback about what's wrong with their robot. Each state could have its own distinct color scheme while maintaining the semi-transparent fill pattern.

custom_components/mqtt_vacuum_camera/config_flow.py (4)

111-112: Add type hints to class attributes

Consider adding type hints to improve code maintainability:

-        self.data = {}
-        self.camera_options = {}
+        self.data: Dict[str, Any] = {}
+        self.camera_options: Dict[str, Any] = {}

182-188: Consider adding error handling for config entry initialization

The initialization looks good, but consider adding error handling for cases where the config entry might be invalid.

     def __init__(self, config_entry: ConfigEntry):
         """Initialize options flow."""
+        if not config_entry or not config_entry.unique_id:
+            raise ConfigEntryError("Invalid config entry")
         self.camera_config = config_entry
         self.unique_id = self.camera_config.unique_id
         self.camera_options = {}

Line range hint 868-878: Add error handling to options saving

The options saving process should handle potential errors during the update process.

     async def async_step_opt_save(self):
         """Save the options in a sorted way. It stores all the options."""
         _LOGGER.info(f"Storing Updated Camera ({self.camera_config.unique_id}) Options.")
-        _, vacuum_device = get_vacuum_device_info(
-            self.camera_config.data.get(CONF_VACUUM_CONFIG_ENTRY_ID), self.hass
-        )
-        opt_update = await update_options(self.bk_options, self.camera_options)
-        _LOGGER.debug(f"updated options:{dict(opt_update)}")
-        return self.async_create_entry(
-            title="",
-            data=opt_update,
-        )
+        try:
+            _, vacuum_device = get_vacuum_device_info(
+                self.camera_config.data.get(CONF_VACUUM_CONFIG_ENTRY_ID), self.hass
+            )
+            opt_update = await update_options(self.bk_options, self.camera_options)
+            _LOGGER.debug(f"updated options:{dict(opt_update)}")
+            return self.async_create_entry(
+                title="",
+                data=opt_update,
+            )
+        except Exception as e:
+            _LOGGER.error(f"Failed to save options: {e}")
+            return self.async_abort(reason="save_error")

873-874: Optimize logging performance

Using % formatting or str.format() for logging is more efficient than f-strings, especially when the log level is not enabled.

-        _LOGGER.debug(f"updated options:{dict(opt_update)}")
+        _LOGGER.debug("updated options: %s", dict(opt_update))
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 68d63ef and 040c189.

📒 Files selected for processing (3)
  • custom_components/mqtt_vacuum_camera/camera.py (1 hunks)
  • custom_components/mqtt_vacuum_camera/config_flow.py (32 hunks)
  • custom_components/mqtt_vacuum_camera/utils/drawable.py (1 hunks)
🧰 Additional context used
📓 Learnings (1)
custom_components/mqtt_vacuum_camera/config_flow.py (1)
Learnt from: sca075
PR: sca075/mqtt_vacuum_camera#196
File: custom_components/mqtt_vacuum_camera/config_flow.py:352-355
Timestamp: 2024-11-12T05:06:42.185Z
Learning: Changes in `config_flow.py` now include handling for `floor_only` and `alpha_floor` steps based on the number of rooms, ensuring proper configuration and error handling for unexpected values of `number_of_rooms`.
🔇 Additional comments (3)
custom_components/mqtt_vacuum_camera/camera.py (2)

Line range hint 327-332: Solid error handling improvement! 🛡️

The addition of proper error handling for JSON parsing failures makes the code more resilient. Setting _vac_json_available to "Error" provides good feedback for debugging.


Line range hint 441-449: Verify test mode usage across the codebase 🔍

Let's verify how test mode is being used across the codebase to ensure this change doesn't break existing functionality.

custom_components/mqtt_vacuum_camera/config_flow.py (1)

14-14: LGTM! Clean import refactoring

The change from config_entries.ConfigEntry to direct ConfigEntry import improves code readability.

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

🧹 Outside diff range and nitpick comments (2)
custom_components/mqtt_vacuum_camera/config_flow.py (2)

185-190: Good addition of error handling, but consider enhancing the error message

The error handling for missing config entry is good, but the error message could be more descriptive.

 if not config_entry:
-    raise ConfigEntryError("Config entry is required.")
+    raise ConfigEntryError("Config entry is required for camera configuration initialization.")

Line range hint 356-361: Enhance room count validation

While the room count validation is good, consider adding an upper limit check to prevent potential issues with extremely large room counts.

 if (
     not isinstance(self.number_of_rooms, int)
-    or self.number_of_rooms < DEFAULT_ROOMS
+    or self.number_of_rooms < DEFAULT_ROOMS
+    or self.number_of_rooms > 16  # Add upper limit check
 ):
     errors["base"] = "no_rooms"
     _LOGGER.error("No rooms found in the configuration. Aborting.")
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 040c189 and a27b273.

📒 Files selected for processing (2)
  • custom_components/mqtt_vacuum_camera/config_flow.py (33 hunks)
  • custom_components/mqtt_vacuum_camera/utils/drawable.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • custom_components/mqtt_vacuum_camera/utils/drawable.py
🧰 Additional context used
📓 Learnings (1)
custom_components/mqtt_vacuum_camera/config_flow.py (1)
Learnt from: sca075
PR: sca075/mqtt_vacuum_camera#196
File: custom_components/mqtt_vacuum_camera/config_flow.py:352-355
Timestamp: 2024-11-12T05:06:42.185Z
Learning: Changes in `config_flow.py` now include handling for `floor_only` and `alpha_floor` steps based on the number of rooms, ensuring proper configuration and error handling for unexpected values of `number_of_rooms`.
🔇 Additional comments (1)
custom_components/mqtt_vacuum_camera/config_flow.py (1)

Line range hint 599-611: LGTM: Floor configuration aligns with previous learnings

The implementation of floor_only step correctly handles the single room case as discussed in previous learnings.

@sca075 sca075 merged commit ad1ee34 into main Nov 30, 2024
6 checks passed
@sca075 sca075 linked an issue Dec 1, 2024 that may be closed by this pull request
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
dependencies Pull requests that update a dependency file Fixes for issues
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Sets option flow config_entry explicitly, which is deprecated Highlight when the Vacuum is in Error State.
1 participant