android_device_discovery.dart 6.01 KB
Newer Older
1 2 3 4
// 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.

5 6
// @dart = 2.8

7
import 'package:meta/meta.dart';
8
import 'package:process/process.dart';
9 10

import '../base/common.dart';
11
import '../base/file_system.dart';
12 13
import '../base/io.dart';
import '../base/logger.dart';
14
import '../base/platform.dart';
15
import '../base/process.dart';
16
import '../base/user_messages.dart';
17 18 19 20
import '../device.dart';
import 'adb.dart';
import 'android_device.dart';
import 'android_sdk.dart';
21
import 'android_workflow.dart';
22

23
/// Device discovery for Android physical devices and emulators.
24 25 26 27 28 29
///
/// This class primarily delegates to the `adb` command line tool provided by
/// the Android SDK to discover instances of connected android devices.
///
/// See also:
///   * [AndroidDevice], the type of discovered device.
30 31
class AndroidDevices extends PollingDeviceDiscovery {
  AndroidDevices({
32 33 34 35
    @required AndroidWorkflow androidWorkflow,
    @required ProcessManager processManager,
    @required Logger logger,
    @required AndroidSdk androidSdk,
36 37 38
    @required FileSystem fileSystem,
    @required Platform platform,
    @required UserMessages userMessages,
39 40
  }) : _androidWorkflow = androidWorkflow,
       _androidSdk = androidSdk,
41
       _processUtils = ProcessUtils(
42 43
         logger: logger,
         processManager: processManager,
44
        ),
45 46
        _processManager = processManager,
        _logger = logger,
47 48 49 50
        _fileSystem = fileSystem,
        _platform = platform,
        _userMessages = userMessages,
        super('Android devices');
51 52 53 54

  final AndroidWorkflow _androidWorkflow;
  final ProcessUtils _processUtils;
  final AndroidSdk _androidSdk;
55 56 57 58
  final ProcessManager _processManager;
  final Logger _logger;
  final FileSystem _fileSystem;
  final Platform _platform;
59
  final UserMessages _userMessages;
60 61

  @override
62
  bool get supportsPlatform => _androidWorkflow.appliesToHostPlatform;
63 64 65 66 67 68

  @override
  bool get canListAnything => _androidWorkflow.canListDevices;

  @override
  Future<List<Device>> pollingGetDevices({ Duration timeout }) async {
69
    if (_doesNotHaveAdb()) {
70 71 72 73
      return <AndroidDevice>[];
    }
    String text;
    try {
74
      text = (await _processUtils.run(<String>[_androidSdk.adbPath, 'devices', '-l'],
75 76 77
        throwOnError: true,
      )).stdout.trim();
    } on ProcessException catch (exception) {
78 79 80 81
      throwToolExit(
        'Unable to run "adb", check your Android SDK installation and '
        '$kAndroidSdkRoot environment variable: ${exception.executable}',
      );
82 83
    }
    final List<AndroidDevice> devices = <AndroidDevice>[];
84
    _parseADBDeviceOutput(
85 86 87
      text,
      devices: devices,
    );
88 89 90 91 92
    return devices;
  }

  @override
  Future<List<String>> getDiagnostics() async {
93
    if (_doesNotHaveAdb()) {
94 95 96
      return <String>[];
    }

97
    final RunResult result = await _processUtils.run(<String>[_androidSdk.adbPath, 'devices', '-l']);
98 99 100
    if (result.exitCode != 0) {
      return <String>[];
    }
101 102 103 104 105 106
    final List<String> diagnostics = <String>[];
    _parseADBDeviceOutput(
      result.stdout,
      diagnostics: diagnostics,
    );
    return diagnostics;
107 108
  }

109 110 111 112 113 114
  bool _doesNotHaveAdb() {
    return _androidSdk == null ||
      _androidSdk.adbPath == null ||
      !_processManager.canRun(_androidSdk.adbPath);
  }

115 116 117 118 119 120
  // 015d172c98400a03       device usb:340787200X product:nakasi model:Nexus_7 device:grouper
  static final RegExp _kDeviceRegex = RegExp(r'^(\S+)\s+(\S+)(.*)');

  /// Parse the given `adb devices` output in [text], and fill out the given list
  /// of devices and possible device issue diagnostics. Either argument can be null,
  /// in which case information for that parameter won't be populated.
121
  void _parseADBDeviceOutput(
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
    String text, {
    List<AndroidDevice> devices,
    List<String> diagnostics,
  }) {
    // Check for error messages from adb
    if (!text.contains('List of devices')) {
      diagnostics?.add(text);
      return;
    }

    for (final String line in text.trim().split('\n')) {
      // Skip lines like: * daemon started successfully *
      if (line.startsWith('* daemon ')) {
        continue;
      }

      // Skip lines about adb server and client version not matching
      if (line.startsWith(RegExp(r'adb server (version|is out of date)'))) {
        diagnostics?.add(line);
        continue;
      }

      if (line.startsWith('List of devices')) {
        continue;
      }

      if (_kDeviceRegex.hasMatch(line)) {
        final Match match = _kDeviceRegex.firstMatch(line);

        final String deviceID = match[1];
        final String deviceState = match[2];
        String rest = match[3];

        final Map<String, String> info = <String, String>{};
        if (rest != null && rest.isNotEmpty) {
          rest = rest.trim();
          for (final String data in rest.split(' ')) {
            if (data.contains(':')) {
              final List<String> fields = data.split(':');
              info[fields[0]] = fields[1];
            }
          }
        }

        if (info['model'] != null) {
          info['model'] = cleanAdbDeviceName(info['model']);
        }

        if (deviceState == 'unauthorized') {
          diagnostics?.add(
            'Device $deviceID is not authorized.\n'
            'You might need to check your device for an authorization dialog.'
          );
        } else if (deviceState == 'offline') {
          diagnostics?.add('Device $deviceID is offline.');
        } else {
          devices?.add(AndroidDevice(
            deviceID,
            productID: info['product'],
            modelID: info['model'] ?? deviceID,
            deviceCodeName: info['device'],
183 184 185 186 187
            androidSdk: _androidSdk,
            fileSystem: _fileSystem,
            logger: _logger,
            platform: _platform,
            processManager: _processManager,
188 189 190 191 192 193
          ));
        }
      } else {
        diagnostics?.add(
          'Unexpected failure parsing device information from adb output:\n'
          '$line\n'
194
          '${_userMessages.flutterToolBugInstructions}');
195 196 197 198
      }
    }
  }
}