/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2026 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "modbus.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/*   uC/OS-II Task Stacks   */
static OS_STK  App_TaskStartStk[APP_TASK_START_STK_SIZE];
static OS_STK  App_TaskLedStk[APP_TASK_LED_STK_SIZE];
static OS_STK  App_TaskModbusStk[256u];
static OS_STK  App_TaskT35CheckStk[128u];

/*   USART1 & Modbus   */
UART_HandleTypeDef      huart1;
static Modbus_Slave_t   ModbusSlave;
static OS_EVENT        *ModbusSem;          /* 信号量: 通知 Modbus 任务有新帧 */

/*   Modbus RX 缓冲区   */
static uint8_t  ModbusRxBuf[MODBUS_RX_BUF_SIZE];
static uint16_t ModbusRxLen  = 0u;
static uint32_t ModbusRxTick = 0u;          /* 最后收到字节的 tick */

/*   Modbus TX 缓冲区   */
static uint8_t  ModbusTxBuf[MODBUS_TX_BUF_SIZE];
static uint16_t ModbusTxLen = 0u;

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
/* USER CODE BEGIN PFP */

/*   uC/OS-II Task Prototypes   */
static void  App_TaskStart(void *p_arg);
static void  App_TaskLed(void *p_arg);
static void  App_TaskModbus(void *p_arg);

/*   Local Functions   */
static void  MX_USART1_UART_Init(void);
static void  USART1_StartRx(void);

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/*
*********************************************************************************************************
*                                          LED 闪烁任务
*********************************************************************************************************
*/
static void App_TaskLed(void *p_arg)
{
    (void)p_arg;

    while (1) {
        LED_TOGGLE();
        OSTimeDlyHMSM(0, 0, 0, 100);                     /* 100ms 闪烁，Modbus 通信时更明显 */
    }
}

/*
*********************************************************************************************************
*                                      MODBUS 从站任务
*
*  等待信号量 → 处理 Modbus 帧 → 发送响应 → 重新启动接收
*********************************************************************************************************
*/
static void App_TaskModbus(void *p_arg)
{
    uint8_t  err;
    uint16_t tx_len;
    INT8U    os_err;

    (void)p_arg;

    Modbus_SlaveInit(&ModbusSlave, MODBUS_SLAVE_ADDR_DEFAULT);
    USART1_StartRx();                                     /* 启动第一次接收 */

    while (1) {
        /* 等待帧接收完成信号（超时 10ms，用于检测 T3.5 超时） */
        OSSemPend(ModbusSem, MODBUS_T35_TIMEOUT, &os_err);

        /* 检查是否收到完整帧 */
        if (ModbusRxLen > 0u) {
            /* 处理 Modbus 帧 */
            err = Modbus_ProcessFrame(&ModbusSlave,
                                      ModbusRxBuf, ModbusRxLen,
                                      ModbusTxBuf, &tx_len);

            /* 发送响应（成功或异常响应都需要发送） */
            if (err >= 0 && tx_len > 0u) {
                HAL_UART_Transmit(&huart1, ModbusTxBuf, tx_len, 50u);
            }

            ModbusRxLen = 0u;                             /* 清空接收缓冲 */
        }

        /* 重新启动 UART 接收 */
        USART1_StartRx();
    }
}

/*
*********************************************************************************************************
*                                      RX 字节接收回调
*********************************************************************************************************
*/
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
    if (huart->Instance == USART1) {
        ModbusRxLen++;
        ModbusRxTick = OSTimeGet();                       /* 记录最后接收时间 */

        if (ModbusRxLen < MODBUS_RX_BUF_SIZE) {
            HAL_UART_Receive_IT(&huart1, &ModbusRxBuf[ModbusRxLen], 1u);
        } else {
            /* 缓冲区溢出，重置 */
            ModbusRxLen = 0u;
            HAL_UART_Receive_IT(&huart1, &ModbusRxBuf[0], 1u);
        }
    }
}

/*
*********************************************************************************************************
*                                      启动 USART1 接收
*********************************************************************************************************
*/
static void USART1_StartRx(void)
{
    ModbusRxLen  = 0u;
    ModbusRxTick = OSTimeGet();
    HAL_UART_Receive_IT(&huart1, &ModbusRxBuf[0], 1u);
}

/*
*********************************************************************************************************
*                                        T3.5 超时检测任务
*
*  周期性检查接收超时，超时后发送信号量给 Modbus 任务
*********************************************************************************************************
*/
static void App_TaskT35Check(void *p_arg)
{
    INT8U os_err;

    (void)p_arg;

    while (1) {
        OSTimeDly(MODBUS_T35_TIMEOUT);                    /* 每隔 T3.5 时间检查一次 */

        if (ModbusRxLen > 0u) {
            uint32_t elapsed = OSTimeGet() - ModbusRxTick;

            /* 如果超过 T3.5 没有收到新数据，认为帧结束 */
            if (elapsed >= MODBUS_T35_TIMEOUT) {
                OSSemPost(ModbusSem);                     /* 通知 Modbus 任务处理 */
            }
        }
    }
}

/*
*********************************************************************************************************
*                                        STARTUP TASK
*********************************************************************************************************
*/
static void App_TaskStart(void *p_arg)
{
    (void)p_arg;

    /* 创建信号量 (初始计数值 = 0) */
    ModbusSem = OSSemCreate(0u);

    /* 创建 LED 闪烁任务 */
    OSTaskCreateExt(App_TaskLed,
                    (void *)0,
                    (OS_STK *)&App_TaskLedStk[APP_TASK_LED_STK_SIZE - 1u],
                    APP_TASK_LED_PRIO,
                    APP_TASK_LED_PRIO,
                    (OS_STK *)&App_TaskLedStk[0],
                    APP_TASK_LED_STK_SIZE,
                    (void *)0,
                    OS_TASK_OPT_STK_CHK | OS_TASK_OPT_STK_CLR);

    /* 创建 Modbus 从站处理任务 */
    OSTaskCreateExt(App_TaskModbus,
                    (void *)0,
                    (OS_STK *)&App_TaskModbusStk[255u],
                    APP_TASK_MODBUS_PRIO,
                    APP_TASK_MODBUS_PRIO,
                    (OS_STK *)&App_TaskModbusStk[0],
                    256u,
                    (void *)0,
                    OS_TASK_OPT_STK_CHK | OS_TASK_OPT_STK_CLR);

    /* T3.5 超时检测任务 */
    OSTaskCreateExt(App_TaskT35Check,
                    (void *)0,
                    (OS_STK *)&App_TaskT35CheckStk[127u],
                    APP_TASK_MODBUS_PRIO + 1u,
                    APP_TASK_MODBUS_PRIO + 1u,
                    (OS_STK *)&App_TaskT35CheckStk[0],
                    128u,
                    (void *)0,
                    OS_TASK_OPT_STK_CHK | OS_TASK_OPT_STK_CLR);

    /* 挂起自身 */
    while (1) {
        OSTaskSuspend(OS_PRIO_SELF);
    }
}

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_USART1_UART_Init();    /* 初始化 Modbus 通信串口 (USART1, 9600-8-N-1) */
  /* USER CODE BEGIN 2 */

  /* uC/OS-II 初始化 */
  OSInit();

  /* 创建启动任务 */
  OSTaskCreateExt(App_TaskStart,
                  (void *)0,
                  (OS_STK *)&App_TaskStartStk[APP_TASK_START_STK_SIZE - 1u],
                  APP_TASK_START_PRIO,
                  APP_TASK_START_PRIO,
                  (OS_STK *)&App_TaskStartStk[0],
                  APP_TASK_START_STK_SIZE,
                  (void *)0,
                  OS_TASK_OPT_STK_CHK | OS_TASK_OPT_STK_CLR);

  /* 启动 uC/OS-II 多任务调度 */
  OSStart();

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  __HAL_RCC_PWR_CLK_ENABLE();
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
  * @brief GPIO Initialization Function
  * @param None
  * @retval None
  */
static void MX_GPIO_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOH_CLK_ENABLE();
  __HAL_RCC_GPIOF_CLK_ENABLE();

  /*Configure GPIO pin : PF6 */
  GPIO_InitStruct.Pin = GPIO_PIN_6;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_PULLUP;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOF, &GPIO_InitStruct);

}

/* USER CODE BEGIN 4 */

/*
*********************************************************************************************************
*                                       USART1 初始化
*********************************************************************************************************
*/
static void MX_USART1_UART_Init(void)
{
    huart1.Instance          = USART1;
    huart1.Init.BaudRate     = 9600u;
    huart1.Init.WordLength   = UART_WORDLENGTH_8B;
    huart1.Init.StopBits     = UART_STOPBITS_1;
    huart1.Init.Parity       = UART_PARITY_NONE;
    huart1.Init.Mode         = UART_MODE_TX_RX;
    huart1.Init.HwFlowCtl    = UART_HWCONTROL_NONE;
    huart1.Init.OverSampling = UART_OVERSAMPLING_16;
    HAL_UART_Init(&huart1);
}

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
