connect method
Future<ConnectionStatus>
connect(
- BlueDevice device, {
- Duration timeout = const Duration(seconds: 5),
When connecting, reassign value selectedDevice from parameter device
and if connection time more than timeout
will return ConnectionStatus.timeout
When connection success, will return ConnectionStatus.connected
Implementation
Future<ConnectionStatus> connect(
BlueDevice device, {
Duration timeout = const Duration(seconds: 5),
}) async {
selectedDevice = device;
try {
if (Platform.isAndroid) {
final blue_thermal.BluetoothDevice bluetoothDeviceAndroid =
blue_thermal.BluetoothDevice(
selectedDevice?.name ?? '', selectedDevice?.address ?? '');
await _bluetoothAndroid?.connect(bluetoothDeviceAndroid);
} else if (Platform.isIOS) {
_bluetoothDeviceIOS = flutter_blue.BluetoothDevice.fromProto(
proto.BluetoothDevice(
name: selectedDevice?.name ?? '',
remoteId: selectedDevice?.address ?? '',
type: proto.BluetoothDevice_Type.valueOf(selectedDevice?.type ?? 0),
),
);
final List<flutter_blue.BluetoothDevice> connectedDevices =
await _bluetoothIOS?.connectedDevices ??
<flutter_blue.BluetoothDevice>[];
final int deviceConnectedIndex = connectedDevices
.indexWhere((flutter_blue.BluetoothDevice bluetoothDevice) {
return bluetoothDevice.id == _bluetoothDeviceIOS?.id;
});
if (deviceConnectedIndex < 0) {
await _bluetoothDeviceIOS?.connect();
}
}
_isConnected = true;
selectedDevice?.connected = true;
return Future<ConnectionStatus>.value(ConnectionStatus.connected);
} on Exception catch (error) {
print('$runtimeType - Error $error');
_isConnected = false;
selectedDevice?.connected = false;
return Future<ConnectionStatus>.value(ConnectionStatus.timeout);
}
}