Skip to content

Conversation

samruddhi-Rahegaonkar
Copy link
Member

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

Fixes #1268

Changes

  • When attempting to connect to an LED badge via Bluetooth, the app displays an error message: "Please turn on Bluetooth", even though Bluetooth is already enabled on the device.
  • Modified logic in badge_message_provider.dart to ensure proper Bluetooth state handling.
  • This improves user experience by reliably handling Bluetooth connection attempts.

Screenshots / Recordings

N/A

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 Bluetooth connection handling by checking adapter state, enabling it on Android, prompting iOS users, and handling unsupported platforms gracefully.

Bug Fixes:

  • Correct Bluetooth state checks to avoid erroneous "Please turn on Bluetooth" messages when Bluetooth is on.

Enhancements:

  • Automatically enable Bluetooth on Android devices and wait for it to turn on before proceeding.
  • Prompt iOS users to enable Bluetooth in Settings and await the state change.
  • Standardize error messaging for unsupported or off Bluetooth states.
  • Add explicit handling for unsupported platforms.

Copy link
Contributor

sourcery-ai bot commented Jun 13, 2025

Reviewer's Guide

Refines Bluetooth connection handling in badge_message_provider.dart by improving status messages, adding platform-specific enablement flows, and consolidating data transfer logic once the adapter is confirmed ON.

Sequence Diagram for Enhanced Bluetooth Enablement Logic

sequenceDiagram
    title Sequence Diagram for Enhanced Bluetooth Enablement Logic
    actor User
    participant App as BadgeMessageProvider
    participant BTPlugin as FlutterBluePlus
    participant OS as OS (Android/iOS)

    User->>App: Initiate Send Message
    App->>BTPlugin: FlutterBluePlus.adapterState.first
    BTPlugin-->>App: Returns initialAdapterState

    alt initialAdapterState is not BluetoothAdapterState.on
        App->>OS: Determine Platform (Android/iOS/Other)
        alt Platform is Android
            App->>User: Toast: "Please enable Bluetooth..."
            App->>BTPlugin: FlutterBluePlus.turnOn()
            BTPlugin->>OS: System prompts/enables Bluetooth
            OS-->>BTPlugin: Bluetooth status updated to ON
            App->>BTPlugin: FlutterBluePlus.adapterState.where(state == ON).first
            BTPlugin-->>App: Confirms adapterState is ON
        else Platform is iOS
            App->>User: Toast: "Bluetooth is OFF. Please enable it from Settings."
            User->>OS: User manually enables Bluetooth in OS Settings
            OS-->>BTPlugin: Bluetooth status updated to ON
            App->>BTPlugin: FlutterBluePlus.adapterState.where(state == ON).first
            BTPlugin-->>App: Confirms adapterState is ON
        else Platform is Other (Unsupported)
            App->>User: Toast: "Unsupported platform"
            App-->>User: Operation Halts
        end
    end

    opt Bluetooth is ON (either initially or after enablement for Android/iOS)
        App->>App: generateData(...)
        App->>App: Create DataTransferManager(...)
        App->>App: transferData(...)
        App-->>User: Message transfer process initiated
    end
Loading

Updated Class Diagram for BadgeMessageProvider

classDiagram
    class BadgeMessageProvider {
        +sendMessageToDevice(jsonData: Map<String, dynamic>?, isSavedBadge: bool): Future<void>
    }
    note for BadgeMessageProvider "Internal logic updated for:
- Correct Bluetooth state detection.
- Platform-specific (Android/iOS) Bluetooth enablement prompts.
- Waiting for Bluetooth to be ON before proceeding.
- Consolidated data transfer logic after Bluetooth ON confirmation."
Loading

File-Level Changes

Change Details Files
Refined user-facing Bluetooth status messages
  • Reworded unsupported-device error toast
  • Updated Android prompt to 'Please enable Bluetooth...'
  • Enhanced iOS error toast with Settings instruction
lib/providers/badge_message_provider.dart
Introduced platform-specific Bluetooth enabling flow
  • Automatically call turnOn() and await ON state on Android
  • Await adapter state change on iOS after user enabling
  • Added fallback error for unsupported platforms
lib/providers/badge_message_provider.dart
Streamlined data preparation and transfer post-ON state
  • Moved Data generation and DataTransferManager logic outside initial check
  • Unified transferData(manager) invocation after adapter validation
lib/providers/badge_message_provider.dart

Assessment against linked issues

Issue Objective Addressed Explanation
#1268 The app should detect when Bluetooth is enabled on the device.
#1268 The app should allow connections to the LED badge when Bluetooth is enabled.
#1268 The app should not display an error message indicating that Bluetooth is off when it is actually on.

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 - here's some feedback:

  • Consider extracting the platform‐specific Bluetooth enablement and state‐waiting logic into a helper method to reduce duplication and improve readability.
  • Add a timeout or error handling when awaiting adapterState.where(...).first to avoid potential infinite waits if the user never enables Bluetooth.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Consider extracting the platform‐specific Bluetooth enablement and state‐waiting logic into a helper method to reduce duplication and improve readability.
- Add a timeout or error handling when awaiting `adapterState.where(...).first` to avoid potential infinite waits if the user never enables Bluetooth.

## Individual Comments

### Comment 1
<location> `lib/providers/badge_message_provider.dart:116` </location>
<code_context>
+        ToastUtils().showToast('Please enable Bluetooth...');
         await FlutterBluePlus.turnOn();
+
+        adapterState = await FlutterBluePlus.adapterState
+            .where((state) => state == BluetoothAdapterState.on)
+            .first;
       } else if (Platform.isIOS) {
-        ToastUtils().showToast('Please turn on Bluetooth');
</code_context>

<issue_to_address>
Awaiting adapterState change can hang indefinitely

Add a timeout or cancellation mechanism to prevent the app from hanging if Bluetooth is not enabled.
</issue_to_address>

### Comment 2
<location> `lib/providers/badge_message_provider.dart:114` </location>
<code_context>
       if (Platform.isAndroid) {
-        ToastUtils().showToast('Turning on Bluetooth...');
+        ToastUtils().showToast('Please enable Bluetooth...');
         await FlutterBluePlus.turnOn();
+
+        adapterState = await FlutterBluePlus.adapterState
</code_context>

<issue_to_address>
Wrap `turnOn()` in error handling

Consider using try/catch or result checking to handle possible exceptions from `turnOn()`.
</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 116 to 118
adapterState = await FlutterBluePlus.adapterState
.where((state) => state == BluetoothAdapterState.on)
.first;
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (bug_risk): Awaiting adapterState change can hang indefinitely

Add a timeout or cancellation mechanism to prevent the app from hanging if Bluetooth is not enabled.

if (Platform.isAndroid) {
ToastUtils().showToast('Turning on Bluetooth...');
ToastUtils().showToast('Please enable Bluetooth...');
await FlutterBluePlus.turnOn();
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (bug_risk): Wrap turnOn() in error handling

Consider using try/catch or result checking to handle possible exceptions from turnOn().

Copy link
Contributor

github-actions bot commented Jun 13, 2025

Build Status

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

Screenshots (Android)

Screenshots (iPhone)

Screenshots (iPad)

@nope3472
Copy link
Contributor

Enabling Bluetooth or performing file operations may take several seconds, but there is no indication (such as a loading spinner or progress message) to inform the user that something is happening. This could lead to confusion or repeated actions.

@samruddhi-Rahegaonkar
Copy link
Member Author

@nope3472 Thank you for the feedback. While enabling Bluetooth or performing file operations may take a few seconds, the current implementation already includes toast messages to inform the user of the ongoing actions.
Isn't It ?

@hpdang
Copy link
Member

hpdang commented Jul 31, 2025

@samruddhi-Rahegaonkar please update this

@hpdang
Copy link
Member

hpdang commented Jul 31, 2025

@nope3472 please review the latest changes

@nope3472
Copy link
Contributor

@hpdang yeah will do it

@hpdang
Copy link
Member

hpdang commented Aug 7, 2025

@samruddhi-Rahegaonkar update the branch please

fix: update Bluetooth flow as suggested by Sourcery AI
@hpdang hpdang self-requested a review August 14, 2025 11:28
@hpdang hpdang merged commit b6f51b0 into fossasia:development Aug 14, 2025
5 of 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.

fix : Bluetooth Connection Issue Despite Being Turned On
3 participants