xcdevice.dart 25.4 KB
Newer Older
1 2 3 4 5 6
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

7
import 'package:meta/meta.dart';
8 9 10 11 12 13 14 15 16 17
import 'package:process/process.dart';

import '../artifacts.dart';
import '../base/io.dart';
import '../base/logger.dart';
import '../base/platform.dart';
import '../base/process.dart';
import '../build_info.dart';
import '../cache.dart';
import '../convert.dart';
18
import '../device.dart';
19
import '../globals.dart' as globals;
20 21 22 23 24 25 26
import '../ios/devices.dart';
import '../ios/ios_deploy.dart';
import '../ios/iproxy.dart';
import '../ios/mac.dart';
import '../reporting/reporting.dart';
import 'xcode.dart';

27 28 29 30 31 32 33 34 35 36 37 38
class XCDeviceEventNotification {
  XCDeviceEventNotification(
    this.eventType,
    this.eventInterface,
    this.deviceIdentifier,
  );

  final XCDeviceEvent eventType;
  final XCDeviceEventInterface eventInterface;
  final String deviceIdentifier;
}

39 40 41 42 43
enum XCDeviceEvent {
  attach,
  detach,
}

44 45 46 47 48 49 50 51 52 53 54 55 56
enum XCDeviceEventInterface {
  usb(name: 'usb', connectionInterface: DeviceConnectionInterface.attached),
  wifi(name: 'wifi', connectionInterface: DeviceConnectionInterface.wireless);

  const XCDeviceEventInterface({
    required this.name,
    required this.connectionInterface,
  });

  final String name;
  final DeviceConnectionInterface connectionInterface;
}

57 58 59
/// A utility class for interacting with Xcode xcdevice command line tools.
class XCDevice {
  XCDevice({
60 61 62 63 64 65 66
    required Artifacts artifacts,
    required Cache cache,
    required ProcessManager processManager,
    required Logger logger,
    required Xcode xcode,
    required Platform platform,
    required IProxy iproxy,
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
  }) : _processUtils = ProcessUtils(logger: logger, processManager: processManager),
      _logger = logger,
      _iMobileDevice = IMobileDevice(
        artifacts: artifacts,
        cache: cache,
        logger: logger,
        processManager: processManager,
      ),
      _iosDeploy = IOSDeploy(
        artifacts: artifacts,
        cache: cache,
        logger: logger,
        platform: platform,
        processManager: processManager,
      ),
      _iProxy = iproxy,
      _xcode = xcode {

    _setupDeviceIdentifierByEventStream();
  }

  void dispose() {
89 90
    _usbDeviceObserveProcess?.kill();
    _wifiDeviceObserveProcess?.kill();
91 92
    _usbDeviceWaitProcess?.kill();
    _wifiDeviceWaitProcess?.kill();
93 94 95 96 97 98 99 100 101
  }

  final ProcessUtils _processUtils;
  final Logger _logger;
  final IMobileDevice _iMobileDevice;
  final IOSDeploy _iosDeploy;
  final Xcode _xcode;
  final IProxy _iProxy;

102
  List<Object>? _cachedListResults;
103 104 105 106

  Process? _usbDeviceObserveProcess;
  Process? _wifiDeviceObserveProcess;
  StreamController<XCDeviceEventNotification>? _observeStreamController;
107

108 109 110 111 112 113
  @visibleForTesting
  StreamController<XCDeviceEventNotification>? waitStreamController;

  Process? _usbDeviceWaitProcess;
  Process? _wifiDeviceWaitProcess;

114
  void _setupDeviceIdentifierByEventStream() {
115
    // _observeStreamController Should always be available for listeners
116
    // in case polling needs to be stopped and restarted.
117
    _observeStreamController = StreamController<XCDeviceEventNotification>.broadcast(
118 119 120 121 122 123 124
      onListen: _startObservingTetheredIOSDevices,
      onCancel: _stopObservingTetheredIOSDevices,
    );
  }

  bool get isInstalled => _xcode.isInstalledAndMeetsVersionCheck;

125
  Future<List<Object>?> _getAllDevices({
126
    bool useCache = false,
127
    required Duration timeout,
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
  }) async {
    if (!isInstalled) {
      _logger.printTrace("Xcode not found. Run 'flutter doctor' for more information.");
      return null;
    }
    if (useCache && _cachedListResults != null) {
      return _cachedListResults;
    }
    try {
      // USB-tethered devices should be found quickly. 1 second timeout is faster than the default.
      final RunResult result = await _processUtils.run(
        <String>[
          ..._xcode.xcrunCommand(),
          'xcdevice',
          'list',
          '--timeout',
          timeout.inSeconds.toString(),
        ],
        throwOnError: true,
      );
      if (result.exitCode == 0) {
149 150
        final String listOutput = result.stdout;
        try {
151
          final List<Object> listResults = (json.decode(result.stdout) as List<Object?>).whereType<Object>().toList();
152 153 154 155 156 157 158
          _cachedListResults = listResults;
          return listResults;
        } on FormatException {
          // xcdevice logs errors and crashes to stdout.
          _logger.printError('xcdevice returned non-JSON response: $listOutput');
          return null;
        }
159 160 161 162 163 164 165 166 167 168 169 170 171
      }
      _logger.printTrace('xcdevice returned an error:\n${result.stderr}');
    } on ProcessException catch (exception) {
      _logger.printTrace('Process exception running xcdevice list:\n$exception');
    } on ArgumentError catch (exception) {
      _logger.printTrace('Argument exception running xcdevice list:\n$exception');
    }

    return null;
  }

  /// Observe identifiers (UDIDs) of devices as they attach and detach.
  ///
172 173 174
  /// Each attach and detach event contains information on the event type,
  /// the event interface, and the device identifer.
  Stream<XCDeviceEventNotification>? observedDeviceEvents() {
175 176 177 178
    if (!isInstalled) {
      _logger.printTrace("Xcode not found. Run 'flutter doctor' for more information.");
      return null;
    }
179
    return _observeStreamController?.stream;
180 181 182 183 184 185 186 187 188
  }

  // Attach: d83d5bc53967baa0ee18626ba87b6254b2ab5418
  // Attach: 00008027-00192736010F802E
  // Detach: d83d5bc53967baa0ee18626ba87b6254b2ab5418
  final RegExp _observationIdentifierPattern = RegExp(r'^(\w*): ([\w-]*)$');

  Future<void> _startObservingTetheredIOSDevices() async {
    try {
189
      if (_usbDeviceObserveProcess != null || _wifiDeviceObserveProcess != null) {
190 191 192
        throw Exception('xcdevice observe restart failed');
      }

193 194
      _usbDeviceObserveProcess = await _startObserveProcess(
        XCDeviceEventInterface.usb,
195 196
      );

197 198 199 200 201 202 203 204
      _wifiDeviceObserveProcess = await _startObserveProcess(
        XCDeviceEventInterface.wifi,
      );

      final Future<void> usbProcessExited = _usbDeviceObserveProcess!.exitCode.then((int status) {
        _logger.printTrace('xcdevice observe --usb exited with code $exitCode');
        // Kill other process in case only one was killed.
        _wifiDeviceObserveProcess?.kill();
205
      });
206 207 208 209 210

      final Future<void> wifiProcessExited = _wifiDeviceObserveProcess!.exitCode.then((int status) {
        _logger.printTrace('xcdevice observe --wifi exited with code $exitCode');
        // Kill other process in case only one was killed.
        _usbDeviceObserveProcess?.kill();
211
      });
212 213 214 215 216 217

      unawaited(Future.wait(<Future<void>>[
        usbProcessExited,
        wifiProcessExited,
      ]).whenComplete(() async {
        if (_observeStreamController?.hasListener ?? false) {
218
          // Tell listeners the process died.
219
          await _observeStreamController?.close();
220
        }
221 222
        _usbDeviceObserveProcess = null;
        _wifiDeviceObserveProcess = null;
223 224 225 226 227

        // Reopen it so new listeners can resume polling.
        _setupDeviceIdentifierByEventStream();
      }));
    } on ProcessException catch (exception, stackTrace) {
228
      _observeStreamController?.addError(exception, stackTrace);
229
    } on ArgumentError catch (exception, stackTrace) {
230
      _observeStreamController?.addError(exception, stackTrace);
231 232 233
    }
  }

234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
  Future<Process> _startObserveProcess(XCDeviceEventInterface eventInterface) {
    // Run in interactive mode (via script) to convince
    // xcdevice it has a terminal attached in order to redirect stdout.
    return _streamXCDeviceEventCommand(
      <String>[
        'script',
        '-t',
        '0',
        '/dev/null',
        ..._xcode.xcrunCommand(),
        'xcdevice',
        'observe',
        '--${eventInterface.name}',
      ],
      prefix: 'xcdevice observe --${eventInterface.name}: ',
      mapFunction: (String line) {
        final XCDeviceEventNotification? event = _processXCDeviceStdOut(
          line,
          eventInterface,
        );
        if (event != null) {
          _observeStreamController?.add(event);
        }
        return line;
      },
    );
  }

  /// Starts the command and streams stdout/stderr from the child process to
  /// this process' stdout/stderr.
  ///
  /// If [mapFunction] is present, all lines are forwarded to [mapFunction] for
  /// further processing.
  Future<Process> _streamXCDeviceEventCommand(
    List<String> cmd, {
    String prefix = '',
    StringConverter? mapFunction,
  }) async {
    final Process process = await _processUtils.start(cmd);

    final StreamSubscription<String> stdoutSubscription = process.stdout
      .transform<String>(utf8.decoder)
      .transform<String>(const LineSplitter())
      .listen((String line) {
        String? mappedLine = line;
        if (mapFunction != null) {
          mappedLine = mapFunction(line);
        }
        if (mappedLine != null) {
          final String message = '$prefix$mappedLine';
          _logger.printTrace(message);
        }
      });
    final StreamSubscription<String> stderrSubscription = process.stderr
      .transform<String>(utf8.decoder)
      .transform<String>(const LineSplitter())
      .listen((String line) {
        String? mappedLine = line;
        if (mapFunction != null) {
          mappedLine = mapFunction(line);
        }
        if (mappedLine != null) {
          _logger.printError('$prefix$mappedLine', wrap: false);
        }
      });

    unawaited(process.exitCode.whenComplete(() {
      stdoutSubscription.cancel();
      stderrSubscription.cancel();
    }));

    return process;
  }

  void _stopObservingTetheredIOSDevices() {
    _usbDeviceObserveProcess?.kill();
    _wifiDeviceObserveProcess?.kill();
  }

313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
  XCDeviceEventNotification? _processXCDeviceStdOut(
    String line,
    XCDeviceEventInterface eventInterface,
  ) {
    // xcdevice observe example output of UDIDs:
    //
    // Listening for all devices, on both interfaces.
    // Attach: d83d5bc53967baa0ee18626ba87b6254b2ab5418
    // Attach: 00008027-00192736010F802E
    // Detach: d83d5bc53967baa0ee18626ba87b6254b2ab5418
    // Attach: d83d5bc53967baa0ee18626ba87b6254b2ab5418
    final RegExpMatch? match = _observationIdentifierPattern.firstMatch(line);
    if (match != null && match.groupCount == 2) {
      final String verb = match.group(1)!.toLowerCase();
      final String identifier = match.group(2)!;
      if (verb.startsWith('attach')) {
        return XCDeviceEventNotification(
          XCDeviceEvent.attach,
          eventInterface,
          identifier,
        );
      } else if (verb.startsWith('detach')) {
        return XCDeviceEventNotification(
          XCDeviceEvent.detach,
          eventInterface,
          identifier,
        );
      }
    }
    return null;
  }

  /// Wait for a connect event for a specific device. Must use device's exact UDID.
  ///
  /// To cancel this process, call [cancelWaitForDeviceToConnect].
  Future<XCDeviceEventNotification?> waitForDeviceToConnect(
    String deviceId,
  ) async {
    try {
      if (_usbDeviceWaitProcess != null || _wifiDeviceWaitProcess != null) {
        throw Exception('xcdevice wait restart failed');
      }

      waitStreamController = StreamController<XCDeviceEventNotification>();

358 359
      _usbDeviceWaitProcess = await _startWaitProcess(
        deviceId,
360 361
        XCDeviceEventInterface.usb,
      );
362 363 364

      _wifiDeviceWaitProcess = await _startWaitProcess(
        deviceId,
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
        XCDeviceEventInterface.wifi,
      );

      final Future<void> usbProcessExited = _usbDeviceWaitProcess!.exitCode.then((int status) {
        _logger.printTrace('xcdevice wait --usb exited with code $exitCode');
        // Kill other process in case only one was killed.
        _wifiDeviceWaitProcess?.kill();
      });

      final Future<void> wifiProcessExited = _wifiDeviceWaitProcess!.exitCode.then((int status) {
        _logger.printTrace('xcdevice wait --wifi exited with code $exitCode');
        // Kill other process in case only one was killed.
        _usbDeviceWaitProcess?.kill();
      });

      final Future<void> allProcessesExited = Future.wait(
          <Future<void>>[
            usbProcessExited,
            wifiProcessExited,
          ]).whenComplete(() async {
        _usbDeviceWaitProcess = null;
        _wifiDeviceWaitProcess = null;
        await waitStreamController?.close();
      });

      return await Future.any(
        <Future<XCDeviceEventNotification?>>[
          allProcessesExited.then((_) => null),
          waitStreamController!.stream.first.whenComplete(() async {
            cancelWaitForDeviceToConnect();
          }),
        ],
      );
    } on ProcessException catch (exception, stackTrace) {
      _logger.printTrace('Process exception running xcdevice wait:\n$exception\n$stackTrace');
    } on ArgumentError catch (exception, stackTrace) {
      _logger.printTrace('Process exception running xcdevice wait:\n$exception\n$stackTrace');
    } on StateError {
      _logger.printTrace('Stream broke before first was found');
      return null;
    }
    return null;
  }

409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
  Future<Process> _startWaitProcess(String deviceId, XCDeviceEventInterface eventInterface) {
    // Run in interactive mode (via script) to convince
    // xcdevice it has a terminal attached in order to redirect stdout.
    return _streamXCDeviceEventCommand(
      <String>[
        'script',
        '-t',
        '0',
        '/dev/null',
        ..._xcode.xcrunCommand(),
        'xcdevice',
        'wait',
        '--${eventInterface.name}',
        deviceId,
      ],
      prefix: 'xcdevice wait --${eventInterface.name}: ',
      mapFunction: (String line) {
        final XCDeviceEventNotification? event = _processXCDeviceStdOut(
          line,
          eventInterface,
        );
        if (event != null && event.eventType == XCDeviceEvent.attach) {
          waitStreamController?.add(event);
        }
        return line;
      },
    );
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
  }

  void cancelWaitForDeviceToConnect() {
    _usbDeviceWaitProcess?.kill();
    _wifiDeviceWaitProcess?.kill();
  }

  /// A list of [IOSDevice]s. This list includes connected devices and
  /// disconnected wireless devices.
  ///
  /// Sometimes devices may have incorrect connection information
  /// (`isConnected`, `connectionInterface`) if it timed out before it could get the
  /// information. Wireless devices can take longer to get the correct
  /// information.
  ///
451
  /// [timeout] defaults to 2 seconds.
452 453
  Future<List<IOSDevice>> getAvailableIOSDevices({ Duration? timeout }) async {
    final List<Object>? allAvailableDevices = await _getAllDevices(timeout: timeout ?? const Duration(seconds: 2));
454

455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
    if (allAvailableDevices == null) {
      return const <IOSDevice>[];
    }

    // [
    //  {
    //    "simulator" : true,
    //    "operatingSystemVersion" : "13.3 (17K446)",
    //    "available" : true,
    //    "platform" : "com.apple.platform.appletvsimulator",
    //    "modelCode" : "AppleTV5,3",
    //    "identifier" : "CBB5E1ED-2172-446E-B4E7-F2B5823DBBA6",
    //    "architecture" : "x86_64",
    //    "modelName" : "Apple TV",
    //    "name" : "Apple TV"
    //  },
    //  {
    //    "simulator" : false,
    //    "operatingSystemVersion" : "13.3 (17C54)",
    //    "interface" : "usb",
    //    "available" : true,
    //    "platform" : "com.apple.platform.iphoneos",
    //    "modelCode" : "iPhone8,1",
    //    "identifier" : "d83d5bc53967baa0ee18626ba87b6254b2ab5418",
    //    "architecture" : "arm64",
    //    "modelName" : "iPhone 6s",
    //    "name" : "iPhone"
    //  },
    //  {
    //    "simulator" : true,
    //    "operatingSystemVersion" : "6.1.1 (17S445)",
    //    "available" : true,
    //    "platform" : "com.apple.platform.watchsimulator",
    //    "modelCode" : "Watch5,4",
    //    "identifier" : "2D74FB11-88A0-44D0-B81E-C0C142B1C94A",
    //    "architecture" : "i386",
    //    "modelName" : "Apple Watch Series 5 - 44mm",
    //    "name" : "Apple Watch Series 5 - 44mm"
    //  },
    // ...

    final List<IOSDevice> devices = <IOSDevice>[];
497 498
    for (final Object device in allAvailableDevices) {
      if (device is Map<String, Object?>) {
499 500 501 502
        // Only include iPhone, iPad, iPod, or other iOS devices.
        if (!_isIPhoneOSDevice(device)) {
          continue;
        }
503 504 505 506 507
        final String? identifier = device['identifier'] as String?;
        final String? name = device['name'] as String?;
        if (identifier == null || name == null) {
          continue;
        }
508

509
        bool isConnected = true;
510
        final Map<String, Object?>? errorProperties = _errorProperties(device);
511
        if (errorProperties != null) {
512 513 514 515 516 517
          final String? errorMessage = _parseErrorMessage(errorProperties);
          if (errorMessage != null) {
            if (errorMessage.contains('not paired')) {
              UsageEvent('device', 'ios-trust-failure', flutterUsage: globals.flutterUsage).send();
            }
            _logger.printTrace(errorMessage);
518
          }
519

520
          final int? code = _errorCode(errorProperties);
521 522 523 524 525

          // Temporary error -10: iPhone is busy: Preparing debugger support for iPhone.
          // Sometimes the app launch will fail on these devices until Xcode is done setting up the device.
          // Other times this is a false positive and the app will successfully launch despite the error.
          if (code != -10) {
526
            isConnected = false;
527
          }
528 529
        }

530
        String? sdkVersion = _sdkVersion(device);
531 532

        if (sdkVersion != null) {
533
          final String? buildVersion = _buildVersion(device);
534 535 536 537 538
          if (buildVersion != null) {
            sdkVersion = '$sdkVersion $buildVersion';
          }
        }

539
        devices.add(IOSDevice(
540 541
          identifier,
          name: name,
542
          cpuArchitecture: _cpuArchitecture(device),
543
          connectionInterface: _interfaceType(device),
544
          isConnected: isConnected,
545
          sdkVersion: sdkVersion,
546 547 548 549 550 551 552
          iProxy: _iProxy,
          fileSystem: globals.fs,
          logger: _logger,
          iosDeploy: _iosDeploy,
          iMobileDevice: _iMobileDevice,
          platform: globals.platform,
        ));
553 554 555 556 557 558 559
      }
    }
    return devices;
  }

  /// Despite the name, com.apple.platform.iphoneos includes iPhone, iPads, and all iOS devices.
  /// Excludes simulators.
560 561 562
  static bool _isIPhoneOSDevice(Map<String, Object?> deviceProperties) {
    final Object? platform = deviceProperties['platform'];
    if (platform is String) {
563 564 565 566 567
      return platform == 'com.apple.platform.iphoneos';
    }
    return false;
  }

568 569 570
  static Map<String, Object?>? _errorProperties(Map<String, Object?> deviceProperties) {
    final Object? error = deviceProperties['error'];
    return error is Map<String, Object?> ? error : null;
571 572
  }

573 574 575 576
  static int? _errorCode(Map<String, Object?>? errorProperties) {
    if (errorProperties == null) {
      return null;
    }
577 578
    final Object? code = errorProperties['code'];
    return code is int ? code : null;
579 580
  }

581 582 583 584 585
  static DeviceConnectionInterface _interfaceType(Map<String, Object?> deviceProperties) {
    // Interface can be "usb" or "network". It can also be missing
    // (e.g. simulators do not have an interface property).
    // If the interface is "network", use `DeviceConnectionInterface.wireless`,
    // otherwise use `DeviceConnectionInterface.attached.
586
    final Object? interface = deviceProperties['interface'];
587 588
    if (interface is String && interface.toLowerCase() == 'network') {
      return DeviceConnectionInterface.wireless;
589
    }
590
    return DeviceConnectionInterface.attached;
591 592
  }

593 594 595
  static String? _sdkVersion(Map<String, Object?> deviceProperties) {
    final Object? operatingSystemVersion = deviceProperties['operatingSystemVersion'];
    if (operatingSystemVersion is String) {
596 597 598
      // Parse out the OS version, ignore the build number in parentheses.
      // "13.3 (17C54)"
      final RegExp operatingSystemRegex = RegExp(r'(.*) \(.*\)$');
599
      if (operatingSystemRegex.hasMatch(operatingSystemVersion.trim())) {
600 601 602 603 604 605 606
        return operatingSystemRegex.firstMatch(operatingSystemVersion.trim())?.group(1);
      }
      return operatingSystemVersion;
    }
    return null;
  }

607 608 609
  static String? _buildVersion(Map<String, Object?> deviceProperties) {
    final Object? operatingSystemVersion = deviceProperties['operatingSystemVersion'];
    if (operatingSystemVersion is String) {
610 611 612
      // Parse out the build version, for example 17C54 from "13.3 (17C54)".
      final RegExp buildVersionRegex = RegExp(r'\(.*\)$');
      return buildVersionRegex.firstMatch(operatingSystemVersion)?.group(0)?.replaceAll(RegExp('[()]'), '');
613 614 615 616
    }
    return null;
  }

617 618 619 620
  DarwinArch _cpuArchitecture(Map<String, Object?> deviceProperties) {
    DarwinArch? cpuArchitecture;
    final Object? architecture = deviceProperties['architecture'];
    if (architecture is String) {
621 622 623 624 625 626 627 628 629 630 631 632
      try {
        cpuArchitecture = getIOSArchForName(architecture);
      } on Exception {
        // Fallback to default iOS architecture. Future-proof against a
        // theoretical version of Xcode that changes this string to something
        // slightly different like "ARM64", or armv7 variations like
        // armv7s and armv7f.
        if (architecture.startsWith('armv7')) {
          cpuArchitecture = DarwinArch.armv7;
        } else {
          cpuArchitecture = DarwinArch.arm64;
        }
633
        _logger.printWarning(
634 635 636 637 638
          'Unknown architecture $architecture, defaulting to '
          '${getNameForDarwinArch(cpuArchitecture)}',
        );
      }
    }
639
    return cpuArchitecture ?? DarwinArch.arm64;
640 641 642
  }

  /// Error message parsed from xcdevice. null if no error.
643
  static String? _parseErrorMessage(Map<String, Object?>? errorProperties) {
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
    //  {
    //    "simulator" : false,
    //    "operatingSystemVersion" : "13.3 (17C54)",
    //    "interface" : "usb",
    //    "available" : false,
    //    "platform" : "com.apple.platform.iphoneos",
    //    "modelCode" : "iPhone8,1",
    //    "identifier" : "98206e7a4afd4aedaff06e687594e089dede3c44",
    //    "architecture" : "arm64",
    //    "modelName" : "iPhone 6s",
    //    "name" : "iPhone",
    //    "error" : {
    //      "code" : -9,
    //      "failureReason" : "",
    //      "underlyingErrors" : [
    //        {
    //          "code" : 5,
    //          "failureReason" : "allowsSecureServices: 1. isConnected: 0. Platform: <DVTPlatform:0x7f804ce32880:'com.apple.platform.iphoneos':<DVTFilePath:0x7f804ce32800:'\/Users\/magder\/Applications\/Xcode_11-3-1.app\/Contents\/Developer\/Platforms\/iPhoneOS.platform'>>. DTDKDeviceIdentifierIsIDID: 0",
    //          "description" : "📱<DVTiOSDevice (0x7f801f190450), iPhone, iPhone, 13.3 (17C54), d83d5bc53967baa0ee18626ba87b6254b2ab5418> -- Failed _shouldMakeReadyForDevelopment check even though device is not locked by passcode.",
    //          "recoverySuggestion" : "",
    //          "domain" : "com.apple.platform.iphoneos"
    //        }
    //      ],
    //      "description" : "iPhone is not paired with your computer.",
    //      "recoverySuggestion" : "To use iPhone with Xcode, unlock it and choose to trust this computer when prompted.",
    //      "domain" : "com.apple.platform.iphoneos"
    //    }
    //  },
    //  {
    //    "simulator" : false,
    //    "operatingSystemVersion" : "13.3 (17C54)",
    //    "interface" : "usb",
    //    "available" : false,
    //    "platform" : "com.apple.platform.iphoneos",
    //    "modelCode" : "iPhone8,1",
    //    "identifier" : "d83d5bc53967baa0ee18626ba87b6254b2ab5418",
    //    "architecture" : "arm64",
    //    "modelName" : "iPhone 6s",
    //    "name" : "iPhone",
    //    "error" : {
    //      "code" : -9,
    //      "failureReason" : "",
    //      "description" : "iPhone is not paired with your computer.",
    //      "domain" : "com.apple.platform.iphoneos"
    //    }
    //  }
    // ...

    if (errorProperties == null) {
      return null;
    }

    final StringBuffer errorMessage = StringBuffer('Error: ');

698 699
    final Object? description = errorProperties['description'];
    if (description is String) {
700 701 702 703 704 705 706 707
      errorMessage.write(description);
      if (!description.endsWith('.')) {
        errorMessage.write('.');
      }
    } else {
      errorMessage.write('Xcode pairing error.');
    }

708 709
    final Object? recoverySuggestion = errorProperties['recoverySuggestion'];
    if (recoverySuggestion is String) {
710 711 712
      errorMessage.write(' $recoverySuggestion');
    }

713
    final int? code = _errorCode(errorProperties);
714 715 716 717 718 719 720 721 722
    if (code != null) {
      errorMessage.write(' (code $code)');
    }

    return errorMessage.toString();
  }

  /// List of all devices reporting errors.
  Future<List<String>> getDiagnostics() async {
723
    final List<Object>? allAvailableDevices = await _getAllDevices(
724 725 726 727 728 729 730 731 732
      useCache: true,
      timeout: const Duration(seconds: 2)
    );

    if (allAvailableDevices == null) {
      return const <String>[];
    }

    final List<String> diagnostics = <String>[];
733 734
    for (final Object deviceProperties in allAvailableDevices) {
      if (deviceProperties is! Map<String, Object?>) {
735 736
        continue;
      }
737 738
      final Map<String, Object?>? errorProperties = _errorProperties(deviceProperties);
      final String? errorMessage = _parseErrorMessage(errorProperties);
739
      if (errorMessage != null) {
740 741 742 743 744 745 746 747
        final int? code = _errorCode(errorProperties);
        // Error -13: iPhone is not connected. Xcode will continue when iPhone is connected.
        // This error is confusing since the device is not connected and maybe has not been connected
        // for a long time. Avoid showing it.
        if (code == -13 && errorMessage.contains('not connected')) {
          continue;
        }

748 749 750 751 752 753
        diagnostics.add(errorMessage);
      }
    }
    return diagnostics;
  }
}