connect method

Future<bool> connect()

Implementation

Future<bool> connect() async {
  if (_socket != null && _socketConnected == true) {
    return _socketConnected;
  }
  try {
    // Create socket connection
    _socket = await Socket.connect(InternetAddress(ip), port, timeout: const Duration(seconds: 1))
      ..setOption(SocketOption.tcpNoDelay, true);

    // Add socket listener
    _socket!.listen(
      _handleAdbInput,
      onDone: () {
        _socketConnected = false;
        _socketConnectedController.add(_socketConnected);
      },
      onError: (error) {
        _socketConnected = false;
        _socketConnectedController.add(_socketConnected);
      },
    );
    _socketConnected = true;
    _socketConnectedController.add(_socketConnected);

    // Listen to adb messages
    _adbStreamController.stream.where((message) => AdbProtocol.validateAdbMessage(message)).listen(_handleAdbMessage);

    _socketConnectedController.stream.listen((connected) => connected ? {} : _adbConnectedController.add(false));
    // Send connection init
    await _connectAdb();

    // wait for adbConnected
    return await _adbConnectedController.stream.first;
  } catch (e) {
    debugPrint('Failed to connect to ADB: $e');
    return false;
  }
}