Skip to content

Commit e22fbb7

Browse files
Fix: BLE connection only allowed one update without app restart
1 parent f20a1dd commit e22fbb7

File tree

3 files changed

+44
-22
lines changed

3 files changed

+44
-22
lines changed

lib/bademagic_module/bluetooth/connect_state.dart

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,13 @@ class ConnectState extends RetryBleState {
1212
@override
1313
Future<BleState?> processState() async {
1414
bool connected = false;
15-
15+
try {
16+
await scanResult.device.disconnect();
17+
logger.d("Pre-emptive disconnect for clean state");
18+
await Future.delayed(const Duration(seconds: 1));
19+
} catch (_) {
20+
// Ignore disconnect errors
21+
}
1622
try {
1723
await scanResult.device.connect(autoConnect: false);
1824
BluetoothConnectionState connectionState =

lib/bademagic_module/bluetooth/scan_state.dart

Lines changed: 33 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@ import 'dart:async';
22
import 'package:badgemagic/bademagic_module/bluetooth/connect_state.dart';
33
import 'package:badgemagic/bademagic_module/bluetooth/datagenerator.dart';
44
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
5-
65
import 'base_ble_state.dart';
76

87
class ScanState extends NormalBleState {
98
final DataTransferManager manager;
9+
1010
ScanState({required this.manager});
1111

1212
@override
@@ -17,59 +17,72 @@ class ScanState extends NormalBleState {
1717
Completer<BleState?> nextStateCompleter = Completer();
1818
bool isCompleted = false;
1919

20-
ScanResult? foundDevice;
21-
2220
try {
2321
subscription = FlutterBluePlus.scanResults.listen(
2422
(results) async {
25-
if (!isCompleted) {
26-
if (results.isNotEmpty) {
27-
foundDevice = results.firstWhere(
23+
if (!isCompleted && results.isNotEmpty) {
24+
try {
25+
final foundDevice = results.firstWhere(
2826
(result) => result.advertisementData.serviceUuids
2927
.contains(Guid("0000fee0-0000-1000-8000-00805f9b34fb")),
28+
orElse: () => throw Exception("Matching device not found."),
3029
);
31-
if (foundDevice != null) {
32-
toast.showToast('Device found. Connecting...');
33-
isCompleted = true;
34-
nextStateCompleter.complete(ConnectState(
35-
scanResult: foundDevice!,
36-
manager: manager,
37-
));
38-
}
30+
toast.showToast('Device found. Connecting...');
31+
isCompleted = true;
32+
await FlutterBluePlus.stopScan();
33+
nextStateCompleter.complete(ConnectState(
34+
scanResult: foundDevice,
35+
manager: manager,
36+
));
37+
38+
toast.showToast('Device found. Connecting...');
39+
isCompleted = true;
40+
FlutterBluePlus.stopScan();
41+
42+
nextStateCompleter.complete(ConnectState(
43+
scanResult: foundDevice,
44+
manager: manager,
45+
));
46+
} catch (e) {
47+
//ignore and keep scanning
3948
}
4049
}
4150
},
42-
onError: (e) async {
51+
onError: (e) {
4352
if (!isCompleted) {
4453
isCompleted = true;
54+
FlutterBluePlus.stopScan();
4555
logger.e("Scan error: $e");
4656
toast.showErrorToast('Scan error occurred.');
47-
nextStateCompleter.completeError(e);
57+
nextStateCompleter
58+
.completeError(Exception("Error during scanning: $e"));
4859
}
4960
},
5061
);
5162

5263
await FlutterBluePlus.startScan(
5364
withServices: [Guid("0000fee0-0000-1000-8000-00805f9b34fb")],
54-
removeIfGone: Duration(seconds: 5),
65+
removeIfGone: const Duration(seconds: 5),
5566
continuousUpdates: true,
56-
timeout: const Duration(seconds: 15), // Reduced scan timeout
67+
timeout: const Duration(seconds: 15),
5768
);
5869

5970
await Future.delayed(const Duration(seconds: 1));
6071

61-
// If no device is found after the scan timeout, complete with an error.
6272
if (!isCompleted) {
73+
isCompleted = true;
74+
FlutterBluePlus.stopScan();
6375
toast.showToast('Device not found.');
6476
nextStateCompleter.completeError(Exception('Device not found.'));
6577
}
6678

6779
return await nextStateCompleter.future;
6880
} catch (e) {
6981
logger.e("Exception during scanning: $e");
70-
throw Exception("please check the device is turned on and retry.");
82+
throw Exception("Please check if the device is turned on and retry.");
7183
} finally {
7284
await subscription?.cancel();
85+
await FlutterBluePlus.stopScan();
7386
}
7487
}
7588
}

lib/bademagic_module/bluetooth/write_state.dart

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,16 +27,19 @@ class WriteState extends NormalBleState {
2727
for (int attempt = 1; attempt <= 3; attempt++) {
2828
try {
2929
await characteristic.write(chunk, withoutResponse: false);
30+
logger.d("Chunk written successfully: $chunk");
3031
success = true;
3132
break;
3233
} catch (e) {
33-
logger.e("Write failed, retrying ($attempt/3): $e");
34+
logger.e("Write failed (attempt $attempt/3): $e");
3435
}
3536
}
3637
if (!success) {
3738
throw Exception("Failed to transfer data. Please try again.");
3839
}
40+
await Future.delayed(Duration(milliseconds: 50));
3941
}
42+
4043
logger.d("Characteristic written successfully");
4144
return CompletedState(
4245
isSuccess: true, message: "Data transferred successfully");

0 commit comments

Comments
 (0)