Skip to content

Conversation

samruddhi-Rahegaonkar
Copy link
Member

@samruddhi-Rahegaonkar samruddhi-Rahegaonkar commented Jun 18, 2025

Fixes #1329

Changes

  • Fixed BLE reconnection issue where app required restart for each update
  • Added pre-emptive disconnect before connecting to ensure clean BLE state
  • Ensured FlutterBluePlus.stopScan() is properly called to prevent multiple connections
  • Added minor delay between chunk writes for better stability

Screenshots / Recordings

Checklist:

  • No hard coding: I have used resources from constants.dart without hard coding any value.
  • No end of file edits: No modifications done at end of resource files.
  • Code reformatting: I have reformatted code and fixed indentation in every file included in this pull request.
  • Code analyzation: My code passes analyzations run in flutter analyze and tests run in flutter test.

Summary by Sourcery

Fix BLE reconnection flow to allow repeated updates without restarting the app and refine dialog layout adjustments.

Bug Fixes:

  • Allow BLE connections to reconnect without requiring an app restart after each update.

Enhancements:

  • Preemptively disconnect the device before connecting and ensure FlutterBluePlus.stopScan() is called on success, error and finally to maintain a clean BLE state.
  • Add minor delay between data chunk writes with improved logging for better stability.
  • Refactor DeleteBadgeDialog layout by replacing fixed container sizing with responsive padding and adjusted spacings.

Summary by Sourcery

Improve BLE reconnection flow to allow repeated firmware updates without restarting the app and refine the badge deletion dialog layout

Bug Fixes:

  • Enable BLE reconnections without requiring an app restart after each update

Enhancements:

  • Preemptively disconnect any existing BLE connection before attempting a new connect
  • Ensure FlutterBluePlus.stopScan() is called on scan success, error, and cleanup for a clean BLE state
  • Add a minor delay between BLE data chunk writes and improve logging for transfer stability
  • Refactor DeleteBadgeDialog to use responsive padding and dynamic sizing instead of fixed dimensions

Copy link
Contributor

sourcery-ai bot commented Jun 18, 2025

Reviewer's Guide

This PR overhauls the BLE reconnection flow by ensuring preemptive cleanup in scan and connect states (calling stopScan and disconnect appropriately), refines write operations with added logging and chunk delays for stability, and updates the delete dialog to use responsive padding and adjusted spacings.

Sequence diagram for improved BLE reconnection flow

sequenceDiagram
    actor User
    participant App
    participant FlutterBluePlus
    participant BLEDevice

    User->>App: Initiate BLE update
    App->>FlutterBluePlus: stopScan() (preemptive)
    App->>BLEDevice: disconnect() (preemptive)
    App->>FlutterBluePlus: startScan()
    FlutterBluePlus-->>App: scanResults
    App->>FlutterBluePlus: stopScan() (on device found or error)
    App->>BLEDevice: connect()
    BLEDevice-->>App: connectionState
    App->>BLEDevice: write data in chunks (with delay)
    BLEDevice-->>App: write response
    App-->>User: Show success or error message
Loading

Class diagram for updated BLE state classes

classDiagram
    class NormalBleState
    class ScanState {
        +DataTransferManager manager
        +Future<BleState?> processState()
    }
    class ConnectState {
        +ScanResult scanResult
        +DataTransferManager manager
        +Future<BleState?> processState()
    }
    class WriteState {
        +BluetoothCharacteristic characteristic
        +List<List<int>> chunks
        +Future<BleState?> processState()
    }
    NormalBleState <|-- ScanState
    NormalBleState <|-- WriteState
    RetryBleState <|-- ConnectState
    class RetryBleState
    class BleState
    ScanState ..> DataTransferManager
    ConnectState ..> ScanResult
    ConnectState ..> DataTransferManager
    WriteState ..> BluetoothCharacteristic
Loading

File-Level Changes

Change Details Files
Robust BLE scanning with clean state management
  • Combined scan result checks and exception handling
  • Added stopScan calls before completing or erroring the scan
  • Ensured stopScan is invoked on error, timeout, and in finally block
scan_state.dart
Preemptive device disconnect before BLE connect
  • Called device.disconnect() with a short delay for a clean state
  • Wrapped disconnect in try/catch to ignore errors
connect_state.dart
Enhanced BLE write stability with delays and logging
  • Logged successful chunk writes and detailed retry errors
  • Inserted a 50ms delay between chunk write attempts
write_state.dart
Refactored delete dialog to use responsive layout
  • Replaced fixed container sizing with Padding and mainAxisSize.min
  • Adjusted vertical spacings and used Expanded for text rows
badge_delete_dialog.dart

Assessment against linked issues

Issue Objective Addressed Explanation
#1329 The app should allow multiple text updates to the connected badge via BLE without requiring an app restart.
#1329 The app should allow connecting to another device after disconnecting from the current one without requiring an app restart.

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @samruddhi-Rahegaonkar - I've reviewed your changes and they look great!

Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments

### Comment 1
<location> `lib/bademagic_module/bluetooth/scan_state.dart:32` </location>
<code_context>
+                orElse: () => throw Exception("Matching device not found."),
               );
-              if (foundDevice != null) {
-                toast.showToast('Device found. Connecting...');
-                isCompleted = true;
-                nextStateCompleter.complete(ConnectState(
-                  scanResult: foundDevice!,
-                  manager: manager,
</code_context>

<issue_to_address>
Duplicate code for handling found device should be removed.

Executing this logic twice may cause issues like repeated toasts or state changes. Please remove the duplicate block to prevent this.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines 32 to 34
await FlutterBluePlus.stopScan();
nextStateCompleter.complete(ConnectState(
scanResult: foundDevice,
Copy link
Contributor

Choose a reason for hiding this comment

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

issue: Duplicate code for handling found device should be removed.

Executing this logic twice may cause issues like repeated toasts or state changes. Please remove the duplicate block to prevent this.

Copy link
Contributor

github-actions bot commented Jun 18, 2025

Build Status

Build successful. APKs to test: https://github.com/fossasia/badgemagic-app/actions/runs/16806247721/artifacts/3710904334.

Screenshots (Android)

Screenshots (iPhone)

Screenshots (iPad)

@@ -12,7 +12,13 @@ class ConnectState extends RetryBleState {
@override
Future<BleState?> processState() async {
bool connected = false;

try {
Copy link
Contributor

Choose a reason for hiding this comment

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

did you verify this change because I dont think so that it will work by just disconnecting before. We already have this removeIfGone property ro handle this case.

nope3472

This comment was marked as off-topic.

@samruddhi-Rahegaonkar samruddhi-Rahegaonkar force-pushed the issue#329 branch 2 times, most recently from 4e0ed3a to 96960e5 Compare June 26, 2025 11:57
fix: duplicate logic removed

fix: Squashed all commits into one

fix: removed comments
@samruddhi-Rahegaonkar
Copy link
Member Author

@Jhalakupadhyay I have tested it on badge its working fine!

@Jhalakupadhyay
Copy link
Contributor

@samruddhi-Rahegaonkar update the branch and I will merge it

@hpdang
Copy link
Member

hpdang commented Jul 31, 2025

@samruddhi-Rahegaonkar please update the branch

Copy link
Contributor

@nope3472 nope3472 left a comment

Choose a reason for hiding this comment

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

This looks good just add
-Error Handling for Disconnects
-Ensure Disconnect After Write

@samruddhi-Rahegaonkar
Copy link
Member Author

@nope3472 Everywhere There is a Error Handling in the code and it disconnects after write.

@samruddhi-Rahegaonkar
Copy link
Member Author

@hpdang This one is also good to merge.

@hpdang hpdang merged commit 197e0ce into fossasia:development Aug 7, 2025
6 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.

BLE Connection Allows Only One Update – Requires App Restart for Reconnect or Text Update
4 participants