run function

Future<void> run()

Run the adb wifi pairing process.

Implementation

Future<void> run() async {
  // On Windows the default console code page (cp850/cp1252) cannot render the
  // unicode block characters used to draw the QR code, which results in a
  // garbled output that cannot be scanned. Switch the active code page of the
  // current console to UTF-8 (65001) before printing.
  if (Platform.isWindows) {
    try {
      await Process.run('chcp', ['65001'], runInShell: true);
      stdout.encoding = const SystemEncoding();
    } catch (_) {
      // Ignore – we tried our best to enable UTF-8 output.
    }
  }

  final name = 'ADB_WIFI_${nanoid()}';
  final password = nanoid();

  _showQrCode(name: name, password: password);

  final discovered = await _discover();

  final ipv4Address = await _lookupAddress(discovered.address);
  if (ipv4Address == null) return;

  final pairOk = await _runAdbPair(
    address: ipv4Address,
    port: discovered.port,
    password: password,
  );

  print('');
  print('[adb_wifi_plus] Pair step finished (success=$pairOk).');
  print('[adb_wifi_plus] Waiting for device to advertise the connect service '
      '(_adb-tls-connect._tcp.local) ...');

  final connectService = await _discoverConnect().timeout(
    const Duration(seconds: 60),
    onTimeout: () {
      print(
        '[adb_wifi_plus] Timed out waiting for the connect mDNS announcement.\n'
        'Open your phone, go to Developer Options > Wireless debugging, and\n'
        'note the "IP address & Port" shown there, then run:\n'
        '   adb connect <ip>:<port>',
      );
      return (address: '', port: 0);
    },
  );

  if (connectService.port == 0) return;

  print('[adb_wifi_plus] Discovered connect endpoint '
      '${connectService.address}:${connectService.port}');

  final connectIp = await _lookupAddress(connectService.address) ?? ipv4Address;
  await _runAdbConnect(address: connectIp, port: connectService.port);
}