#include "calib_public.h"
#include "calib_private.h"

int8_t Calib_Init(void)
{
    int8_t ret = 0;
    uint8_t i = 0;

    for(i=0; i<total_data; i++)
    {
        CalibDataCtl[i].index = 0;
        CalibDataCtl[i].status = 0;
        CalibDataCtl[i].addr = i*8;
        Calib_Read(CalibDataCtl[i].addr, CalibDataCtl[i].data.byte, Calib_Data_Size);
        if((CalibDataCtl[i].data.def.sign) != Calib_Data_Sign)
        {
            CalibDataCtl[i].data.def.value = 0;
        }
    }

    return ret;   
}

uint16 Calib_GetData(uint8_t index)
{
    return CalibDataCtl[index].data.def.value;
}

void Calib_Task(void)
{
    static uint8_t delay = 0;
    uint8_t i = 0;
    
    if(delay++ < 25) return;
    delay = 0;
        
    for(i=0; i<total_data; i++)
    {
         if((CalibDataCtl[i].status&Calib_RequestBit) == Calib_RequestBit)
         {
            CalibDataCtl[i].buffer[CalibDataCtl[i].index] = Calib_GetData4Save();
            CalibDataCtl[i].index ++;

            if(CalibDataCtl[i].index >= Calib_Buffer_size)
            {
                CalibDataCtl[i].data.def.value = Calib_FilterData(CalibDataCtl[i].buffer);
                CalibDataCtl[i].data.def.sign = Calib_Data_Sign;
                Calib_Write(CalibDataCtl[i].addr, CalibDataCtl[i].data.byte, Calib_Data_Size);
                CalibDataCtl[i].status &= ~Calib_RequestBit;
                CalibDataCtl[i].status |= Calib_FinishedBit;
                CalibDataCtl[i].index = 0;
            }
         }
    }
}

int8_t Calib_Trigger(uint8_t index, uint16_t data)
{
    int8_t ret = 0;

    if(data > 0)
    {
        CalibDataCtl[index].data.def.value = data;
        CalibDataCtl[index].data.def.sign = Calib_Data_Sign;  
        Calib_Write(CalibDataCtl[index].addr, CalibDataCtl[index].data.byte, Calib_Data_Size);
    }else
    {
        CalibDataCtl[index].status |= Calib_RequestBit;
    }
    
    return ret;
}

int8_t Calib_FinishCheck(uint8_t index)
{
    int8_t ret = -1;

    if((CalibDataCtl[index].status&Calib_FinishedBit) == Calib_FinishedBit)
    {
        CalibDataCtl[index].status = 0;
        ret = 0;
    }

    return ret;
}

uint16_t Calib_FilterData(uint16_t * data)
{
    uint32_t Sum = 0;
    uint8_t i = 0;

    for(i=0; i<Calib_Buffer_size; i++)
    {
        Sum += *(data+i);
    }

    return Sum/Calib_Buffer_size;
}


