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

Fix carriage detection on the right #205

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

Conversation

jonathanperret
Copy link
Contributor

@jonathanperret jonathanperret commented Oct 14, 2024

Problem

Fixes carriages not being detected on the right on KH930-like machines (#175 and #176).

Proposed solution

On the KH910/KH950, we can't fix detecting Lace or Garter carriages on the right without an AYAB hardware change. But on other machines, the right sensor is just as functional as the left one.

So in this PR, we mostly copy the logic from encA_rising into encA_falling, and add a special case for the KH910 with its inverted K-only reading.

We also have to change the initialization logic (in knitter.cpp) slightly: the "carriage passed the turn mark" test does not work for the Garter carriage, because the position we track is actually that of its rightmost magnet pair. It turns out we can declare the machine ready as soon as a Garter carriage has been detected, since that means the carriage type cannot change further.

How to test

A firmware built from this PR can we flashed at this URL: https://code.jonathanperret.net/ayab-webtool/#pr=205

Summary by CodeRabbit

  • New Features

    • Introduced a new constant for garter carriage magnet spacing to enhance configuration.
    • Added state management for the carriage type in the Knitter class, improving operational logic.
  • Bug Fixes

    • Adjusted logic for encoder interrupts to prevent incorrect state changes based on carriage type.
    • Updated minimum filter values for consistent sensor behavior across machine types.
  • Tests

    • Updated test cases for the Encoders class to reflect new expected behaviors and sensor readings.

Copy link

coderabbitai bot commented Nov 15, 2024

Walkthrough

The changes in this pull request involve modifications to the encoder logic and the knitter's state management within the AYAB firmware. Key updates include the introduction of new conditions in the interrupt service routines for encoder A, particularly for handling the Carriage_t::Garter type. Additionally, a new constant for magnet spacing is added, and adjustments are made to filter values for consistency across machine types. The knitter class is enhanced with a new carriage state variable, affecting solenoid calculations and readiness checks. Test cases are also updated to reflect these changes.

Changes

File Change Summary
src/ayab/encoders.cpp Modified logic in encA_rising and encA_falling methods to handle Carriage_t::Garter with early returns and refined carriage type detection for Kh910.
src/ayab/encoders.h Added constant GARTER_L_MAGNET_SPACING and updated FILTER_R_MIN values for consistency across machine types.
src/ayab/knitter.cpp Introduced new member variable m_carriage, updated isReady() and calculatePixelAndSolenoid() methods to incorporate carriage state management.
test/test_encoders.cpp Adjusted test cases for Encoders class to align expected behavior with updated logic, including changes in expected sensor readings and carriage type assertions.

Possibly related issues

Possibly related PRs

Suggested reviewers

  • dl1com: Suggested as a potential reviewer for the changes made in this PR.

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>, please review it.
    • 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 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 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.

Mostly by copying the logic from encA_rising into encA_falling, and
special-casing the KH910 with its inverted K-only reading.

Also, if we have detected a Garter carriage, we already decided that it's
too hard to try to reset the position when it crosses the turn marks.
If we punt on resetting the belt shift as well, we save some logic and
fix the few weird spots where it turns while its outer magnet is right
on the turn mark.
@jonathanperret jonathanperret force-pushed the fix-right-sensor branch 2 times, most recently from e031e83 to 43e53f4 Compare November 15, 2024 22:18
@jonathanperret jonathanperret changed the title encoders: fix carriage detection on the right Fix carriage detection on the right Nov 15, 2024
@jonathanperret jonathanperret marked this pull request as ready for review November 15, 2024 22:43
The "pass turn mark" test is not appropriate for the Garter
carriage.
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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (3)
test/test_encoders.cpp (2)

134-161: LGTM! Consider adding test case documentation.

The test case correctly validates the sequence of carriage detection transitions from Lace to Garter, including both rising and falling edge scenarios. This aligns well with the PR's objective of improving right-side carriage detection.

Consider adding a brief comment explaining the expected behavior sequence, as this test case covers a complex state transition:

+// Test case verifies Garter carriage detection through a sequence of:
+// 1. Initial rising edge (detecting Lace carriage)
+// 2. Falling edge validation
+// 3. Second rising edge (confirming Garter carriage)
 TEST_F(EncodersTest, test_encA_rising_in_front_G_carriage) {

223-230: LGTM! Consider additional edge case validation.

The test case correctly validates the special case handling for KH910's inverted K-only reading, as mentioned in the PR objectives.

Consider adding test cases for edge conditions:

+// Test invalid hall sensor values
+TEST_F(EncodersTest, test_encA_falling_invalid_hall_values_KH910) {
+  encoders->init(Machine_t::Kh910);
+  
+  // Test with hall sensor value at exactly FILTER_R_MIN
+  EXPECT_CALL(*arduinoMock, digitalRead(ENC_PIN_A)).WillOnce(Return(false));
+  EXPECT_CALL(*arduinoMock, digitalRead(ENC_PIN_B));
+  EXPECT_CALL(*arduinoMock, analogRead(EOL_PIN_R))
+      .WillOnce(Return(FILTER_R_MIN[static_cast<int8_t>(encoders->getMachineType())]));
+  
+  encoders->encA_interrupt();
+  ASSERT_EQ(encoders->getCarriage(), Carriage_t::NoCarriage);
+}
src/ayab/knitter.cpp (1)

220-225: LGTM: Early Garter carriage initialization

The documentation clearly explains the need for early initialization with Garter carriages, and the implementation correctly allows for solenoid setting before the carriage center crosses the turn mark.

Consider moving the Garter carriage check before the hall sensor checks for better performance, as it could avoid unnecessary calculations when a Garter carriage is detected:

-  bool passedLeft = (Direction_t::Right == m_direction) && (Direction_t::Left == m_lastHall) &&
-        (m_position > (END_LEFT_PLUS_OFFSET[static_cast<uint8_t>(m_machineType)] + GARTER_SLOP));
-  bool passedRight = (Direction_t::Left == m_direction) && (Direction_t::Right == m_lastHall) &&
-        (m_position < (END_RIGHT_MINUS_OFFSET[static_cast<uint8_t>(m_machineType)] - GARTER_SLOP));
-
-  if (passedLeft || passedRight || m_carriage == Carriage::Garter) {
+  if (m_carriage == Carriage::Garter) {
+    return true;
+  }
+
+  bool passedLeft = (Direction_t::Right == m_direction) && (Direction_t::Left == m_lastHall) &&
+        (m_position > (END_LEFT_PLUS_OFFSET[static_cast<uint8_t>(m_machineType)] + GARTER_SLOP));
+  bool passedRight = (Direction_t::Left == m_direction) && (Direction_t::Right == m_lastHall) &&
+        (m_position < (END_RIGHT_MINUS_OFFSET[static_cast<uint8_t>(m_machineType)] - GARTER_SLOP));
+
+  if (passedLeft || passedRight) {
🛑 Comments failed to post (3)
src/ayab/encoders.cpp (3)

191-193: ⚠️ Potential issue

Fix enum type usage: Use Carriage_t instead of Carriage

There's a syntax error in the enum comparison. The code uses Carriage:: but the enum type is Carriage_t::.

Apply this fix:

-    } else if (m_carriage == Carriage::Lace &&
-               detected_carriage == Carriage::Knit &&
+    } else if (m_carriage == Carriage_t::Lace &&
+               detected_carriage == Carriage_t::Knit &&
📝 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.

    } else if (m_carriage == Carriage_t::Lace &&
               detected_carriage == Carriage_t::Knit &&
               m_position > start_position) {

241-244: ⚠️ Potential issue

Fix enum type usage and enhance comment

Two issues to address:

  1. Incorrect enum type usage (MachineType:: instead of Machine_t::)
  2. Comment could be more specific about future support plans

Apply this fix:

-  if (m_machineType == MachineType::Kh270) {
+  if (m_machineType == Machine_t::Kh270) {

Consider enhancing the comment to be more specific about future support plans:

-  // No attempt to support KH270 on the right for now as I can't test it
+  // TODO: Add KH270 right side support after hardware testing capability is available
📝 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.

  // TODO: Add KH270 right side support after hardware testing capability is available
  if (m_machineType == Machine_t::Kh270) {
    return;
  }

272-281: ⚠️ Potential issue

Fix enum type and consider hardware fix for KH910

The code contains two issues:

  1. Incorrect enum type usage (MachineType:: instead of Machine_t::)
  2. Hardware limitation requiring software workaround

Apply this fix:

-    if (m_machineType == MachineType::Kh910) {
+    if (m_machineType == Machine_t::Kh910) {

The current workaround for KH910's wiring issue, while functional, might be better addressed through a hardware fix. Consider:

  1. Documenting the exact wiring issue in the codebase
  2. Creating a hardware fix proposal
  3. Adding this to the project's roadmap for a more permanent solution
📝 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.

    if (m_machineType == Machine_t::Kh910) {
      // Due to an error in wiring on the shield, the sensor only triggers for the K carriage,
      // and with a low voltage so we can't use the same logic as for other machines.
      detected_carriage = Carriage_t::Knit;
    } else {
      if (hallValue >= FILTER_R_MIN[static_cast<uint8_t>(m_machineType)]) {
        detected_carriage = Carriage_t::Knit;
      } else {
        detected_carriage = Carriage_t::Lace;
      }

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 and nitpick comments (1)
src/ayab/knitter.cpp (1)

Line range hint 214-219: Document GARTER_SLOP constant

The GARTER_SLOP constant is used in position calculations but its purpose and value determination aren't documented. Consider:

  1. Adding a comment explaining what this constant represents
  2. Documenting how the value was determined
  3. Moving it to a named constant with clear documentation if it's defined elsewhere
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 43e53f4 and 35ea8fb.

📒 Files selected for processing (1)
  • src/ayab/knitter.cpp (2 hunks)
🔇 Additional comments (2)
src/ayab/knitter.cpp (2)

79-79: LGTM: Good addition of carriage state tracking

The new member variable m_carriage properly encapsulates the carriage state and follows good initialization practices.


220-225: Verify carriage type stability assumption

The comment suggests that once a Garter carriage is detected, the carriage type won't change. Let's verify this assumption across the codebase.

✅ Verification successful

Carriage type detection is stable and correctly implemented

The verification shows that the carriage type detection is implemented safely:

  • The Garter carriage is only detected through a specific sequence: first detecting Lace followed by Knit pattern in a specific position (due to magnet placement)
  • Once detected as Garter, there's no code path that changes the carriage type back to another type
  • The carriage type is only modified in two scenarios:
    1. Initial detection when m_carriage is NoCarriage
    2. Specific Garter carriage detection sequence

The assumption in the code is valid - once a Garter carriage is detected, the type remains stable.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if carriage type can change after Garter detection

# Search for places where carriage type is modified
echo "Searching for carriage type modifications..."
rg -A 5 "Carriage::(Garter|NoCarriage)" --type cpp

# Search for relevant test cases
echo "Searching for related test cases..."
rg -A 5 "TEST.*Garter.*carriage" --type cpp

Length of output: 911


Script:

#!/bin/bash
# Let's search for all places where m_carriage is assigned or modified
echo "Searching for m_carriage assignments..."
rg -A 5 "m_carriage\s*=" --type cpp

# Let's also look for the Carriage enum definition
echo "Searching for Carriage enum definition..."
rg -B 5 -A 5 "enum\s+class\s+Carriage" --type cpp

# Search for carriage detection logic
echo "Searching for carriage detection logic..."
rg -B 5 "setCarriage|detectCarriage" --type cpp

Length of output: 5903

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.

1 participant