createBond method

Future<void> createBond({
  1. int timeout = 90,
})

Force the bonding popup to show now (Android Only) Note! calling this is usually not necessary!! The platform does it automatically.

Implementation

Future<void> createBond({int timeout = 90}) async {
  // check android
  if (Platform.isAndroid == false) {
    throw FlutterBluePlusException(ErrorPlatform.fbp, "createBond",
        FbpErrorCode.androidOnly.index, "android-only");
  }

  // check connected
  if (isDisconnected) {
    throw FlutterBluePlusException(ErrorPlatform.fbp, "createBond",
        FbpErrorCode.deviceIsDisconnected.index, "device is not connected");
  }

  // Only allow a single ble operation to be underway at a time
  _Mutex mtx = _MutexFactory.getMutexForKey("global");
  await mtx.take();

  try {
    var responseStream = FlutterBluePlus._methodStream.stream
        .where((m) => m.method == "OnBondStateChanged")
        .map((m) => m.arguments)
        .map((args) => BmBondStateResponse.fromMap(args))
        .where((p) => p.remoteId == remoteId)
        .where((p) => p.bondState != BmBondStateEnum.bonding);

    // Start listening now, before invokeMethod, to ensure we don't miss the response
    Future<BmBondStateResponse> futureResponse = responseStream.first;

    // invoke
    bool changed =
        await FlutterBluePlus._invokeMethod('createBond', remoteId.str);

    // only wait for 'bonded' if we weren't already bonded
    if (changed) {
      BmBondStateResponse bs = await futureResponse
          .fbpEnsureAdapterIsOn("createBond")
          .fbpEnsureDeviceIsConnected(this, "createBond")
          .fbpTimeout(timeout, "createBond");

      // success?
      if (bs.bondState != BmBondStateEnum.bonded) {
        throw FlutterBluePlusException(
            ErrorPlatform.fbp,
            "createBond",
            FbpErrorCode.createBondFailed.hashCode,
            "Failed to create bond. ${bs.bondState}");
      }
    }
  } finally {
    mtx.give();
  }
}