getCurrentConnectionState method
Fetches the current connection state of a Bluetooth Low Energy (BLE) device.
The deviceAddress
parameter specifies the MAC address of the target device.
This method calls the 'getCurrentConnectionState' method on the native Android implementation via a method channel. It then returns a Future that resolves to the ConnectionState enum, which represents the current connection state of the device.
Returns a Future containing the ConnectionState representing the current connection state of the BLE device with the specified address.
Implementation
@override
Future<BleConnectionState> getCurrentConnectionState(
String deviceAddress,
) async {
try {
// Invoke the method channel to fetch the current connection state for the BLE device.
final String connectionStateString = await channel.invokeMethod('getCurrentConnectionState', {
'address': deviceAddress,
}) as String;
// Convert the string received from Kotlin to the Dart enum value.
return BleConnectionState.values.firstWhere((e) => e.identifier == connectionStateString);
} on PlatformException catch (e) {
// Handle different error types accordingly.
if (e.message?.contains('permissions') ?? false) {
throw BluetoothPermissionException('Permission error: ${e.message}');
} else {
throw BluetoothConnectionException(
'Failed to get current connection state: ${e.message}',
);
}
}
}