ihaque / pelomon

Source code for the PeloMon Bluetooth LE sensor relay and for decoding Peloton communications
GNU General Public License v3.0
97 stars 15 forks source link

Resistance calculation #8

Open brettjurgens opened 6 months ago

brettjurgens commented 6 months ago

I've been working on an app for my peloton on and off for the last few years. Your blog posts were incredibly helpful in helping get the sensor data.

I thought I could help out a little bit... From what I've found, the proper way to calculate resistance is:

// CALIBRATION is a float array

private fun getCalibrationValue(raw: Float, i: Int): Float {
    if (i == 0) return 0.0f
    val prevIndex = i - 1
    val prevIndexVal = CALIBRATION[prevIndex]
    val currIndexVal = CALIBRATION[i]
    val size = CALIBRATION.size
    var f = 0f
    if (currIndexVal > prevIndexVal) {
        f = (raw - prevIndexVal) / (currIndexVal - prevIndexVal)
    }
    return (prevIndex.toFloat() + f) * 100.0f / (size - 1).toFloat()
}

fun calculateResistance(raw: Float): Float {
    val calibrationLen = CALIBRATION.size
    if (raw < CALIBRATION[0]) return 0.0f
    if (raw > CALIBRATION[calibrationLen - 1]) return 100.0f
    if (raw < CALIBRATION[3]) return (raw - CALIBRATION[0]) * 10.0f / (CALIBRATION[3] - CALIBRATION[0])
    if (raw > CALIBRATION[27]) return (raw - CALIBRATION[27]) * 10.0f / (CALIBRATION[30] - CALIBRATION[27]) + 90.0f
    for (i in 0 until calibrationLen) {
        if (raw >= CALIBRATION[i]) continue
        return getCalibrationValue(raw, i)
    }
    return -1.0f
}

Hope this is helpful!