#include "at32f403a_407.h"
#include "filter.h"
#include "utility.h"
#include "FreeRTOS.h"
#include "task.h"
#include "settings_api.h"

#include <stdio.h>

#undef DBG
#define DBG if(0)

#if defined (MAI_12)  


#define AVERAGE_LEN     10


uint32_t average_data_buf[AI_COMMON_NUMBER][AVERAGE_LEN];
average_int_t average_filter[AI_COMMON_NUMBER];


#if 0
    uint8_t     head;
    uint8_t     count;
    uint8_t     len;
    uint32_t    sum;
    uint32_t    *data;
#endif

    
    
//    
void average_filter_init(void)
{
    for (int i = 0; i < AI_COMMON_NUMBER; i++)
    {
        average_filter[i].len = AVERAGE_LEN;
        average_filter[i].data = &average_data_buf[i][0];
    }
    
#if 0    
    // tests
    for (int i = 0; i < AI_COMMON_NUMBER; i++)
    {
        for (int j = 0; j < 5; j++)
            average_filter[i].data[j] = j;
    }
#endif    
}

//
uint32_t average_int(average_int_t *fil, uint32_t value)
{
    if (!(fil->head < fil->len))
        fil->head = 0;
    
    if (fil->count < fil->len)
        fil->count++;
    
    fil->sum -= fil->data[fil->head];
    fil->sum += value;
    fil->data[fil->head++] = value;
    
    return fil->sum/fil->count;
}

#if 0
float fil_average(ADC_FILTER_t *flt, float new_value)
{
    if (!(flt->head < ADC_FILTER_LEN))
        flt->head = 0;

    if (flt->count < ADC_FILTER_LEN)
        flt->count++;
    
    flt->sum -= flt->buf[flt->head];
    flt->sum += new_value;
    flt->buf[flt->head++] = new_value;
  
    return flt->sum/(flt->count);
}
#endif

#endif