//
// Created by ZK on 2023/3/10.
//

#include "APP_Main.h"

#include "Angle.h"
#include "InteriorADC.h"
//#include "Data/Current/InteriorADC/InteriorADC.h"

float CurrA, CurrB, CurrC;
float Current_Temp, V_Temp;
float32_t NowAngle;

void APP_Init() {
    tData Data;

    Data.Angle.EncoderModel = MT6816;
    Data_Init(&Data);

    NowAngle = Data.Angle.getAngle();


    __HAL_SPI_ENABLE(&hspi1);
    HAL_Delay(10);

    //开启内部运放
    HAL_OPAMP_Start(&hopamp1);
    HAL_OPAMP_Start(&hopamp2);
    HAL_OPAMP_Start(&hopamp3);
    HAL_Delay(10);

    while (InteriorADC_Init());
    HAL_ADC_Start_DMA(&hadc1, (uint32_t *) adc1_RegularBuf, 2);

    HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_1);
    HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_2);
    HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_3);
    HAL_TIMEx_PWMN_Start(&htim1, TIM_CHANNEL_1);
    HAL_TIMEx_PWMN_Start(&htim1, TIM_CHANNEL_2);
    HAL_TIMEx_PWMN_Start(&htim1, TIM_CHANNEL_3);
    HAL_Delay(10);
    __HAL_TIM_ENABLE_IT(&htim1, TIM_IT_UPDATE);
    HAL_Delay(10);

    GPIOE->BSRR = 1 << 7;
    HAL_Delay(10);
}

uint16_t ADC_VAL1, ADC_VAL2;

//MCU内部温度传感器
#define TS_CAL1    ((uint16_t*) ((uint32_t) 0x1FFF75A8))    // 30摄氏度时的MCU内部温度传感器校准值
#define TS_CAL2    ((uint16_t*) ((uint32_t) 0x1FFF75CA))    //110摄氏度时的MCU内部温度传感器校准值

/*滑动平均滤波器长度*/
#define MVF_LENGTH 128

float moving_average_filtre(float xn) {
    static int index = -1;
    static float buffer[MVF_LENGTH];
    static float sum = 0;
    float yn = 0;
    int i = 0;
    if (index == -1) {
        //初始化
        for (i = 0; i < MVF_LENGTH; i++) {
            buffer[i] = xn;
        }
        sum = xn * MVF_LENGTH;
        index = 0;
    } else {
        sum -= buffer[index];
        buffer[index] = xn;
        sum += xn;
        index++;
        if (index >= MVF_LENGTH) {
            index = 0;
        }
    }
    yn = sum / MVF_LENGTH;
    return yn;
}

static float Current_Temp1, ii;

void APP_Main() {
//    TIM1->CCR1 = 0;
//    TIM1->CCR2 = 0;
//    TIM1->CCR3 = 100;
//    TIM1->CCR4 = 10;

    ii += 0.001f;
    Current_Temp = ((110.0 - 30) / (*TS_CAL2 - *TS_CAL1) * (int16_t) (adc1_RegularBuf[1] * 3.3 / 3.0 - *TS_CAL1)) + 30;
    Current_Temp1 = moving_average_filtre(Current_Temp * sinf(ii));
    SendCurrent_Vofa(Current_Temp * sinf(ii), Current_Temp1, 0);


//    usb_printf("%f\r\n", NowAngle);


//    usb_printf("CoreTemp:%d,%d, %.2f\r\n", adc1_RegularBuf[0], adc1_RegularBuf[1], Current_Temp);
//    usb_printf("PhaseCurrent:%d, %d, %d\r\n", ADC1->JDR1 - 2040, ADC2->JDR1 - 2024, ADC1->JDR2 - 2024);
//    usb_printf("PhaseVoltage:%d, %d, %d\r\n", ADC2->JDR2, ADC2->JDR3, ADC2->JDR4);



//    HAL_Delay(10);
}


//软件循环读取ADC
//    HAL_ADC_Start(&hadc1);
//    if (HAL_OK == HAL_ADC_PollForConversion(&hadc1, 50)) {
//        ADC_VAL1 = HAL_ADC_GetValue(&hadc1);
//    }

void APP_Task() {
//    Current_Temp = 1.0f;
//    Current_Temp = (1.43 - adc1_RegularBuf[0] * 3.3 / 4096) * 1000 / 4.35 + 25;
}