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

Clarify state attributes rules for entity #2437

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

gjohansson-ST
Copy link
Member

@gjohansson-ST gjohansson-ST commented Nov 3, 2024

Proposed change

Clarify the rules regarding additional state attributes as decided in home-assistant/architecture#680

Type of change

  • Document existing features within Home Assistant
  • Document new or changing features which there is an existing pull request elsewhere
  • Spelling or grammatical corrections, or rewording for improved clarity
  • Changes to the backend of this documentation
  • Removed stale or deprecated documentation

Additional information

  • This PR fixes or closes issue: fixes #
  • Link to relevant existing code or pull request:

Summary by CodeRabbit

  • Documentation
    • Added new sections on "State attributes" and "System properties" to clarify entity management.
    • Updated "Entity naming" section to emphasize the mandatory nature of the has_entity_name property.
    • Enhanced "Property implementation" section with additional best practice examples.
    • Refined "Lifecycle hooks" section to specify the asynchronous nature of hooks.

Copy link
Contributor

coderabbitai bot commented Nov 3, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces significant updates to the docs/core/entity.md document. It adds new sections on "State attributes" and "System properties," clarifying the handling of entity attributes and properties controlled by Home Assistant. The "Entity naming" section is revised to emphasize the mandatory nature of the has_entity_name property, while the "Property implementation" section is enhanced with additional examples. The "Lifecycle hooks" section is also refined to specify the asynchronous nature of the hooks, improving the overall clarity and comprehensiveness of the documentation.

Changes

File Change Summary
docs/core/entity.md - Added new section: "State attributes" detailing extra_state_attributes management.
- Added new section: "System properties" describing properties controlled by Home Assistant.
- Updated "Entity naming" section to clarify has_entity_name requirements.
- Enhanced "Property implementation" section with additional examples.
- Refined "Lifecycle hooks" section to specify asynchronous nature of hooks.

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 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 and nitpick comments (2)
docs/core/entity.md (2)

122-132: Fix grammar and consider adding a code example.

  1. There's a grammatical error in the text. Please fix:
-If an attributes is not expected
+If an attribute is not expected
  1. Consider adding a code example to illustrate these rules. For instance:
class MyEntity(Entity):
    @property
    def extra_state_attributes(self):
        """Return entity specific state attributes."""
        attributes = {
            "expected_attribute": self._value or None,  # Always present
            "configuration_dependent": "value"  # Only when configured
        }
        return attributes
🧰 Tools
🪛 LanguageTool

[grammar] ~131-~131: The plural noun “attributes” cannot be used with the article “an”. Did you mean “an attribute” or “attributes”?
Context: ...None` and remain in the dictionary - If an attributes is not expected, it should not be in th...

(A_NNS)


Line range hint 134-139: Consider enhancing the System properties documentation.

The section could be more helpful with additional context:

  1. Add a note explaining that these properties are managed through the entity registry.
  2. Add a warning about not implementing custom logic for these properties, as they are system-managed.

Example addition:

:::warning
These properties are managed by Home Assistant through the entity registry. Integrations should not implement custom logic for these properties as it may conflict with system behavior.
:::
🧰 Tools
🪛 LanguageTool

[grammar] ~131-~131: The plural noun “attributes” cannot be used with the article “an”. Did you mean “an attribute” or “attributes”?
Context: ...None` and remain in the dictionary - If an attributes is not expected, it should not be in th...

(A_NNS)

🪛 Markdownlint

120-120: Expected: 4; Actual: 3; Too few cells, row will be missing data
Table column count

(MD056, table-column-count)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4bd68db and ec175df.

📒 Files selected for processing (1)
  • docs/core/entity.md (1 hunks)
🧰 Additional context used
🪛 LanguageTool
docs/core/entity.md

[grammar] ~131-~131: The plural noun “attributes” cannot be used with the article “an”. Did you mean “an attribute” or “attributes”?
Context: ...None` and remain in the dictionary - If an attributes is not expected, it should not be in th...

(A_NNS)

🔇 Additional comments (1)
docs/core/entity.md (1)

Line range hint 1-1000: Overall documentation changes look good!

The additions effectively clarify the rules for state attributes and system properties, which aligns well with the PR objectives. The document maintains good structure and readability.

🧰 Tools
🪛 LanguageTool

[grammar] ~131-~131: The plural noun “attributes” cannot be used with the article “an”. Did you mean “an attribute” or “attributes”?
Context: ...None` and remain in the dictionary - If an attributes is not expected, it should not be in th...

(A_NNS)

🪛 Markdownlint

120-120: Expected: 4; Actual: 3; Too few cells, row will be missing data
Table column count

(MD056, table-column-count)

docs/core/entity.md Outdated Show resolved Hide resolved
docs/core/entity.md Outdated Show resolved Hide resolved
docs/core/entity.md Outdated Show resolved Hide resolved
docs/core/entity.md Outdated Show resolved Hide resolved
@home-assistant home-assistant bot marked this pull request as draft November 4, 2024 10:53
@home-assistant
Copy link

home-assistant bot commented Nov 4, 2024

Please take a look at the requested changes, and use the Ready for review button when you are done, thanks 👍

Learn more about our pull request process.

@gjohansson-ST gjohansson-ST marked this pull request as ready for review November 9, 2024 21:25
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 and nitpick comments (2)
docs/core/entity.md (2)

122-132: Enhance the state attributes section with examples

While the rules are clear, adding concrete examples would help developers better understand when attributes should be included or excluded from the dictionary. Consider adding examples for:

  1. Expected attributes (e.g., supported features)
  2. Attributes that should be None
  3. Attributes that should not be in the dictionary

Here's a suggested addition after line 132:

- If an attribute is not expected, it should not be in the dictionary. An attribute is expected if supported by the entity, for example as indicated by `supported_features`.
+ If an attribute is not expected, it should not be in the dictionary. An attribute is expected if supported by the entity, for example as indicated by `supported_features`.
+
+ ### Examples
+
+ ```python
+ @property
+ def extra_state_attributes(self):
+     """Return entity specific state attributes."""
+     attributes = {}
+     
+     # Example 1: Expected attribute based on supported features
+     if self._attr_supported_features & SUPPORT_BRIGHTNESS:
+         attributes["brightness"] = self._brightness
+     
+     # Example 2: Expected attribute that might be None
+     if self._attr_supported_features & SUPPORT_COLOR:
+         attributes["rgb_color"] = self._rgb_color  # Could be None
+     
+     # Example 3: Conditional attribute that should not be included
+     # Don't do this:
+     # if self._is_dimmable:
+     #     attributes["brightness"] = self._brightness
+     
+     return attributes
+ ```

Line range hint 143-401: LGTM with a minor suggestion

The updated sections on entity naming and property implementation are clear and well-documented. The examples effectively demonstrate best practices. Consider adding a note about error handling in the property implementation example to make it more complete.

Add error handling to the example:

     def update(self) -> None:
         """Update entity state."""
         try:
             self._device.update()
-        except ExampleException:
+        except ExampleException as ex:
             if self.available:  # Read current state, no need to prefix with _attr_
-                LOGGER.warning("Update failed for %s", self.entity_id)
+                LOGGER.warning("Update failed for %s: %s", self.entity_id, str(ex))
             self._attr_available = False  # Set property value
             return
+        except Exception as ex:
+            LOGGER.error("Unexpected error updating %s: %s", self.entity_id, str(ex))
+            self._attr_available = False
+            return
🧰 Tools
🪛 Markdownlint

120-120: Expected: 4; Actual: 3; Too few cells, row will be missing data
Table column count

(MD056, table-column-count)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ec175df and eabb8aa.

📒 Files selected for processing (1)
  • docs/core/entity.md (1 hunks)
🔇 Additional comments (1)
docs/core/entity.md (1)

Line range hint 134-141: LGTM!

The new "System properties" section clearly explains that these properties are controlled by Home Assistant and should not be overridden by integrations. The documentation for the enabled property is accurate and helpful.

🧰 Tools
🪛 Markdownlint

120-120: Expected: 4; Actual: 3; Too few cells, row will be missing data
Table column count

(MD056, table-column-count)

Comment on lines +122 to +129
## State attributes

Entities can provide additional state attributes besides the built-in ones, to provide further details to its state.
This should be done by providing a dictionary with keys and values to the `extra_state_attributes` property.

Providing state attributes comes with the following rules:

- If an attribute is expected, it should be in the dictionary. Attributes should not "come and go".
Copy link
Member

Choose a reason for hiding this comment

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

Should we also indicate our rules for what belongs in state attributes and what should be separate entities and what should be action calls?

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 think that would probably be good although do we really have clear rules?
I think we could do that in a follow-up in that case.

Copy link
Member

Choose a reason for hiding this comment

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

Frenck once mentioned this in the members channel

Some helpful guidance with that, that I apply (for myself)

  • Would someone extract it using a template into an other (binary) sensor -> Not an attribute
  • It is essential to automation on? Can it be standalone as its own entity? -> Not an attribute
  • It is static, e.g., from configuration; doesn't belong in the state machine -> Not an attribute
  • Do we want to track long term stats of the value? -> Not an attribute

Additionally:

  • Does is have historical value? If not, exlude it from being recorded.

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 think that makes sense but I'm not sure we can classify it as rules?
Maybe as "guidelines"?

Copy link
Member

Choose a reason for hiding this comment

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

Oh right. I think that if we are going to talk about state attributes, that we also explain that we are picky in what we want using these guidelines :)


- If an attribute is expected, it should be in the dictionary. Attributes should not "come and go".
- If an attribute is expected, but it's not providing a value right now, its value should be `None` and remain in the dictionary.
- If an attribute is not expected, it should not be in the dictionary. An attribute is expected if supported by the entity, for example as indicated by `supported_features`.
Copy link
Member

Choose a reason for hiding this comment

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

I am not really sure what this means and how it would look in practice

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 an example, in statistics the buffer_usage_ratio attribute is only shown if the sensor is configured to handle a buffer size. Otherwise this attribute would be irrelevant hence not showing in that case.

Copy link
Member

Choose a reason for hiding this comment

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

But how can someone expect it to be there? We're quite bad with describing entities in the docs, let alone describing the state attributes

Copy link
Member

Choose a reason for hiding this comment

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

This is the developer docs not the user docs. The attribute is expected if it's part of a supported feature and that feature is supported or if it's an extra state attribute the attribute is expected if the device has support for that attribute.

Providing state attributes comes with the following rules:

- If an attribute is expected, it should be in the dictionary. Attributes should not "come and go".
- If an attribute is expected, but it's not providing a value right now, its value should be `None` and remain in the dictionary.
Copy link
Member

Choose a reason for hiding this comment

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

I think the first 2 rules are quite similar. I also think we should explain what happens when for example the entity is unavailable. What should we do then?

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 could perhaps combine the first two as they talk about the same thing.
I'm not sure what you mean by unavailable? Should there be any special consideration for it?

Copy link
Member

Choose a reason for hiding this comment

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

If an entity is unavailable, does it still read the extra state attributes property when writing state? And if so, should everything be set to None?

Copy link
Member

Choose a reason for hiding this comment

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

State attributes are only set if the state of the entity is not unavailable. This is part of the base entity logic. Integrations should not adjust any logic concerning availability and state attributes.

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.

3 participants