read method

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

read a characteristic

Implementation

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

  // return value
  List<int> responseValue = [];

  try {
    var request = BmReadCharacteristicRequest(
      remoteId: remoteId,
      characteristicUuid: characteristicUuid,
      serviceUuid: serviceUuid,
      secondaryServiceUuid: null,
    );

    var responseStream = FlutterBluePlus._methodStream.stream
        .where((m) => m.method == "OnCharacteristicReceived")
        .map((m) => m.arguments)
        .map((args) => BmCharacteristicData.fromMap(args))
        .where((p) => p.remoteId == request.remoteId)
        .where((p) => p.serviceUuid == request.serviceUuid)
        .where((p) => p.characteristicUuid == request.characteristicUuid);

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

    // invoke
    await FlutterBluePlus._invokeMethod('readCharacteristic', request.toMap());

    // wait for response
    BmCharacteristicData response = await futureResponse
        .fbpEnsureAdapterIsOn("readCharacteristic")
        .fbpEnsureDeviceIsConnected(device, "readCharacteristic")
        .fbpTimeout(timeout, "readCharacteristic");

    // failed?
    if (!response.success) {
      throw FlutterBluePlusException(_nativeError, "readCharacteristic", response.errorCode, response.errorString);
    }

    // set return value
    responseValue = response.value;
  } finally {
    mtx.give();
  }

  return responseValue;
}