/**
 * calibration.c - 电容值到油水比例的标定模块
 *
 * 支持:
 * - 添加/读取标定点
 * - 分段线性插值计算 (float cap -> float ratio)
 *
 */

#include "calibration.h"
#include <string.h>
#include <stdio.h>

CalibrationTable g_calibrationTable;

// 初始化标定表
void Calibration_Init(void)
{
    memset(&g_calibrationTable, 0, sizeof(g_calibrationTable));
//    Calibration_LoadFromFlash(); 
}

// 添加或更新一个标定点
bool Calibration_SetPoint(uint8_t index, float cap, float ratio)
{
    if (index >= CALIBRATION_POINTS_MAX)
        return false;

    g_calibrationTable.points[index].cap_value = cap;
    g_calibrationTable.points[index].oil_water_ratio = ratio;

    // 更新有效点数量
    if (index >= g_calibrationTable.count)
        g_calibrationTable.count = index + 1;

    return true;
}

// 获取某个标定点
bool Calibration_GetPoint(uint8_t index, float *cap, float *ratio)
{
    if (index >= g_calibrationTable.count)
        return false;

    *cap = g_calibrationTable.points[index].cap_value;
    *ratio = g_calibrationTable.points[index].oil_water_ratio;
    return true;
}

// 插值转换：cap -> ratio（返回值带小数点后1位）
float Calibration_ComputeRatio(float cap)
{
    if (g_calibrationTable.count < 2)
        return 0.0f;

    for (int i = 0; i < g_calibrationTable.count - 1; i++)
    {
        CalibrationPoint p1 = g_calibrationTable.points[i];
        CalibrationPoint p2 = g_calibrationTable.points[i + 1];

        if (cap >= p1.cap_value && cap <= p2.cap_value)
        {
            float ratio = p1.oil_water_ratio + 
                          (cap - p1.cap_value) * (p2.oil_water_ratio - p1.oil_water_ratio) /
                          (p2.cap_value - p1.cap_value);
            if (ratio < 0.0f) ratio = 0.0f;
            if (ratio > 100.0f) ratio = 100.0f;
            return ((int)(ratio * 10 + 0.5f)) / 10.0f;  // 保留1位小数
        }
    }

    // 超出边界处理
    if (cap < g_calibrationTable.points[0].cap_value)
        return g_calibrationTable.points[0].oil_water_ratio;

    return g_calibrationTable.points[g_calibrationTable.count - 1].oil_water_ratio;
}


