forked from fossasia/badgemagic-app
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase_ble_state.dart
More file actions
66 lines (56 loc) · 1.62 KB
/
base_ble_state.dart
File metadata and controls
66 lines (56 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import 'package:badgemagic/bademagic_module/bluetooth/completed_state.dart';
import 'package:badgemagic/bademagic_module/utils/toast_utils.dart';
import 'package:logger/logger.dart';
abstract class BleState {
Future<BleState?> process();
}
abstract class NormalBleState extends BleState {
final logger = Logger();
final toast = ToastUtils();
Future<BleState?> processState();
@override
Future<BleState?> process() async {
try {
return await processState();
} on Exception catch (e) {
String errorMessage = e.toString().replaceFirst('Exception: ', '');
return CompletedState(
isSuccess: false,
message: errorMessage,
shouldDisconnect: true,
);
}
}
}
abstract class RetryBleState extends BleState {
final logger = Logger();
final toast = ToastUtils();
final _maxRetries = 3;
Future<BleState?> processState();
@override
Future<BleState?> process() async {
int attempt = 0;
Exception? lastException;
while (attempt < _maxRetries) {
try {
return await processState();
} on Exception catch (e) {
logger.e(e);
lastException = e;
attempt++;
if (attempt < _maxRetries) {
logger.d("Retrying ($attempt/$_maxRetries)...");
} else {
logger.e("Max retries reached. Last exception: $lastException");
lastException =
Exception("Max retries reached. Last exception: $lastException");
}
}
}
return CompletedState(
isSuccess: false,
message: lastException?.toString() ?? "Unknown error",
shouldDisconnect: true,
);
}
}