android_console.dart 2.31 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6 7 8 9
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:async/async.dart';
import '../base/io.dart';
import '../convert.dart';

/// Default factory that creates a real Android console connection.
10 11 12 13
///
/// The default implementation will create real connections to a device.
/// Override this in tests with an implementation that returns mock responses.
Future<Socket> kAndroidConsoleSocketFactory(String host, int port) => Socket.connect(host, port);
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42

/// Currently active implementation of the AndroidConsoleFactory.
///
/// The default implementation will create real connections to a device.
/// Override this in tests with an implementation that returns mock responses.
typedef AndroidConsoleSocketFactory = Future<Socket> Function(String host, int port);

/// Creates a console connection to an Android emulator that can be used to run
/// commands such as "avd name" which are not available to ADB.
///
/// See documentation at
/// https://developer.android.com/studio/run/emulator-console
class AndroidConsole {
  AndroidConsole(this._socket);

  Socket _socket;
  StreamQueue<String> _queue;

  Future<void> connect() async {
    assert(_socket != null);
    assert(_queue == null);

    _queue = StreamQueue<String>(_socket.asyncMap(ascii.decode));

    // Discard any initial connection text.
    await _readResponse();
  }

  Future<String> getAvdName() async {
43 44 45
    if (_queue == null) {
      return null;
    }
46 47 48 49 50
    _write('avd name\n');
    return _readResponse();
  }

  void destroy() {
51 52 53
    _socket?.destroy();
    _socket = null;
    _queue = null;
54 55 56
  }

  Future<String> _readResponse() async {
57 58 59
    if (_queue == null) {
      return null;
    }
60 61
    final StringBuffer output = StringBuffer();
    while (true) {
62 63 64 65
      if (!await _queue.hasNext) {
        destroy();
        return null;
      }
66 67
      final String text = await _queue.next;
      final String trimmedText = text.trim();
68
      if (trimmedText == 'OK') {
69
        break;
70
      }
71 72 73 74 75 76 77 78 79 80
      if (trimmedText.endsWith('\nOK')) {
        output.write(trimmedText.substring(0, trimmedText.length - 3));
        break;
      }
      output.write(text);
    }
    return output.toString().trim();
  }

  void _write(String text) {
81
    _socket?.add(ascii.encode(text));
82 83
  }
}