The Camera SDK is a PPG recording module that you can use in combination with the FibriCheck Cloud SDK. A FibriCheck measurement contains PPG data. To obtain this data, the Camera SDK communicates with the native iOS/Android camera layer, processes this data, and returns an object to submit to our backend for analysis. Multiple properties and listeners can be adjusted/attached for improving the visualization/customization of the process.
The different phases of a FibriCheck measurement are:
Finger detection
Check for the presence of a finger on the camera. You can set the timeout to 0 to skip this phase. By default, this value is set to -1 which means that it keeps checking until a finger has been detected.
Pulse detection
Check if a pulse is present. When no pulse has been detected for 10 seconds, the calibration phase will start.
Calibration
When performing a measurement, a baseline needs to be calculated. When this baseline has been calculated, the calibration is ready and recording can start.
Recording
During the recording phase, the Camera SDK algorithm calculates the PPG data by processing the mobile device's camera feed.
Processing
When the recording is finished, some additional processing needs to be done on the measurement. When done, a measurement object is presented via the onMeasurementProcessed event.
The Camera SDK is currently available for Flutter, React Native, Cordova, iOS and Android
Installation
Set the correct permissions
The recording makes use of the device's camera. So you'll need to make sure that your application has access to the camera.
Depending on the operating system, you will need to make changes to the project's configuration file.
Next to modifying the project configuration, your app will also have to ask the user to allow using the camera:
To ask for the correct permissions we use the permission_handler package.
Add the following snippet to your Podfile:
post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_ios_build_settings(target)
target.build_configurations.each do |config|
config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
'$(inherited)',
## dart: PermissionGroup.camera
'PERMISSION_CAMERA=1',
]
end
end
end
Then in your code you can request the camera permission:
var status =awaitPermission.camera.status;if (status.isDenied) {PermissionStatus requestResult requestResult =awaitPermission.camera.request()if (requestResult.isGranted) {// Request has been granted }}
As you can see in the snippet, we used the react-native-permissions library. The installation guide can be found in the readme of the library's repository.
The following snippet from the Android documentation on requesting runtime permissions shows how to request the CAMERA permission:
if (ContextCompat.checkSelfPermission( context,Manifest.permission.CAMERA) ==PackageManager.PERMISSION_GRANTED) {// You can use the API that requires the permission.performAction(...);} elseif (shouldShowRequestPermissionRationale(...)) {// In an educational UI, explain to the user why your app requires this// permission for a specific feature to behave as expected, and what// features are disabled if it's declined. In this UI, include a// "cancel" or "no thanks" button that lets the user continue// using your app without granting the permission.showInContextUI(...);} else {// You can directly ask for the permission.// The registered ActivityResultCallback gets the result of this request.requestPermissionLauncher.launch(Manifest.permission.CAMERA);}
The following snippet has been extracted from the Apple Documentation and shows how to check if the user has given permission to use the camera:
var isAuthorized: Bool {getasync {let status = AVCaptureDevice.authorizationStatus(for: .video)// Determine if the user previously authorized camera access.var isAuthorized = status == .authorized// If the system hasn't determined the user's authorization status,// explicitly prompt them for approval.if status == .notDetermined { isAuthorized =await AVCaptureDevice.requestAccess(for: .video) }return isAuthorized }}funcsetUpCaptureSession() async {guardawait isAuthorized else { return }// Set up the capture session.}
No specific action needed for the Cordova SDK. The SDK will automatically ask permission to the user if the permissions are configured correctly in the previous step.
Install the Camera SDK
In your project, you can add the package below to the pubspec.yaml file. Replace {TOKEN} with the personal access token you've received from FibriCheck.
In your project, if you are using yarn or npm you need to create a file called .npmrc at the root level of your project and add these lines. Replace {AUTH_TOKEN} with the personal access token you've received from FibriCheck
Alternatively, this file can be added/edited in your home directory and it will be applied to all projects.
Explanation from GitHub on how to add your token can be found here.
using npm:
npm install @fibricheck/react-native-camera-sdk
using yarn:
yarn add @fibricheck/react-native-camera-sdk
You will receive access to the Native Camera SDK repository. This repository will contain the source files that you can include directly in your project.
To install the Camera SDK for Cordova, you will receive an authentication token to access the private npm package hosted on GitHub Packages.
To include the cordova-camera-sdk package in your application, follow these steps:
Add a .npmrc file to the root of your project with the following content:
You can use the FibriCheckView exported from the package:camera_sdk/fibri_check_view.dart package to perform a measurement and hook up sdk.postMeasurement to post the data returned from the camera to the backend in the onMeasurementProcessed event.
Before taking a measurement, you need to check if you are entitled to perform a measurement. This can be achieved by invoking sdk.canPerformMeasurement. If you try to execute a measurement when you are not entitled, a NoActivePrescriptionError will be thrown. So make sure you've Activated a Prescription.
It is highly recommended to provide the camera SDK version as a second argument, as shown in the example.
The Camera SDK provides a React Native Component that you can integrate quickly in your application.
<RNFibriCheckViewstyle={{ flex:1, backgroundColor:'#ffffff' }}onFingerDetected={() =>console.log('finger detected')}onFingerRemoved={() =>console.log('finger removed')}onCalibrationReady={() =>console.log('calibration ready')}onMeasurementFinished={() =>console.log('measurement finished')}onMeasurementStart={() =>console.log('measurement recording started')}onFingerDetectionTimeExpired={() =>console.log('finger detection time expired') }onPulseDetected={() =>console.log('pulse detected')}onPulseDetectionTimeExpired={() =>console.log('pulse detection time is expired') }onMovementDetected={() =>console.log('movement detected')}onHeartBeat={(heartRate) =>console.log(`current heart rate: ${heartRate}`)}onTimeRemaining={(seconds) =>console.log(`time remaining: ${seconds}`)}onMeasurementError={(error) =>console.log(`measurement error occured: ${error}`)}onMeasurementProcessed={(data) =>console.log('measurement processed and ready to send!'); }/>
You can use the RNFibriCheckView exported from the @fibricheck/react-native-camera-sdk package to perform a measurement and hook up sdk.postMeasurement to post the data returned from the camera to the backend in the onMeasurementProcessed event.
Before taking a measurement, you need to check if you are entitled to perform a measurement. This can be achieved by invoking sdk.canPerformMeasurement. If you try to execute a measurement when you are not entitled, a NoActivePrescriptionError will be thrown. So make sure you've Activated a Prescription.
It is highly recommended to provide the camera sdk version as a second argument, as shown in the example.
The measurement context is prefilled here, but needs to be completed by the user. The best practice is to add this at a later stage with sdk.updateMeasurementContext. More information about this can be found in the Measurement Structure.
The FibriChecker class is the main class that you have to use to implement FibriCheck in your application.
importcom.qompium.fibrichecker.FibriChecker;importcom.qompium.fibrichecker.listeners.FibriListener;importcom.qompium.fibrichecker.measurement.MeasurementData;publicclassMeasurementViewextendsLinearLayout { linearLayout =newLinearLayout(context); linearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
linearLayout.setOrientation(LinearLayout.HORIZONTAL); fibriChecker =new FibriChecker.FibriBuilder(context.getCurrentActivity(), linearLayout).build(); fibriChecker.setFibriListener(newFibriListener() { @OverridepublicvoidonSampleReady(finaldouble ppg,double raw) {// Invoked multiple times during the measurement// Contains data to update visualisations in your views } @OverridepublicvoidonFingerDetected() {// Invoked when the finger is placed correctly } @OverridepublicvoidonFingerRemoved(double y,double v,double stdDevY) {// Invoked when the finger is removed } @OverridepublicvoidonCalibrationReady() { } @OverridepublicvoidonHeartBeat(int value) { } @OverridepublicvoidtimeRemaining(int seconds) { } @OverridepublicvoidonMeasurementFinished() { } @OverridepublicvoidonMeasurementStart() { } @OverridepublicvoidonFingerDetectionTimeExpired() { } @OverridepublicvoidonPulseDetected() { } @OverridepublicvoidonPulseDetectionTimeExpired() { } @OverridepublicvoidonMovementDetected() { } @OverridepublicvoidonMeasurementProcessed(MeasurementData measurementData) { } @OverridepublicvoidonMeasurementError(String message) { } }); fibriChecker.start(); return linearLayout;}
The iOS Native SDK is written in Objective-C. Newer iOS applications are typically developed in Swift. It's possible to use Objective-C files and Swift files in the same project. See the Apple documentation for more info.
The following code snippet is a working example that will show the heart rate, calculated using the Native SDK, on the main screen:
const { FibriCheckCordovaSDK: fc } =cordova.plugins;// Step 1: initialise the SDKawaitfc.initialise();// Set listeners for events (full list available in docs)fc.onMeasurementStart(() => {console.log("Measurement Started")});fc.onSampleReady((ppg:number, raw:number) => {console.log("PPG Sample Received");// use ppg value to visualize a graph});fc.onHeartBeat((hr:number) => {console.log(`Heartbeat ${hr}`);});fc.onMeasurementProcessed((data) => {console.log("Measurement Processed");// data object should be sent to FibriCheck Cloud});awaitfc.startMeasurement();
In rare cases, it can occur that the motion sensors don't provide the correct data. Because the algorithm requires motion sensor data to be available, an onMeasurementError event will be thrown in this case. Look here for more information.
Device Requirements
A full FibriCheck measurement consists of an on-device data acquisition step and a cloud data analysis step, performed by an AI algorithm. The on-device algorithms extracts a raw measurement from the the camera feed.
The use of the SDK has no significant impact on storage or memory usage of the device. The frames from the camera feed are processed on-the-fly by memory-efficient algorithms.
During the measurement there will be a significant CPU usage caused by the on-the-fly processing of the camera feed. However these processing algorithms also power the FibriCheck application which is broadly available on low-end and high-end smartphones. In this respect, we don't expect any performance issues by using the Camera SDK's in your application.
The following table lists the required minimum mobile operating system versions, and minimum framework versions:
Platform
Minimum OS (and framework)
Android
Android KitKat (4.4)
API Level 19
iOS
iOS 11 (Sept. 17)
Important Remarks
Camera selection
Modern phones have multiple cameras. The Camera SDK uses the default capture device that is able to record video content.
To guide the user in putting their finger on the correct camera, it's recommended to show the camera output as a "peephole" in the interface at the start of a measurement.
In order to aid the user in using the correct camera lens, you can provide a preview of the relevant camera via the following package: https://pub.dev/packages/camera.
The Camera SDK uses the default camera.
There is a library react-native-vision-camera that is able to select the correct lens. The following snippet provides an example of how this can be implemented:
An ongoing measurement will stop when a measurement error occurs. Make sure that an onMeasurementError has been defined. See the onMeasurementError documentation for more information
Framework-specific remarks
Drawing on the JS Thread
When benchmarking the SDK, we noticed that drawing on the JS Thread while taking a measurement caused severe spikes in the processing power. This will results in a bad quality measurement. So when creating a visualisation, for example counting down the seconds that are left in a measurement, make sure you are not drawing on the JS Thread. Either make use of Native Driver or use React Reanimated. When using third party libraries for creating animations, make sure they also offload the drawing from the JS Thread.
Not using Hermes
When benchmarking the SDK, we noticed that Hermes also had a big impact on the performance of low-end devices. So we advice you to enable it if possible. Instructions can be found in their documentation.
Visualizing the ongoing measurement
The SDK emits an onSampleReady event on each processed frame. The event contains a filtered ppg value and a raw measurement value of the latest received video frame.
You can use these values to visualize the PPG graph to the user during the measurement. Depending on the lightning conditions, the variance of the ppg values can be very low during most part of the measurement (decimal values between -1 and +1). Make sure to apply appropriate scaling to the graph to correctly visualize the PPG measurement to the user. Avoid visualizing an apparently flat line.