uploadBufferedMeasurements method

Future<void> uploadBufferedMeasurements()

Upload buffered measurements to CAWS.

Implementation

Future<void> uploadBufferedMeasurements() async {
  debug("$runtimeType - Starting upload of data batches...");

  // fast exit if not connected
  if (connectivity.contains(ConnectivityResult.none)) {
    warning('$runtimeType - Offline - cannot upload buffered data.');
    return;
  }

  // fast exit if only upload on wifi and we're not on wifi
  if (carpEndPoint.onlyUploadOnWiFi &&
      !connectivity.contains(ConnectivityResult.wifi)) {
    warning(
        '$runtimeType - WiFi required by the data endpoint, but no wifi connectivity - '
        'cannot upload buffered data.');
    return;
  }

  // now start trying to upload data...
  // try {
  // check if authenticated to CAWS and fast exit if not
  if (!CarpAuthService().authenticated) {
    warning('No user authenticated to CAWS. Cannot upload data.');
    return;
  }

  // check if token has expired, and try to refresh token, if so
  if (CarpAuthService().currentUser.token!.hasExpired) {
    try {
      await CarpAuthService().refresh();
    } catch (error) {
      warning('$runtimeType - Failed to refresh access token - $error. '
          'Cannot upload data.');
      return;
    }
  }

  final batches = await buffer.getDataStreamBatches(
      // carpEndPoint.deleteWhenUploaded,
      );

  switch (carpEndPoint.uploadMethod) {
    case CarpUploadMethod.stream:
      await CarpDataStreamService().appendToDataStreams(
        studyDeploymentId,
        batches,
      );
      addEvent(
          DataManagerEvent(CarpDataManagerEventTypes.dataStreamAppended));
      break;
    case CarpUploadMethod.datapoint:
      await uploadDataStreamBatchesAsDataPoint(
        batches,
      );
      addEvent(DataManagerEvent(
          CarpDataManagerEventTypes.dataPointsBatchUploaded));
      break;
    case CarpUploadMethod.file:
      // TODO - implement file method.
      warning('$runtimeType - CarpUploadMethod.file not supported (yet).');
      break;
    default:
  }

  // Count the total amount of measurements and check if any measurement
  // has a separate file to be uploaded
  var count = 0;
  for (var batch in batches) {
    count += batch.measurements.length;
    for (var measurement in batch.measurements) {
      if (measurement.data is FileData) {
        var fileData = measurement.data as FileData;
        if (fileData.upload) uploadFile(fileData);
      }
    }
  }

  info("$runtimeType - Upload of data batches done. "
      "${batches.length} batches with $count measurements in total uploaded.");

  // if everything is uploaded successfully, then clean up the DB
  await buffer.cleanup(carpEndPoint.deleteWhenUploaded);
  // } catch (error) {
  //   warning('$runtimeType - Data upload failed - $error');
  // }
}