Skip to content

Commit

Permalink
Merge pull request #1 from adityastic/jhalak-sm
Browse files Browse the repository at this point in the history
chore: suggestions
  • Loading branch information
Jhalakupadhyay authored Jul 3, 2024
2 parents fd3c1da + 9cfc62f commit 999a797
Show file tree
Hide file tree
Showing 10 changed files with 163 additions and 169 deletions.
62 changes: 62 additions & 0 deletions lib/bademagic_module/bluetooth/base_ble_state.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
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) {
return CompletedState(isSuccess: false, message: e.toString());
}
}
}

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)...");
await Future.delayed(
const Duration(seconds: 2)); // Wait before retrying
} else {
logger.e("Max retries reached. Last exception: $lastException");
lastException =
Exception("Max retries reached. Last exception: $lastException");
}
}
}

// After max retries, return a CompletedState indicating failure.
return CompletedState(
isSuccess: false,
message: lastException?.toString() ?? "Unknown error");
}
}
3 changes: 0 additions & 3 deletions lib/bademagic_module/bluetooth/ble_state_interface.dart

This file was deleted.

18 changes: 18 additions & 0 deletions lib/bademagic_module/bluetooth/completed_state.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import 'package:badgemagic/bademagic_module/bluetooth/base_ble_state.dart';

class CompletedState extends NormalBleState {
final bool isSuccess;
final String message;

CompletedState({required this.isSuccess, required this.message});

@override
Future<BleState?> processState() async {
if (isSuccess) {
toast.showToast(message);
} else {
toast.showErrorToast(message);
}
return null;
}
}
19 changes: 0 additions & 19 deletions lib/bademagic_module/bluetooth/completedstate.dart

This file was deleted.

38 changes: 38 additions & 0 deletions lib/bademagic_module/bluetooth/connect_state.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import 'package:badgemagic/bademagic_module/bluetooth/write_state.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'base_ble_state.dart';

class ConnectState extends RetryBleState {
final ScanResult scanResult;

ConnectState({required this.scanResult});

@override
Future<BleState?> processState() async {
bool connected = false;

try {
await scanResult.device.connect(autoConnect: false);
BluetoothConnectionState connectionState =
await scanResult.device.connectionState.first;

if (connectionState == BluetoothConnectionState.connected) {
connected = true;

logger.d("Device connected");
toast.showToast('Device connected successfully.');

return WriteState(device: scanResult.device);
} else {
throw Exception("Failed to connect to the device");
}
} catch (e) {
toast.showErrorToast('Failed to connect retry');
rethrow;
} finally {
if (!connected) {
await scanResult.device.disconnect();
}
}
}
}
53 changes: 0 additions & 53 deletions lib/bademagic_module/bluetooth/connectstate.dart

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,22 +1,18 @@
import 'dart:async';
import 'package:badgemagic/bademagic_module/bluetooth/connectstate.dart';
import 'package:badgemagic/bademagic_module/bluetooth/connect_state.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:logger/logger.dart';
import 'ble_state_interface.dart';
import 'bletoast.dart';

class ScanState implements BleState {
ScanResult? foundDevice;
final Logger logger = Logger();
BleStateToast toast = BleStateToast();
import 'base_ble_state.dart';

class ScanState extends NormalBleState {
@override
Future<BleState?> processState() async {
StreamSubscription<List<ScanResult>>? subscription;
toast.successToast("Searching for device...");
toast.showToast("Searching for device...");

Completer<BleState?> nextStateCompleter = Completer();

ScanResult? foundDevice;

try {
subscription = FlutterBluePlus.scanResults.listen(
(results) async {
Expand All @@ -26,20 +22,22 @@ class ScanState implements BleState {
.contains(Guid("0000fee0-0000-1000-8000-00805f9b34fb")),
);
if (foundDevice != null) {
toast.successToast('Device found. Connecting...');
if (!nextStateCompleter.isCompleted) {
nextStateCompleter
.complete(ConnectState(scanResult: foundDevice!));
}
toast.showToast('Device found. Connecting...');
nextStateCompleter
.complete(ConnectState(scanResult: foundDevice!));
} else {
nextStateCompleter
.completeError(Exception('BLE LED Device not found.'));
}
} else {
nextStateCompleter
.completeError(Exception('No BLE Devices not found.'));
}
},
onError: (e) async {
logger.e("Scan error: $e");
toast.failureToast('Scan error occurred.');
if (!nextStateCompleter.isCompleted) {
nextStateCompleter.complete(null);
}
toast.showErrorToast('Scan error occurred.');
nextStateCompleter.completeError(e);
},
);

Expand All @@ -49,15 +47,13 @@ class ScanState implements BleState {
);

await Future.delayed(const Duration(seconds: 6));

return await nextStateCompleter.future;
} catch (e) {
logger.e("Exception during scanning: $e");
throw Exception("Exception during scanning: $e");
} finally {
await subscription?.cancel();
}

if (!nextStateCompleter.isCompleted) {
nextStateCompleter.complete(
foundDevice != null ? ConnectState(scanResult: foundDevice!) : null);
}

return nextStateCompleter.future;
}
}
Original file line number Diff line number Diff line change
@@ -1,20 +1,12 @@
import 'package:badgemagic/bademagic_module/bluetooth/datagenerator.dart';
import 'package:badgemagic/providers/cardsprovider.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:get_it/get_it.dart';
import 'package:logger/logger.dart';
import 'ble_state_interface.dart';
import 'bletoast.dart';
import 'completedstate.dart';
import 'base_ble_state.dart';
import 'completed_state.dart';

class WriteState implements BleState {
class WriteState extends NormalBleState {
final BluetoothDevice device;
final Logger logger = Logger();

GetIt getIt = GetIt.instance;
final CardProvider cardData = GetIt.instance<CardProvider>();
DataTransferManager manager = DataTransferManager();
BleStateToast toast = BleStateToast();

WriteState({required this.device});

Expand Down Expand Up @@ -53,11 +45,10 @@ class WriteState implements BleState {
}
}
}
return CompletedState(
isSuccess: false, message: "Please use the correct Badge");
throw Exception("Please use the correct Badge");
} catch (e) {
logger.e("Failed to write characteristic: $e");
throw Exception("Failed to write characteristic: $e");
}
return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import 'package:badgemagic/providers/cardsprovider.dart';
import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';

class BleStateToast {
class ToastUtils {
CardProvider contextProvider = GetIt.instance<CardProvider>();

//create a toast message for success state of BLE
void successToast(String message) {
// Create a toast message
void showToast(String message) {
ScaffoldMessenger.of(contextProvider.getContext()!).showSnackBar(
SnackBar(
margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
Expand Down Expand Up @@ -38,36 +38,8 @@ class BleStateToast {
);
}

//show toast for failure state of BLE
void failureToast(String message) {
ScaffoldMessenger.of(contextProvider.getContext()!).showSnackBar(
SnackBar(
margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
elevation: 10,
duration: const Duration(seconds: 1),
content: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Image(
image: AssetImage('assets/icons/icon.png'),
height: 20,
),
const SizedBox(
width: 10,
),
Text(
message,
style: const TextStyle(color: Colors.black),
)
],
),
backgroundColor: Colors.white,
behavior: SnackBarBehavior.floating,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
dismissDirection: DismissDirection.startToEnd,
),
);
// Create a error toast
void showErrorToast(String message) {
showToast('Error: $message');
}
}
Loading

0 comments on commit 999a797

Please sign in to comment.