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

refactor(OpenGloves): decouple from Arduino SDK #100

Merged
merged 3 commits into from
Feb 27, 2024

Conversation

leon0399
Copy link
Member

No description provided.

Copy link
Contributor

sweep-ai bot commented Feb 27, 2024

Apply Sweep Rules to your PR?

  • Apply: All docstrings and comments should be up to date.
  • Apply: There should be no trailing whitespace in the code.
  • Apply: There should be no commented-out code in the codebase.
  • Apply: Variable names should be descriptive and follow a consistent naming convention.
  • Apply: There should be no unnecessary blank lines in the code.
  • Apply: There should be no unused imports in the code.

This is an automated message generated by Sweep AI.

@leon0399
Copy link
Member Author

@CodiumAI-Agent /review

@CodiumAI-Agent
Copy link

PR Review

⏱️ Estimated effort to review [1-5]

3, because the PR involves refactoring and decoupling from the Arduino SDK, which requires a detailed review of the changes to ensure compatibility and functionality are maintained. The changes span multiple files and include modifications to configuration definitions, sensor handling, and component definitions, making the review moderately complex.

🧪 Relevant tests

No

🔍 Possible issues

The refactoring introduces a new macro SS_OG_COLLECT_DATA for collecting data from sensors. While this macro improves code reuse, it heavily relies on macros and pointers, which could potentially lead to harder-to-debug issues if not carefully managed.

The changes in autoconfig.hpp significantly alter how button and force feedback (FFB) configurations are determined. This could potentially introduce logical errors if not all edge cases are considered, especially in environments with different or undefined pin configurations.

🔒 Security concerns

No

Code feedback:
relevant filelib/opengloves/senseshift/opengloves/autoconfig.hpp
suggestion      

Consider adding explicit checks for PIN_BUTTON_A and other pins being defined to -1 directly in the #ifdef blocks to simplify the logic and avoid potential misconfigurations. [medium]

relevant line#ifdef PIN_BUTTON_A

relevant filelib/opengloves/senseshift/opengloves/opengloves.hpp
suggestion      

Refactor the SS_OG_COLLECT_DATA macro to a template function to improve type safety and readability. Macros can lead to obscure errors and are harder to debug. [important]

relevant line#define SS_OG_COLLECT_DATA(FN)

relevant filelib/opengloves/senseshift/opengloves/opengloves_component.hpp
suggestion      

Ensure that all necessary headers are included after refactoring. Removing headers such as "senseshift/arduino/input/sensor/analog.hpp" might lead to compilation errors if they are not included elsewhere as needed. [medium]

relevant line-#include "senseshift/arduino/input/sensor/analog.hpp"

relevant filefirmware/mode_configs/opengloves/opengloves.cpp
suggestion      

Verify that the change from opengloves_task.hpp to opengloves_component.hpp does not introduce any missing dependencies or functionality, especially in initialization and task handling. [important]

relevant line#include


✨ Review tool usage guide:

Overview:
The review tool scans the PR code changes, and generates a PR review. The tool can be triggered automatically every time a new PR is opened, or can be invoked manually by commenting on any PR.
When commenting, to edit configurations related to the review tool (pr_reviewer section), use the following template:

/review --pr_reviewer.some_config1=... --pr_reviewer.some_config2=...

With a configuration file, use the following template:

[pr_reviewer]
some_config1=...
some_config2=...
Utilizing extra instructions

The review tool can be configured with extra instructions, which can be used to guide the model to a feedback tailored to the needs of your project.

Be specific, clear, and concise in the instructions. With extra instructions, you are the prompter. Specify the relevant sub-tool, and the relevant aspects of the PR that you want to emphasize.

Examples for extra instructions:

[pr_reviewer] # /review #
extra_instructions="""
In the 'possible issues' section, emphasize the following:
- Does the code logic cover relevant edge cases?
- Is the code logic clear and easy to understand?
- Is the code logic efficient?
...
"""

Use triple quotes to write multi-line instructions. Use bullet points to make the instructions more readable.

How to enable\disable automation
  • When you first install PR-Agent app, the default mode for the review tool is:
pr_commands = ["/review", ...]

meaning the review tool will run automatically on every PR, with the default configuration.
Edit this field to enable/disable the tool, or to change the used configurations

Auto-labels

The review tool can auto-generate two specific types of labels for a PR:

  • a possible security issue label, that detects possible security issues (enable_review_labels_security flag)
  • a Review effort [1-5]: x label, where x is the estimated effort to review the PR (enable_review_labels_effort flag)
Extra sub-tools

The review tool provides a collection of possible feedbacks about a PR.
It is recommended to review the possible options, and choose the ones relevant for your use case.
Some of the feature that are disabled by default are quite useful, and should be considered for enabling. For example:
require_score_review, require_soc2_ticket, and more.

Auto-approve PRs

By invoking:

/review auto_approve

The tool will automatically approve the PR, and add a comment with the approval.

To ensure safety, the auto-approval feature is disabled by default. To enable auto-approval, you need to actively set in a pre-defined configuration file the following:

[pr_reviewer]
enable_auto_approval = true

(this specific flag cannot be set with a command line argument, only in the configuration file, committed to the repository)

You can also enable auto-approval only if the PR meets certain requirements, such as that the estimated_review_effort is equal or below a certain threshold, by adjusting the flag:

[pr_reviewer]
maximal_review_effort = 5
More PR-Agent commands

To invoke the PR-Agent, add a comment using one of the following commands:

  • /review: Request a review of your Pull Request.
  • /describe: Update the PR title and description based on the contents of the PR.
  • /improve [--extended]: Suggest code improvements. Extended mode provides a higher quality feedback.
  • /ask <QUESTION>: Ask a question about the PR.
  • /update_changelog: Update the changelog based on the PR's contents.
  • /add_docs 💎: Generate docstring for new components introduced in the PR.
  • /generate_labels 💎: Generate labels for the PR based on the PR's contents.
  • /analyze 💎: Automatically analyzes the PR, and presents changes walkthrough for each component.

See the tools guide for more details.
To list the possible configuration parameters, add a /config comment.

See the review usage page for a comprehensive guide on using this tool.

@CodiumAI-Agent
Copy link

PR Analysis

  • 🎯 Main theme: Refactoring OpenGloves code to decouple it from Arduino SDK
  • 📝 PR summary: This PR is focused on refactoring the OpenGloves code to decouple it from the Arduino SDK. The changes include modifications to the way buttons are enabled, the collection of data, and the handling of communication. The PR also introduces a new macro to collect data and refactors the collectData method to use this macro.
  • 📌 Type of PR: Enhancement
  • 🧪 Relevant tests added: No
  • ⏱️ Estimated effort to review [1-5]: 4, because the PR involves significant changes to the codebase, including the introduction of new macros and changes to the way data is collected and handled. It requires a good understanding of the existing codebase and the changes made to review effectively.
  • 🔒 Security concerns: No

PR Feedback

💡 General suggestions: The PR is well-structured and the changes are logically grouped. However, it would be beneficial to add some comments explaining the purpose and usage of the newly introduced macros and methods. This would make the code easier to understand for other developers. Additionally, it would be good to add tests to verify the functionality of the new code.

🤖 Code feedback:
relevant filelib/opengloves/senseshift/opengloves/opengloves.hpp
suggestion      

Consider breaking down the SS_OG_COLLECT_DATA macro into smaller, more manageable parts. This would make the code easier to understand and maintain. [important]

relevant line#define SS_OG_COLLECT_DATA(FN) </td>

relevant filelib/opengloves/senseshift/opengloves/opengloves.hpp
suggestion      

It would be beneficial to add error handling or checks to ensure that the FN passed to the SS_OG_COLLECT_DATA macro is valid and does not cause any runtime errors. [important]

relevant linedata.curl.fingers[i].curl[j] = joint_sensor->FN(); </a>

relevant filelib/opengloves/senseshift/opengloves/autoconfig.hpp
suggestion      

The changes to the button enabling code are good, but it might be more efficient to use a function or method to handle this instead of repeating the same code for each button. This would reduce code duplication and make the code easier to maintain. [medium]

relevant line#ifdef PIN_BUTTON_A

relevant filefirmware/mode_configs/opengloves/opengloves.cpp
suggestion      

It seems like the setupMode function is incomplete. Consider adding the necessary code to complete this function or remove it if it is not needed. [medium]

relevant linevoid setupMode()


✨ Usage guide:

Overview:
The review tool scans the PR code changes, and generates a PR review. The tool can be triggered automatically every time a new PR is opened, or can be invoked manually by commenting on any PR.
When commenting, to edit configurations related to the review tool (pr_reviewer section), use the following template:

/review --pr_reviewer.some_config1=... --pr_reviewer.some_config2=...

With a configuration file, use the following template:

[pr_reviewer]
some_config1=...
some_config2=...
Utilizing extra instructions

The review tool can be configured with extra instructions, which can be used to guide the model to a feedback tailored to the needs of your project.

Be specific, clear, and concise in the instructions. With extra instructions, you are the prompter. Specify the relevant sub-tool, and the relevant aspects of the PR that you want to emphasize.

Examples for extra instructions:

[pr_reviewer] # /review #
extra_instructions="""
In the code feedback section, emphasize the following:
- Does the code logic cover relevant edge cases?
- Is the code logic clear and easy to understand?
- Is the code logic efficient?
...
"""

Use triple quotes to write multi-line instructions. Use bullet points to make the instructions more readable.

How to enable\disable automation
  • When you first install PR-Agent app, the default mode for the review tool is:
pr_commands = ["/review", ...]

meaning the review tool will run automatically on every PR, with the default configuration.
Edit this field to enable/disable the tool, or to change the used configurations

About the 'Code feedback' section

The review tool provides several type of feedbacks, one of them is code suggestions.
If you are interested only in the code suggestions, it is recommended to use the improve feature instead, since it dedicated only to code suggestions, and usually gives better results.
Use the review tool if you want to get a more comprehensive feedback, which includes code suggestions as well.

Auto-labels

The review tool can auto-generate two specific types of labels for a PR:

  • a possible security issue label, that detects possible security issues (enable_review_labels_security flag)
  • a Review effort [1-5]: x label, where x is the estimated effort to review the PR (enable_review_labels_effort flag)
Extra sub-tools

The review tool provides a collection of possible feedbacks about a PR.
It is recommended to review the possible options, and choose the ones relevant for your use case.
Some of the feature that are disabled by default are quite useful, and should be considered for enabling. For example:
require_score_review, require_soc2_review, enable_review_labels_effort, and more.

More PR-Agent commands

To invoke the PR-Agent, add a comment using one of the following commands:

  • /review: Request a review of your Pull Request.
  • /describe: Update the PR title and description based on the contents of the PR.
  • /improve [--extended]: Suggest code improvements. Extended mode provides a higher quality feedback.
  • /ask <QUESTION>: Ask a question about the PR.
  • /update_changelog: Update the changelog based on the PR's contents.
  • /add_docs 💎: Generate docstring for new components introduced in the PR.
  • /generate_labels 💎: Generate labels for the PR based on the PR's contents.
  • /analyze 💎: Automatically analyzes the PR, and presents changes walkthrough for each component.

See the tools guide for more details.
To list the possible configuration parameters, add a /config comment.

See the review usage page for a comprehensive guide on using this tool.

Copy link

codecov bot commented Feb 27, 2024

Codecov Report

Merging #100 (2040226) into develop (2a88d35) will increase coverage by 1.13%.
The diff coverage is 66.66%.

Additional details and impacted files
@@             Coverage Diff             @@
##           develop     #100      +/-   ##
===========================================
+ Coverage    43.61%   44.75%   +1.13%     
===========================================
  Files           42       42              
  Lines         1229     1200      -29     
===========================================
+ Hits           536      537       +1     
+ Misses         693      663      -30     
Flag Coverage Δ
unittests 44.75% <66.66%> (+1.13%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

@leon0399
Copy link
Member Author

@CodiumAI-Agent /describe --pr_description.add_original_user_description=true --pr_description.keep_original_user_title=true

@leon0399
Copy link
Member Author

@CodiumAI-Agent /review -i --pr_reviewer.remove_previous_review_comment=true

@leon0399
Copy link
Member Author

@CodiumAI-Agent /improve

@CodiumAI-Agent
Copy link

CodiumAI-Agent commented Feb 27, 2024

PR Code Suggestions

Suggestions                                                                                                                                                     
enhancement
Use a temporary variable to avoid recalculating the same expression.         

Consider using a temporary variable for std::abs(value - this->center_) to avoid
recalculating the same expression twice. This can improve readability and potentially
performance if the compiler doesn't optimize this case.

lib/io/senseshift/input/filter.hpp [272]

-return std::abs(value - this->center_) < deadzone_ ? this->center_ : value;
+auto deviation = std::abs(value - this->center_);
+return deviation < deadzone_ ? this->center_ : value;
 
Isolate filter effects in tests for clearer granularity.                     

For the test_sensor_multiple_filters function, consider verifying the behavior of the
filters separately to isolate their effects and make the tests more granular.

test/test_io_sensor/main.cpp [154-155]

-sensor->addFilters({ new ::SenseShift::Input::Filter::MultiplyFilter(2),
-                     new ::SenseShift::Input::Filter::AddFilter(1) });
+// Test MultiplyFilter separately
+sensor->addFilter(new ::SenseShift::Input::Filter::MultiplyFilter(2));
+// Test AddFilter separately
+sensor->addFilter(new ::SenseShift::Input::Filter::AddFilter(1));
 
maintainability
Use a macro function to reduce repetitive code blocks.                       

Replace the repetitive #ifdef blocks with a macro function to reduce code duplication and
improve maintainability.

lib/opengloves/senseshift/opengloves/autoconfig.hpp [147-193]

-#ifdef PIN_BUTTON_A
-#define BUTTON_A_ENABLED (PIN_BUTTON_A != -1)
-#else
-#define BUTTON_A_ENABLED false
-#endif
+#define CHECK_PIN_ENABLED(PIN) ((PIN) != -1 ? true : false)
+#define BUTTON_A_ENABLED CHECK_PIN_ENABLED(PIN_BUTTON_A)
 
Document the rationale behind configuration changes.                         

Consider documenting the reason for changing the JOYSTICK_DEADZONE value from 0.1 to 0.03
in the configuration file or in related documentation to provide context for this change.

ini/opengloves.ini [39]

--D JOYSTICK_DEADZONE=0.03
+-D JOYSTICK_DEADZONE=0.03 # Reduced to improve joystick responsiveness, based on user feedback
 
best practice
Replace the macro with a template function for type safety and better maintainability.

Instead of using a macro for SS_OG_COLLECT_DATA, consider implementing a template
function. Macros can lead to harder-to-debug code and lack type safety.

lib/opengloves/senseshift/opengloves/opengloves.hpp [14-62]

-#define SS_OG_COLLECT_DATA(FN)                                     \
-    og::InputPeripheralData data{};                                \
+template<typename SensorFunction>
+og::InputPeripheralData collectData(SensorFunction fn) {
+    og::InputPeripheralData data{};
     ...
     return data;
+}
 
Initialize member variables in the constructor.                              

Consider initializing raw_plotter_ and calibrated_plotter_ in the constructor of
OpenGlovesTrackingComponent to ensure they are properly set up before use.

lib/opengloves/senseshift/opengloves/opengloves_component.hpp [18-19]

-// Plotter raw_plotter_ = Plotter(&Serial, "Raw");
-// Plotter calibrated_plotter_ = Plotter(&Serial, "Cal");
+OpenGlovesTrackingComponent() : raw_plotter_(&Serial, "Raw"), calibrated_plotter_(&Serial, "Cal") {}
 
Use const char* for string literals to ensure type safety.      

For better type safety and avoiding potential memory issues, consider changing char
prefix_ to const char
prefix_ in the Plotter class.**

lib/opengloves_arduino/senseshift/opengloves/opengloves_plotter.hpp [10]

-Plotter(Print* output, char* prefix) : output_(output), prefix_(prefix){};
+Plotter(Print* output, const char* prefix) : output_(output), prefix_(prefix){};
 
Initialize class members in the constructor for consistency.                 

Consider initializing value and setupCounter in the constructor of TestFloatSensor to
ensure that all members are explicitly initialized in a consistent manner.

test/test_io_sensor/main.cpp [29-30]

-float value = 0.0f;
-int setupCounter = 0;
+TestFloatSensor() : value(0.0f), setupCounter(0) {}
 
Use smart pointers for automatic resource management.                        

Use std::unique_ptr for managing the lifetime of inner and sensor objects in
test_sensor_filter_center_deadzone to ensure proper resource management and avoid memory
leaks.

test/test_io_sensor/main.cpp [121-122]

-auto inner = new TestFloatSensor();
-auto sensor = new SimpleSensorDecorator(inner);
+auto inner = std::make_unique<TestFloatSensor>();
+auto sensor = std::make_unique<SimpleSensorDecorator>(inner.get());
 
Ensure idempotency of the init method to avoid unintended side effects.

Instead of manually incrementing setupCounter in init, consider using a more robust method
to track initialization or ensure that init can safely be called multiple times without
side effects.

test/test_io_sensor/main.cpp [32]

-void init() override { this->setupCounter++; };
+void init() override {
+  if (!initialized) {
+    // Initialization logic here
+    initialized = true;
+    this->setupCounter++;
+  }
+}
 

✨ Improve tool usage guide:

Overview:
The improve tool scans the PR code changes, and automatically generates suggestions for improving the PR code. The tool can be triggered automatically every time a new PR is opened, or can be invoked manually by commenting on a PR.
When commenting, to edit configurations related to the improve tool (pr_code_suggestions section), use the following template:

/improve --pr_code_suggestions.some_config1=... --pr_code_suggestions.some_config2=...

With a configuration file, use the following template:

[pr_code_suggestions]
some_config1=...
some_config2=...
Enabling\disabling automation

When you first install the app, the default mode for the improve tool is:

pr_commands = ["/improve --pr_code_suggestions.summarize=true", ...]

meaning the improve tool will run automatically on every PR, with summarization enabled. Delete this line to disable the tool from running automatically.

Utilizing extra instructions

Extra instructions are very important for the improve tool, since they enable to guide the model to suggestions that are more relevant to the specific needs of the project.

Be specific, clear, and concise in the instructions. With extra instructions, you are the prompter. Specify relevant aspects that you want the model to focus on.

Examples for extra instructions:

[pr_code_suggestions] # /improve #
extra_instructions="""
Emphasize the following aspects:
- Does the code logic cover relevant edge cases?
- Is the code logic clear and easy to understand?
- Is the code logic efficient?
...
"""

Use triple quotes to write multi-line instructions. Use bullet points to make the instructions more readable.

A note on code suggestions quality
  • While the current AI for code is getting better and better (GPT-4), it's not flawless. Not all the suggestions will be perfect, and a user should not accept all of them automatically.
  • Suggestions are not meant to be simplistic. Instead, they aim to give deep feedback and raise questions, ideas and thoughts to the user, who can then use his judgment, experience, and understanding of the code base.
  • Recommended to use the 'extra_instructions' field to guide the model to suggestions that are more relevant to the specific needs of the project, or use the custom suggestions 💎 tool
  • With large PRs, best quality will be obtained by using 'improve --extended' mode.
More PR-Agent commands

To invoke the PR-Agent, add a comment using one of the following commands:

  • /review: Request a review of your Pull Request.
  • /describe: Update the PR title and description based on the contents of the PR.
  • /improve [--extended]: Suggest code improvements. Extended mode provides a higher quality feedback.
  • /ask <QUESTION>: Ask a question about the PR.
  • /update_changelog: Update the changelog based on the PR's contents.
  • /add_docs 💎: Generate docstring for new components introduced in the PR.
  • /generate_labels 💎: Generate labels for the PR based on the PR's contents.
  • /analyze 💎: Automatically analyzes the PR, and presents changes walkthrough for each component.

See the tools guide for more details.
To list the possible configuration parameters, add a /config comment.

See the improve usage page for a more comprehensive guide on using this tool.

@CodiumAI-Agent
Copy link

PR Code Suggestions

💡 [maintainability]

Consider using a macro to reduce the repetition of the button enabled checks.

File: lib/opengloves/senseshift/opengloves/autoconfig.hpp (147-151)

Example code:

Existing code:

#ifdef PIN_BUTTON_A
#define BUTTON_A_ENABLED (PIN_BUTTON_A != -1)
#else
#define BUTTON_A_ENABLED false
#endif

Improved code:

#define CHECK_BUTTON_ENABLED(BUTTON) \
#ifdef PIN_##BUTTON \
#define BUTTON_##BUTTON##_ENABLED (PIN_##BUTTON != -1) \
#else \
#define BUTTON_##BUTTON##_ENABLED false \
#endif

CHECK_BUTTON_ENABLED(BUTTON_A)
CHECK_BUTTON_ENABLED(BUTTON_B)
CHECK_BUTTON_ENABLED(BUTTON_MENU)
CHECK_BUTTON_ENABLED(BUTTON_JOYSTICK)
CHECK_BUTTON_ENABLED(BUTTON_CALIBRATE)
CHECK_BUTTON_ENABLED(BUTTON_TRIGGER)
CHECK_BUTTON_ENABLED(BUTTON_GRAB)
CHECK_BUTTON_ENABLED(BUTTON_PINCH)

💡 [best practice]

Consider removing commented out code if it is not needed.

File: lib/opengloves/senseshift/opengloves/opengloves_component.hpp (18-19)

Example code:

Existing code:

// Plotter raw_plotter_ = Plotter(&Serial, "Raw");
// Plotter calibrated_plotter_ = Plotter(&Serial, "Cal");

Improved code:


💡 [best practice]

Consider using a for-each loop to iterate over curls and splays in the collectData method.

File: lib/opengloves/senseshift/opengloves/opengloves_component.hpp (17-26)

Example code:

Existing code:

const auto& curls = this->curl.fingers;
const auto& splays = this->splay.fingers;
for (auto i = 0; i < curls.size(); i++) {
    const auto& finger_curl = curls[i].curl;
    for (auto j = 0; j < finger_curl.size(); j++) {
        auto* joint_sensor = finger_curl[j];
        if (joint_sensor != nullptr) {
            data.curl.fingers[i].curl[j] = joint_sensor->FN();
        }
    }

Improved code:

const auto& curls = this->curl.fingers;
const auto& splays = this->splay.fingers;
for (const auto& finger_curl : curls) {
    for (auto* joint_sensor : finger_curl.curl) {
        if (joint_sensor != nullptr) {
            data.curl.fingers[i].curl[j] = joint_sensor->FN();
        }
    }

💡 [best practice]

Consider making output_ and prefix_ const to ensure they are not accidentally modified.

File: lib/opengloves_arduino/senseshift/opengloves/opengloves_plotter.hpp (34-35)

Example code:

Existing code:

Print* output_;
char* prefix_;

Improved code:

Print* const output_;
char* const prefix_;

@leon0399 leon0399 force-pushed the feature/opengloves-plotter branch from 5432c49 to 2040226 Compare February 27, 2024 10:37
@leon0399 leon0399 merged commit ff83152 into develop Feb 27, 2024
41 checks passed
@leon0399 leon0399 deleted the feature/opengloves-plotter branch February 27, 2024 10:48
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