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

Systemic changes to support garter carriage on the full bed #196

Merged

Conversation

clholgat
Copy link
Contributor

@clholgat clholgat commented Jul 31, 2024

#179

Things in this PR:

  • Belt shift only set once per line (when the first magnet crosses the turn mark).
  • Belt shift swapped (only for the first magnet of the garter carriage's that crosses the turn mark on the left)
  • m_position increment/decrement no longer bounded, allowed to overflow correctly
  • Offsets updated for G-carriage, L-carriage, K-carraige
  • m_solenoid to set is now based on m_pixelToSet

Things that still need to be fixed (and will be before I request review):

  • Verification that the 930 works
  • 270 offsets and functionality need to be checked

After this PR, alignment issues will only ever show up at multiples of 8. I am so excited for this.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced a new error signaling mechanism in the Beeper class, enhancing audible alerts for error conditions.
    • Added new constants for magnet sensor states to improve encoder functionality.
    • Implemented error handling capabilities in the GlobalBeeper class.
  • Improvements

    • Simplified logic for position updates in the encoder, enhancing efficiency and robustness.
    • Adjusted parameters for encoder behavior related to machine configurations, improving operational accuracy.
    • Streamlined calculations for solenoid and pixel values in the knitting process, enhancing clarity and responsiveness.
  • Bug Fixes

    • Improved handling of edge cases in encoder position updates, preventing erroneous state transitions.
    • Updated test cases to reflect changes in expected encoder behavior, ensuring accurate validation.

Copy link

coderabbitai bot commented Jul 31, 2024

Walkthrough

The recent changes enhance the AYAB firmware by implementing an error signaling mechanism across the Beeper, GlobalBeeper, and BeeperInterface classes. Additionally, the encoder logic has been refined with new member variables for better tracking of carriage positions and belt shifts during signal transitions. The knitting logic has also been updated for improved error feedback and streamlined calculations.

Changes

Files Change Summary
src/ayab/beeper.cpp, src/ayab/beeper.h, src/ayab/global_beeper.cpp Introduced error signaling capabilities with new methods and constants for the Beeper, GlobalBeeper, and BeeperInterface classes.
src/ayab/encoders.cpp, src/ayab/encoders.h Enhanced carriage position handling with new member variables; updated constants and streamlined logic in encoder methods.
src/ayab/knitter.cpp Modified control flow in knit() for error feedback and restructured calculations in calculatePixelAndSolenoid() for efficiency.
test/mocks/beeper_mock.cpp, test/mocks/beeper_mock.h Added mock methods for error handling in BeeperMock to simulate error states in tests.
test/test_encoders.cpp Updated assertions for getBeltShift() in tests and removed obsolete test cases to streamline the test suite.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant GlobalBeeper
    participant Beeper

    User->>GlobalBeeper: call error()
    GlobalBeeper->>Beeper: invoke m_instance.error()
    Beeper->>Beeper: check m_enabled
    Beeper->>Beeper: trigger beep with BEEP_NUM_ERROR
Loading

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai 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

@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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between f69d0e7 and 702e55b.

Files selected for processing (2)
  • src/ayab/encoders.cpp (3 hunks)
  • src/ayab/encoders.h (2 hunks)
Additional comments not posted (6)
src/ayab/encoders.h (2)

86-87: Adjustments to START_OFFSET array for KH910 machine configuration.

The changes to the START_OFFSET array modify the initial offsets for the Left and Right directions for the Garter carriage. Ensure that these adjustments have been tested and validated to confirm their impact on the encoder logic.


114-114: Addition of HALF_MAGNET_DISTANCE_G constant.

The new constant HALF_MAGNET_DISTANCE_G with a value of 12U suggests a potential enhancement or new feature related to magnet distance calculations. Ensure that this constant is used consistently and correctly in the codebase.

Verification successful

Addition of HALF_MAGNET_DISTANCE_G constant.

The new constant HALF_MAGNET_DISTANCE_G with a value of 12U is used consistently and correctly in the codebase, specifically within the logic that adjusts the start_position based on the detected carriage type and position.

  • src/ayab/encoders.cpp: Used in a conditional block to adjust start_position.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of the `HALF_MAGNET_DISTANCE_G` constant in the codebase.

# Test: Search for the usage of the constant. Expect: Consistent and correct usage.
rg --type cpp 'HALF_MAGNET_DISTANCE_G'

Length of output: 192


Script:

#!/bin/bash
# Description: Extract surrounding lines of code where `HALF_MAGNET_DISTANCE_G` is used in `encoders.cpp` to understand its context.

# Extract 5 lines before and after the usage of `HALF_MAGNET_DISTANCE_G` in `encoders.cpp`
rg --type cpp 'HALF_MAGNET_DISTANCE_G' -A 5 -B 5

Length of output: 1175


Script:

#!/bin/bash
# Description: Extract definitions and usages of `start_position`, `m_carriage`, and `detected_carriage` in `encoders.cpp`.

# Search for the definitions and usages of `start_position`
rg --type cpp 'start_position' -A 5 -B 5

# Search for the definitions and usages of `m_carriage`
rg --type cpp 'm_carriage' -A 5 -B 5

# Search for the definitions and usages of `detected_carriage`
rg --type cpp 'detected_carriage' -A 5 -B 5

Length of output: 15881

src/ayab/encoders.cpp (4)

136-137: Simplified condition for updating m_position in encA_rising method.

The condition for updating m_position has been simplified by removing the upper boundary check against END_RIGHT. Ensure that this change has been tested and validated to confirm its impact on the encoder logic.


179-180: Altered handling of start_position in encA_rising method.

The handling of start_position has been altered by replacing the return statement with a decrement operation. Ensure that this change has been tested and validated to confirm its impact on the encoder logic.


205-207: Simplified condition for updating m_position in encA_falling method.

The condition for updating m_position has been simplified by removing the lower boundary check against END_LEFT. Ensure that this change has been tested and validated to confirm its impact on the encoder logic.


208-213: New condition to return early if carriage type is Garter in encA_falling method.

A new condition has been introduced to return early if the carriage type is Garter, preventing further processing. Ensure that this change has been tested and validated to confirm its impact on the encoder logic.

@jonathanperret
Copy link
Contributor

jonathanperret commented Jul 31, 2024

First, congratulations on isolating this bug, it must not have been easy!

The following question is asked out of curiosity, feel free to disregard it.

Also typecast increment/decrement so if it does overflow, it overflows correctly.

1 is an int so m_position - 1 gets coerced to an int and then typecast back to a uint8_t upon assignment

I feel like I'm missing something here. I agree that 1 is treated as an int. And because int is wider than uint8_t, the operation m_position - 1 is done by first widening the unsigned byte m_position to a signed 16-bit int, subtracting 1, and casting the result back to an unsigned byte. But this still underflows "correctly", i.e. when m_position is 0, the intermediate result is (int)-1, which casts to (uint8_t)255 as expected.

Likewise when overflowing, if m_position is 255 the intermediate result is 256 which casts to 0.

Compiler explorer seems to show that the same assembly code is generated with or without the (uint8_t) cast.

Did you observe different behavior when adding the (uint8_t) cast?

Finally, as suggested by @X-sam on Discord, wouldn't it be safer all around to upgrade m_position to an int?

@jonathanperret
Copy link
Contributor

Finally, as suggested by @X-sam on Discord, wouldn't it be safer all around to upgrade m_position to an int?

Just thought of a potential downside to making m_position an int: updates wouldn’t be atomic anymore, so accesses outside of an ISR would require more care.

@clholgat clholgat closed this Aug 18, 2024
@clholgat clholgat reopened this Aug 18, 2024
@clholgat
Copy link
Contributor Author

Not ready for review, still sorting out RTL offsets and then need to do a lot of cleanup.

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, codebase verification and nitpick comments (2)
src/ayab/encoders.h (2)

114-114: Unused constant HALF_MAGNET_DISTANCE_G.

The constant HALF_MAGNET_DISTANCE_G is defined but not used anywhere in the codebase. Consider reviewing its intended purpose and ensure it is integrated where necessary. If it is not needed, consider removing it to maintain code clarity and cleanliness.

  • Location: src/ayab/encoders.h at line 114
Analysis chain

Addition of HALF_MAGNET_DISTANCE_G.

The new constant HALF_MAGNET_DISTANCE_G has been introduced. Verify its usage in the codebase to ensure it is correctly integrated and serves its intended purpose.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of `HALF_MAGNET_DISTANCE_G` to ensure it's correctly integrated.

# Test: Search for the constant usage. Expect: Proper integration and usage.
rg --type cpp --word-regexp 'HALF_MAGNET_DISTANCE_G'

Length of output: 120


80-80: Potential Type Mismatch with GARTER_SLOP Usage

The change of GARTER_SLOP to uint16_t may cause issues when used in arithmetic operations with uint8_t variables, as seen in:

  • test/test_fsm.cpp: Assignments to uint8_t variables positionPassedLeft and positionPassedRight.
  • test/test_knitter.cpp: Return values involving GARTER_SLOP.
  • src/ayab/knitter.cpp: Conditional checks involving GARTER_SLOP.

Ensure that these operations do not result in values exceeding the uint8_t range, or consider adjusting the types of the variables involved to prevent truncation.

Analysis chain

Type Change for GARTER_SLOP.

The change from uint8_t to uint16_t for GARTER_SLOP allows for larger values, which may be necessary for accommodating larger offsets or precision. Ensure that all usages of GARTER_SLOP are compatible with this type change.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all usages of `GARTER_SLOP` are compatible with `uint16_t`.

# Test: Search for the constant usage. Expect: No type mismatch errors.
rg --type cpp --word-regexp 'GARTER_SLOP'

Length of output: 863

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 702e55b and f273377.

Files selected for processing (3)
  • src/ayab/encoders.cpp (5 hunks)
  • src/ayab/encoders.h (2 hunks)
  • src/ayab/knitter.cpp (3 hunks)
Additional comments not posted (8)
src/ayab/encoders.h (1)

86-87: Modification of START_OFFSET Values.

The START_OFFSET array values for the KH910 machine have been adjusted. Ensure these changes align with the intended machine configuration and verify that they do not introduce any inconsistencies in the logic where they are used.

Verification successful

Modification of START_OFFSET Values Verified.

The changes to the START_OFFSET values for the KH910 machine have been tested in various scenarios within test/test_knitter.cpp. These tests cover different directions and machine configurations, ensuring the modifications align with the intended logic without introducing inconsistencies.

  • Test cases in test/test_knitter.cpp verify the correct behavior of getStartOffset under different conditions.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of `START_OFFSET` to ensure consistency with the new values.

# Test: Search for the array usage. Expect: No logic errors due to value changes.
rg --type cpp --word-regexp 'START_OFFSET'

Length of output: 290


Script:

#!/bin/bash
# Search for the definition and usage of m_machineType, direction, and m_carriage
rg --type cpp 'm_machineType|direction|m_carriage' -A 5

Length of output: 26943


Script:

#!/bin/bash
# Search for test cases involving getStartOffset or START_OFFSET in test files
rg --type cpp 'getStartOffset|START_OFFSET' test/test_knitter.cpp -A 5

Length of output: 2830

src/ayab/encoders.cpp (4)

222-223: ```shell
#!/bin/bash

Use ripgrep to search for the encA_falling function definition in the codebase.

rg --type cpp --word-regexp 'void encA_falling'


---

`146-147`: ```shell
#!/bin/bash
# Extract the implementation of the `encA_rising` function from `src/ayab/encoders.cpp`.
ast-grep --lang cpp --pattern 'void Encoders::encA_rising() { $$$ }'

206-207: Simplification of Position Update Logic in encA_falling.

The position update logic has been simplified by removing boundary checks and directly decrementing m_position. Ensure this change does not introduce errors in scenarios where boundary checks were previously necessary.


136-137: Simplification of Position Update Logic in encA_rising.

The position update logic has been simplified by removing boundary checks and directly incrementing m_position. Ensure this change does not introduce errors in scenarios where boundary checks were previously necessary.

src/ayab/knitter.cpp (3)

274-274: Commented Out GlobalBeeper::finishedLine in knit.

The invocation of GlobalBeeper::finishedLine based on m_position has been commented out. Verify that this change does not affect the intended functionality and that the new conditions for calling this function are correct.

#!/bin/bash
# Description: Verify the impact of commenting out `GlobalBeeper::finishedLine` in `knit`.

# Test: Search for all `GlobalBeeper::finishedLine` invocations. Expect: Correct conditions for invocation.
rg --type cpp --word-regexp 'GlobalBeeper::finishedLine'

286-292: New Conditions for GlobalBeeper::finishedLine in knit.

The function is now called when m_pixelToSet equals 0 or 200. Ensure these conditions are correct and align with the intended functionality.

#!/bin/bash
# Description: Verify the correctness of the new conditions for `GlobalBeeper::finishedLine` in `knit`.

# Test: Search for logic related to `m_pixelToSet`. Expect: Correct conditions for invocation.
rg --type cpp --word-regexp 'm_pixelToSet'

431-437: Modification of Logic in calculatePixelAndSolenoid.

The conditions for calculating m_solenoidToSet have been adjusted. Ensure these changes maintain the intended functionality and do not introduce errors.

#!/bin/bash
# Description: Verify the impact of changes in `calculatePixelAndSolenoid`.

# Test: Search for logic related to `m_solenoidToSet`. Expect: Correct calculation and no errors.
rg --type cpp --word-regexp 'm_solenoidToSet'

@clholgat clholgat changed the title Start G-carriage earlier to avoid overflowing m_position Systemic changes to support garter carriage on the full bed Aug 25, 2024
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between f273377 and 1d0d6cf.

Files selected for processing (3)
  • src/ayab/encoders.cpp (6 hunks)
  • src/ayab/encoders.h (3 hunks)
  • src/ayab/knitter.cpp (3 hunks)
Additional comments not posted (14)
src/ayab/encoders.h (6)

77-77: LGTM!

The constant ALL_MAGNETS_CLEARED_LEFT is correctly defined and initialized.

The code changes are approved.


78-78: LGTM!

The constant ALL_MAGNETS_CLEARED_RIGHT is correctly defined and initialized.

The code changes are approved.


83-83: LGTM!

Changing the type of GARTER_SLOP from uint8_t to uint16_t is appropriate to accommodate a larger range of values.

The code changes are approved.


89-90: LGTM!

The updated values in the START_OFFSET array reflect new configurations for the left and right offsets, suggesting a recalibration of the machine's operational parameters.

The code changes are approved.


117-117: LGTM!

The constant HALF_MAGNET_DISTANCE_G is correctly defined and initialized.

The code changes are approved.


188-189: LGTM!

The member variables m_passedLeft and m_passedRight are correctly defined and initialized.

The code changes are approved.

src/ayab/encoders.cpp (3)

78-79: LGTM!

The member variables m_passedLeft and m_passedRight are correctly initialized in the init method.

The code changes are approved.


138-144: LGTM!

The logic for updating m_position and m_passedLeft in the encA_rising method is streamlined and ensures that the state is only reset when appropriate.

The code changes are approved.


218-224: LGTM!

The logic for updating m_position and m_passedRight in the encA_falling method is streamlined and ensures that the state is only reset when appropriate.

The code changes are approved.

src/ayab/knitter.cpp (5)

274-274: LGTM!

The addition of GlobalBeeper::finishedLine() in the knit method indicates a modification in the control flow that may affect the feedback mechanism of the knitting process.

The code changes are approved.


349-349: LGTM!

Commenting out the call to GlobalBeeper::finishedLine() in the setNextLine method alters the behavior of the method by potentially suppressing feedback when no new line is requested.

The code changes are approved.


401-405: LGTM!

The new implementation in the calculatePixelAndSolenoid method directly calculates m_pixelToSet based on the startOffset and modifies how m_solenoidToSet is determined based on the BeltShift state.

The code changes are approved.


412-417: LGTM!

The new implementation in the calculatePixelAndSolenoid method directly calculates m_pixelToSet based on the startOffset and modifies how m_solenoidToSet is determined based on the BeltShift state.

The code changes are approved.


349-349: LGTM!

Commenting out the call to GlobalBeeper::finishedLine() in the setNextLine method alters the behavior of the method by potentially suppressing feedback when no new line is requested.

The code changes are approved.

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 1d0d6cf and 600d0e3.

Files selected for processing (1)
  • src/ayab/encoders.h (2 hunks)
Files skipped from review as they are similar to previous changes (1)
  • src/ayab/encoders.h

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 600d0e3 and b013100.

Files selected for processing (2)
  • src/ayab/encoders.h (2 hunks)
  • src/ayab/knitter.cpp (3 hunks)
Files skipped from review as they are similar to previous changes (2)
  • src/ayab/encoders.h
  • src/ayab/knitter.cpp

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, codebase verification and nitpick comments (2)
src/ayab/knitter.cpp (2)

407-409: Remove commented-out code if no longer needed.

The commented-out code related to the Knit carriage should be removed if it is no longer needed to keep the codebase clean.

-    //if (Carriage_t::Knit == m_carriage) {
-    //  beltShift = !beltShift;
-    //}

405-406: Replace magic numbers with named constants.

The magic numbers should be replaced with named constants for better readability and maintainability.

-    // See page 7 of the 930 service manual https://mkmanuals.com/downloadable/download/sample/sample_id/27/
-    // It's probably more apt to say that the other carriages are special but the 
+    // See page 7 of the 930 service manual https://mkmanuals.com/downloadable/download/sample/sample_id/27/
+    // It's probably more apt to say that the other carriages are special but the 
+    // Named constants for magic numbers
+    constexpr uint8_t KNIT_CARRIAGE_PAGE = 7;
+    constexpr uint8_t KH270_SOLENOID_SHIFT = 3;
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between b013100 and 2d56775.

Files selected for processing (6)
  • src/ayab/beeper.cpp (1 hunks)
  • src/ayab/beeper.h (4 hunks)
  • src/ayab/encoders.cpp (6 hunks)
  • src/ayab/encoders.h (2 hunks)
  • src/ayab/global_beeper.cpp (1 hunks)
  • src/ayab/knitter.cpp (2 hunks)
Files skipped from review as they are similar to previous changes (2)
  • src/ayab/encoders.cpp
  • src/ayab/encoders.h
Additional comments not posted (7)
src/ayab/global_beeper.cpp (1)

50-52: LGTM!

The method correctly delegates the error handling to m_instance.

The code changes are approved.

src/ayab/beeper.cpp (1)

80-84: LGTM!

The method correctly implements the error signaling functionality.

The code changes are approved.

src/ayab/beeper.h (4)

36-36: LGTM!

The constant is correctly defined and follows the naming convention of other constants in the file.

The code changes are approved.


53-53: LGTM!

The method is correctly added as a pure virtual function, ensuring that any implementing class must provide an implementation for handling error beeps.

The code changes are approved.


77-77: LGTM!

The method is correctly added to the class, providing a static method for error handling.

The code changes are approved.


92-92: LGTM!

The method is correctly added to the class, providing an implementation for handling error beeps.

The code changes are approved.

src/ayab/knitter.cpp (1)

273-274: Good addition of error handling.

The addition of GlobalBeeper::error() provides useful feedback in case of an error.

The code changes are approved.

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 2d56775 and 20bbb23.

Files selected for processing (1)
  • src/ayab/encoders.cpp (6 hunks)
Files skipped from review as they are similar to previous changes (1)
  • src/ayab/encoders.cpp

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, codebase verification and nitpick comments (5)
src/ayab/encoders.cpp (5)

Line range hint 139-218: Refactor suggestion: Simplify nested if-else structure.

The nested if-else structure can be simplified for better readability. Consider refactoring the code as follows:

if (Direction_t::Right == m_direction) {
  m_position = m_position + (uint8_t) 1;

  if (m_position > ALL_MAGNETS_CLEARED_LEFT[static_cast<uint8_t>(m_machineType)]) {
    m_passedLeft = false;
  }
}

uint16_t hallValue = analogRead(EOL_PIN_L);
if ((hallValue < FILTER_L_MIN[static_cast<uint8_t>(m_machineType)]) ||
    (hallValue > FILTER_L_MAX[static_cast<uint8_t>(m_machineType)])) {
  m_hallActive = Direction_t::Left;

  if (!m_passedLeft && Direction_t::Right == m_direction) {
    m_beltShift = digitalRead(ENC_PIN_C) != 0 ? BeltShift::Shifted : BeltShift::Regular;
    m_passedLeft = true;

    if (Carriage_t::Garter == m_carriage && m_position < 30) {
      m_beltShift = (BeltShift::Regular == m_beltShift) ? BeltShift::Shifted : BeltShift::Regular;
    }
  }

  if (m_carriage == Carriage_t::Garter || 
      (m_carriage == Carriage_t::Knit && m_machineType == Machine_t::Kh270)) {
    return;
  }

  Carriage detected_carriage = (hallValue >= FILTER_L_MIN[static_cast<uint8_t>(m_machineType)]) ? 
                                Carriage_t::Knit : Carriage_t::Lace;

  uint8_t start_position = END_LEFT_PLUS_OFFSET[static_cast<uint8_t>(m_machineType)];
  if (m_machineType == Machine_t::Kh270) {
    m_carriage = Carriage_t::Knit;
    if (detected_carriage == Carriage_t::Knit) {
      start_position += MAGNET_DISTANCE_270;
    }
  } else if (m_carriage == Carriage_t::NoCarriage) {
    m_carriage = detected_carriage;
  } else if (m_carriage != detected_carriage && m_position > start_position) {
    m_carriage = Carriage_t::Garter;
    m_beltShift = (BeltShift::Regular == m_beltShift) ? BeltShift::Shifted : BeltShift::Regular;
    return;
  } else {
    m_carriage = detected_carriage;
  }

  m_position = start_position;
}

Line range hint 243-283: Refactor suggestion: Simplify nested if-else structure.

The nested if-else structure can be simplified for better readability. Consider refactoring the code as follows:

if (Direction_t::Left == m_direction) {
  m_position = m_position - (uint8_t) 1;

  if (m_position < ALL_MAGNETS_CLEARED_RIGHT[static_cast<uint8_t>(m_machineType)]) {
    m_passedRight = false;
  }
}

uint16_t hallValue = analogRead(EOL_PIN_R);
bool hallValueSmall = (hallValue < FILTER_R_MIN[static_cast<uint8_t>(m_machineType)]);

if (hallValueSmall || hallValue > FILTER_R_MAX[static_cast<uint8_t>(m_machineType)]) {
  m_hallActive = Direction_t::Right;

  if (!m_passedRight && Direction_t::Left == m_direction) {
    m_beltShift = digitalRead(ENC_PIN_C) != 0 ? BeltShift::Regular : BeltShift::Shifted;
    m_passedRight = true;
  }

  if (m_carriage == Carriage_t::Garter) {
    return;
  }

  if (hallValueSmall) {
    m_carriage = Carriage_t::Knit;
  }

  m_position = END_RIGHT_MINUS_OFFSET[static_cast<uint8_t>(m_machineType)];
}

Line range hint 139-218: Suggestion: Add comments to explain complex logic.

The method contains several nested conditions and assignments. Adding comments to explain the logic will improve readability and maintainability.


Line range hint 243-283: Suggestion: Add comments to explain complex logic.

The method contains several nested conditions and assignments. Adding comments to explain the logic will improve readability and maintainability.


Line range hint 139-218: Performance optimization: Minimize time spent in ISR.

Reading from analog pins and performing multiple conditional checks in an interrupt service routine (ISR) can impact performance. Consider optimizing the code to minimize the time spent in the ISR.

Also applies to: 243-283

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 20bbb23 and fe3a180.

Files selected for processing (3)
  • src/ayab/encoders.cpp (6 hunks)
  • src/ayab/encoders.h (3 hunks)
  • src/ayab/knitter.cpp (2 hunks)
Files skipped from review as they are similar to previous changes (2)
  • src/ayab/encoders.h
  • src/ayab/knitter.cpp
Additional comments not posted (1)
src/ayab/encoders.cpp (1)

74-80: LGTM!

The initialization of new member variables m_passedLeft and m_passedRight is correct.

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between fe3a180 and 9bcfd16.

Files selected for processing (2)
  • src/ayab/encoders.cpp (6 hunks)
  • src/ayab/encoders.h (3 hunks)
Files skipped from review as they are similar to previous changes (1)
  • src/ayab/encoders.h
Additional comments not posted (5)
src/ayab/encoders.cpp (5)

78-79: LGTM!

The initialization of m_passedLeft and m_passedRight to false is correct.


138-144: LGTM!

The changes in the encA_rising method enhance the robustness of the encoder's functionality by ensuring accurate tracking of belt shift and carriage state.

Also applies to: 153-217


242-248: LGTM!

The changes in the encA_falling method enhance the robustness of the encoder's functionality by ensuring accurate tracking of belt shift and carriage state.

Also applies to: 263-277, 280-282


153-171: LGTM!

The logic for setting the belt shift signal is correct and ensures that the signal is only set once per turn mark crossing.


263-271: LGTM!

The logic for setting the belt shift signal is correct and ensures that the signal is only set once per turn mark crossing.

@dl1com dl1com force-pushed the clholgat/garter_carriage branch from b802f75 to b309e39 Compare August 30, 2024 19:19
dl1com and others added 2 commits August 30, 2024 21:19
Co-authored-by: Jonathan Perret <[email protected]>
Co-authored-by: Jonathan Perret <[email protected]>
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between b802f75 and 67affda.

Files selected for processing (6)
  • src/ayab/beeper.cpp (1 hunks)
  • src/ayab/beeper.h (4 hunks)
  • src/ayab/encoders.cpp (6 hunks)
  • src/ayab/encoders.h (3 hunks)
  • src/ayab/global_beeper.cpp (1 hunks)
  • src/ayab/knitter.cpp (2 hunks)
Files skipped from review as they are similar to previous changes (4)
  • src/ayab/beeper.cpp
  • src/ayab/encoders.cpp
  • src/ayab/encoders.h
  • src/ayab/knitter.cpp
Additional comments not posted (5)
src/ayab/global_beeper.cpp (1)

50-52: Approved: New error() method in GlobalBeeper.

The addition of the error() method in the GlobalBeeper class is well-implemented. It correctly delegates the error handling to the m_instance member, which is expected to be an instance of a class implementing the BeeperInterface. This change aligns with the PR's goal to enhance error management capabilities in the firmware.

src/ayab/beeper.h (4)

36-36: Approved: New constant BEEP_NUM_ERROR.

The definition of BEEP_NUM_ERROR with a value of 15 is a clear and straightforward way to standardize the number of beeps for error conditions across the system. This constant should be used consistently wherever error beeps are handled to maintain uniformity.


53-53: Approved: New pure virtual error() method in BeeperInterface.

Adding a pure virtual error() method to the BeeperInterface ensures that all implementing classes must provide their own implementation of error handling. This is a good design choice that enforces consistency and makes the error handling mechanism extensible.


77-77: Approved: New static error() method in GlobalBeeper.

The addition of a static error() method to the GlobalBeeper class allows for easy access to error signaling functionality from anywhere in the code that has access to GlobalBeeper. This enhances the modularity and accessibility of the error handling.


92-92: Approved: Implementation of error() method in Beeper.

The implementation of the error() method in the Beeper class, which finalizes the method from the BeeperInterface, is crucial for actual error signaling. This method should correctly handle the error beeping logic, potentially utilizing the BEEP_NUM_ERROR constant for the number of beeps.

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, codebase verification and nitpick comments (2)
test/test_encoders.cpp (1)

127-127: Inconsistency in Belt Shift Handling for KH270 Machine Type

There is a discrepancy in the expected belt shift behavior for the KH270 machine type. The test case in test/test_encoders.cpp expects BeltShift::Shifted, while test/test_knitter.cpp expects BeltShift::Regular. This inconsistency should be reviewed and resolved to ensure consistent behavior across the firmware.

  • test/test_encoders.cpp: Expects BeltShift::Shifted
  • test/test_knitter.cpp: Expects BeltShift::Regular
Analysis chain

Updated Assertion for Belt Shift in KH270 Context

The assertion update in test_encA_rising_in_front_KH270 also changes the expected belt shift to BeltShift::Shifted. This specific test case targets the KH270 machine type, suggesting that the behavior of the belt shift is consistently modified across different machine types under certain conditions. It's crucial to ensure that these changes are consistent and correctly implemented across all relevant parts of the firmware.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the consistency of belt shift behavior across different machine types.

# Test: Search for conditional logic handling different machine types in relation to belt shifts. Expect: Consistent handling of belt shifts for KH270 and other types.
rg --type cpp -A 5 $'Machine_t::Kh270'

Length of output: 5256


Script:

#!/bin/bash
# Description: Search for instances where BeltShift is used in conjunction with Machine_t::Kh270 to verify consistency.

# Test: Search for BeltShift usage in relation to Machine_t::Kh270.
rg --type cpp -A 5 'BeltShift' | rg 'Machine_t::Kh270'

Length of output: 430

src/ayab/knitter.cpp (1)

Line range hint 390-422: Refactor suggestion for calculatePixelAndSolenoid() method.

The changes in this method streamline the calculation of m_pixelToSet and m_solenoidToSet based on the carriage direction and belt shift state. However, the logic can be further simplified or clarified:

  1. Simplification of Belt Shift Logic: The toggling of beltShift based on the carriage type (Lace) could be encapsulated into a helper function to improve readability and reusability.
  2. Magic Numbers and Documentation: The use of magic numbers directly in the code (e.g., HALF_SOLENOIDS_NUM) should be documented or defined as constants with descriptive names to improve code maintainability.
  3. Conditional Logic for Solenoid Setting: The setting of m_solenoidToSet based on beltShift is clear, but the addition of 3 for the Kh270 machine type appears arbitrary without context. This should either be explained or refactored into a more descriptive mechanism.

Consider applying the following refactor to encapsulate the belt shift logic:

bool Knitter::shouldInvertBeltShift(Carriage_t carriage) {
  // Inverts belt shift for Lace carriage as per the 930 service manual
  return Carriage_t::Lace == carriage;
}

// Usage in calculatePixelAndSolenoid()
beltShift = shouldInvertBeltShift(m_carriage) ? !beltShift : beltShift;

Additionally, define magic numbers as constants and add comments for unusual operations like the addition for Kh270.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 67affda and 52cd583.

Files selected for processing (5)
  • src/ayab/encoders.cpp (6 hunks)
  • src/ayab/knitter.cpp (3 hunks)
  • test/mocks/beeper_mock.cpp (1 hunks)
  • test/mocks/beeper_mock.h (1 hunks)
  • test/test_encoders.cpp (5 hunks)
Files skipped from review as they are similar to previous changes (1)
  • src/ayab/encoders.cpp
Additional comments not posted (4)
test/mocks/beeper_mock.h (1)

38-38: Approved: Addition of the error method in BeeperMock.

The addition of the error method is correctly implemented using the MOCK_METHOD0 macro. This method will enhance the testing capabilities by allowing the simulation of error states, which aligns with the objectives of improving error handling in the system.

test/mocks/beeper_mock.cpp (1)

66-69: New method Beeper::error() correctly implemented.

The addition of the error() method to the Beeper class is correctly implemented and follows the established pattern of using assert to check for null pointers before proceeding with method calls on gBeeperMock. This ensures that the method behaves as expected without causing null pointer dereferences.

test/test_encoders.cpp (1)

96-96: Updated Assertion for Belt Shift

The change in the expected value for getBeltShift() from BeltShift::Regular to BeltShift::Shifted in the test case test_encA_rising_in_front_notKH270 reflects the updated logic in the firmware that handles belt shifts differently. This change should be verified to ensure it aligns with the intended behavior changes in the firmware, especially since it affects how the encoders interpret the position and movement of the carriages.

src/ayab/knitter.cpp (1)

271-272: Clarification and error handling in knit() method.

The addition of a call to GlobalBeeper::error() in the event of an error during pixel and solenoid calculation is a good practice as it enhances error feedback to the user. This change aligns with the PR's objective to improve error signaling mechanisms.

@clholgat
Copy link
Contributor Author

clholgat commented Sep 6, 2024

Can I get a review?

Copy link
Member

@X-sam X-sam left a comment

Choose a reason for hiding this comment

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

Lgtm

@X-sam X-sam merged commit 278cbbe into AllYarnsAreBeautiful:v1.0-dev Sep 8, 2024
2 checks passed
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.

4 participants