tryRegisterConnectedDevice method

Future<void> tryRegisterConnectedDevice(
  1. DeviceConfiguration<DeviceRegistration> device
)

Tries to register the connected device with the deployment service.

The device must be:

  • a connected device (i.e., not the primary device),
  • connected to this phone, and
  • available in the device controller.

Implementation

Future<void> tryRegisterConnectedDevice(DeviceConfiguration device) async {
  final deviceType = device.type;
  final deviceRoleName = device.roleName;

  if (deployment?.deviceConfiguration.roleName == deviceRoleName) {
    warning(
      "$runtimeType - Trying to register the primary device with role name "
      "'$deviceRoleName' as a connected device for study deployment '${study.studyDeploymentId}'. "
      "Primary devices are automatically registered when the deployment is received, "
      "so this should not be necessary. Continuing without registration.",
    );
    return;
  }

  info(
    "$runtimeType - Trying to register connected device with role name "
    "'$deviceRoleName' for study deployment '${study.studyDeploymentId}'.",
  );

  // Check if this phone has this type of device
  if (!_deviceController.hasDevice(deviceType)) {
    warning(
      "$runtimeType - Trying to register device of type '$deviceType' playing the role "
      "'$deviceRoleName' for study deployment '${study.studyDeploymentId}'. "
      "But this smartphone does not have such a type of device."
      "Continuing without registration.",
    );
    return;
  }

  // Check if the device is connected.
  DeviceManager deviceManager = _deviceController.getDeviceManager(
    deviceType,
  )!;

  if (!deviceManager.isConnected) {
    warning(
      "$runtimeType - Trying to register device with role name '$deviceRoleName' "
      "for study deployment '${study.studyDeploymentId}', "
      "but this device is not connected. Continuing without registration.",
    );
    return;
  }

  // Now try to register this device with the deployment service.
  DeviceRegistration registration = deviceManager.createRegistration();
  try {
    final deploymentStatus = await _deploymentService.registerDevice(
      study.studyDeploymentId,
      deviceRoleName,
      registration,
    );

    // Also update local deployment information about the connected device registrations,
    // so that it is in sync with the deployment service.
    if (device is! PrimaryDeviceConfiguration) {
      deployment?.connectedDeviceRegistrations[deviceRoleName] = registration;
    }
    study.deploymentStatusReceived(deploymentStatus);
  } catch (error) {
    warning(
      "$runtimeType - Failed to register device with role name "
      "'$deviceRoleName' for study deployment '${study.studyDeploymentId}' "
      "at deployment service '$_deploymentService'.\n"
      "Error: $error\n"
      "Continuing without registration.",
    );
  }
}