#include "main.h"
#include "motorControl.h"
#include "modbus_slave.h"
#include <math.h>

#define MODEL_NAME pmsm_target
#define INIT _init()
#define ISR _isr(0)
#define ISR_DEC _isr(double)
#define CONCAT(A,B) A ## B
#define PYSIM_INIT(A,B) CONCAT(A, B)
#define PYSIM_ISR(A,B) CONCAT(A, B)

extern void PYSIM_INIT(MODEL_NAME, INIT);
extern void PYSIM_ISR(MODEL_NAME, ISR_DEC);

#define OFFSET_THETA 800

extern void SystemClock_Config(void);
extern void findFirstIndex();
extern void MX_TIM1_Init(void);
extern void MC_FOC_Start_PWM_driving(void);
extern void MC_FOC_EnableInputs();

extern int32_t quadPos, theta_elec;
extern q31_t iq_mes;
extern int first_index_reached;
extern TIM_HandleTypeDef TimHandle_period;
extern uint16_t potentiometre;
extern uint16_t Ia_mes, Ib_mes, Ic_mes;
extern int32_t Ia_mes_ext, Ib_mes_ext;
extern q31_t alpha, beta, sinVal, cosVal;

int16_t speed_mes;

uint16_t g_ADCBuffer[3];
int16_t Ia_bias, Ib_bias;
int32_t pulse = -1;

extern double potentiometre_pysim;
extern double pulse_pysim;
extern double theta_elec_pysim;
extern double Ia_pysim;
extern double Ib_pysim;
extern double speed_pysim;
extern double duty1_pysim, duty2_pysim, duty3_pysim;

static volatile int16_t rpm = 0; // consigne globale

static volatile int16_t g_last_applied_speed_rpm = 0;

static void ApplySpeedCommand(int16_t new_rpm, const char *origin) {
    if (new_rpm > 500) new_rpm = 500;
    else if (new_rpm < -500) new_rpm = -500;
    g_last_applied_speed_rpm = new_rpm;
    pulse = (int32_t)new_rpm;
    rpm = new_rpm;  // synchronise consigne globale
    potentiometre_pysim = (double)rpm;
    pulse_pysim = (double)pulse;
    if (origin == NULL) origin = "CMD";
    term_printf("[CMD %s] %d rpm\r\n", origin, new_rpm);
}

static void Fast_Task(void *pvParameters) {
    vTaskDelay(5);
    Ia_bias = Ia_mes;
    Ib_bias = Ib_mes;
    int cnt_5 = 4;
    int16_t signe;
    int index = 0;

    for (;;) {
        if (first_index_reached == 0) {
#if USE_MOTOR
            findFirstIndex();
#else
            first_index_reached = 1;
#endif
        } else {
            HAL_GPIO_WritePin(GPIOC, GPIO_PIN_9, 1);

            // Utilisation directe de rpm synchronisé
            potentiometre_pysim = (double)rpm;
            pulse_pysim = (double)pulse;

            quadPos = quadEncoder_GetPos16();
            signe = ((int16_t)quadPos + OFFSET_THETA);
            if (signe > 8000)
                quadPos = quadPos + OFFSET_THETA - 8000;
            else
                quadPos = quadPos + OFFSET_THETA;

            theta_elec = quadPos % 2000;
            theta_elec_ex = (int32_t)(theta_elec) * 16;
            theta_elec_pysim = theta_elec_ex;

            Ia_mes_ext = ((int32_t)Ia_mes) - Ia_bias;
            Ib_mes_ext = ((int32_t)Ib_mes) - Ib_bias;
            Ia_pysim = Ia_mes_ext;
            Ib_pysim = Ib_mes_ext;

            if (cnt_5 == 0) {
                speed_mes = -quadEncoder_GetSpeed();
                speed_pysim = speed_mes;
                cnt_5 = 4;
                if (index < 5000) {
                    tab_speed[index] = speed_mes;
                    index++;
                }
            }
            cnt_5--;

            PYSIM_ISR(MODEL_NAME, ISR);

            pwmSetDutyCycle((uint16_t)duty1_pysim, (uint16_t)duty2_pysim, (uint16_t)duty3_pysim);
            HAL_GPIO_WritePin(GPIOC, GPIO_PIN_9, 0);
            xSemaphoreGive(xSemaphore_Slow);
        }
        xSemaphoreTake(xSemaphore_Fast, portMAX_DELAY);
    }
}

int main(void) {
    HAL_Init();
    SystemClock_Config();
    adc1_Init();
    uart2_Init();

    quadEncoder_Init();
    pwmTimer_Init();
    tickTimerInit(FAST_TASK_COUNT_PERIOD);

    first_index_reached = 0;
    MC_FOC_Nucleo_Init();
    MC_FOC_Start_PWM_driving();
    pwmSetDutyCycle(420, 420, 420);
    HAL_GPIO_WritePin(GPIOB, GPIO_PIN_2, GPIO_PIN_SET);
    MC_FOC_EnableInputs();

#if USE_PULSE
    pulseGenerator_Init(3000);
#endif

    can_Init();
    can_Filter_disable();
    can_IrqInit();
    can_IrqSet(&can_callback);

    txMsg.id = 0x7FF;
    txMsg.data[0] = 1;
    txMsg.data[1] = 2;
    txMsg.len = 2;
    txMsg.format = CANStandard;
    txMsg.type = CANData;

    can_Write(txMsg);
    HAL_Delay(100);

    PYSIM_INIT(MODEL_NAME, INIT);

    xTaskCreate(Fast_Task, "Fast_Task", 512, NULL, tskIDLE_PRIORITY + 3, NULL);
    // autres tâches (Modbus, Print..) à créer ici aussi

    vSemaphoreCreateBinary(xSemaphore_Fast);
    xSemaphoreTake(xSemaphore_Fast, portMAX_DELAY);
    vSemaphoreCreateBinary(xSemaphore_Slow);
    xSemaphoreTake(xSemaphore_Slow, portMAX_DELAY);

    __HAL_TIM_ENABLE_IT(&TimHandle_period, TIM_IT_UPDATE);
    HAL_TIM_OC_Start(&TimHandle_period, TIM_CHANNEL_1);
    HAL_ADC_Start_DMA(&hadc1, (uint32_t *)g_ADCBuffer, 3);

    vTaskStartScheduler();

    return 0;
}
