connect method

Future<void> connect({
  1. Duration timeout = const Duration(seconds: 35),
  2. int? mtu = 512,
})

Implementation

Future<void> connect({
  Duration timeout = const Duration(seconds: 35),
  int? mtu = 512,
}) async {
  if (isConnected) {
    if (mtu != null) {
      await requestMtu(mtu);
    }
    return;
  }

  final Future<BleConnectionEvent> stateFuture = BlePlatform
      .instance
      .connectionState
      .firstWhere((event) => event.remoteId == remoteId);

  final bool changed = await BlePlatform.instance.connect(remoteId.str);

  if (changed) {
    final BleConnectionEvent response = await stateFuture.timeout(
      timeout,
      onTimeout: () {
        throw BleException(
          operation: 'connect',
          message: 'Timed out after ${timeout.inSeconds}s',
        );
      },
    );

    if (response.connectionState == BleConnectionState.disconnected) {
      throw BleException(
        operation: 'connect',
        code: response.disconnectReasonCode,
        message: response.disconnectReasonString ?? 'connection failed',
      );
    }
  }

  if (isConnected && mtu != null) {
    await requestMtu(mtu);
  }
}