onMeasurement method

  1. @override
Future<void> onMeasurement(
  1. Measurement measurement
)
override

On each measurement collected, the onMeasurement handler is called.

Implementations of this interface should handle how to save or upload the measurement.

Implementation

@override
Future<void> onMeasurement(Measurement measurement) async {
  // If the database hasn't been created yet, wait for 3 secs
  if (database == null) {
    return Future.delayed(
        const Duration(seconds: 3), () => onMeasurement(measurement));
  }

  final Map<String, dynamic> map = {
    UPLOADED_COLUMN: 0,
    DEPLOYMENT_ID_COLUMN: deployment.studyDeploymentId,
    TRIGGER_ID_COLUMN: measurement.taskControl?.triggerId ?? 0,
    DEVICE_ROLE_NAME_COLUMN:
        measurement.taskControl?.destinationDeviceRoleName ??
            deployment.deviceConfiguration.roleName,
    DATATYPE_COLUMN: measurement.dataType.toString(),
    MEASUREMENT_COLUMN: jsonEncode(measurement),
  };

  // Fast out if DB has been closed.
  // This may happen when the data manager is closed while some probes are still
  // running and sampling measurements.
  if (!database!.isOpen) return;

  try {
    int? id = await database?.insert(
      MEASUREMENT_TABLE_NAME,
      map,
      conflictAlgorithm: ConflictAlgorithm.ignore,
    );

    debug('$runtimeType - wrote measurement to SQLite - '
        'id: $id, type: ${measurement.data.format}, '
        'device role name: ${measurement.taskControl?.destinationDeviceRoleName}.');
  } catch (error) {
    warning('$runtimeType - Error writing measurement to database - $error');
  }
}