Skip to content
CARP Docs
Ask AISystemLightDark
On this page

Extending CAMS

Extend CARP Mobile Sensing with custom triggers, sampling packages, data managers and data or privacy transformers.

Copy MarkdownOpen inOpen in GitHubView as MarkdownOpen in Scira AIOpen in ChatGPTOpen in ClaudeOpen in Cursor

CARP Mobile Sensing (CAMS) is designed to be extended with domain-specific studies, triggers, tasks, measures, probes and data types. You extend it by implementing classes that inherit from the abstract classes in the library and registering them with CAMS.

ExtensionWhat you implementWhere you register it
TriggerTriggerConfiguration, TriggerExecutor, TriggerFactoryExecutorFactory().registerTriggerFactory()
Sampling packageSamplingPackage, Data, Probe, optionally DeviceManagerSamplingPackageRegistry().register()
Data managerDataEndPoint, DataManager, DataManagerFactoryDataManagerRegistry().register()
Data transformerDataTransformerSchema, DataTransformer functionsDataTransformerSchemaRegistry().register()
Privacy transformerTransformer functions that privacy-protect Data propertiesThe PrivacySchema.DEFAULT schema in the DataTransformerSchemaRegistry
User taskUserTask, UserTaskFactoryAppTaskController().registerUserTaskFactory()

JSON serialization

Most extensions rely on serialization to and from JSON. This applies to triggers, measures, sampling schemas, data and more. CAMS uses polymorphic serialization as supported by the carp_serializable package, an extension of the standard json_serializable package.

Polymorphic JSON serialization requires four steps when you design your classes:

  1. Define a serializable class

    Extend from Serializable and annotate the class:

    @JsonSerializable(includeIfNull: false, explicitToJson: true)
    class FreeMemory extends Data {
      ...
    }
  2. Implement the JSON methods

    Implement the three JSON serialization methods:

      @override
      Function get fromJsonFunction => _$FreeMemoryFromJson;
      factory FreeMemory.fromJson(Map<String, dynamic> json) =>
          FromJsonFactory().fromJson<FreeMemory>(json);
      @override
      Map<String, dynamic> toJson() => _$FreeMemoryToJson(this);
  3. Register the class

    Register the class's fromJsonFunction in the FromJsonFactory, for example in the onRegister() callback of a sampling package:

      @override
      void onRegister() {
        FromJsonFactory()
            .register(FreeMemory());
      } 
  4. Run the code generator

    When all JSON classes are implemented, generate the JSON serialization helper classes using build_runner. Run this command in the root of your Flutter project:

    dart run build_runner build --delete-conflicting-outputs

    This generates the necessary .g.dart files.

For details, see the carp_serializable and json_serializable packages.

Adding new triggers

Triggers are a central part of a StudyProtocol, and you can create your own triggers and add them to CAMS:

  1. Define one or more new triggers.
  2. Define a TriggerExecutor for each new trigger.
  3. Define and register a TriggerFactory that creates the correct TriggerExecutor for a specific trigger.

Define a trigger

A trigger extends the TriggerConfiguration class and adds the domain-specific fields that configure it. The RemoteTrigger below listens to a resource on a server identified by a URI and triggers when this resource is available.

/// A trigger that triggers based on event from a remote server.
@JsonSerializable(includeIfNull: false, explicitToJson: true)
class RemoteTrigger extends TriggerConfiguration {
  RemoteTrigger({
    required this.uri,
    this.interval = const Duration(minutes: 10),
  }) : super();

  /// The URI of the resource to listen to.
  String uri;

  /// How often should we check the server?
  Duration interval;

  @override
  Function get fromJsonFunction => _$RemoteTriggerFromJson;
  factory RemoteTrigger.fromJson(Map<String, dynamic> json) =>
      FromJsonFactory().fromJson<RemoteTrigger>(json);
  @override
  Map<String, dynamic> toJson() => _$RemoteTriggerToJson(this);
}

Trigger configurations are part of a study protocol, so they must support JSON serialization.

Define a trigger executor

Each trigger needs a corresponding TriggerExecutor that executes the trigger at sampling runtime.

  • Every Executor in CAMS can implement runtime behavior on init, start, stop, restart and dispose.
  • The abstract TriggerExecutor class has default implementations of all these methods, so you only override the lifecycle methods where something needs to happen.
  • Typically you override onStart(), which is called when sensing starts, and implement the trigger logic there. Call the onTrigger() callback to fire the trigger.

The RemoteTriggerExecutor starts a periodic timer that checks the resource at the URI in the trigger configuration. If the resource is available, it calls onTrigger().

/// Executes a [RemoteTrigger], i.e. check if there is a resource on
/// the server and triggers if so.
class RemoteTriggerExecutor extends TriggerExecutor<RemoteTrigger> {
  final client = Client();

  @override
  Future<bool> onStart() async {
    // Set up a periodic timer to look for a resource at the specified URI
    timer = Timer.periodic(configuration!.interval, (_) async {
      var response = await client.get(
        Uri.parse(Uri.encodeFull(configuration!.uri)),
      );

      if (response.statusCode == HttpStatus.ok) {
        // If there is a resource at the specified URI, then trigger this executor
        onTrigger();
      }
    });
    return true;
  }
}

Warning

This trigger executor is very simplistic and does not cover any edge cases, such as exceptions from network errors.

Define and register a trigger factory

A TriggerFactory maps triggers to their executors at runtime.

  • A factory can handle multiple triggers, as listed in the set of trigger types it supports.
  • The create() method creates the correct trigger executor for the specified trigger.
  • The onRegister() callback adds the trigger configurations to the FromJsonFactory(), so trigger configurations in a study protocol can be serialized to and from JSON.
/// A [TriggerFactory] for remote triggers.
class RemoteTriggerFactory implements TriggerFactory {
  @override
  Set<Type> types = {
    // Note that this factory might support several types of remote triggers
    RemoteTrigger,
  };

  @override
  void onRegister() {
    // When registering this factory add the triggers to the JSON serialization
    FromJsonFactory().registerAll([RemoteTrigger(uri: 'uri')]);
  }

  @override
  TriggerExecutor<TriggerConfiguration> create(TriggerConfiguration trigger) =>
      switch (trigger) {
        RemoteTrigger _ => RemoteTriggerExecutor(),
        _ => ImmediateTriggerExecutor(),
      };
}

Register the trigger factory with CAMS:

ExecutorFactory().registerTriggerFactory(RemoteTriggerFactory());

Do this when you initialize CAMS, before any protocol is created or loaded.

Adding new sampling capabilities

A SamplingPackage adds measures to CAMS. It defines the measure types and their data classes and creates a probe for each type. For an external device or an online service, it also provides the device manager. Building sampling packages walks through every part with a complete, tested example package:

Building sampling packages

Build, test and publish a sampling package of your own.

Devices and services

Add a device manager for a wearable or an online service.

You can release a sampling package as a Dart package on pub.dev. The existing sampling packages cover onboard phone sensors, external wearable devices and online services; see Measure types.

Adding a new data manager

CAMS comes with a set of built-in and external data managers. See Data managers for an overview.

To save or upload data to a custom data backend, implement three interfaces:

  1. Create a data endpoint

    Implement the DataEndPoint interface, which is used in the study protocol.

  2. Create a data manager

    Implement the DataManager interface, which saves or uploads measurements as they are sampled.

  3. Create a data manager factory

    Create a DataManagerFactory that creates a data manager based on the data endpoint configuration.

Data endpoint

A data endpoint is part of the study protocol. It specifies which data manager stores or forwards data, and how that data manager is configured. Every new data manager needs a corresponding data endpoint that extends the DataEndPoint class.

For example, the FileDataEndPoint specifies that data is saved to a file with the FileDataManager. It configures the data manager with a buffer size and whether the file is zipped or encrypted.

Warning

A DataEndPoint must support JSON serialization to be part of a study protocol.

Data manager

A data manager stores or forwards the collected measurements. Every new data manager implements the DataManager interface:

/// The [DataManager] interface is used to upload [Measurement] objects to any
/// data manager that implements this interface.
abstract class DataManager {
  /// The deployment using this data manager.
  PrimaryDeviceDeployment get deployment;

  /// The ID of the study deployment that this manager is handling.
  String get studyDeploymentId;

  /// The type of this data manager as enumerated in [DataEndPointTypes].
  String get type;

  /// Configure the data manager by specifying the study [deployment], the
  /// [dataEndPoint], and the stream of [measurements] events to handle.
  Future<void> configure({
    required DataEndPoint dataEndPoint,
    required SmartphoneDeployment deployment,
    required Stream<Measurement> measurements,
  });

  /// Flush any buffered data and close this data manager.
  /// After calling [close] the data manager can no longer be used.
  Future<void> close();

  /// Stream of data manager events.
  Stream<DataManagerEvent> get events;

  /// On each measurement collected, the [onMeasurement] handler is called.
  ///
  /// Implementations of this interface should handle how to save
  /// or upload the [measurement].
  Future<void> onMeasurement(Measurement measurement);

  /// When the data stream closes, the [onDone] handler is called.
  Future<void> onDone();

  /// When an error event is send on the stream, the [onError] handler is called.
  Future<void> onError(Object error);
}

All of these methods must be implemented. The AbstractDataManager class is a useful starting point. For example, the ConsoleDataManager is a minimal data manager that prints a JSON-encoded version of the data to the console:

/// A very simple data manager that just "uploads" the data to the
/// console (i.e., prints it). Used mainly for testing and debugging purposes.
class ConsoleDataManager extends AbstractDataManager {
  @override
  String get type => DataEndPointTypes.PRINT;

  @override
  Future<void> onMeasurement(Measurement measurement) async =>
      debugPrint(jsonEncode(measurement));
}

Data manager factory

Each new data manager needs a corresponding DataManagerFactory, which creates a data manager of a specific type when the study protocol is loaded. The interface:

/// A factory which can create a [DataManager] based on the `type` of an
/// [DataEndPoint].
abstract class DataManagerFactory {
  /// The [DataEndPoint] type.
  String get type;

  /// Create a [DataManager].
  DataManager create();
}

The factory for the ConsoleDataManager:

class ConsoleDataManagerFactory implements DataManagerFactory {
  @override
  String get type => DataEndPointTypes.PRINT;

  @override
  DataManager create() => ConsoleDataManager();
}

Register the factory in the DataManagerRegistry singleton:

DataManagerRegistry().register(ConsoleDataManagerFactory());

Do this at app start-up, before the protocol is loaded and sensing is started.

Adding data and privacy transformers

For how to use transformers and privacy schemas in a study protocol, see Data transformation and privacy.

Creating data transformer schemas

To create a DataTransformerSchema, implement the namespace getter and the onRegister() callback. This is the Open mHealth transformer schema:

/// A default [DataTransformerSchema] for Open mHealth (OMH) transformers
class OMHTransformerSchema extends DataTransformerSchema {
  @override
  String get namespace => NameSpace.OMH;
  @override
  void onRegister() {}
}

Register each transformer schema in the DataTransformerSchemaRegistry singleton as part of your app setup:

DataTransformerSchemaRegistry().register(OMHTransformerSchema());

Once the schema is registered, you can create transformers for each data type. A data transformer transforms one type of data into another, as defined by the DataTransformer typedef:

typedef DataTransformer = Data Function(Data);

For each Data type you want to transform, define a new class that also extends Data. For example, the OMHGeopositionDataPoint class represents an OMH Geoposition data point:

/// Holds an OMH [Geoposition] data point.
class OMHGeopositionDataPoint extends OMHContextDataPoint
    implements DataTransformerFactory {
  OMHGeopositionDataPoint(DataPoint datapoint) : super(datapoint);

  factory OMHGeopositionDataPoint.fromLocationData(Location location) {
    var pos = Geoposition(
        latitude: PlaneAngleUnitValue(
            unit: PlaneAngleUnit.DEGREE_OF_ARC, value: location.latitude),
        longitude: PlaneAngleUnitValue(
            unit: PlaneAngleUnit.DEGREE_OF_ARC, value: location.longitude),
        positioningSystem: PositioningSystem.GPS);

    return OMHGeopositionDataPoint(
        DataPoint(body: pos, provenance: OMHContextDataPoint.provenance));
  }

  factory OMHGeopositionDataPoint.fromJson(Map<String, dynamic> json) =>
      OMHGeopositionDataPoint(DataPoint.fromJson(json));

  static DataTransformer get transformer =>
      ((data) => OMHGeopositionDataPoint.fromLocationData(data as Location));
}
  • The most important member is transformer, a function that transforms one type of Data into another. The mapping between the two data types happens in the fromLocationData factory.
  • The class must support JSON serialization. Here the superclass OMHContextDataPoint handles it. The toJson method is needed to serialize and store the data.
  • The namespace of the DataType of OMHGeopositionDataPoint is OMH.

Add the transformer to the schema:

DataTransformerSchemaRegistry().lookup(NameSpace.OMH)!
  ..add(LOCATION, OMHGeopositionDataPoint.transformer);

In carp_context_package, this happens in the onRegister() method of the ContextSamplingPackage.

Using data transformer schemas

You can transform data manually by looking up a transformer schema and applying its transformer. This code transforms a Location into an OMHGeopositionDatum:

    Location loc = Location()
      ..longitude = 12.23342
      ..latitude = 3.34224
      ..altitude = 124.2134235;
    OMHGeopositionDatum geo = TransformerSchemaRegistry().lookup(NameSpace.OMH).transform(loc);

More commonly, you set the data format of the DataEndPoint with its dataFormat property, which specifies the namespace, such as NameSpace.OMH. This data endpoint saves measurements to a file in the Open mHealth (OMH) data format:

  // Create a study protocol storing data in files using the OMH data format
  var protocol = SmartphoneStudyProtocol(
    ownerId: 'AB',
    name: 'Track patient movement',
    dataEndPoint: FileDataEndPoint(
      bufferSize: 500 * 1000,
      zip: true,
      encrypt: false,
      dataFormat: NameSpace.OMH,
    ),
  );

Note

Not all data types in CAMS have an OMH data format. If no OMH transformer is found, the data is stored in the original CARP data format.

Adding privacy transformers

A PrivacySchema is a special data transformer schema that takes a piece of data and protects its relevant properties. CAMS has a built-in privacy schema with the transformer namespace PrivacySchema.DEFAULT. To add privacy protection:

  1. Write a transformer function that transforms a Data object so that its properties are privacy-protected.
  2. Register this function in the DataTransformerSchemaRegistry as part of the PrivacySchema.DEFAULT schema.

These privacy functions anonymize text messages and phone calls:

textMessageAnonymizerphoneCallAnonymizer
/// A [TextMessage] anonymizer function. Anonymizes:
///  - address
///  - body
TextMessage textMessageAnonymizer(Data data) {
  assert(data is TextMessage);
  var msg = data as TextMessage;
  if (msg.address != null) {
    msg.address = sha1.convert(utf8.encode(msg.address!)).toString();
  }
  if (msg.body != null) {
    msg.body = sha1.convert(utf8.encode(msg.body!)).toString();
  }

  return msg;
}
/// A [PhoneCall] anonymizer function. Anonymizes:
///  - formattedNumber
///  - number
///  - name
PhoneCall phoneCallAnonymizer(PhoneCall call) {
  if (call.formattedNumber != null) {
    call.formattedNumber = sha1
        .convert(utf8.encode(call.formattedNumber!))
        .toString();
  }
  if (call.number != null) {
    call.number = sha1.convert(utf8.encode(call.number!)).toString();
  }
  if (call.name != null) {
    call.name = sha1.convert(utf8.encode(call.name!)).toString();
  }

  return call;
}

You can put these functions anywhere in the sampling package. Typically you put them in a separate file if you have many, or in the package Dart file if you have only a few.

Register the anonymizer functions in the PrivacySchema.DEFAULT schema, typically in the package's onRegister() callback:

TransformerSchemaRegistry().lookup(PrivacySchema.DEFAULT)!.add(TEXT_MESSAGE, textMessageAnoymizer);

This example is implemented in the carp_communication_package.

Tip

Consider whether your sampling package needs to supply privacy-protecting functions, and if so, add them to the default privacy schema.

Quick links

Page · DocumentationCARP DocumentationPage · DocumentationIntroductionPage · DocumentationQuickstartPage · DocumentationTerminologyPage · DocumentationArchitecture