/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2024 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 "adc.h"
#include "can.h"
#include "dma.h"
#include "iwdg.h"
#include "rtc.h"
#include "spi.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

/* USER CODE END Includes */

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

uint8_t dataReceive1[BUFFER_SIZE]__attribute__((section(".ccmram")));;//调试
uint8_t dataReceive2[BUFFER_SIZE2]__attribute__((section(".ccmram")));;// 485
uint8_t uart2RXDATAbuffer[BUFFER_SIZE2]__attribute__((section(".ccmram")));;

uint8_t receiveBuff4G[BUFFER_SIZE4G]__attribute__((section(".ccmram")));;//4G
extern circle_buf_t uart3CircleBuf;  // 环形缓冲区管理结构体
uint8_t receiveBuff4G_MIPURC[256]__attribute__((section(".ccmram")));;//4G处理mipurc的接收缓冲区

/* USER CODE END PTD */

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

uint8_t RX_Data[8];
uint8_t TX_Data[8];

/* USER CODE END PD */

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

/* USER CODE END PM */

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

/* USER CODE BEGIN PV */


/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
void MX_FREERTOS_Init(void);
/* USER CODE BEGIN PFP */
void uart_enable(void);
HAL_StatusTypeDef CAN_FilterInit(void);
void CAN_Send_Msg(uint8_t *msg,uint8_t len,uint32_t id);

/* 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 */
	
//	__disable_irq();  // 关闭中断	
	
  /* 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_USART2_UART_Init();
  MX_CAN1_Init();
  MX_RTC_Init();
  MX_USART3_UART_Init();
  MX_IWDG_Init();
  MX_ADC1_Init();
  MX_SPI2_Init();
  /* USER CODE BEGIN 2 */
//	MX_IWDG_Init();
	uart_enable();
	
	HAL_GPIO_WritePin(GPIOB, RESET_4G_Pin, GPIO_PIN_RESET);
	HAL_Delay(500);
	HAL_GPIO_WritePin(GPIOB, RESET_4G_Pin, GPIO_PIN_SET);
	HAL_Delay(3000);
		
	CAN_FilterInit();
	printf("MainBoard Hello V2025_0520\r\n");
//	__enable_irq();  // 开启中断
  /* USER CODE END 2 */

  /* Init scheduler */
  osKernelInitialize();  /* Call init function for freertos objects (in freertos.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
  */
  if (HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1) != HAL_OK)
  {
    Error_Handler();
  }

  /** Configure LSE Drive Capability
  */
  HAL_PWR_EnableBkUpAccess();
  __HAL_RCC_LSEDRIVE_CONFIG(RCC_LSEDRIVE_LOW);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI|RCC_OSCILLATORTYPE_LSI
                              |RCC_OSCILLATORTYPE_LSE;
  RCC_OscInitStruct.LSEState = RCC_LSE_ON;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.LSIState = RCC_LSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
  RCC_OscInitStruct.PLL.PLLM = 1;
  RCC_OscInitStruct.PLL.PLLN = 8;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV7;
  RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
  RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
  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_DIV4;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

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

/* USER CODE BEGIN 4 */
void uart_enable(void)
{
	memset(dataReceive1, 0, sizeof(dataReceive1));
	memset(dataReceive2, 0, sizeof(dataReceive2));
	memset(receiveBuff4G, 0, sizeof(receiveBuff4G));//3
	circle_buf_init(&uart3CircleBuf, BUFFER_SIZE4G, receiveBuff4G);
	
	__HAL_UART_ENABLE_IT(&huart1, UART_IT_IDLE);//使能IDLE中断
	__HAL_UART_ENABLE_IT(&huart2, UART_IT_IDLE);

  HAL_UART_Receive_DMA(&huart1, dataReceive1, BUFFER_SIZE);	
  HAL_UART_Receive_DMA(&huart2, dataReceive2, BUFFER_SIZE2); // 启动USART2的DMA接收485
}

HAL_StatusTypeDef CAN_FilterInit(void)
{
	CAN_FilterTypeDef CAN_FilterInitStructure;
	CAN_FilterInitStructure.FilterBank=0;
	CAN_FilterInitStructure.FilterScale=CAN_FILTERSCALE_32BIT;
	CAN_FilterInitStructure.FilterMode=CAN_FILTERMODE_IDMASK;
	CAN_FilterInitStructure.FilterFIFOAssignment=CAN_FILTER_FIFO0;
	CAN_FilterInitStructure.FilterIdHigh=0x0000;
	CAN_FilterInitStructure.FilterIdLow=0x0000;
	CAN_FilterInitStructure.FilterMaskIdHigh=0x0000;
	CAN_FilterInitStructure.FilterMaskIdLow=0x0000;
	CAN_FilterInitStructure.FilterActivation=CAN_FILTER_ENABLE;
	if(HAL_CAN_ConfigFilter(&hcan1,&CAN_FilterInitStructure) != HAL_OK)
	{
//		Error_Handler();
		return HAL_ERROR;
	}
	
  if (HAL_CAN_Start(&hcan1) != HAL_OK)
  {
		uint32_t can_error = HAL_CAN_GetError(&hcan1);
    printf("CAN Initialization Error: %ld\n", can_error);
		printf("CAN_start_FAIL\r\n");
//    Error_Handler();
  }else{
//			printf("CAN_start_OK\r\n");
	}
	
	  /*##-4- Activate CAN RX notification #######################################*/
  if (HAL_CAN_ActivateNotification(&hcan1, CAN_IT_RX_FIFO0_MSG_PENDING) != HAL_OK)
  {
    printf("CAN_Activate_FAIL\r\n");
    Error_Handler();
  }else{
//		printf("CAN_Activate_OK\r\n");
	}
	return HAL_OK;
}

void CAN_Send_Msg(uint8_t *msg,uint8_t len,uint32_t id)
{
	CAN_TxHeaderTypeDef Tx_Header;
	uint32_t TxMailBox;	
	Tx_Header.StdId = id;
	Tx_Header.ExtId = id;	
	Tx_Header.IDE = CAN_ID_EXT;
	Tx_Header.RTR = CAN_RTR_DATA;
	Tx_Header.DLC = len;
	if (HAL_CAN_AddTxMessage(&hcan1, &Tx_Header, msg, &TxMailBox) != HAL_OK)
    {
        Error_Handler();
    }	
}


/*
	+MGNSSLOC:
<UTC>,<latitude>,<longtitude>,<hdop>,<altitude>,<fix>,<cog>,<spkm>,<spkn>,<date>,<
nstat>,<dtype>

<UTC>(hhmmss.sss) UTC时间，时分秒.毫秒，位�?10�?
<latitude> (ddmm.mmmmN/S)
纬度，dd:度，mm.mmmm:分，N/S:北纬/南纬，保�?4位小数�??
<longtitude> (dddmm.mmmmE/W)
经度，ddd:度，mm.mmmm:分，E/W:东经/西经，保�?4位小�?
<hdop> (x.x) 水平精度因子，保�?1位小数�??
<altitude> (x.x) 海拔高度，单�?:米，保留1位小数�??
<fix> (n) 定位类型�?1:未定位，2:2D定位�?3:3D定位；位�?1�?
<cog> (ddd.dd) 运动角度，真北参照系，单�?:度，保留2位小�?
<spkm> (x.x) 水平运动速度，单位Km/h，保�?1位小�?
<date> (ddmmyy) 当前日期，日月年，位�?6
<nsat> (nn) 参与定位的卫星数量，位宽2
<dtype> (n) 差分定位标识，位�?1�?0:无效�?1:单点定位�?2:差分定位

*/
//void ML307A_Read_Location(void) 
//{
//    char response[256];
//    
//    // 获取定位信息
//    Send_Command_Check_Response("AT+MGNSSLOC?", response, sizeof(response));
//    
//    // 解析响应
//    if (strstr(response, "+MGNSSLOC:") != NULL) {
//        // 示例解析�?+MGNSSLOC: 005031.833,2937.1685N,10629.6172E,2.1,453.3,3,0.00,0.1,0.1,141222,06,1
//        char utc[11]; // UTC时间
//        float lat, lon, hdop, altitude, spkm;
//        int fix, cog, day, month, year, nsat, dtype;
//        int hour, minute, second, millisecond; // 添加毫秒的定�?

//        // 解析定位信息
//        sscanf(response, "+MGNSSLOC: %10s,%f,%f,%f,%f,%d,%d,%f,%f,%6d,%d,%d",
//               utc, &lat, &lon, &hdop, &altitude, &fix, &cog, &spkm, &spkm, &day, &month, &year, &nsat, &dtype);
//        
//        // 处理时间
//        sscanf(utc, "%2d%2d%2d.%3d", &hour, &minute, &second, &millisecond);
//        year = 2000 + (year % 100); // 假设年份�?2000年后�?
//        
//        printf("经度: %.4f, 纬度: %.4f\n", lon, lat);
//        printf("时间: %04d-%02d-%02d %02d:%02d:%02d\n", year, month, day, hour, minute, second);      
//        
//        // 上传到MQTT
//        send_mqtt_tphcll(tem, pre, H2, CO, lon, lat);
//        send_mqtt_time_nsat_alt_spkm(year, month, day, hour, minute, second, nsat, altitude, spkm);
//    } else {
//        printf("fail\n");
//    }
//}




/* USER CODE END 4 */

/**
  * @brief  Period elapsed callback in non blocking mode
  * @note   This function is called  when TIM6 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 == TIM6) {
    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)
  {
//		NVIC_SystemReset(); // 执行芯片复位
  }
  /* 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 */
