#include "main.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

#include "app_main.h"
#include "Com_type.h"
#include "Com_debug.h"
#include "Int_Encoder.h"
#include "Int_TMC2209.h"
#include "app_key.h"
#include "app_motor.h"
#include "app_param_store.h"
#include "app_test.h"
#include "CANopen.h"
#include "CO_app_STM32.h"
#include "can.h"

Encoder_t encoder_1 = {0};

Stepper_t stepper_1 = {
    .dir = GPIO_PIN_RESET,  // 方向(1为手轮方向，0为电机方向)
    .distance = 100.0f,
    .speed = 50.0f,
    .acc = 40.0f,
    .dec = 40.0f,
    .start_speed = 5.0f,
};

CANopenNodeSTM32 CANopenNode;

static void App_PrintKeyUsage(void)
{
    debug_printf("%s", "================ 按键功能说明 ================");
    debug_printf("%s", "K1 (单击): 自动回零 (HOME, 低速 5 mm/s)");
    debug_printf("%s", "K2 (长按): JOG+ 正向点动, 松开后减速停止");
    debug_printf("%s", "K3 (长按): JOG- 反向点动, 松开后减速停止");
    debug_printf("%s", "K4 (单击): 速度档位循环 5 -> 25 -> 60 mm/s");
    debug_printf("%s", "K5 (单击): 紧急停止 (立即停机)");
    debug_printf("%s", "提示: 回零完成以零位开关触发为准");
    debug_printf("%s", "==============================================");
}

static void CANopenNode_init(void)
{
    CANopenNode.CANHandle = &hcan1;
    CANopenNode.HWInitFunction = MX_CAN1_Init;
    CANopenNode.timerHandle = &htim11;
    CANopenNode.desiredNodeID = 3;
    CANopenNode.baudrate = 500;
    canopen_app_init(&CANopenNode);
}

void app_main(void)
{
    debug_printf("hello three-axis steppers");
    App_PrintKeyUsage();
    CANopenNode_init();
    App_Motor_Init();
    App_ParamStore_Init();
    (void)App_ParamStore_LoadAndApply();
    while (1)
    {
        App_key_run(&stepper_1);
        canopen_app_process();
        App_Motor_Process();
        App_ParamStore_Process();
    }
}

void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
    switch (GPIO_Pin)
    {
    case X_ZERO_Pin:
        stepper_1.x_zero = 1;
        break;
    case ENCODER1_Z_Pin:
        encoder_1.z++;
    default:
        break;
    }
}

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
    if (htim == CANopenNode.timerHandle)
    {
        canopen_app_interrupt();
    }

    if (htim->Instance == TIM12)
    {
        App_Motor_StepLossCheck();
    }
}
