polarofficial / polar-ble-sdk

Repository includes SDK and code examples. More info https://polar.com/en/developers
Other
447 stars 147 forks source link

How to get Timestamp with heart rate value #465

Open pranav243 opened 3 weeks ago

pranav243 commented 3 weeks ago

Platform your question concerns:

Device:

Description: There is a timeStamp attribute with ecg and ACC values. But there isn't for HR. How to get timeStamp for the HR samples?

orestesgaolin commented 3 weeks ago

I think you cannot get timestamp of the HR sample received via polarBleApi.startHrStreaming. On Android we just assume it's a sample from a given second Instant.now().truncatedTo(ChronoUnit.SECONDS).

When it comes to offline recordings you can determine HR samples timestamps from the recording start and sampling rate:

private fun mapRecordingToBatch(recording: PolarRecording): HeartRateBatch? {
    val data = recording.data

    if (data is PolarOfflineRecordingData.HrOfflineRecording) {
        val samples = data.data.samples
        val numberOfSamples = samples.size

        /// Get the HR interval from the recording settings.
        val intervalInMs =
                recording.settings.settings[PolarSensorSetting.SettingType.SAMPLE_RATE]!!.first() * 1000

        /// Get the date of the first sample.
        val firstSampleDateUTC = data.startTime.timeInMillis + intervalInMs

        Logger.info(
                TAG,
                "Received recording data. Number of samples: $numberOfSamples. Started at: $firstSampleDateUTC"
        )

        /// Assigns a date for each hr sample. To better understand how it works, consider
        /// the following example.
        ///
        /// Let's assume that:
        /// - the first sample's date in UTC is 1670411716852 (Wed Dec 07 2022 11:15:16)
        /// - the number of samples in the exercise is 5
        /// - the interval is 1s.
        ///
        /// The consecutive samples' date such be set to:
        /// 1. 1670411716852 // 1670411716852 + 1000 * 0 (Wed Dec 07 2022 11:15:16)
        /// 2. 1670411717852 // 1670411716852 + 1000 * 1 (Wed Dec 07 2022 11:15:17)
        /// 3. 1670411718852 // 1670411716852 + 1000 * 2 (Wed Dec 07 2022 11:15:18)
        /// 4. 1670411719852 // 1670411716852 + 1000 * 3 (Wed Dec 07 2022 11:15:19)
        /// 5. 1670411720852 // 1670411716852 + 1000 * 4 (Wed Dec 07 2022 11:15:20)
        val mappedSamples = samples.mapIndexed { index, hr ->
            /// Calculate the date for each sample based on the first sample's date, interval
            /// and positional distance from the first sample.
            val date = Instant.ofEpochMilli(firstSampleDateUTC + intervalInMs * index)

            HeartRate(hr.hr, date, recording.deviceId)
        }

        val heartRateBatch = HeartRateBatch(
                samples = mappedSamples,
                recording = recording,
                deviceId = recording.deviceId
        )

        return heartRateBatch;
    }
    return null;
}