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 relay on display as light mode #55

Merged
merged 7 commits into from
Dec 23, 2024
Merged

Fix relay on display as light mode #55

merged 7 commits into from
Dec 23, 2024

Conversation

edwardtfn
Copy link
Owner

@edwardtfn edwardtfn commented Dec 22, 2024

Solves #28

Summary by CodeRabbit

  • New Features

    • Introduced a new event handler for button clicks, improving relay control.
    • Added new light entities, enhancing lighting capabilities.
  • Improvements

    • Updated light configurations to ensure accurate state reflection based on relay status.
    • Enhanced readability and maintainability of relay mode selections and switch configurations.
    • Improved error logging for light state changes, increasing clarity.
    • Enhanced button action handling with improved logging and state management.
    • Extended package refresh interval for better performance.

Copy link
Contributor

coderabbitai bot commented Dec 22, 2024

Walkthrough

The pull request modifies the ESPHome configuration files for hardware relays, LED lights, and button interactions. Key changes include the introduction of a consolidated event handler for button clicks, updates to light configurations to accurately reflect relay states, and enhancements to the readability of relay mode selections and switch configurations through the use of substitution variables and clearer naming conventions. Additionally, new light entities are added, and improvements are made to error logging and button action handling.

Changes

File Change Summary
ESPHome/TX-Ultimate-Easy-ESPHome_core_hw_relays.yaml - Added new button_click_event handler for consolidated button click logic
- Updated light configurations with explicit on_turn_on and on_turn_off actions
- Modified relay mode select options using substitution variables
- Updated switch configurations to improve relay and light state handling
ESPHome/TX-Ultimate-Easy-ESPHome_core_hw_leds.yaml - Added new light entities (light_28 to light_31)
- Updated light_set_state script for improved error logging
- Expanded light segment configurations for US model
- Defined relay light modes using templates for consistency
TX-Ultimate-Easy-ESPHome.yaml - Updated package reference from main to latest
- Extended refresh interval from 30s to 5min
ESPHome/TX-Ultimate-Easy-ESPHome_core_hw_buttons.yaml - Added constants for button IDs (BUTTON_1_ID to BUTTON_4_ID)
- Updated button action handling with logging and state resets
- Enhanced touch handling and button press duration logic

Possibly related PRs

  • Rebuild Button click engine #50: The changes in this PR involve a redesign of the button click handling mechanism, which directly relates to the new event handler for button clicks introduced in the main PR. Both PRs focus on improving how button actions are processed, ensuring that the relay toggling logic is correctly managed based on button interactions.
  • Testing new versioning #40: Although this PR primarily addresses versioning and does not directly modify button handling, it is related to the overall configuration structure that includes button handling files. However, the connection is weaker compared to Rebuild Button click engine #50.

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

@edwardtfn edwardtfn linked an issue Dec 22, 2024 that may be closed by this pull request
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 (3)
ESPHome/TX-Ultimate-Easy-ESPHome_core_hw_relays.yaml (3)

27-45: LGTM! Good state synchronization between lights and relays

The handlers ensure that light states accurately reflect relay states, preventing inconsistencies.

Consider reducing code duplication in light configurations

The four light configurations are nearly identical, differing only in their IDs and associated relay numbers.

Consider using ESPHome's substitutions and templating to reduce duplication:

substitutions:
  # Add these to your existing substitutions
  LIGHT_TEMPLATE: &light_template
    platform: binary
    internal: true
    on_turn_on:
      then:
        - if:
            condition:
              - switch.is_off: sw_relay_$num
            then:
              - switch.turn_on: sw_relay_$num
    on_turn_off:
      then:
        - if:
            condition:
              - switch.is_on: sw_relay_$num
            then:
              - switch.turn_off: sw_relay_$num

light:
  - id: light_output_1
    name: Light output 1
    output: output_relay_1
    <<: *light_template
    substitutions:
      num: "1"
  # Repeat for lights 2-4 with corresponding numbers

Also applies to: 49-64, 68-83, 87-102


176-209: LGTM! Well-structured event handler with proper validation

The event handler properly validates click counts and touch events before processing, with clear control flow.

Consider using substitutions for button IDs in switch cases

The switch statement uses button IDs directly in case statements.

Consider defining button IDs as substitutions for better maintainability:

substitutions:
  BUTTON_1_CASE: "${BUTTON_1_ID}"
  BUTTON_2_CASE: "${BUTTON_2_ID}"
  BUTTON_3_CASE: "${BUTTON_3_ID}"
  BUTTON_4_CASE: "${BUTTON_4_ID}"

315-405: LGTM! Good state management in switch configurations

The switches properly manage state synchronization with lights and include appropriate restore behavior.

Consider reducing code duplication in switch configurations

Similar to the light configurations, the switch configurations are nearly identical.

Consider using YAML anchors and substitutions:

switch:
  - &switch_base
    platform: output
    restore_mode: RESTORE_DEFAULT_OFF
    internal: true
    on_turn_on:
      then:
        - script.execute: show_relay_status
        - if:
            condition:
              - light.is_off: light_output_$num
            then:
              - light.turn_on: light_output_$num
    on_turn_off:
      then:
        - script.execute: show_relay_status
        - if:
            condition:
              - light.is_on: light_output_$num
            then:
              - light.turn_off: light_output_$num

  - id: sw_relay_1
    name: Relay 1
    output: output_relay_1
    <<: *switch_base
    substitutions:
      num: "1"
  # Repeat for switches 2-4 with corresponding numbers
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bbbaeeb and 5ae45ff.

📒 Files selected for processing (1)
  • ESPHome/TX-Ultimate-Easy-ESPHome_core_hw_relays.yaml (5 hunks)
🔇 Additional comments (2)
ESPHome/TX-Ultimate-Easy-ESPHome_core_hw_relays.yaml (2)

14-17: LGTM! Good use of substitutions for relay modes

The substitutions provide clear, reusable text constants for relay modes, improving maintainability.


Line range hint 288-311: LGTM! Well-structured select configurations

Good use of YAML anchors and substitutions to maintain consistency across relay mode selections. The naming clearly indicates these are display modes.

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 (2)
ESPHome/TX-Ultimate-Easy-ESPHome_core_hw_leds.yaml (2)

Line range hint 798-836: Document index conversion in logging messages

The logging messages now display 1-based indices (light_index+1) while the internal logic uses 0-based indices. Consider adding a comment to explain this conversion to prevent confusion in future maintenance.

 ESP_LOGE("core_hw_leds", "Invalid set with %s light for Relay %" PRIu8,
-                                          light_mode_group_1.c_str(), light_index+1);
+                                          light_mode_group_1.c_str(), light_index+1);  // Convert to 1-based index for user-friendly logs

Line range hint 844-922: Consider consolidating common template properties

The EU and US relay light mode templates share many properties. Consider extracting common properties into a base template to reduce duplication and improve maintainability.

+  # Base relay light mode template
+  - &relay_light_mode_base
+    platform: template
+    optimistic: true
+    restore_value: true
+    internal: true
+    entity_category: config
+    disabled_by_default: false
+    icon: mdi:dots-square

   # EU relay light mode template
   - &relay_light_mode_eu
     id: sl_relay_1_light_mode_eu
     name: Relay 1 light mode
-    platform: template
+    <<: *relay_light_mode_base
     options:
       - "${LIGHT_MODE_DISABLED_TEXT}"
       - "${LIGHT_MODE_BOTTOM_TEXT}"
       - "${LIGHT_MODE_TOP_TEXT}"
       - "${LIGHT_MODE_BOTH_TEXT}"
     initial_option: "${LIGHT_MODE_BOTTOM_TEXT}"
-    optimistic: true
-    restore_value: true
-    internal: true
-    entity_category: config
-    disabled_by_default: false
-    icon: mdi:dots-square

   # US relay light mode template similar changes...
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5ae45ff and aa4e27e.

📒 Files selected for processing (1)
  • ESPHome/TX-Ultimate-Easy-ESPHome_core_hw_leds.yaml (4 hunks)
🔇 Additional comments (1)
ESPHome/TX-Ultimate-Easy-ESPHome_core_hw_leds.yaml (1)

Line range hint 428-460: LGTM: New light entities for US model

The new light entities (light_28 to light_31) are correctly implemented and follow the established pattern, properly marked as internal for the US model.

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

🧹 Nitpick comments (2)
ESPHome/TX-Ultimate-Easy-ESPHome_core_hw_buttons.yaml (2)

29-34: LGTM! Consider adding documentation.

The introduction of button ID constants improves maintainability and reduces magic numbers in the code. The naming convention is clear and consistent.

Consider adding a brief comment explaining the purpose and usage of these constants, for example:

  # Button ID constants used for event handling and state management
  # These IDs correspond to the physical button positions on the device
  BUTTON_1_ID: '1'
  BUTTON_2_ID: '2'
  BUTTON_3_ID: '3'
  BUTTON_4_ID: '4'

Line range hint 141-169: Consider improving button handling robustness.

The button handling implementation has several areas that could benefit from additional safeguards:

  1. Multi-click Detection:

    • The delay between clicks (BUTTON_MULTI_CLICK_DELAY: '250') might need adjustment based on user testing
    • Consider adding a maximum click count to prevent overflow
  2. Touch Position Calculation:

    • Add bounds checking for touch_position input
    • Consider logging invalid positions for debugging
    • Document the position calculation formula
  3. Timing Constants:

    • Consider making timing constants configurable via Home Assistant
    • Add validation for timing constant relationships (e.g., BUTTON_CLICK_MAX_LENGTH should be less than BUTTON_LONG_PRESS_DELAY)

Would you like me to provide specific code examples for any of these improvements?

Also applies to: 249-266

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ee6f565 and 552b83f.

📒 Files selected for processing (1)
  • ESPHome/TX-Ultimate-Easy-ESPHome_core_hw_buttons.yaml (1 hunks)
🔇 Additional comments (1)
ESPHome/TX-Ultimate-Easy-ESPHome_core_hw_buttons.yaml (1)

29-34: Verify integration with relay control system.

Since this PR aims to fix relay display in light mode, we should verify that the button ID constants are correctly integrated with the relay control system.

✅ Verification successful

Button ID constants are correctly integrated with relay control system

The verification shows that:

  1. The button IDs (1-4) are properly used in the relay control system through the button_click_event script
  2. Each button correctly maps to its corresponding relay (BUTTON_1_ID -> sw_relay_1, etc.)
  3. The relay control system properly handles both switch and light modes as part of the fix
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for relay-related configurations and verify button ID usage
echo "Searching for relay configurations..."
rg -l "relay" . --type yaml

echo "Checking button-to-relay mappings..."
rg "BUTTON_.*_ACTION_TEXT.*[Rr]elay" . --type yaml

echo "Verifying event handler implementations..."
rg "button_click_event.*[Rr]elay" . --type yaml

Length of output: 942


Script:

#!/bin/bash
# Let's check the actual button-relay interaction implementation
echo "Checking button event handlers and relay interactions..."
rg -A 5 "on_click:" . --type yaml

echo "Checking relay component definitions..."
cat ./ESPHome/TX-Ultimate-Easy-ESPHome_core_hw_relays.yaml

echo "Checking if button IDs are used in relay control..."
rg "id: ['\"]?[1-4]['\"]?" . --type yaml

Length of output: 16949

@edwardtfn edwardtfn merged commit 98ea881 into main Dec 23, 2024
14 checks passed
@edwardtfn edwardtfn deleted the relay-on-light-mode branch December 23, 2024 00:14
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.

After the last changes the Relay button lights no longer work
1 participant