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

Attempt at multi-bike support #82

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

Attempt at multi-bike support #82

wants to merge 9 commits into from

Conversation

CoMPaTech
Copy link
Owner

@CoMPaTech CoMPaTech commented Feb 3, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a reset button for trip data in the BETA phase.
    • Added support for multiple bikes.
    • New Stromer Button component for Home Assistant.
  • Enhancements

    • Improved bike selection process during configuration.
    • Updated translations for new button functionality in English and Dutch.
  • Version Updates

    • Incremented version to 0.4.0a2.

@CoMPaTech CoMPaTech self-assigned this Feb 3, 2024
@CoMPaTech CoMPaTech added the enhancement New feature or request label Feb 3, 2024
Copy link

sonarcloud bot commented Feb 4, 2024

Quality Gate Passed Quality Gate passed

The SonarCloud Quality Gate passed, but some issues were introduced.

5 New issues
0 Security Hotspots
No data about Coverage
0.0% Duplication on New Code

See analysis details on SonarCloud

@CoMPaTech CoMPaTech changed the title Attempt for multi-bike support Attempt at multi-bike support Mar 15, 2024
@CoMPaTech
Copy link
Owner Author

@coderabbitai review

Copy link

coderabbitai bot commented May 27, 2024

Actions Performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link

coderabbitai bot commented May 27, 2024

Walkthrough

The update introduces multibike support and a new button feature for resetting trip data in the Stromer Home Assistant integration. It enhances the configuration flow, adds new translations, and updates the core logic to support these functionalities. The version has been incremented, and debug logging has been improved.

Changes

File(s) Change Summary
CHANGELOG.md, README.md Documented new features and changes including multibike support and trip data reset button.
custom_components/stromer/__init__.py Added Platform.BUTTON and initialized bike-related attributes from entry.data.
custom_components/stromer/button.py Introduced the Stromer Button component, allowing setup and handling of button presses for trip data reset.
custom_components/stromer/config_flow.py Enhanced configuration flow with bike selection and validation logic.
custom_components/stromer/const.py Added a new constant BIKE_DETAILS.
custom_components/stromer/manifest.json Updated version to 0.4.0a2.
custom_components/stromer/strings.json, translations/en.json, translations/nl.json Added translations for the new trip data reset button.
custom_components/stromer/stromer.py Incremented version, added methods for bike detection and trip data reset, and updated API call logic.

Sequence Diagram(s) (Beta)

sequenceDiagram
    participant User
    participant HomeAssistant
    participant StromerIntegration
    participant StromerAPI

    User->>HomeAssistant: Configure Stromer Integration
    HomeAssistant->>StromerIntegration: async_step_user
    StromerIntegration->>StromerAPI: Validate Input
    StromerAPI-->>StromerIntegration: Return Bike Data
    StromerIntegration->>User: Select Bike
    User->>StromerIntegration: Select Bike
    StromerIntegration->>HomeAssistant: Create Entry

    User->>HomeAssistant: Press Reset Trip Data Button
    HomeAssistant->>StromerIntegration: async_press
    StromerIntegration->>StromerAPI: Reset Trip Data
    StromerAPI-->>StromerIntegration: Confirm Reset
    StromerIntegration-->>HomeAssistant: Update State

In fields of code, where logic blooms,
New buttons press, and bikes resume.
With multibike support, we now embrace,
A smoother ride, a swifter pace.
Reset your trips, start anew,
Stromer’s here, for me and you. 🚴‍♂️🐇


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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.

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 as 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 full the 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 help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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

@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

Outside diff range and nitpick comments (1)
custom_components/stromer/stromer.py (1)

Line range hint 225-239: The method stromer_call_api is well-implemented for fetching data from the API. Consider using format specifiers for string formatting for consistency and readability.

-        log = "API call status: %s" % res.status
-        log = "API call returns: %s" % ret
+        log = f"API call status: {res.status}"
+        log = f"API call returns: {ret}"
Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between ead07af and e348bd8.
Files selected for processing (11)
  • CHANGELOG.md (1 hunks)
  • README.md (1 hunks)
  • custom_components/stromer/init.py (2 hunks)
  • custom_components/stromer/button.py (1 hunks)
  • custom_components/stromer/config_flow.py (4 hunks)
  • custom_components/stromer/const.py (1 hunks)
  • custom_components/stromer/manifest.json (1 hunks)
  • custom_components/stromer/strings.json (1 hunks)
  • custom_components/stromer/stromer.py (6 hunks)
  • custom_components/stromer/translations/en.json (1 hunks)
  • custom_components/stromer/translations/nl.json (1 hunks)
Files skipped from review due to trivial changes (4)
  • CHANGELOG.md
  • custom_components/stromer/const.py
  • custom_components/stromer/manifest.json
  • custom_components/stromer/translations/nl.json
Additional Context Used
Ruff (9)
custom_components/stromer/stromer.py (9)

129-129: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling


189-189: Use format specifiers instead of percent format


191-191: Use format specifiers instead of percent format


205-205: Use format specifiers instead of percent format


207-207: Use format specifiers instead of percent format


220-220: Use format specifiers instead of percent format


222-222: Use format specifiers instead of percent format


234-234: Use format specifiers instead of percent format


236-236: Use format specifiers instead of percent format

Additional comments not posted (13)
custom_components/stromer/strings.json (1)

26-30: The addition of the "Reset trip data" button entity is correctly implemented and aligns with the new feature requirements.

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

26-30: The English translation for the "Reset trip data" button is correctly implemented.

custom_components/stromer/button.py (4)

4-8: The imports are well-organized and correctly scoped for the functionality required in this file.

Also applies to: 13-15


17-24: The BUTTONS tuple is correctly defined with appropriate attributes for the "Reset trip data" button.


26-37: The async_setup_entry function is properly updated to handle the dynamic addition of button entities based on the bike data.


40-67: The StromerButton class is well-implemented with clear and concise logic for handling button presses and entity setup.

custom_components/stromer/__init__.py (2)

19-19: The addition of Platform.BUTTON to the PLATFORMS list is appropriate for supporting the new button functionality.


39-41: The handling of bike-specific data in the async_setup_entry function is correctly implemented, enhancing the configuration capabilities for individual bikes.

custom_components/stromer/config_flow.py (2)

Line range hint 27-42: The validate_input function is correctly updated to handle bike data validation, crucial for the multi-bike support feature.


50-79: The async_step_bike method is well-implemented, providing a clear and user-friendly flow for bike selection during configuration.

README.md (1)

38-39: The README is updated to include information about the new "Reset trip data" button, providing clear guidance to users on the new feature.

custom_components/stromer/stromer.py (2)

3-3: Updated version number to "0.2.0" aligns with the PR's intent to introduce significant functionality.


39-39: Initialization of full_data, bike_id, bike_name, and bike_model supports the new multi-bike functionality.

custom_components/stromer/stromer.py Outdated Show resolved Hide resolved
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link

sonarcloud bot commented May 27, 2024

Quality Gate Passed Quality Gate passed

Issues
5 New issues
0 Accepted issues

Measures
0 Security Hotspots
No data about Coverage
0.0% Duplication on New Code

See analysis details on SonarCloud

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

Commits Files that changed from the base of the PR and between e348bd8 and f205025.
Files selected for processing (1)
  • custom_components/stromer/stromer.py (6 hunks)
Additional Context Used
Ruff (9)
custom_components/stromer/stromer.py (9)

129-129: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling


189-189: Use format specifiers instead of percent format


191-191: Use format specifiers instead of percent format


205-205: Use format specifiers instead of percent format


207-207: Use format specifiers instead of percent format


220-220: Use format specifiers instead of percent format


222-222: Use format specifiers instead of percent format


233-233: Use format specifiers instead of percent format


235-235: Use format specifiers instead of percent format

Additional comments not posted (3)
custom_components/stromer/stromer.py (3)

3-3: Updated module version to "0.2.0" aligns with the PR's objective to introduce significant new features.


39-39: Initialization of new attributes for handling bike data is a good practice for managing state within the class.


237-238: The conditional return based on the full flag is a good practice for API data fetching, allowing for flexible data retrieval.

Comment on lines +66 to +76
async def stromer_detect(self) -> dict:
"""Get full data (to determine bike(s))."""
try:
await self.stromer_update()
self.full_data = await self.stromer_call_api(endpoint="bike/", full=True)
except Exception as e:
log = f"Stromer unable to update: {e}"
log = f"Stromer unable to fetch full data: {e}"
LOGGER.error(log)

LOGGER.debug("Stromer connected!")

return self.status
log = f"Stromer full_data : {self.full_data}"
LOGGER.debug(log)
return self.full_data
Copy link

Choose a reason for hiding this comment

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

Ensure proper error handling in stromer_detect by using raise ... from e to maintain the traceback.

-            log = f"Stromer unable to fetch full data: {e}"
-            LOGGER.error(log)
+            LOGGER.error(f"Stromer unable to fetch full data: {e}")
+            raise ApiError from e

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.

Suggested change
async def stromer_detect(self) -> dict:
"""Get full data (to determine bike(s))."""
try:
await self.stromer_update()
self.full_data = await self.stromer_call_api(endpoint="bike/", full=True)
except Exception as e:
log = f"Stromer unable to update: {e}"
log = f"Stromer unable to fetch full data: {e}"
LOGGER.error(log)
LOGGER.debug("Stromer connected!")
return self.status
log = f"Stromer full_data : {self.full_data}"
LOGGER.debug(log)
return self.full_data
async def stromer_detect(self) -> dict:
"""Get full data (to determine bike(s))."""
try:
self.full_data = await self.stromer_call_api(endpoint="bike/", full=True)
except Exception as e:
LOGGER.error(f"Stromer unable to fetch full data: {e}")
raise ApiError from e
log = f"Stromer full_data : {self.full_data}"
LOGGER.debug(log)
return self.full_data

Comment on lines +55 to +64
# try:
# await self.stromer_update()
# except Exception as e:
# log = f"Stromer unable to update: {e}"
# LOGGER.error(log)

LOGGER.debug("Stromer connected!")

# return self.status
return True
Copy link

Choose a reason for hiding this comment

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

The commented-out code should be removed if it's no longer needed, to keep the codebase clean and maintainable.

- #        try:
- #            await self.stromer_update()
- #        except Exception as e:
- #            log = f"Stromer unable to update: {e}"
- #            LOGGER.error(log)
- #        LOGGER.debug("Stromer connected!")
- #        return self.status
- #        return True

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.

Suggested change
# try:
# await self.stromer_update()
# except Exception as e:
# log = f"Stromer unable to update: {e}"
# LOGGER.error(log)
LOGGER.debug("Stromer connected!")
# return self.status
return True
LOGGER.debug("Stromer connected!")
return True

Comment on lines +210 to +224
async def stromer_reset_trip_data(self) -> None:
"""Reset the trip data through the API."""
endpoint = f"bike/id/{self.bike_id}/trip_data/"
url = f"{self.base_url}/rapi/mobile/v4.1/{endpoint}"
if self._api_version == "v3":
url = f"{self.base_url}/rapi/mobile/v2/{endpoint}"

headers = {"Authorization": f"Bearer {self._token}"}
res = await self._websession.delete(url, headers=headers)
ret = json.loads(await res.text())
log = "API call trip data reset status: %s" % res.status
LOGGER.debug(log)
log = "API call trip data reset returns: %s" % ret
LOGGER.debug(log)
async def stromer_call_api(self, endpoint: str, full=False) -> Any:
Copy link

Choose a reason for hiding this comment

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

Method stromer_reset_trip_data correctly implements the API call to reset trip data. However, consider using format specifiers for logging.

-        log = "API call trip data reset status: %s" % res.status
-        LOGGER.debug(log)
-        log = "API call trip data reset returns: %s" % ret
+        log = f"API call trip data reset status: {res.status}"
+        LOGGER.debug(log)
+        log = f"API call trip data reset returns: {ret}"

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.

Suggested change
async def stromer_reset_trip_data(self) -> None:
"""Reset the trip data through the API."""
endpoint = f"bike/id/{self.bike_id}/trip_data/"
url = f"{self.base_url}/rapi/mobile/v4.1/{endpoint}"
if self._api_version == "v3":
url = f"{self.base_url}/rapi/mobile/v2/{endpoint}"
headers = {"Authorization": f"Bearer {self._token}"}
res = await self._websession.delete(url, headers=headers)
ret = json.loads(await res.text())
log = "API call trip data reset status: %s" % res.status
LOGGER.debug(log)
log = "API call trip data reset returns: %s" % ret
LOGGER.debug(log)
async def stromer_call_api(self, endpoint: str, full=False) -> Any:
async def stromer_reset_trip_data(self) -> None:
"""Reset the trip data through the API."""
endpoint = f"bike/id/{self.bike_id}/trip_data/"
url = f"{self.base_url}/rapi/mobile/v4.1/{endpoint}"
if self._api_version == "v3":
url = f"{self.base_url}/rapi/mobile/v2/{endpoint}"
headers = {"Authorization": f"Bearer {self._token}"}
res = await self._websession.delete(url, headers=headers)
ret = json.loads(await res.text())
log = f"API call trip data reset status: {res.status}"
LOGGER.debug(log)
log = f"API call trip data reset returns: {ret}"
LOGGER.debug(log)
async def stromer_call_api(self, endpoint: str, full=False) -> Any:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant