connectDevice method

Future<bool> connectDevice({
  1. String targetDevice = '',
  2. bool isStrict = false,
})

Implementation

Future<bool> connectDevice(
    {String targetDevice = '', bool isStrict = false}) async {
  if (isSimulator) {
    isSimulatorConnected = true;
    return true;
  }

  /// 0. initialize
  device = null;
  'Device is set to $device'.log;

  /// 1. devices which are connected
  final connected = await findConnectedDevices();

  device = connected
      .where((device) => device.remoteId.str == targetDevice)
      .firstOrNull;
  if (device != null) return true;

  if (!isStrict && device == null) {
    device = connected.firstOrNull;
  }
  if (device != null) return true;

  /// 2. perform scanning process
  final scanned = await findScannedDevices();

  device = scanned
      .where((r) => r.device.remoteId.str == targetDevice)
      .firstOrNull
      ?.device;
  if (device != null) {
    await device?.connect();
    'Device named ${device?.platformName} has been connected'.log;
    setDevice?.call(device!);
    return true;
  }

  if (!isStrict && device == null) {
    device = scanned.firstOrNull?.device;
  }

  if (device != null) {
    await device?.connect();
    'Device named ${device?.platformName} has been connected'.log;
    setDevice?.call(device!);
    return true;
  }

  /// 3. fail to connect device
  return false;
}