readRssi method

Future<int> readRssi({
  1. int timeout = 15,
})

Read the RSSI of connected remote device

Implementation

Future<int> readRssi({int timeout = 15}) async {
  // check connected
  if (isDisconnected) {
    throw FlutterBluePlusException(ErrorPlatform.fbp, "readRssi",
        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();

  int rssi = 0;

  try {
    var responseStream = FlutterBluePlus._methodStream.stream
        .where((m) => m.method == "OnReadRssi")
        .map((m) => m.arguments)
        .map((args) => BmReadRssiResult.fromMap(args))
        .where((p) => (p.remoteId == remoteId));

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

    // invoke
    await FlutterBluePlus._invokeMethod('readRssi', remoteId.str);

    // wait for response
    BmReadRssiResult response = await futureResponse
        .fbpEnsureAdapterIsOn("readRssi")
        .fbpEnsureDeviceIsConnected(this, "readRssi")
        .fbpTimeout(timeout, "readRssi");

    // failed?
    if (!response.success) {
      throw FlutterBluePlusException(
          _nativeError, "readRssi", response.errorCode, response.errorString);
    }
    rssi = response.rssi;
  } finally {
    mtx.give();
  }

  return rssi;
}