/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2026 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "cmsis_os.h"
#include "dma.h"
#include "i2c.h"
#include "spi.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include <string.h>
#include <stdio.h>
#include "ch395f.h"
#include "gd5f2gq5ue.h"
#include "tpafe5160.h"
#include "sd2506.h"
#include "rs485.h"
#include "net_socket.h"
#include "net_select.h"
#include "app_main.h"
#include "sys_clock.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 */
#define DBG_TAG "[MAIN]"
#include "dbg_log.h"
/* USER CODE END PM */

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

/* USER CODE BEGIN PV */
/* RS-485 通信实例（UART5: PC12=TX, PD2=RX, PD0=DE） */
rs485_handle_t g_rs485;
#define RS485_RX_BUF_SIZE  256
uint8_t g_rs485_rx_buf[RS485_RX_BUF_SIZE];
/* USER CODE END PV */

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

/* USER CODE END PFP */

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

/* 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_DMA_Init();
  MX_USART1_UART_Init();
  MX_SPI2_Init();
  MX_SPI1_Init();
  MX_I2C1_Init();
  MX_UART4_Init();
  MX_UART5_Init();
  MX_USART2_UART_Init();
  MX_USART3_UART_Init();
  /* USER CODE BEGIN 2 */
    HAL_Delay(100);

    /*
     * 时间子系统初始化（尽早完成，后续所有日志带时间戳）
     * sd2506_init() 从 RTC 读取初始时间
     * sys_clock_init() 将 RTC 时间转为 Unix epoch，建立墙钟基准
     */
    app_main_init();
    sd2506_init();
    sys_clock_init();

    /* RS-485 初始化（UART5 + PD0 方向控制） */
    rs485_init(&g_rs485, &huart5, ST_DIR4_GPIO_Port, ST_DIR4_Pin);
    DBG_INFO("RS485 init: OK (UART5, DE=PD0)");

    /* 启动第一次 RS-485 接收 */
    rs485_receive_start(&g_rs485, g_rs485_rx_buf, RS485_RX_BUF_SIZE);

    /* GD5F 初始化测试 */
    int ret = gd5f2gq5ue_init();
    DBG_INFO("NAND init: %s",
             (ret == GD5F_OK)           ? "OK" :
             (ret == GD5F_ERROR)        ? "ERROR" :
             (ret == GD5F_BUSY_TIMEOUT) ? "BUSY TIMEOUT" :
             (ret == GD5F_ECC_ERROR)    ? "ECC ERROR" :
             (ret == GD5F_PROGRAM_FAIL) ? "PROGRAM FAIL" :
             (ret == GD5F_ERASE_FAIL)   ? "ERASE FAIL" :
             (ret == GD5F_ID_MISMATCH)  ? "ID MISMATCH" : "UNKNOWN");

    /* TPAFE5160 ADC 测试 */
    int tp_ret = tpafe5160_init();
    DBG_INFO("ADC init: %s",
             (tp_ret == TPAFE5160_OK) ? "OK" : "TIMEOUT");

    /* SD2506 RTC 诊断信息 */
    {
        /* 读取 ID */
        uint8_t sd_id[8];
        sd2506_get_id(sd_id);
        DBG_INFO("SD2506 ID: %02X%02X%02X%02X%02X%02X%02X%02X",
                 sd_id[0], sd_id[1], sd_id[2], sd_id[3],
                 sd_id[4], sd_id[5], sd_id[6], sd_id[7]);

        /* 读取当前时间 */
        sd2506_time_t sd_time;
        sd2506_get_time(&sd_time);
        DBG_INFO("SD2506 time: %04d-%02d-%02d %02d:%02d:%02d (week %d)",
                 sd_time.year, sd_time.month, sd_time.day,
                 sd_time.hour, sd_time.minute, sd_time.second,
                 sd_time.week);

        /* 读取温度 */
        int8_t sd_temp;
        sd2506_get_temperature(&sd_temp);
        DBG_INFO("SD2506 temp: %d C", sd_temp);

        /* 读取电池电压 */
        uint16_t sd_vbat;
        sd2506_get_battery_voltage(&sd_vbat);
        DBG_INFO("SD2506 battery: %d.%02d V",
                 sd_vbat / 1000, (sd_vbat % 1000) / 10);
    }

    /* 启动第一次转换（CubeMX 已配置 BUSY EXTI 中断） */
    tpafe5160_start_conv_irq();

    /* CH395F 测试已全部移至 ch395fTestTask */
  /* USER CODE END 2 */

  /* Init scheduler */
  osKernelInitialize();  /* Call init function for freertos objects (in cmsis_os2.c) */
  MX_FREERTOS_Init();

  /* Start scheduler */
  osKernelStart();

  /* We should never get here as control is now taken by the scheduler */

  /* 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_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = 4;
  RCC_OscInitStruct.PLL.PLLN = 168;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = 4;
  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_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;

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

/* USER CODE BEGIN 4 */

/*
 * HAL UART 扩展接收回调（IDLE 空闲帧中断触发）
 * 当 RS-485 总线空闲超过 1 个字符时间后触发
 */
void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
{
    if (huart->Instance == UART5) {
        rs485_rx_set_size(&g_rs485, Size);

        /* TODO: 在此处处理接收到的 RS-485 数据
         * g_rs485_rx_buf[0 .. Size-1] 为有效数据
         * 例如：rs485_transmit(&g_rs485, g_rs485_rx_buf, Size, 0);
         */

        /* 重新开启接收 */
        rs485_receive_start(&g_rs485, g_rs485_rx_buf, RS485_RX_BUF_SIZE);
    }
}

/*
 * HAL UART 错误回调
 */
void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart)
{
    if (huart->Instance == UART5) {
        /* STM32F4 通过读 SR + DR 清除 ORE/NE/FE/PE 错误标志 */
        (void)huart->Instance->SR;
        (void)huart->Instance->DR;
        /* 重新开启接收 */
        rs485_receive_start(&g_rs485, g_rs485_rx_buf, RS485_RX_BUF_SIZE);
    }
}
/* USER CODE END 4 */

/**
  * @brief  Period elapsed callback in non blocking mode
  * @note   This function is called  when TIM7 interrupt took place, inside
  * HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment
  * a global variable "uwTick" used as application time base.
  * @param  htim : TIM handle
  * @retval None
  */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
  /* USER CODE BEGIN Callback 0 */

  /* USER CODE END Callback 0 */
  if (htim->Instance == TIM7)
  {
    HAL_IncTick();
  }
  /* USER CODE BEGIN Callback 1 */

  /* USER CODE END Callback 1 */
}

/**
  * @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 */
