Skip to content

Commit

Permalink
Example:: additional cleanup and refactor
Browse files Browse the repository at this point in the history
Lib:: enchanced error handling, refined nullability on certain types
  • Loading branch information
okocsis committed Apr 1, 2021
1 parent 44cb104 commit 67f1b5a
Show file tree
Hide file tree
Showing 6 changed files with 108 additions and 123 deletions.
151 changes: 56 additions & 95 deletions example/lib/device_details/device_details_bloc.dart
Original file line number Diff line number Diff line change
Expand Up @@ -91,159 +91,122 @@ class DeviceDetailsBloc {

void readRssi() {
_clearLogs();
// _bleDevice.stream.listen((bleDevice) async {
PeripheralTestOperations(_bleManager, _bleDevice.peripheral, log, logError)
.testReadingRssi();
// });
PeripheralTestOperations(_bleManager, _bleDevice.peripheral, log, logError)
.testReadingRssi();
}

void discovery() {
_clearLogs();
// _bleDevice.stream.listen((bleDevice) async {
PeripheralTestOperations(_bleManager, _bleDevice.peripheral, log, logError)
.discovery();
// });
PeripheralTestOperations(_bleManager, _bleDevice.peripheral, log, logError)
.discovery();
}

void fetchConnectedDevices() {
_clearLogs();
// _bleDevice.stream.listen((bleDevice) async {
PeripheralTestOperations(_bleManager, _bleDevice.peripheral, log, logError)
.fetchConnectedDevice();
// });
PeripheralTestOperations(_bleManager, _bleDevice.peripheral, log, logError)
.fetchConnectedDevice();
}

void fetchKnownDevices() {
_clearLogs();
// _bleDevice.stream.listen((bleDevice) async {
PeripheralTestOperations(_bleManager, _bleDevice.peripheral, log, logError)
.fetchKnownDevice();
// });
PeripheralTestOperations(_bleManager, _bleDevice.peripheral, log, logError)
.fetchKnownDevice();
}

void readCharacteristicForPeripheral() {
_clearLogs();
// _bleDevice.stream.listen((bleDevice) async {
PeripheralTestOperations(_bleManager, _bleDevice.peripheral, log, logError)
.readCharacteristicForPeripheral();
// });
PeripheralTestOperations(_bleManager, _bleDevice.peripheral, log, logError)
.readCharacteristicForPeripheral();
}

void readCharacteristicForService() {
_clearLogs();
// _bleDevice.stream.listen((bleDevice) async {
PeripheralTestOperations(_bleManager, _bleDevice.peripheral, log, logError)
.readCharacteristicForService();
// });
PeripheralTestOperations(_bleManager, _bleDevice.peripheral, log, logError)
.readCharacteristicForService();
}

void readCharacteristicDirectly() {
_clearLogs();
// _bleDevice.stream.listen((bleDevice) async {
PeripheralTestOperations(_bleManager, _bleDevice.peripheral, log, logError)
.readCharacteristic();
// });
PeripheralTestOperations(_bleManager, _bleDevice.peripheral, log, logError)
.readCharacteristic();
}

void writeCharacteristicForPeripheral() {
_clearLogs();
// _bleDevice.stream.listen((bleDevice) async {
PeripheralTestOperations(_bleManager, _bleDevice.peripheral, log, logError)
.writeCharacteristicForPeripheral();
// });
PeripheralTestOperations(_bleManager, _bleDevice.peripheral, log, logError)
.writeCharacteristicForPeripheral();
}

void writeCharacteristicForService() {
_clearLogs();
// _bleDevice.stream.listen((bleDevice) async {
PeripheralTestOperations(_bleManager, _bleDevice.peripheral, log, logError)
.writeCharacteristicForService();
// });
PeripheralTestOperations(_bleManager, _bleDevice.peripheral, log, logError)
.writeCharacteristicForService();
}

void writeCharacteristicDirectly() {
_clearLogs();
// _bleDevice.stream.listen((bleDevice) async {
PeripheralTestOperations(_bleManager, _bleDevice.peripheral, log, logError)
.writeCharacteristic();
// });
PeripheralTestOperations(_bleManager, _bleDevice.peripheral, log, logError)
.writeCharacteristic();
}

void monitorCharacteristicForPeripheral() {
_clearLogs();
// _bleDevice.stream.listen((bleDevice) async {
PeripheralTestOperations(_bleManager, _bleDevice.peripheral, log, logError)
.monitorCharacteristicForPeripheral();
// });
}

void monitorCharacteristicForService() {
_clearLogs();
// _bleDevice.stream.listen((bleDevice) async {
PeripheralTestOperations(_bleManager, _bleDevice.peripheral, log, logError)
.monitorCharacteristicForService();
// });
PeripheralTestOperations(_bleManager, _bleDevice.peripheral, log, logError)
.monitorCharacteristicForService();
}

void monitorCharacteristicDirectly() {
_clearLogs();
// _bleDevice.stream.listen((bleDevice) async {
PeripheralTestOperations(_bleManager, _bleDevice.peripheral, log, logError)
.monitorCharacteristic();
// });
PeripheralTestOperations(_bleManager, _bleDevice.peripheral, log, logError)
.monitorCharacteristic();
}

void disableBluetooth() {
_clearLogs();
// _bleDevice.stream.listen((bleDevice) async {
PeripheralTestOperations(_bleManager, _bleDevice.peripheral, log, logError)
.disableBluetooth();
// });
PeripheralTestOperations(_bleManager, _bleDevice.peripheral, log, logError)
.disableBluetooth();
}

void enableBluetooth() {
_clearLogs();
// _bleDevice.stream.listen((bleDevice) async {
PeripheralTestOperations(_bleManager, _bleDevice.peripheral, log, logError)
.enableBluetooth();
// });
PeripheralTestOperations(_bleManager, _bleDevice.peripheral, log, logError)
.enableBluetooth();
}

void fetchBluetoothState() {
_clearLogs();
// _bleDevice.stream.listen((bleDevice) async {
PeripheralTestOperations(_bleManager, _bleDevice.peripheral, log, logError)
.fetchBluetoothState();
// });
PeripheralTestOperations(_bleManager, _bleDevice.peripheral, log, logError)
.fetchBluetoothState();
}

Future<void> connect() async {
_clearLogs();
// _bleDevice.stream.listen((bleDevice) async {
var peripheral = _bleDevice.peripheral;

peripheral
.observeConnectionState(
emitCurrentValue: true, completeOnDisconnect: true)
.listen((connectionState) {
log('Observed new connection state: \n$connectionState');
_connectionStateController.add(connectionState);
});

try {
log("Connecting to ${peripheral.name}");
await peripheral.connect();
log("Connected!");
} on BleError catch (e) {
logError(e.toString());
}
// });
var peripheral = _bleDevice.peripheral;

peripheral
.observeConnectionState(
emitCurrentValue: true, completeOnDisconnect: true)
.listen((connectionState) {
log('Observed new connection state: \n$connectionState');
_connectionStateController.add(connectionState);
});

try {
log("Connecting to ${peripheral.name}");
await peripheral.connect();
log("Connected!");
} on BleError catch (e) {
logError(e.toString());
}
}

void dispose() async {
// await _bleDevice.drain();
// _bleDevice.close();

await _connectionStateController.drain();
_connectionStateController.close();
}
Expand Down Expand Up @@ -276,17 +239,15 @@ class DeviceDetailsBloc {
void startAutoTest() {
_clearLogs();

// _bleDevice.stream.listen((bleDevice) {
Fimber.d("got bleDevice: $_bleDevice");
_bleDevice.peripheral.isConnected().then((isConnected) {
Fimber.d('The device is connected: $isConnected');
if (!isConnected) {
_connectTo(_bleDevice);
}
}).catchError((error) {
logError('Connection problem: ${error.toString()}');
});
// });
Fimber.d("got bleDevice: $_bleDevice");
_bleDevice.peripheral.isConnected().then((isConnected) {
Fimber.d('The device is connected: $isConnected');
if (!isConnected) {
_connectTo(_bleDevice);
}
}).catchError((error) {
logError('Connection problem: ${error.toString()}');
});
}

void _clearLogs() {
Expand Down
12 changes: 7 additions & 5 deletions example/lib/devices_list/devices_bloc.dart
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,7 @@ class DevicesBloc {
BleManager? bleManager
})
: _deviceRepository = deviceRepository ?? DeviceRepository(),
_bleManager = bleManager ?? BleManager() {

}
_bleManager = bleManager ?? BleManager();

bool clientCreated = false;

Expand All @@ -49,7 +47,7 @@ class DevicesBloc {
_visibleDevicesController.close();
_devicePickerController.close();
_scanSubscription?.cancel();
_bleManager.destroyClient();
// _bleManager.destroyClient();
}

void init() {
Expand Down Expand Up @@ -103,7 +101,11 @@ class DevicesBloc {

Future<void> _checkPermissions() async {
if (Platform.isAndroid) {
if (await Permission.location.isGranted) {
var locGranted = await Permission.location.isGranted;
if (locGranted == false) {
locGranted = (await Permission.location.request()).isGranted;
}
if (locGranted == false) {
return Future.error(Exception("Location permission not granted"));
}
}
Expand Down
4 changes: 1 addition & 3 deletions example/lib/model/ble_device.dart
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@ class BleDevice {
@override
bool operator ==(other) =>
other is BleDevice &&
this.name != null &&
other.name != null &&
compareAsciiLowerCase(this.name, other.name) == 0 &&
this.id == other.id;

Expand All @@ -39,7 +37,7 @@ extension on ScanResult {
DeviceCategory get category {
if (name == "SensorTag") {
return DeviceCategory.sensorTag;
} else if (name != null && name.startsWith("Hex")) {
} else if (name.startsWith("Hex")) {
return DeviceCategory.hex;
} else {
return DeviceCategory.other;
Expand Down
2 changes: 1 addition & 1 deletion lib/peripheral.dart
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class Peripheral {
static const int NO_MTU_NEGOTIATION = 0;
final ManagerForPeripheral _manager;

String name;
String? name;
String identifier;

Peripheral.fromJson(Map<String, dynamic> json, ManagerForPeripheral manager)
Expand Down
51 changes: 35 additions & 16 deletions lib/scan_result.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,26 +14,43 @@ abstract class _ScanResultMetadata {

/// A scan result emitted by the scanning operation, containing [Peripheral] and [AdvertisementData].
class ScanResult {
Peripheral peripheral;
final Peripheral peripheral;

/// Signal strength of the peripheral in dBm.
int rssi;
final int rssi;

/// An indicator whether the peripheral is connectable (iOS only).
bool isConnectable;
late final bool isConnectable;

/// A list of UUIDs found in the overflow area of the advertisement data (iOS only).
List<String> overflowServiceUuids;
late final List<String> overflowServiceUuids;

/// A packet of data advertised by the peripheral.
AdvertisementData advertisementData;

ScanResult.fromJson(Map<String, dynamic> json, ManagerForPeripheral manager)
: peripheral = Peripheral.fromJson(json, manager),
rssi = json[_ScanResultMetadata.rssi],
isConnectable = json[_ScanResultMetadata.isConnectable],
overflowServiceUuids = json[_ScanResultMetadata.overflowServiceUuids],
advertisementData = AdvertisementData._fromJson(json);
final AdvertisementData advertisementData;

ScanResult._(
this.peripheral,
this.rssi,
this.advertisementData,
{bool? isConnectable,
List<String>? overflowServiceUuids,
}) : isConnectable = isConnectable ?? false,
overflowServiceUuids = overflowServiceUuids ?? <String>[];


factory ScanResult.fromJson(
Map<String, dynamic?> json,
ManagerForPeripheral manager
) {
assert(json[_ScanResultMetadata.rssi] is int);
return ScanResult._(
Peripheral.fromJson(json, manager),
json[_ScanResultMetadata.rssi],
AdvertisementData._fromJson(json),
isConnectable: json[_ScanResultMetadata.isConnectable],
overflowServiceUuids: json[_ScanResultMetadata.overflowServiceUuids]
);
}
}

/// Data advertised by the [Peripheral]: power level, local name,
Expand All @@ -50,10 +67,10 @@ class AdvertisementData {

/// The local name of the [Peripheral]. Might be different than
/// [Peripheral.name].
String localName;
String? localName;

/// The transmit power of the peripheral.
int txPowerLevel;
int? txPowerLevel;

/// A list of solicited service UUIDs.
List<String>? solicitedServiceUuids;
Expand All @@ -67,8 +84,10 @@ class AdvertisementData {
_mapToListOfStringsOrNull(json[_ScanResultMetadata.serviceUuids]),
localName = json[_ScanResultMetadata.localName],
txPowerLevel = json[_ScanResultMetadata.txPowerLevel],
solicitedServiceUuids = _mapToListOfStringsOrNull(
json[_ScanResultMetadata.solicitedServiceUuids]);
solicitedServiceUuids =
_mapToListOfStringsOrNull(
json[_ScanResultMetadata.solicitedServiceUuids]
);

static Map<String, Uint8List>? _getServiceDataOrNull(
Map<String, dynamic>? serviceData) {
Expand Down
11 changes: 8 additions & 3 deletions lib/src/bridge/device_connection_mixin.dart
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,14 @@ mixin DeviceConnectionMixin on FlutterBLE {
.invokeMethod(MethodName.isDeviceConnected, <String, dynamic>{
ArgumentName.deviceIdentifier: peripheralIdentifier,
}).catchError(
(errorJson) => Future.error(
BleError.fromJson(jsonDecode(errorJson.details)),
),
(errorJson) {
if (errorJson is MissingPluginException) {
return Future.error(errorJson);
}
return Future.error(
BleError.fromJson(jsonDecode(errorJson.details))
);
}
);
}

Expand Down

0 comments on commit 67f1b5a

Please sign in to comment.