Skip to content

hslink: add button trigger reset #67

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

Merged
merged 5 commits into from
Aug 6, 2025
Merged

Conversation

kaidegit
Copy link
Collaborator

@kaidegit kaidegit commented Aug 5, 2025

Summary by CodeRabbit

  • New Features

    • Added hardware reset functionalities, including software, power-on, and pin reset options.
    • Integrated MultiTimer for improved timer-driven operations and button event handling.
    • Enhanced single button click behavior to trigger different reset actions based on mode settings.
  • Chores

    • Added and configured the MultiTimer third-party component to the project build system.
    • Updated build configurations to include new source files and submodules.

@kaidegit kaidegit requested a review from HalfSweet August 5, 2025 14:50
Copy link

coderabbitai bot commented Aug 5, 2025

Walkthrough

This change adds the MultiTimer component as a new Git submodule and integrates it into the build system. It introduces new source and header files implementing hardware reset functions, relocating reset logic from existing files. Button event handling is migrated from manual polling to timer-driven callbacks using MultiTimer. Build configuration and header inclusions are updated accordingly.

Changes

Cohort / File(s) Change Summary
MultiTimer Integration
.gitmodules, projects/HSLink-Pro/third_party_components/MultiTimer/MultiTimer, projects/HSLink-Pro/third_party_components/CMakeLists.txt, projects/HSLink-Pro/third_party_components/MultiTimer/CMakeLists.txt
Added MultiTimer as a Git submodule, updated third-party component CMake files to include MultiTimer sources.
Reset Logic Refactor and Implementation
projects/HSLink-Pro/src/dp_common.c, projects/HSLink-Pro/src/dp_common.h, projects/HSLink-Pro/src/reset_way.cpp, projects/HSLink-Pro/src/reset_way.h
Removed software_reset and por_reset from dp_common, implemented these and a new srst_reset in reset_way.cpp; updated declarations accordingly.
Build System Updates
projects/HSLink-Pro/src/CMakeLists.txt
Added reset_way.cpp to the application source files list.
Header Inclusion Update
projects/HSLink-Pro/src/DAP_config.h
Added #include "reset_way.h" before the reset pin output function definition.
Button and Timer Logic Enhancement
projects/HSLink-Pro/src/HSLink_Pro_expansion.cpp
Replaced manual button tick polling with a MultiTimer-driven callback; enhanced button single-click handler to invoke reset functions based on reset mode.
Main Application Timer Integration
projects/HSLink-Pro/src/main.cpp
Initialized MultiTimer system with millis callback and created a 5 ms board timer invoking multiTimerYield() periodically.

Sequence Diagram(s)

Button Single Click Reset Flow (New Logic)

sequenceDiagram
    participant User as User
    participant Button as Button
    participant MultiTimer as MultiTimer
    participant HSLink_Pro_expansion as HSLink_Pro_expansion
    participant reset_way as reset_way

    User->>Button: Single click
    Button->>MultiTimer: Event detected (via timer)
    MultiTimer->>HSLink_Pro_expansion: button_ticks() callback
    HSLink_Pro_expansion->>HSLink_Pro_expansion: Button event handler
    alt Reset mode: SRST
        HSLink_Pro_expansion->>reset_way: srst_reset()
    else Reset mode: Software
        HSLink_Pro_expansion->>reset_way: software_reset()
    else Reset mode: POR
        HSLink_Pro_expansion->>reset_way: por_reset()
    end
Loading

MultiTimer Integration in Main Application

sequenceDiagram
    participant main_cpp as main.cpp
    participant MultiTimer as MultiTimer
    participant BoardTimer as Board Timer (5ms)

    main_cpp->>MultiTimer: Install with millis callback
    main_cpp->>BoardTimer: Create timer (5ms interval)
    BoardTimer->>MultiTimer: multiTimerYield() (every 5ms)
    MultiTimer->>MultiTimer: Process timer callbacks (e.g., button_ticks)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

In the warren where code bunnies dwell,
Timers now tick and buttons reset well.
With MultiTimer’s hop, events never lag,
Old reset logic packed in a new bag.
From polling to callbacks, the flow is refined—
A carrot for progress, in source lines we find! 🥕

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fda1263 and 96b813f.

📒 Files selected for processing (1)
  • projects/HSLink-Pro/src/reset_way.cpp (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • projects/HSLink-Pro/src/reset_way.cpp
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

🧹 Nitpick comments (2)
projects/HSLink-Pro/third_party_components/MultiTimer/MultiTimer (1)

1-1: Consider vendoring vs. submodule to reduce operational overhead.

Submodules complicate cloning, CI, and downstream forks. If MultiTimer is small and rarely updated, pulling the source directly (or using a package manager) may simplify maintenance.

projects/HSLink-Pro/src/HSLink_Pro_expansion.cpp (1)

433-438: Consider timer interval alignment.

The button timer uses a 10ms interval, but the main timer in main.cpp uses 5ms. Consider aligning intervals or documenting the rationale for different intervals to optimize system timing.

-    multiTimerStart(&timer_btn, 10, true, button_ticks_, NULL);
+    multiTimerStart(&timer_btn, 5, true, button_ticks_, NULL);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3ea472c and fda1263.

📒 Files selected for processing (12)
  • .gitmodules (1 hunks)
  • projects/HSLink-Pro/src/CMakeLists.txt (1 hunks)
  • projects/HSLink-Pro/src/DAP_config.h (1 hunks)
  • projects/HSLink-Pro/src/HSLink_Pro_expansion.cpp (3 hunks)
  • projects/HSLink-Pro/src/dp_common.c (0 hunks)
  • projects/HSLink-Pro/src/dp_common.h (1 hunks)
  • projects/HSLink-Pro/src/main.cpp (2 hunks)
  • projects/HSLink-Pro/src/reset_way.cpp (1 hunks)
  • projects/HSLink-Pro/src/reset_way.h (1 hunks)
  • projects/HSLink-Pro/src/third_party_components/CMakeLists.txt (1 hunks)
  • projects/HSLink-Pro/third_party_components/MultiTimer/CMakeLists.txt (1 hunks)
  • projects/HSLink-Pro/third_party_components/MultiTimer/MultiTimer (1 hunks)
💤 Files with no reviewable changes (1)
  • projects/HSLink-Pro/src/dp_common.c
🔇 Additional comments (13)
projects/HSLink-Pro/third_party_components/MultiTimer/MultiTimer (1)

1-1: Validate submodule metadata (.gitmodules, license, reproducibility).

The file only records the pinned commit (fe77487…) but gives no visibility into:

  1. Whether .gitmodules was updated with the correct URL/branch.
  2. The upstream licence compatibility with HSLink-Pro.
  3. Whether we intend to track a tag/release instead of a floating SHA for long-term reproducibility.

Please double-check these points before merge.

projects/HSLink-Pro/src/dp_common.h (1)

10-10: LGTM - Code refactoring aligns with modularization.

The removal of reset function declarations from this header is appropriate as they've been moved to the dedicated reset_way.h module. This improves code organization and separation of concerns.

projects/HSLink-Pro/src/CMakeLists.txt (1)

95-95: LGTM - Proper integration of new reset module.

The addition of reset_way.cpp to the build configuration is necessary and correctly placed among other source files to support the new reset functionality.

.gitmodules (1)

28-30: Submodule configuration verified

  • The GitHub URL returns a 301 redirect (expected for .git endpoints), confirming the repo is accessible
  • The submodule directory is present at projects/HSLink-Pro/third_party_components/MultiTimer/MultiTimer
  • Follows existing submodule patterns—no further changes needed
projects/HSLink-Pro/src/third_party_components/CMakeLists.txt (2)

26-27: Clarify the crc32 component addition.

The crc32 component addition wasn't mentioned in the PR objectives or AI summary. Please verify if this is intentionally part of this PR or if it should be in a separate change.


28-28: LGTM - MultiTimer integration follows established pattern.

The MultiTimer subdirectory addition is correctly configured and aligns with the PR objective to integrate timer-based button handling.

projects/HSLink-Pro/src/DAP_config.h (1)

638-638: LGTM - Proper header inclusion for refactored reset functionality.

The inclusion of reset_way.h is correctly placed before the PIN_nRESET_OUT function that uses the reset functions (software_reset() and por_reset() on lines 650 and 653). This supports the code refactoring that moved reset functionality to a dedicated module.

projects/HSLink-Pro/third_party_components/MultiTimer/CMakeLists.txt (1)

1-2: LGTM! Clean third-party component integration.

The CMake configuration correctly sets up the MultiTimer component with proper include path and source file compilation.

projects/HSLink-Pro/src/main.cpp (2)

14-14: LGTM! Proper header inclusion.

The MultiTimer header is correctly included to support the timer functionality.


73-74: Audit MultiTimer callback ISR safety

The only multiTimerStart callbacks found are:

  • projects/HSLink-Pro/src/reset_way.cpp
    timer_cb lambdas calling Power_Turn(...) and gpio_write_pin(...)
  • projects/HSLink-Pro/src/HSLink_Pro_expansion.cpp
    button_ticks_ lambda calling button_ticks()

Please confirm that all three routines—Power_Turn(), gpio_write_pin(), and button_ticks()—are safe to invoke in an ISR context (no blocking calls, minimal execution time). If any perform heavy work or OS/API calls, defer that logic outside the ISR (e.g., post a flag or enqueue to a background task).

projects/HSLink-Pro/src/reset_way.h (1)

5-22: LGTM! Well-structured header file.

The header properly uses include guards, C++ compatibility, and appropriate function declarations. The structure follows good practices for a modular reset interface.

projects/HSLink-Pro/src/HSLink_Pro_expansion.cpp (1)

18-30: LGTM! Proper header inclusions.

The new headers correctly support the enhanced reset functionality and timer management.

projects/HSLink-Pro/src/reset_way.cpp (1)

22-31: LGTM! Correct software reset implementation.

The function properly checks debug port type and implements ARM Cortex-M system reset via AIRCR register with appropriate error handling.

Comment on lines +411 to +419
if (SETTING_GET_RESET_MODE(HSLink_Setting.reset, RESET_NRST)) {
srst_reset();
}
if (SETTING_GET_RESET_MODE(HSLink_Setting.reset, RESET_ARM_SWD_SOFT)) {
software_reset();
}
if (SETTING_GET_RESET_MODE(HSLink_Setting.reset, RESET_POR)) {
por_reset();
}
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify reset function ISR safety.

The button callback now calls reset functions (srst_reset(), software_reset(), por_reset()) which will execute in ISR context due to the timer-driven approach. Ensure these functions are ISR-safe and don't perform blocking operations.


🏁 Script executed:

#!/bin/bash
# Description: Analyze reset functions for ISR safety
# Expected: Functions should be lightweight and avoid blocking operations

echo "=== Checking reset function implementations ==="
ast-grep --pattern 'uint8_t software_reset(void) {
  $$$
}'

ast-grep --pattern 'void por_reset(void) {
  $$$
}'

ast-grep --pattern 'void srst_reset(void) {
  $$$
}'

Length of output: 275


🏁 Script executed:

#!/bin/bash
echo "=== Locating reset function implementations ==="
rg -n "software_reset" -C5
rg -n "por_reset" -C5
rg -n "srst_reset" -C5

Length of output: 9914


Heavy reset calls in ISR: software_reset() and por_reset() are not ISR-safe

software_reset() (reset_way.cpp:22–31) invokes swd_read_word() and swd_write_word(), which perform bit-banged SWD transfers with inherent delays.
por_reset() (reset_way.cpp:33–43) calls Power_Turn() and multiTimerStart(), scheduling timers and manipulating power rails.
These operations can block or re-enter timer APIs and must not run in interrupt context.

• srst_reset() (reset_way.cpp:45–50) merely toggles a GPIO and is ISR-safe.
• Defer software_reset() and por_reset() to a task or the main loop (e.g., post an event or set a flag) so they execute outside the ISR.

🤖 Prompt for AI Agents
In projects/HSLink-Pro/src/HSLink_Pro_expansion.cpp around lines 411 to 419,
software_reset() and por_reset() are called directly in an ISR, but these
functions are not ISR-safe due to blocking operations and timer usage. To fix
this, remove direct calls to software_reset() and por_reset() from the ISR and
instead set flags or post events indicating these resets are needed. Then,
handle these flags or events in the main loop or a dedicated task to perform the
resets safely outside the interrupt context.

Comment on lines 33 to 43
void por_reset(void) {
if ((!VREF_ENABLE && HSLink_Setting.power.power_on)
|| VREF_ENABLE) {
Power_Turn(false);
static MultiTimer timer_;
static auto timer_cb = [](MultiTimer *timer, void *user_data) {
Power_Turn(true);
};
multiTimerStart(&timer_, 10, false, timer_cb, NULL);
}
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix potential concurrency issue with static timer.

The static MultiTimer timer_ could cause issues if por_reset() is called multiple times before the timer expires. Each call would overwrite the previous timer state.

 void por_reset(void) {
     if ((!VREF_ENABLE && HSLink_Setting.power.power_on)
         || VREF_ENABLE) {
         Power_Turn(false);
-        static MultiTimer timer_;
-        static auto timer_cb = [](MultiTimer *timer, void *user_data) {
+        static MultiTimer timer_por;
+        static bool timer_active = false;
+        if (timer_active) return; // Prevent overlapping calls
+        timer_active = true;
+        static auto timer_cb = [](MultiTimer *timer, void *user_data) {
             Power_Turn(true);
+            timer_active = false;
         };
-        multiTimerStart(&timer_, 10, false, timer_cb, NULL);
+        multiTimerStart(&timer_por, 10, false, timer_cb, NULL);
     }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
void por_reset(void) {
if ((!VREF_ENABLE && HSLink_Setting.power.power_on)
|| VREF_ENABLE) {
Power_Turn(false);
static MultiTimer timer_;
static auto timer_cb = [](MultiTimer *timer, void *user_data) {
Power_Turn(true);
};
multiTimerStart(&timer_, 10, false, timer_cb, NULL);
}
}
void por_reset(void) {
if ((!VREF_ENABLE && HSLink_Setting.power.power_on)
|| VREF_ENABLE) {
Power_Turn(false);
static MultiTimer timer_por;
static bool timer_active = false;
if (timer_active)
return; // Prevent overlapping calls
timer_active = true;
static auto timer_cb = [](MultiTimer *timer, void *user_data) {
Power_Turn(true);
timer_active = false;
};
multiTimerStart(&timer_por, 10, false, timer_cb, NULL);
}
}
🤖 Prompt for AI Agents
In projects/HSLink-Pro/src/reset_way.cpp around lines 33 to 43, the static
MultiTimer timer_ inside por_reset() can cause concurrency issues if por_reset()
is called multiple times before the timer expires, as it reuses the same timer
instance. To fix this, avoid using a static timer variable; instead, allocate a
new MultiTimer instance for each call or manage timer instances to ensure they
do not overwrite each other, preventing state conflicts.

Comment on lines 45 to 62
void srst_reset(void) {
gpio_write_pin(
HPM_FGPIO,
GPIO_GET_PORT_INDEX(PIN_SRST),
GPIO_GET_PIN_INDEX(PIN_SRST),
!HSLink_Global.reset_level
);
static MultiTimer timer_;
static auto timer_cb = [](MultiTimer *timer, void *user_data) {
gpio_write_pin(
HPM_FGPIO,
GPIO_GET_PORT_INDEX(PIN_SRST),
GPIO_GET_PIN_INDEX(PIN_SRST),
HSLink_Global.reset_level
);
};
multiTimerStart(&timer_, 50, false, timer_cb, NULL);
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix potential concurrency issue with static timer.

Similar to por_reset(), the static MultiTimer timer_ could cause issues if srst_reset() is called multiple times. Also, using the same variable name timer_ in both functions could be confusing.

 void srst_reset(void) {
     gpio_write_pin(
         HPM_FGPIO,
         GPIO_GET_PORT_INDEX(PIN_SRST),
         GPIO_GET_PIN_INDEX(PIN_SRST),
         !HSLink_Global.reset_level
     );
-    static MultiTimer timer_;
-    static auto timer_cb = [](MultiTimer *timer, void *user_data) {
+    static MultiTimer timer_srst;
+    static bool timer_active = false;
+    if (timer_active) return; // Prevent overlapping calls
+    timer_active = true;
+    static auto timer_cb = [](MultiTimer *timer, void *user_data) {
         gpio_write_pin(
             HPM_FGPIO,
             GPIO_GET_PORT_INDEX(PIN_SRST),
             GPIO_GET_PIN_INDEX(PIN_SRST),
             HSLink_Global.reset_level
         );
+        timer_active = false;
     };
-    multiTimerStart(&timer_, 50, false, timer_cb, NULL);
+    multiTimerStart(&timer_srst, 50, false, timer_cb, NULL);
 }

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In projects/HSLink-Pro/src/reset_way.cpp between lines 45 and 62, the static
MultiTimer variable timer_ inside srst_reset() can cause concurrency issues if
srst_reset() is called multiple times, and sharing the same variable name with
por_reset() is confusing. To fix this, remove the static keyword from timer_ to
ensure a new timer instance is created on each call, and rename the timer
variable to a unique name like srst_timer to avoid confusion with other
functions.

@kaidegit
Copy link
Collaborator Author

kaidegit commented Aug 5, 2025

por_reset异步的话会被hsp loop输出控制回来。。

@HalfSweet
Copy link
Collaborator

引入定时器之后感觉事情就变得更复杂了……能不能换成rtt nano作为操作系统呢

@kaidegit
Copy link
Collaborator Author

kaidegit commented Aug 6, 2025

下个大版本咯

@kaidegit kaidegit merged commit 907a735 into cherry-embedded:master Aug 6, 2025
1 check 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.

2 participants