Skip to content

feat: new sensor displaying wire quality and related sensor details, available in diagnostics#321

Merged
geertmeersman merged 1 commit into
mainfrom
dev-current
Aug 10, 2025
Merged

feat: new sensor displaying wire quality and related sensor details, available in diagnostics#321
geertmeersman merged 1 commit into
mainfrom
dev-current

Conversation

@geertmeersman

@geertmeersman geertmeersman commented Aug 10, 2025

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • New Features
    • Added a new sensor displaying wire quality and related sensor details, available in diagnostics.
  • Bug Fixes
    • Improved handling of list-type sensor attributes to ensure correct display of sensor data.
  • Documentation
    • Added translations for the new wire quality sensor in English, German, French, and Dutch.

@coderabbitai

coderabbitai Bot commented Aug 10, 2025

Copy link
Copy Markdown

Walkthrough

A new "wire" quality sensor feature has been introduced to the Robonect integration. The code now calculates and exposes the minimum wire sensor quality from API responses, adds a corresponding sensor entity, and ensures proper attribute handling. Translation entries for the new sensor have been added in German, English, French, and Dutch.

Changes

Cohort / File(s) Change Summary
Wire Quality Calculation & Response Handling
custom_components/robonect/client/client.py
Adds logic to extract the "sensors" list from "wire" command responses, computes the minimum "quality" value, and inserts it as "lowest_quality" in the JSON response.
Sensor Entity Definition
custom_components/robonect/definitions.py
Adds a new sensor entity description for the wire quality sensor, mapping its state and attributes to the new JSON response fields.
Sensor Attribute Handling
custom_components/robonect/sensor.py
Updates attribute processing to support list-type attributes by assigning them under a derived key, ensuring correct sensor attribute representation.
Translations
custom_components/robonect/translations/en.json,
custom_components/robonect/translations/de.json,
custom_components/robonect/translations/fr.json,
custom_components/robonect/translations/nl.json
Adds translation entries for the new "wire" sensor in English, German, French, and Dutch, including sensor name and attribute labels.

Sequence Diagram(s)

sequenceDiagram
    participant RobonectAPI
    participant Client
    participant SensorEntity

    Client->>RobonectAPI: Send "wire" command
    RobonectAPI-->>Client: Return JSON response with sensors list
    Client->>Client: Calculate min "quality" in sensors
    Client->>Client: Add "lowest_quality" to response
    SensorEntity->>Client: Retrieve wire sensor data
    Client-->>SensorEntity: Provide "lowest_quality" and sensors attributes
    SensorEntity->>SensorEntity: Set state and attributes
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

A wire runs through the garden green,
Now sensors check just what’s unseen.
With numbers crunched and values found,
The lowest quality is passed around.
In every tongue, the news is told—
The wire’s health, both new and bold!
🐇✨

Note

🔌 MCP (Model Context Protocol) integration is now available in Early Access!

Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch dev-current

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
  • 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 explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this 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.

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.

@github-actions github-actions Bot added feat A new feature minor A change requiring a minor version bump labels Aug 10, 2025
@geertmeersman geertmeersman changed the title feat: wire quality sensor feat: new sensor displaying wire quality and related sensor details, available in diagnostics Aug 10, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🔭 Outside diff range comments (2)
custom_components/robonect/sensor.py (1)

325-340: Avoid calling adapt_attributes() on lists; handle list vs. dict attributes explicitly

Currently adapt_attributes(attrs, ...) is executed before the isinstance(attrs, list) check. If attrs is a list (e.g., $.wire.sensors), this can fail or silently do nothing depending on implementation. Also, empty lists are skipped due to the truthiness check.

Apply this diff to safely support lists and preserve previous behavior for dicts; also include empty lists by checking for None instead of truthiness:

-            if self.entity_description.rest_attrs:
-                attrs = get_json_dict_path(
-                    self.coordinator.data, self.entity_description.rest_attrs
-                )
-                attrs = copy.copy(attrs)
-                if attrs:
-                    adapt_attributes(
-                        attrs, self.category, self.entry.data[CONF_ATTRS_UNITS]
-                    )
-                    if not isinstance(attrs, list):
-                        attributes.update(attrs)
-                    else:
-                        # Get last segment after dot
-                        key_name = self.entity_description.rest_attrs.split(".")[-1]
-                        attributes[key_name] = attrs
+            if self.entity_description.rest_attrs:
+                attrs = get_json_dict_path(
+                    self.coordinator.data, self.entity_description.rest_attrs
+                )
+                attrs = copy.copy(attrs)
+                if attrs is not None:
+                    if isinstance(attrs, list):
+                        # Optionally adapt each element if they are mappings
+                        for i, item in enumerate(attrs):
+                            if isinstance(item, dict):
+                                adapt_attributes(
+                                    item, self.category, self.entry.data[CONF_ATTRS_UNITS]
+                                )
+                        key_name = self.entity_description.rest_attrs.split(".")[-1]
+                        attributes[key_name] = attrs
+                    elif isinstance(attrs, dict):
+                        adapt_attributes(
+                            attrs, self.category, self.entry.data[CONF_ATTRS_UNITS]
+                        )
+                        attributes.update(attrs)
+                    else:
+                        key_name = self.entity_description.rest_attrs.split(".")[-1]
+                        attributes[key_name] = attrs
custom_components/robonect/definitions.py (1)

25-31: Type annotation mismatch: rest_attrs is used as a JSONPath string, not a dict

Both RobonectSwitchEntityDescription.rest_attrs and RobonectSensorEntityDescription.rest_attrs are annotated as dict | None but are consistently used as strings (JSON paths). This confuses type checkers and contributors.

Apply this diff to align annotations with usage:

 class RobonectSwitchEntityDescription(SwitchEntityDescription):
@@
-    rest_attrs: dict | None = None
+    rest_attrs: str | None = None
@@
 class RobonectSensorEntityDescription(SensorEntityDescription):
@@
-    rest_attrs: dict | None = None
+    rest_attrs: str | None = None

Also applies to: 37-43

🧹 Nitpick comments (1)
custom_components/robonect/translations/nl.json (1)

463-470: Dutch wording and attribute translation tweaks

  • Line 464: Prefer “Draadkwaliteit” as a single compound word in Dutch.
  • Line 467: Translate “Sensors” to “Sensoren” for consistency with other locales.

Apply this diff:

-        "name": "Draad kwaliteit",
+        "name": "Draadkwaliteit",
@@
-          "sensors": {
-            "name": "Sensors"
-          }
+          "sensors": {
+            "name": "Sensoren"
+          }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a6c1d1d and d676ff4.

📒 Files selected for processing (7)
  • custom_components/robonect/client/client.py (1 hunks)
  • custom_components/robonect/definitions.py (1 hunks)
  • custom_components/robonect/sensor.py (1 hunks)
  • custom_components/robonect/translations/de.json (1 hunks)
  • custom_components/robonect/translations/en.json (1 hunks)
  • custom_components/robonect/translations/fr.json (1 hunks)
  • custom_components/robonect/translations/nl.json (1 hunks)
🔇 Additional comments (3)
custom_components/robonect/translations/fr.json (1)

463-470: LGTM — correct French localization

“Qualité du fil” and “Capteurs” read well and align with other locales. No issues spotted.

custom_components/robonect/translations/de.json (1)

463-470: LGTM — correct German localization

“Drahtqualität” and “Sensoren” are appropriate and consistent.

custom_components/robonect/translations/en.json (1)

463-470: LGTM — clear English labeling

“Wire quality” and “Sensors” are accurate and consistent with feature intent.

Comment on lines +177 to +186
if command == "wire":
# Extract the lowest quality value from the sensors list
sensors = result_json.get("sensors", [])
if sensors:
min_quality = min(
sensor.get("quality", float("inf")) for sensor in sensors
)
result_json["lowest_quality"] = min_quality
else:
result_json["lowest_quality"] = None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle None/missing/non-numeric qualities and avoid returning infinity

Current logic can:

  • Raise a TypeError if any sensor has quality=None (min compares None with float).
  • Return float("inf") when all qualities are missing, which is not meaningful for a sensor.

Filter to numeric (or castable) qualities and set None if none are valid.

Apply this diff:

-            if command == "wire":
-                # Extract the lowest quality value from the sensors list
-                sensors = result_json.get("sensors", [])
-                if sensors:
-                    min_quality = min(
-                        sensor.get("quality", float("inf")) for sensor in sensors
-                    )
-                    result_json["lowest_quality"] = min_quality
-                else:
-                    result_json["lowest_quality"] = None
+            if command == "wire":
+                # Extract the lowest quality value from the sensors list
+                sensors = result_json.get("sensors", [])
+                if sensors:
+                    qualities = []
+                    for sensor in sensors:
+                        q = sensor.get("quality")
+                        try:
+                            if q is not None:
+                                qualities.append(float(q))
+                        except (TypeError, ValueError):
+                            continue
+                    result_json["lowest_quality"] = min(qualities) if qualities else None
+                else:
+                    result_json["lowest_quality"] = None
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if command == "wire":
# Extract the lowest quality value from the sensors list
sensors = result_json.get("sensors", [])
if sensors:
min_quality = min(
sensor.get("quality", float("inf")) for sensor in sensors
)
result_json["lowest_quality"] = min_quality
else:
result_json["lowest_quality"] = None
if command == "wire":
# Extract the lowest quality value from the sensors list
sensors = result_json.get("sensors", [])
if sensors:
qualities = []
for sensor in sensors:
q = sensor.get("quality")
try:
if q is not None:
qualities.append(float(q))
except (TypeError, ValueError):
continue
result_json["lowest_quality"] = min(qualities) if qualities else None
else:
result_json["lowest_quality"] = None
🤖 Prompt for AI Agents
In custom_components/robonect/client/client.py around lines 177 to 186, the
current code can raise a TypeError if any sensor's quality is None and may
return float("inf") if all qualities are missing. To fix this, filter the sensor
qualities to include only numeric values before computing the minimum. If no
valid numeric qualities are found, set result_json["lowest_quality"] to None
instead of infinity.

Comment on lines +178 to +188
RobonectSensorEntityDescription(
key=".wire",
rest="$.wire.lowest_quality",
rest_attrs="$.wire.sensors",
state_class=SensorStateClass.MEASUREMENT,
native_unit_of_measurement=PERCENTAGE,
entity_category=EntityCategory.DIAGNOSTIC,
icon="mdi:check-network",
category="wire",
translation_key="wire",
),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

New wire quality sensor looks correct and consistent with attribute handling

State path, units, and state class make sense; attributes path returns the sensors list which matches the updated list-handling in sensor.py. Icon, translation_key, and category align.

If useful, verify the upstream client always provides a numeric 0–100 lowest_quality and a list at $.wire.sensors:


🏁 Script executed:

#!/bin/bash
rg -n --hidden -A2 -B2 'lowest_quality' custom_components
rg -n --hidden -A2 -B2 '\.wire\.sensors' custom_components

Length of output: 1649


🏁 Script executed:

#!/bin/bash
# Inspect how "wire" and its sensors list are populated in the client
rg -n 'result_json\["wire"' -A5 custom_components/robonect/client/client.py
rg -n 'wire\s*=' -A5 custom_components/robonect/client/client.py
rg -n 'sensors\s*=' -A5 custom_components/robonect/client/client.py

Length of output: 530


🏁 Script executed:

#!/bin/bash
# Find where the client fetches data and how it structures the JSON
rg -n 'async def' -A2 custom_components/robonect/client/client.py
rg -n 'class .*Client' -A2 custom_components/robonect/client/client.py
rg -n 'await .*get' -A3 custom_components/robonect/client/client.py

Length of output: 2196


🏁 Script executed:

#!/bin/bash
# Display the full implementation of the state() method to verify JSON structure
rg -n -A30 'async def state' custom_components/robonect/client/client.py

Length of output: 1210


Adjust JSONPath for wire quality sensor

The client’s status JSON places lowest_quality and sensors at the top level—not under a wire object—so the current paths won’t match. Update the entity description in custom_components/robonect/definitions.py accordingly.

• File: custom_components/robonect/definitions.py (around line 178)
Change the JSONPath for rest and rest_attrs:

     RobonectSensorEntityDescription(
         key=".wire",
-        rest="$.wire.lowest_quality",
-        rest_attrs="$.wire.sensors",
+        rest="$.lowest_quality",
+        rest_attrs="$.sensors",
         state_class=SensorStateClass.MEASUREMENT,
         native_unit_of_measurement=PERCENTAGE,
         entity_category=EntityCategory.DIAGNOSTIC,
         icon="mdi:check-network",
         category="wire",
         translation_key="wire",
     ),
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
RobonectSensorEntityDescription(
key=".wire",
rest="$.wire.lowest_quality",
rest_attrs="$.wire.sensors",
state_class=SensorStateClass.MEASUREMENT,
native_unit_of_measurement=PERCENTAGE,
entity_category=EntityCategory.DIAGNOSTIC,
icon="mdi:check-network",
category="wire",
translation_key="wire",
),
RobonectSensorEntityDescription(
key=".wire",
rest="$.lowest_quality",
rest_attrs="$.sensors",
state_class=SensorStateClass.MEASUREMENT,
native_unit_of_measurement=PERCENTAGE,
entity_category=EntityCategory.DIAGNOSTIC,
icon="mdi:check-network",
category="wire",
translation_key="wire",
),
🤖 Prompt for AI Agents
In custom_components/robonect/definitions.py around lines 178 to 188, the
JSONPath expressions for the wire quality sensor are incorrect because
`lowest_quality` and `sensors` are at the top level of the `status` JSON, not
under a `wire` object. Update the `rest` path from `$.wire.lowest_quality` to
`$.lowest_quality` and the `rest_attrs` path from `$.wire.sensors` to
`$.sensors` to correctly reflect the JSON structure.

@geertmeersman geertmeersman merged commit d074de5 into main Aug 10, 2025
17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feat A new feature minor A change requiring a minor version bump

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant