#include "calc.h"
#include "device.h"
#include "ltc1867.h"

uint16_t calc_freq(uint32_t pre, uint32_t now)
{
    uint32_t freq;

    if (now > pre) {
        freq = now - pre;
    } else {
        freq = pre - now;
    }
    freq = (LEDIR_FREQ * SAMPLES_PER_PERIOD * 10 + freq / 2) / freq;

    return (uint16_t)freq;
}

uint16_t calc_peak(int ch, uint32_t pre, uint32_t now)
{
    uint16_t min, max, val;

    min = 65535;
    max = 0;
    for (uint32_t i = data_ltc1867.sample_pre[ch]; i < data_ltc1867.sample_now[ch]; i++) {
        val = data_ltc1867_raw[ch][i % LTC1867_RAW_BUFF_SIZE];
        if (min > val) {
            min = val;
        }
        if (max < val) {
            max = val;
        }
    }
    return (max - min + 8) / 16;
}

void calc_loop(void)
{
    static uint32_t sample_cnt = 0;
    static uint32_t pre[LTC1867_CH_CNT] = {0, 0, 0, 0};

    if (sample_cnt == data_ltc1867.sample_cnt) {
        return;
    }
    sample_cnt = data_ltc1867.sample_cnt;

    for (int i = 0; i < LTC1867_CH_CNT; i++) {
        if (pre[i] != data_ltc1867.sample_pre[i]) {
            pre[i] = data_ltc1867.sample_pre[i];
            device_data.freq[i] = calc_freq(data_ltc1867.sample_pre[i], data_ltc1867.sample_now[i]);
            device_data.peak[i] = calc_peak(i, data_ltc1867.sample_pre[i], data_ltc1867.sample_now[i]);
        }
    }
}
