Skip to content

Feature/arnout/correct message count #250

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

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

ArnoutD
Copy link
Contributor

@ArnoutD ArnoutD commented Jun 2, 2025

  • Change the addition of the queue counter (only on accepted messages)
  • Only query logs for the number of logaddresses since 0:00 UTC
  • Log the node type on NodeInfoResponse (to recognize the type of node)
  • Back to gather (< 6 requests for power history)
  • Ruff fixing and formatting

Summary by CodeRabbit

  • Bug Fixes

    • Improved the calculation of missing energy logs for Circle nodes to use the current time and enabled concurrent updates for better efficiency.
    • Enhanced the detail of hardware identifiers in node information outputs.
    • Corrected indentation in energy log response handling and improved consistency in boolean property expressions.
  • Style

    • Reformatted code throughout for improved readability, including multi-line formatting, consistent spacing, and clearer docstrings.
    • Updated logging statements to a more readable multi-line format.
    • Standardized blank lines and removed extraneous whitespace in multiple files.
    • Improved formatting of exception messages and docstrings for clarity.
  • Documentation

    • Added and refined docstrings to explain property behaviors and method purposes.
  • Tests

    • Updated test assertions to use identity checks for None and improved formatting in test data.
  • Chores

    • Updated linting configuration to adjust rule selection and ignored docstring rules.

@ArnoutD ArnoutD requested a review from a team as a code owner June 2, 2025 17:41
Copy link

coderabbitai bot commented Jun 2, 2025

Walkthrough

This set of changes is primarily focused on code formatting, stylistic consistency, and minor documentation improvements across the codebase. A few properties and method signatures were renamed or reformatted for clarity, and logging statements were adjusted for readability. No functional logic or core behavior was altered except for a change in how the expected response count is tracked in the sender component, and a concurrency improvement in gathering missing energy logs.

Changes

File(s) Change Summary
plugwise_usb/__init__.py, plugwise_usb/nodes/helpers/__init__.py, plugwise_usb/nodes/helpers/counter.py, plugwise_usb/nodes/helpers/pulses.py, plugwise_usb/nodes/helpers/subscription.py, plugwise_usb/nodes/node.py, plugwise_usb/nodes/scan.py, plugwise_usb/nodes/sed.py, plugwise_usb/nodes/stealth.py, plugwise_usb/nodes/switch.py, plugwise_usb/constants.py, plugwise_usb/messages/__init__.py, plugwise_usb/connection/receiver.py, plugwise_usb/connection/queue.py, plugwise_usb/network/__init__.py, plugwise_usb/network/cache.py, plugwise_usb/helpers/cache.py, plugwise_usb/helpers/util.py, plugwise_usb/messages/properties.py, plugwise_usb/messages/requests.py, plugwise_usb/messages/responses.py, plugwise_usb/connection/__init__.py, plugwise_usb/api.py Formatting and stylistic refinements, including blank line additions/removals, reformatting docstrings, method signatures, multi-line expressions, logging calls, and import order. No logic changes except minor signature and annotation spacing updates.
plugwise_usb/connection/manager.py Added detailed docstrings to queue_depth property and correct_received_messages method; changed queue_depth logic to use expected responses instead of processed messages.
plugwise_usb/connection/sender.py Renamed internal counter and property from processed messages to expected responses; increment now occurs only when an ACCEPT response is received and sequence ID is assigned; logging reformatted.
plugwise_usb/nodes/circle.py Changed missing energy log calculation to be dynamic; switched from sequential to concurrent awaiting of energy log updates using asyncio.gather.
pyproject.toml Linting configuration updated: removed/added codes, adjusted comments, and ignored certain docstring rules.
tests/test_usb.py Changed assertions from equality to identity checks for None; removed trailing whitespace.
tests/stick_test_data.py Minor formatting fixes: added spaces after comment markers and colons in dictionary keys; no data or logic changes.

Sequence Diagram(s)

sequenceDiagram
    participant Node as Node
    participant Circle as Circle Node
    participant EnergyLog as Energy Log Updater

    Note over Circle: get_missing_energy_logs (old)
    Circle->>EnergyLog: Await energy_log_update (sequentially)
    loop For each missing address
        EnergyLog-->>Circle: Return result
    end

    Note over Circle: get_missing_energy_logs (new)
    Circle->>EnergyLog: Gather energy_log_update tasks (concurrently)
    EnergyLog-->>Circle: Return all results (as a group)
Loading
sequenceDiagram
    participant Sender as StickSender
    participant Manager as StickConnectionManager
    participant Receiver as StickReceiver

    Note over Sender: write_request_to_port
    Sender->>Manager: Send request
    Manager->>Sender: Receive ACCEPT response
    Sender->>Sender: Increment expected_responses
    Manager->>Receiver: Process messages
    Manager->>Manager: queue_depth = expected_responses - processed_messages
Loading

Possibly related PRs

Suggested reviewers

  • ArnoutD
  • dirixmjm
  • brefra

Poem

In the warren where code lines grow,
The rabbits hop and style they sow.
With blank lines here, and commas there,
They gather logs with utmost care.
Now responses count with clarity,
And linting rules bring parity.
🐇✨ — The code hops on, neat as can be!

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 Pylint (3.3.7)
plugwise_usb/__init__.py
plugwise_usb/connection/__init__.py
plugwise_usb/connection/manager.py
  • 25 others
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Commit Unit Tests in branch feature/arnout/correct_message_count
  • Post Copyable Unit Tests in Comment

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.
    • @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 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.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

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

codecov bot commented Jun 2, 2025

Codecov Report

Attention: Patch coverage is 69.64286% with 17 lines in your changes missing coverage. Please review.

Project coverage is 81.08%. Comparing base (d53077d) to head (f521fa7).

Files with missing lines Patch % Lines
plugwise_usb/nodes/circle.py 33.33% 4 Missing ⚠️
plugwise_usb/__init__.py 62.50% 3 Missing ⚠️
plugwise_usb/messages/responses.py 50.00% 3 Missing ⚠️
plugwise_usb/network/__init__.py 0.00% 3 Missing ⚠️
plugwise_usb/helpers/cache.py 60.00% 2 Missing ⚠️
plugwise_usb/connection/queue.py 0.00% 1 Missing ⚠️
plugwise_usb/nodes/node.py 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #250      +/-   ##
==========================================
- Coverage   81.13%   81.08%   -0.06%     
==========================================
  Files          36       36              
  Lines        7502     7506       +4     
==========================================
- Hits         6087     6086       -1     
- Misses       1415     1420       +5     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 44947ea and 4138888.

📒 Files selected for processing (31)
  • plugwise_usb/__init__.py (7 hunks)
  • plugwise_usb/api.py (0 hunks)
  • plugwise_usb/connection/__init__.py (1 hunks)
  • plugwise_usb/connection/manager.py (1 hunks)
  • plugwise_usb/connection/queue.py (2 hunks)
  • plugwise_usb/connection/receiver.py (1 hunks)
  • plugwise_usb/connection/sender.py (4 hunks)
  • plugwise_usb/constants.py (2 hunks)
  • plugwise_usb/helpers/cache.py (4 hunks)
  • plugwise_usb/helpers/util.py (2 hunks)
  • plugwise_usb/messages/__init__.py (1 hunks)
  • plugwise_usb/messages/properties.py (2 hunks)
  • plugwise_usb/messages/requests.py (2 hunks)
  • plugwise_usb/messages/responses.py (3 hunks)
  • plugwise_usb/network/__init__.py (4 hunks)
  • plugwise_usb/network/cache.py (1 hunks)
  • plugwise_usb/nodes/celsius.py (1 hunks)
  • plugwise_usb/nodes/circle.py (4 hunks)
  • plugwise_usb/nodes/helpers/__init__.py (1 hunks)
  • plugwise_usb/nodes/helpers/counter.py (3 hunks)
  • plugwise_usb/nodes/helpers/pulses.py (3 hunks)
  • plugwise_usb/nodes/helpers/subscription.py (2 hunks)
  • plugwise_usb/nodes/node.py (3 hunks)
  • plugwise_usb/nodes/scan.py (5 hunks)
  • plugwise_usb/nodes/sed.py (1 hunks)
  • plugwise_usb/nodes/sense.py (1 hunks)
  • plugwise_usb/nodes/stealth.py (1 hunks)
  • plugwise_usb/nodes/switch.py (3 hunks)
  • pyproject.toml (2 hunks)
  • tests/stick_test_data.py (1 hunks)
  • tests/test_usb.py (4 hunks)
💤 Files with no reviewable changes (1)
  • plugwise_usb/api.py
🧰 Additional context used
🧬 Code Graph Analysis (14)
plugwise_usb/connection/__init__.py (2)
plugwise_usb/messages/requests.py (17)
  • NodePingRequest (602-632)
  • send (367-376)
  • send (389-398)
  • send (440-442)
  • send (478-487)
  • send (514-523)
  • send (544-555)
  • send (568-577)
  • send (590-599)
  • send (623-632)
  • send (669-678)
  • send (721-730)
  • send (777-786)
  • send (810-819)
  • send (850-859)
  • send (882-891)
  • NodeInfoRequest (894-923)
plugwise_usb/exceptions.py (1)
  • StickError (32-33)
plugwise_usb/nodes/helpers/counter.py (1)
plugwise_usb/nodes/helpers/pulses.py (1)
  • add_log (418-453)
plugwise_usb/connection/queue.py (1)
plugwise_usb/connection/manager.py (1)
  • queue_depth (40-47)
plugwise_usb/nodes/switch.py (2)
plugwise_usb/api.py (1)
  • NodeFeature (39-54)
plugwise_usb/messages/responses.py (1)
  • switch_state (857-859)
plugwise_usb/nodes/helpers/__init__.py (2)
plugwise_usb/nodes/node.py (2)
  • is_loaded (201-203)
  • mac (228-230)
plugwise_usb/exceptions.py (1)
  • NodeError (24-25)
plugwise_usb/network/cache.py (3)
plugwise_usb/api.py (1)
  • mac (270-271)
plugwise_usb/messages/__init__.py (1)
  • mac (53-57)
plugwise_usb/nodes/node.py (1)
  • mac (228-230)
plugwise_usb/helpers/cache.py (2)
plugwise_usb/exceptions.py (1)
  • CacheError (8-9)
tests/test_usb.py (3)
  • makedirs (1540-1545)
  • makedirs (1643-1648)
  • os_path_join (1519-1521)
plugwise_usb/messages/requests.py (1)
plugwise_usb/messages/responses.py (1)
  • PlugwiseResponse (98-215)
plugwise_usb/connection/manager.py (2)
plugwise_usb/connection/sender.py (1)
  • expected_responses (48-50)
plugwise_usb/connection/receiver.py (1)
  • processed_messages (142-144)
plugwise_usb/nodes/scan.py (1)
plugwise_usb/messages/responses.py (1)
  • switch_state (857-859)
plugwise_usb/messages/properties.py (1)
plugwise_usb/exceptions.py (1)
  • MessageError (20-21)
plugwise_usb/network/__init__.py (3)
plugwise_usb/messages/requests.py (1)
  • CirclePlusAllowJoiningRequest (456-487)
plugwise_usb/nodes/node.py (1)
  • mac (228-230)
plugwise_usb/messages/responses.py (1)
  • NodeResponseType (56-72)
tests/test_usb.py (4)
plugwise_usb/__init__.py (1)
  • nodes (95-99)
plugwise_usb/network/__init__.py (1)
  • nodes (138-142)
plugwise_usb/api.py (1)
  • node_info (246-247)
plugwise_usb/nodes/node.py (1)
  • node_info (223-225)
plugwise_usb/messages/responses.py (2)
plugwise_usb/__init__.py (1)
  • hardware (128-130)
plugwise_usb/messages/properties.py (14)
  • value (76-80)
  • value (96-100)
  • value (125-129)
  • value (159-163)
  • value (187-191)
  • value (207-211)
  • value (251-255)
  • value (276-280)
  • value (301-305)
  • value (330-334)
  • value (359-363)
  • value (380-384)
  • value (403-407)
  • value_set (244-248)
🪛 GitHub Check: codecov/patch
plugwise_usb/connection/queue.py

[warning] 150-150: plugwise_usb/connection/queue.py#L150
Added line #L150 was not covered by tests

plugwise_usb/helpers/cache.py

[warning] 77-77: plugwise_usb/helpers/cache.py#L77
Added line #L77 was not covered by tests


[warning] 85-85: plugwise_usb/helpers/cache.py#L85
Added line #L85 was not covered by tests

plugwise_usb/nodes/node.py

[warning] 514-514: plugwise_usb/nodes/node.py#L514
Added line #L514 was not covered by tests

plugwise_usb/nodes/circle.py

[warning] 451-451: plugwise_usb/nodes/circle.py#L451
Added line #L451 was not covered by tests


[warning] 479-479: plugwise_usb/nodes/circle.py#L479
Added line #L479 was not covered by tests

plugwise_usb/network/__init__.py

[warning] 263-263: plugwise_usb/network/init.py#L263
Added line #L263 was not covered by tests


[warning] 561-561: plugwise_usb/network/init.py#L561
Added line #L561 was not covered by tests


[warning] 565-565: plugwise_usb/network/init.py#L565
Added line #L565 was not covered by tests

plugwise_usb/__init__.py

[warning] 175-175: plugwise_usb/init.py#L175
Added line #L175 was not covered by tests


[warning] 250-250: plugwise_usb/init.py#L250
Added line #L250 was not covered by tests


[warning] 331-331: plugwise_usb/init.py#L331
Added line #L331 was not covered by tests

plugwise_usb/messages/responses.py

[warning] 781-781: plugwise_usb/messages/responses.py#L781
Added line #L781 was not covered by tests


[warning] 785-785: plugwise_usb/messages/responses.py#L785
Added line #L785 was not covered by tests


[warning] 789-789: plugwise_usb/messages/responses.py#L789
Added line #L789 was not covered by tests

🪛 Ruff (0.11.9)
plugwise_usb/helpers/cache.py

83-83: No whitespaces allowed surrounding docstring text

(D210)

🔇 Additional comments (65)
plugwise_usb/nodes/celsius.py (1)

5-5: Skip formatting-only change.
The added blank line after the module docstring improves readability but introduces no behavioral or API changes.

plugwise_usb/nodes/stealth.py (1)

2-2: Skip formatting-only change.
Introducing a blank line after the module docstring aligns with the project's style conventions; no functional impact.

plugwise_usb/messages/__init__.py (1)

22-22: Skip formatting-only change.
The blank line added between the Priority enum and PlugwiseMessage class is purely stylistic and does not affect functionality.

plugwise_usb/connection/receiver.py (1)

516-516: Skip formatting-only change.
A trailing blank line was added at the end of the method for consistency with surrounding code style. No behavior was altered.

plugwise_usb/constants.py (1)

35-35: Skip formatting-only change.
Removal of a trailing space on the STICK_TIME_OUT assignment is a whitespace cleanup with no effect on logic.

plugwise_usb/messages/properties.py (2)

12-14: LGTM! Improved readability.

The multi-line formatting of the DESERIALIZE_ERROR constant improves code readability without changing functionality.


397-397: Good simplification.

Removing the unnecessary int() wrapper around 0 is a good simplification since 0 is already an integer literal.

plugwise_usb/helpers/util.py (2)

2-2: Good formatting improvement.

Adding a blank line after the module docstring follows standard Python formatting conventions.


25-25: Consistent type hint formatting.

Adding spaces around the union operator (str | None) improves readability and follows Python typing conventions.

plugwise_usb/network/cache.py (1)

37-39: Improved readability with multi-line formatting.

The multi-line formatting of the string assignment improves code readability without changing functionality.

pyproject.toml (3)

261-261: Fixed typo in comment.

Good correction of the typo in the S319 rule comment from "suspicious-xml-pull-dom-usag" to "suspicious-xml-pull-dom-usage".


280-280: Verify the TRY rule change is intentional.

The change from "TRY302" to "TRY203" modifies which exception handling rule is active. Please confirm this change aligns with the intended linting policy.

  • TRY203: Remove exception handler; error is immediately re-raised
  • TRY302 (if it exists): Would need verification of what this rule covers

288-290: Added docstring rules to ignore list.

Adding D205 (blank line between summary and description) and D401 (imperative mood) to the ignore list is consistent with the project's approach to docstring formatting flexibility.

plugwise_usb/nodes/scan.py (4)

52-52: Define consistent sensitivity values
The addition of SENSITIVITY_MEDIUM_VALUE = 30 aligns with existing sensitivity constants for motion sensor configuration, improving code clarity and maintainability.


176-180: Improve conditional readability
The multi-line formatting of the cached motion validation condition enhances readability without altering its logic.


362-366: Use actual switch state in update
Switching to response.switch_state instead of hard-coded True ensures the motion state update accurately reflects the incoming response.


482-484: Refactor sensitivity mapping formatting
Breaking the sensitivity_map.get(...) call into multiple lines improves readability while preserving behavior.

plugwise_usb/nodes/sense.py (1)

119-121: This removes an extraneous blank line before the return statement, which is purely formatting and has no impact on functionality.

plugwise_usb/connection/__init__.py (2)

212-213: Consolidate NodePingRequest instantiation
The single-line constructor call for NodePingRequest enhances readability by eliminating the previous multi-line invocation without changing behavior.


220-220: Consolidate NodeInfoRequest instantiation
Similarly, the NodeInfoRequest instantiation is now on one line for consistency with other request calls.

plugwise_usb/nodes/helpers/__init__.py (1)

28-34: Enhance decorator readability
Adding blank lines around the inner decorated function improves visual separation in the raise_not_loaded decorator without modifying its functionality.

plugwise_usb/nodes/sed.py (1)

240-242: The removal of extra blank lines around the early return False makes the code more compact; this is strictly a formatting tweak.

tests/stick_test_data.py (1)

63-63: LGTM: Minor formatting improvements

Good formatting fixes - adding proper spacing after comment markers and colons improves code readability and follows Python style conventions.

Also applies to: 67-67

plugwise_usb/nodes/helpers/subscription.py (2)

23-29: Excellent documentation improvement

The detailed docstring clearly explains the purpose and structure of the _feature_update_subscribers dictionary, making the code more maintainable and easier to understand.


66-68: Good formatting improvement

Converting the method call to multi-line format enhances readability while maintaining the same functionality.

plugwise_usb/nodes/switch.py (3)

56-61: Improved readability with multi-line formatting

Expanding the NodeFeature tuple to multiple lines makes the code easier to read and maintain, especially when reviewing which features are being set up.


97-97: Consistent comment formatting

Good spacing standardization for the region end marker.


107-107: Good practice: Added trailing comma

The trailing comma after the second coroutine argument follows Python best practices and makes future additions to the gather call cleaner.

plugwise_usb/nodes/helpers/pulses.py (2)

10-10: Import ordering improvement

Reordering the imports for better organization while maintaining the same functionality.


176-176: Good practice: Added trailing commas

Adding trailing commas in the logging calls follows Python best practices and makes future parameter additions cleaner.

Also applies to: 378-378

plugwise_usb/nodes/helpers/counter.py (3)

83-88: Formatting-only change: add_pulse_log conditional reflow
The refactored multi-line conditional improves readability without altering functionality.


166-168: Formatting-only change: multi-line PRODUCTION_HOUR.update call
Splitting the update invocation across lines is purely stylistic; logic remains intact.


303-305: Formatting-only change: multi-line last_reset.replace call
The re-indentation of the replace call enhances clarity but doesn’t affect behavior.

tests/test_usb.py (3)

593-593: Assertion updated to use is None
Using is None to check model_type adheres to PEP 8 and is correct.


2547-2547: Assertion updated to use is None
Consistent Pythonic check for None in node discovery test.


2612-2612: Assertion updated to use is None
Correctly verifies model_type remains None for the Switch node.

plugwise_usb/connection/queue.py (2)

105-106: LGTM: Formatting improvement

Good formatting change that improves readability by splitting the logging call into multiple lines with a trailing comma for consistency.


150-152: LGTM: Formatting improvement

Consistent formatting change that matches the multi-line logging style used elsewhere in the codebase.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 150-150: plugwise_usb/connection/queue.py#L150
Added line #L150 was not covered by tests

plugwise_usb/messages/requests.py (2)

315-317: LGTM: Method signature formatting improvement

Good formatting change that improves readability by splitting the method signature into multiple lines.


1269-1269: LGTM: Docstring cleanup

Good cleanup of trailing whitespace in the docstring.

plugwise_usb/nodes/circle.py (2)

5-5: LGTM: Import additions for new functionality

The new imports for gather and floor support the functional improvements in this file.

Also applies to: 11-11


512-512: LGTM: Formatting improvement

Good consolidation of the debug log call from multi-line to single-line for better readability.

plugwise_usb/network/__init__.py (4)

19-19: LGTM: Import reordering

The import reordering improves alphabetical consistency.


263-265: LGTM: Improved readability with multi-line formatting

The multi-line formatting of the debug log statement improves readability and aligns with the broader code style improvements in this PR.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 263-263: plugwise_usb/network/init.py#L263
Added line #L263 was not covered by tests


537-538: LGTM: Consistent tuple formatting

The multi-line formatting of the tuple improves readability and maintains consistency.


561-567: LGTM: Multi-line formatting improvements

Both the ValueError message and debug log statement benefit from multi-line formatting for better readability.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 561-561: plugwise_usb/network/init.py#L561
Added line #L561 was not covered by tests


[warning] 565-565: plugwise_usb/network/init.py#L565
Added line #L565 was not covered by tests

plugwise_usb/helpers/cache.py (2)

56-58: LGTM: Consistent multi-line formatting for error messages

The multi-line formatting of CacheError messages improves readability and maintains consistency across the codebase.

Also applies to: 77-79, 85-87, 126-128


159-159: LGTM: Slice notation formatting

The space addition in the slice notation follows a consistent formatting style, though it doesn't affect functionality.

plugwise_usb/messages/responses.py (3)

654-654: LGTM: Improved debug output with hardware substring

Displaying a substring of the hardware identifier ([4:10]) in the __repr__ method provides more focused and readable debug output while maintaining essential information.


781-793: LGTM: Consistent indentation formatting

The indentation adjustments improve code consistency and readability without affecting functionality.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 781-781: plugwise_usb/messages/responses.py#L781
Added line #L781 was not covered by tests


[warning] 785-785: plugwise_usb/messages/responses.py#L785
Added line #L785 was not covered by tests


[warning] 789-789: plugwise_usb/messages/responses.py#L789
Added line #L789 was not covered by tests


859-859: LGTM: Simplified expression

Removing unnecessary parentheses simplifies the boolean expression while maintaining the same logic.

plugwise_usb/nodes/node.py (3)

52-52: LGTM: Improved visual separation

The blank line addition after the constant improves visual separation and code readability.


339-341: LGTM: Conditional expression formatting

The multi-line conditional expression maintains readability while following consistent formatting patterns.


514-516: LGTM: List formatting consistency

The multi-line formatting of the model_info assignment improves readability and aligns with the broader formatting improvements in this PR.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 514-514: plugwise_usb/nodes/node.py#L514
Added line #L514 was not covered by tests

plugwise_usb/connection/sender.py (3)

41-41: LGTM: Improved semantic clarity with rename

The rename from _processed_msgs/processed_messages to _expected_responses/expected_responses better reflects the actual purpose of this counter - tracking expected responses rather than processed messages.

Also applies to: 48-50


82-84: LGTM: Multi-line formatting for debug logs

The multi-line formatting of debug log statements improves readability and aligns with the consistent formatting improvements throughout this PR.

Also applies to: 111-115, 130-132


124-124:

✅ Verification successful

Verify the logic change for counter increment

The counter increment has been moved to only occur when a StickResponse of type ACCEPT is received. This changes the counting logic from incrementing on every request to only incrementing on accepted requests.

Verify this logic change aligns with the queue depth calculation in plugwise_usb/connection/manager.py:


🏁 Script executed:

#!/bin/bash
# Description: Verify the usage of expected_responses in queue depth calculation

# Search for usage of expected_responses or queue_depth calculation
rg -A 5 -B 5 "expected_responses|queue_depth"

# Check manager.py specifically for queue depth calculation
ast-grep --pattern 'def queue_depth($_) {
  $$$
}'

Length of output: 4902


Confirmed: counter increment on ACCEPT aligns with queue depth calculation

The queue_depth property in plugwise_usb/connection/manager.py is defined as:

@property
def queue_depth(self) -> int:
    return self._sender.expected_responses - self._receiver.processed_messages

Since expected_responses is now only incremented when a StickResponse of type ACCEPT is received, the queue depth correctly represents the number of accepted requests still awaiting their corresponding node responses. No changes are needed.

plugwise_usb/__init__.py (6)

22-24: Improved readability with single-line string formatting

The reformatting of the multi-line string concatenation to a single expression improves readability and follows modern Python conventions.


47-49: Consistent string formatting improvement

Good improvement in code readability by consolidating the multi-line string concatenation into a single expression.


174-175: Note: Enhanced error message formatting lacks test coverage

The reformatted error condition and message improve readability, but static analysis indicates this line lacks test coverage. This appears to be a pre-existing gap rather than introduced by these changes.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 175-175: plugwise_usb/init.py#L175
Added line #L175 was not covered by tests


250-252: Improved exception formatting with test coverage gap

The single-line SubscriptionError creation is more readable than the previous multi-line format. However, static analysis shows this line lacks test coverage.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 250-250: plugwise_usb/init.py#L250
Added line #L250 was not covered by tests


283-285: Consistent string concatenation improvements

The conversion of multi-line string concatenations to single expressions enhances code readability and maintainability across the connection error handling.

Also applies to: 292-295


331-331: Error message formatting improvement with test coverage concern

The single-line error message is cleaner and more readable. Static analysis indicates this line lacks test coverage, which may be worth addressing in future test improvements.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 331-331: plugwise_usb/init.py#L331
Added line #L331 was not covered by tests

plugwise_usb/connection/manager.py (2)

41-47: Improved queue depth calculation logic and documentation

The updated queue_depth property now correctly calculates the number of expected responses that haven't been processed yet, which is a more accurate representation of the actual queue state. The enhanced docstring clearly explains the purpose and return value.

This change aligns with the PR objective of correcting message count logic to apply only to accepted messages.


49-59: Enhanced method documentation

The detailed docstring for correct_received_messages greatly improves code maintainability by clearly explaining the method's purpose, parameters, and return value.

@@ -474,8 +476,7 @@
create_task(self.energy_log_update(address))
for address in missing_addresses
]
for task in tasks:
await task
await gather(*tasks, return_exceptions=True)
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Excellent improvement: Concurrent task execution

Changing from sequential await to gather(*tasks, return_exceptions=True) significantly improves performance by executing all energy log update tasks concurrently. The return_exceptions=True parameter ensures that failures in individual tasks don't break the entire operation.

However, this change lacks test coverage according to static analysis. Please ensure this concurrent execution path is properly tested:


🏁 Script executed:

#!/bin/bash
# Description: Search for tests covering the concurrent energy log update logic
# Expected: Find test coverage for the gather-based task execution

# Search for tests that might cover the missing energy logs functionality
rg -A 15 -B 5 "missing.*energy.*log" --type py

# Look for tests that use or mock create_task or gather
rg -A 10 -B 5 "(create_task|gather).*energy" --type py

# Check if there are integration tests for energy log collection
fd test_.*\.py --exec rg -l "(energy.*log|log.*energy)" {} \;

Length of output: 10118


Excellent improvement: Concurrent task execution

Changing from sequential await to gather(*tasks, return_exceptions=True) significantly improves performance by executing all energy‐log update tasks concurrently. The return_exceptions=True parameter ensures that failures in individual tasks don’t break the entire operation.

However, our search shows existing tests in tests/test_usb.py mock get_missing_energy_logs, but there are currently no tests explicitly covering the concurrent execution path via gather. Please add unit tests to exercise the branch where more than one log address is missing. For example:

• Simulate a PlugwiseCircle instance with log_addresses_missing = [addr1, addr2, …]
• Monkeypatch energy_log_update to record calls and to raise an exception for at least one address
• Invoke await circle.get_missing_energy_logs() and assert:
energy_log_update was scheduled via create_task for each missing address
gather awaited all tasks, capturing exceptions rather than failing fast
– Side effects (cache save, power update) occur as expected after concurrent execution

Consider adding these tests in a new file (e.g. tests/test_circle_concurrency.py) or expanding tests/test_usb.py.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 479-479: plugwise_usb/nodes/circle.py#L479
Added line #L479 was not covered by tests

🤖 Prompt for AI Agents
In plugwise_usb/nodes/circle.py at line 479, the change to use gather for
concurrent execution of energy log update tasks lacks test coverage. Add unit
tests that simulate a PlugwiseCircle instance with multiple missing log
addresses, monkeypatch energy_log_update to track calls and raise exceptions for
some addresses, then call get_missing_energy_logs and assert that create_task
schedules all updates, gather awaits all tasks capturing exceptions without
failing fast, and that subsequent side effects like cache saving and power
updates occur correctly. Place these tests in a new file like
tests/test_circle_concurrency.py or extend tests/test_usb.py.

return os_path_join(os_path_expand_user("~"), CACHE_DIR)

async def write_cache(self, data: dict[str, str], rewrite: bool = False) -> None:
""""Save information to cache file."""
""" "Save information to cache file."""
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix docstring formatting issue

The static analysis tool correctly identifies a whitespace issue in the docstring.

Apply this diff to fix the docstring formatting:

-    """ "Save information to cache file."""
+    """Save information to cache file."""
📝 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
""" "Save information to cache file."""
"""Save information to cache file."""
🧰 Tools
🪛 Ruff (0.11.9)

83-83: No whitespaces allowed surrounding docstring text

(D210)

🤖 Prompt for AI Agents
In plugwise_usb/helpers/cache.py at line 83, the docstring has an extra leading
space before the opening quotes. Remove the extra space so the docstring starts
immediately with triple quotes followed by the text, ensuring proper formatting
and compliance with docstring standards.

@bouwew
Copy link
Contributor

bouwew commented Jun 2, 2025

Please see my feedback on going back to the gather() construct on Discord.

@bouwew bouwew force-pushed the feature/arnout/correct_message_count branch 3 times, most recently from aff5624 to e848f5b Compare June 9, 2025 13:18
@bouwew bouwew force-pushed the feature/arnout/correct_message_count branch 2 times, most recently from 5983104 to 86f2e8d Compare June 10, 2025 18:19
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 comments (1)
plugwise_usb/helpers/cache.py (1)

150-159: ⚠️ Potential issue

Invalid-line handling prematurely aborts parsing

Breaking out of the loop stops processing any subsequent valid lines.
Switch to continue so only the faulty line is skipped, and drop superfluous str().

-                    data,
-                    str(self._cache_file),
+                    data,
+                    self._cache_file,
                 )
-                break
+                continue
             current_data[data[:index_separator]] = data[index_separator + 1 :]
♻️ Duplicate comments (1)
plugwise_usb/helpers/cache.py (1)

83-83: Remove stray space/quote in docstring

Same issue flagged previously; docstring still violates D210.

-        """ "Save information to cache file."""
+        """Save information to cache file."""
🧰 Tools
🪛 Ruff (0.11.9)

83-83: No whitespaces allowed surrounding docstring text

(D210)

🧹 Nitpick comments (4)
plugwise_usb/helpers/cache.py (4)

56-58: Grammar correction in CacheError message

does not existsdoes not exist.

-                raise CacheError(
-                    f"Unable to initialize caching. Cache folder '{self._root_dir}' does not exists."
-                )
+                raise CacheError(
+                    f"Unable to initialize caching. Cache folder '{self._root_dir}' does not exist."
+                )

120-121: Misleading line-count & redundant str() in debug log

len(data) only reflects the new keys, not the total lines written.
Also, logging will stringify the value – the explicit str() call is unnecessary.

-                "Saved %s lines to cache file %s", str(len(data)), self._cache_file
+                "Saved %s lines to cache file %s",
+                len(data_to_write),
+                self._cache_file,

126-128: Wrong context in error text

The method is read_cache, but the message says save.

-                f"Unable to save cache. Initialize cache file '{self._file_name}' first."
+                f"Unable to read cache. Initialize cache file '{self._file_name}' first."

132-134: Minor grammar fix in debug message

does not existsdoes not exist.

-                "Cache file '%s' does not exists, return empty cache data",
+                "Cache file '%s' does not exist, returning empty cache data",
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5983104 and 86f2e8d.

📒 Files selected for processing (30)
  • plugwise_usb/__init__.py (6 hunks)
  • plugwise_usb/api.py (0 hunks)
  • plugwise_usb/connection/__init__.py (1 hunks)
  • plugwise_usb/connection/manager.py (1 hunks)
  • plugwise_usb/connection/queue.py (2 hunks)
  • plugwise_usb/connection/receiver.py (1 hunks)
  • plugwise_usb/connection/sender.py (4 hunks)
  • plugwise_usb/constants.py (1 hunks)
  • plugwise_usb/helpers/cache.py (4 hunks)
  • plugwise_usb/helpers/util.py (2 hunks)
  • plugwise_usb/messages/__init__.py (1 hunks)
  • plugwise_usb/messages/properties.py (2 hunks)
  • plugwise_usb/messages/requests.py (2 hunks)
  • plugwise_usb/messages/responses.py (3 hunks)
  • plugwise_usb/network/__init__.py (3 hunks)
  • plugwise_usb/network/cache.py (1 hunks)
  • plugwise_usb/nodes/celsius.py (1 hunks)
  • plugwise_usb/nodes/circle.py (4 hunks)
  • plugwise_usb/nodes/helpers/__init__.py (1 hunks)
  • plugwise_usb/nodes/helpers/counter.py (3 hunks)
  • plugwise_usb/nodes/helpers/pulses.py (3 hunks)
  • plugwise_usb/nodes/helpers/subscription.py (2 hunks)
  • plugwise_usb/nodes/node.py (3 hunks)
  • plugwise_usb/nodes/scan.py (5 hunks)
  • plugwise_usb/nodes/sed.py (1 hunks)
  • plugwise_usb/nodes/stealth.py (1 hunks)
  • plugwise_usb/nodes/switch.py (3 hunks)
  • pyproject.toml (2 hunks)
  • tests/stick_test_data.py (1 hunks)
  • tests/test_usb.py (4 hunks)
💤 Files with no reviewable changes (1)
  • plugwise_usb/api.py
✅ Files skipped from review due to trivial changes (3)
  • tests/stick_test_data.py
  • plugwise_usb/nodes/helpers/pulses.py
  • tests/test_usb.py
🚧 Files skipped from review as they are similar to previous changes (25)
  • plugwise_usb/messages/init.py
  • plugwise_usb/constants.py
  • plugwise_usb/connection/init.py
  • plugwise_usb/connection/receiver.py
  • plugwise_usb/nodes/celsius.py
  • plugwise_usb/nodes/helpers/subscription.py
  • plugwise_usb/nodes/stealth.py
  • plugwise_usb/init.py
  • plugwise_usb/nodes/switch.py
  • plugwise_usb/nodes/helpers/init.py
  • plugwise_usb/connection/queue.py
  • plugwise_usb/messages/requests.py
  • plugwise_usb/network/init.py
  • plugwise_usb/nodes/helpers/counter.py
  • plugwise_usb/helpers/util.py
  • plugwise_usb/nodes/node.py
  • plugwise_usb/network/cache.py
  • plugwise_usb/nodes/sed.py
  • plugwise_usb/connection/sender.py
  • pyproject.toml
  • plugwise_usb/connection/manager.py
  • plugwise_usb/messages/responses.py
  • plugwise_usb/messages/properties.py
  • plugwise_usb/nodes/scan.py
  • plugwise_usb/nodes/circle.py
🧰 Additional context used
🧬 Code Graph Analysis (1)
plugwise_usb/helpers/cache.py (2)
plugwise_usb/exceptions.py (1)
  • CacheError (8-9)
tests/test_usb.py (3)
  • makedirs (1556-1561)
  • makedirs (1659-1664)
  • os_path_join (1535-1537)
🪛 Ruff (0.11.9)
plugwise_usb/helpers/cache.py

83-83: No whitespaces allowed surrounding docstring text

(D210)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Check commit

@bouwew bouwew force-pushed the feature/arnout/correct_message_count branch from 86f2e8d to f521fa7 Compare June 13, 2025 18:07
Copy link

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

♻️ Duplicate comments (1)
plugwise_usb/helpers/cache.py (1)

83-83: Fix docstring formatting – duplicate of earlier feedback

Extra leading space breaks PEP-257 style and Ruff’s D210 rule.

-        """ "Save information to cache file."""
+        """Save information to cache file."""
🧰 Tools
🪛 Ruff (0.11.9)

83-83: No whitespaces allowed surrounding docstring text

(D210)

🧹 Nitpick comments (5)
plugwise_usb/helpers/cache.py (5)

56-58: Grammar fix in error message

does not existsdoes not exist.
Minor but worth correcting for professional log output.

-                    f"Unable to initialize caching. Cache folder '{self._root_dir}' does not exists."
+                    f"Unable to initialize caching. Cache folder '{self._root_dir}' does not exist."

77-79: Grammar fix in error message

Same typo here.

-                "Unable to detect writable cache folder based on 'APPDATA' environment variable."
+                "Unable to detect a writable cache folder based on the 'APPDATA' environment variable."

118-121: Incorrect line count & unnecessary str() conversion in debug log

len(data) only counts the new keys, not the total lines written, and logging handles type conversion.

-                "Saved %s lines to cache file %s", str(len(data)), self._cache_file
+                "Saved %s lines to cache file %s", len(data_to_write), self._cache_file

126-128: Error message references the wrong action

This is in read_cache, not save_cache.

-                f"Unable to save cache. Initialize cache file '{self._file_name}' first."
+                f"Unable to read cache. Initialize cache file '{self._file_name}' first."

132-134: Minor grammar tweak in log message

does not existsdoes not exist.

-                "Cache file '%s' does not exists, return empty cache data",
+                "Cache file '%s' does not exist, returning empty cache data",
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 86f2e8d and f521fa7.

📒 Files selected for processing (30)
  • plugwise_usb/__init__.py (6 hunks)
  • plugwise_usb/api.py (0 hunks)
  • plugwise_usb/connection/__init__.py (1 hunks)
  • plugwise_usb/connection/manager.py (1 hunks)
  • plugwise_usb/connection/queue.py (2 hunks)
  • plugwise_usb/connection/receiver.py (1 hunks)
  • plugwise_usb/connection/sender.py (4 hunks)
  • plugwise_usb/constants.py (1 hunks)
  • plugwise_usb/helpers/cache.py (4 hunks)
  • plugwise_usb/helpers/util.py (2 hunks)
  • plugwise_usb/messages/__init__.py (1 hunks)
  • plugwise_usb/messages/properties.py (2 hunks)
  • plugwise_usb/messages/requests.py (2 hunks)
  • plugwise_usb/messages/responses.py (3 hunks)
  • plugwise_usb/network/__init__.py (2 hunks)
  • plugwise_usb/network/cache.py (1 hunks)
  • plugwise_usb/nodes/celsius.py (1 hunks)
  • plugwise_usb/nodes/circle.py (4 hunks)
  • plugwise_usb/nodes/helpers/__init__.py (1 hunks)
  • plugwise_usb/nodes/helpers/counter.py (3 hunks)
  • plugwise_usb/nodes/helpers/pulses.py (3 hunks)
  • plugwise_usb/nodes/helpers/subscription.py (2 hunks)
  • plugwise_usb/nodes/node.py (3 hunks)
  • plugwise_usb/nodes/scan.py (5 hunks)
  • plugwise_usb/nodes/sed.py (1 hunks)
  • plugwise_usb/nodes/stealth.py (1 hunks)
  • plugwise_usb/nodes/switch.py (3 hunks)
  • pyproject.toml (2 hunks)
  • tests/stick_test_data.py (1 hunks)
  • tests/test_usb.py (4 hunks)
💤 Files with no reviewable changes (1)
  • plugwise_usb/api.py
✅ Files skipped from review due to trivial changes (2)
  • plugwise_usb/nodes/helpers/counter.py
  • plugwise_usb/network/cache.py
🚧 Files skipped from review as they are similar to previous changes (26)
  • plugwise_usb/nodes/celsius.py
  • plugwise_usb/nodes/stealth.py
  • plugwise_usb/messages/init.py
  • plugwise_usb/connection/init.py
  • plugwise_usb/constants.py
  • plugwise_usb/connection/receiver.py
  • plugwise_usb/nodes/helpers/init.py
  • plugwise_usb/nodes/switch.py
  • plugwise_usb/nodes/sed.py
  • plugwise_usb/init.py
  • plugwise_usb/nodes/helpers/subscription.py
  • plugwise_usb/helpers/util.py
  • plugwise_usb/connection/queue.py
  • plugwise_usb/messages/requests.py
  • plugwise_usb/nodes/circle.py
  • plugwise_usb/connection/sender.py
  • plugwise_usb/messages/properties.py
  • tests/stick_test_data.py
  • plugwise_usb/connection/manager.py
  • plugwise_usb/nodes/scan.py
  • plugwise_usb/messages/responses.py
  • plugwise_usb/nodes/helpers/pulses.py
  • pyproject.toml
  • tests/test_usb.py
  • plugwise_usb/network/init.py
  • plugwise_usb/nodes/node.py
🧰 Additional context used
🧬 Code Graph Analysis (1)
plugwise_usb/helpers/cache.py (2)
plugwise_usb/exceptions.py (1)
  • CacheError (8-9)
tests/test_usb.py (3)
  • makedirs (1551-1556)
  • makedirs (1654-1659)
  • os_path_join (1530-1532)
🪛 Ruff (0.11.9)
plugwise_usb/helpers/cache.py

83-83: No whitespaces allowed surrounding docstring text

(D210)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Check commit
  • GitHub Check: Check commit

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.

2 participants