protocol_discovery.dart 1.62 KB
Newer Older
1 2 3 4 5 6 7 8 9
// Copyright 2016 The Chromium 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';

import 'device.dart';

/// Discover service protocol ports on devices.
10
class ProtocolDiscovery {
Devon Carew's avatar
Devon Carew committed
11
  /// [logReader] - a [DeviceLogReader] to look for service messages in.
12
  ProtocolDiscovery(DeviceLogReader logReader, String serviceName)
Devon Carew's avatar
Devon Carew committed
13
      : _logReader = logReader, _serviceName = serviceName {
14
    assert(_logReader != null);
Devon Carew's avatar
Devon Carew committed
15
    _subscription = _logReader.logLines.listen(_onLine);
16 17
  }

Devon Carew's avatar
Devon Carew committed
18 19 20
  static const String kObservatoryService = 'Observatory';
  static const String kDiagnosticService = 'Diagnostic server';

21
  final DeviceLogReader _logReader;
22
  final String _serviceName;
Devon Carew's avatar
Devon Carew committed
23

Ian Hickson's avatar
Ian Hickson committed
24
  Completer<int> _completer = new Completer<int>();
Devon Carew's avatar
Devon Carew committed
25
  StreamSubscription<String> _subscription;
26

27 28 29
  /// The [Future] returned by this function will complete when the next service
  /// protocol port is found.
  Future<int> nextPort() => _completer.future;
30

Devon Carew's avatar
Devon Carew committed
31 32 33 34
  void cancel() {
    _subscription.cancel();
  }

35 36
  void _onLine(String line) {
    int portNumber = 0;
37
    if (line.contains('$_serviceName listening on http://')) {
38 39
      try {
        RegExp portExp = new RegExp(r"\d+.\d+.\d+.\d+:(\d+)");
Ian Hickson's avatar
Ian Hickson committed
40
        String port = portExp.firstMatch(line).group(1);
41 42 43 44 45
        portNumber = int.parse(port);
      } catch (_) {
        // Ignore errors.
      }
    }
Ian Hickson's avatar
Ian Hickson committed
46
    if (portNumber != 0)
47 48 49 50 51 52
      _located(portNumber);
  }

  void _located(int port) {
    assert(_completer != null);
    assert(!_completer.isCompleted);
Devon Carew's avatar
Devon Carew committed
53

54
    _completer.complete(port);
Ian Hickson's avatar
Ian Hickson committed
55
    _completer = new Completer<int>();
56 57
  }
}