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

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include <stdio.h>
#include "button.h"
#include "buzzer.h"
#include "relais.h"
#include "leds.h"
#include "fan.h"
#include "chip_temperature.h"
#include "modeswitch.h"
#include "mode_mainswitch.h"
#include "mode_secondaryprotection.h"
#include "mode_secondaryprotection_plus.h"
#include "mode_lvp.h"
#include "mode_ovp.h"
#include "mode_lvp_ovp.h"
#include "voltage_meas.h"
/* USER CODE END Includes */

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

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
int oldTimeMSTick;
int oldTimeSeconds;
int msCounter;
/* USER CODE END PD */

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

/* USER CODE END PM */

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

/* USER CODE BEGIN PV */
static volatile uint32_t adcData[5];
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(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 */
  int temperature = 0;
  unsigned pwm = 0U;
  uint32_t uin = 0;
  uint32_t uout = 0;
  /* 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_ADC1_Init();
  MX_TIM16_Init();
  MX_TIM17_Init();
  MX_IWDG_Init();
 // MX_USART1_UART_Init();
  /* USER CODE BEGIN 2 */
  printf("debug io test...ok\r\n");
  HAL_GPIO_WritePin(GPIO_OUTPUT_BUZZER_GPIO_Port, GPIO_OUTPUT_BUZZER_Pin, GPIO_PIN_SET);
  HAL_GPIO_WritePin(GPIO_OUTPUT_LED_ERROR_GPIO_Port, GPIO_OUTPUT_LED_ERROR_Pin, GPIO_PIN_SET);
  HAL_GPIO_WritePin(GPIO_OUTPUT_LED_ON_GPIO_Port, GPIO_OUTPUT_LED_ON_Pin, GPIO_PIN_SET);
  HAL_Delay(500);
  HAL_GPIO_WritePin(GPIO_OUTPUT_BUZZER_GPIO_Port, GPIO_OUTPUT_BUZZER_Pin, GPIO_PIN_RESET);
  HAL_GPIO_WritePin(GPIO_OUTPUT_LED_ERROR_GPIO_Port, GPIO_OUTPUT_LED_ERROR_Pin, GPIO_PIN_RESET);
  HAL_GPIO_WritePin(GPIO_OUTPUT_LED_ON_GPIO_Port, GPIO_OUTPUT_LED_ON_Pin, GPIO_PIN_RESET);

    //--- RELAIS ZURÜCKSETZEN, damit es definitiv aus ist ---
  //Sicherstellen das nicht noch die Set Spule aktiv geschaltet ist
  HAL_GPIO_WritePin(GPIO_OUTPUT_RELAIS_SET_GPIO_Port, GPIO_OUTPUT_RELAIS_SET_Pin, GPIO_PIN_RESET);

  //Puls starten
  HAL_GPIO_WritePin(GPIO_OUTPUT_RELAIS_RESET_GPIO_Port, GPIO_OUTPUT_RELAIS_RESET_Pin, GPIO_PIN_SET);
  HAL_Delay(50);
  HAL_GPIO_WritePin(GPIO_OUTPUT_RELAIS_RESET_GPIO_Port, GPIO_OUTPUT_RELAIS_RESET_Pin, GPIO_PIN_RESET);
  //--- RELAIS ZURÜCKSETZEN ENDE ----

  MODESWITCH_ReadMode();

  CHIP_TEMPERATURE_Calibration(/*&sys_data*/);
  HAL_ADCEx_Calibration_Start(&hadc1);
  HAL_ADC_Start_DMA(&hadc1, (uint32_t*)adcData, 5);


	
extern uint32_t frequency, ic_overflows;
  ic_overflows = 0U;
  __HAL_TIM_SetCounter(&htim16, 0U);

  HAL_TIM_Base_Start_IT(&htim16);
  HAL_TIM_IC_Start_IT(&htim16, TIM_CHANNEL_1);
  int oldcaptureValue=0;


  /* USER CODE END 2 */

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

    /* USER CODE BEGIN 3 */
	HAL_IWDG_Refresh(&hiwdg);


	if (oldTimeMSTick != HAL_GetTick())
    {
      BUTTON_Exec();
      BUZZER_Exec();
      RELAIS_Exec();
      LEDS_Exec();
	  VOLTAGE_MEAS_Exec(adcData[1],adcData[2]);
      oldTimeMSTick = HAL_GetTick();
	  msCounter++;
    }


	//Sekunden tick
	if (msCounter >= 999)
	{
	  msCounter = 0;
      CHIP_TEMPERATURE_Exec(adcData[4]);
	  temperature=CHIP_TEMPERATURE_GetTemp();
	  if ( temperature > 50)
	  {  
		  pwm++;
		  if (pwm > 100U) pwm = 100U;	
		  
	  }
	  if (temperature < 50)
	  {
		if (pwm > 0) pwm--;
	  }
	 
	  FAN_SetSpeed(pwm);

	  uin = VOLTAGE_MEAS_GetUin();
	  uout = VOLTAGE_MEAS_GetUout();
	  uint32_t rpm;
	  rpm = frequency / 2;
	  rpm = rpm * 60;
	  printf("uin= %d, uout=%d, temp=%d, pwm=%d, fan=%d\r\n", uin, uout, temperature,pwm,rpm);
	  
	  
	} //endsecond tick



    switch (MODESWITCH_GetMode())
    {
      case MODE_MAINSWITCH: //0
        MODE_MAINSWITCH_Exec();
      break;

      case MODE_MAINSWITCH_SECONDARYPROTECTION://1
        MODE_SECONDARYPROTECTION_Exec(0);
      break;

      case MODE_MAINSWITCH_SECONDARYPROTECTION_PLUS://2
        MODE_SECONDARYPROTECTION_PLUS_Exec(0);
      break;

      case MODE_MAINSWITCH_SECONDARYPROTECTION_AUTO_RETRY://3
        MODE_SECONDARYPROTECTION_Exec(1);
      break;

      case MODE_MAINSWITCH_SECONDARYPROTECTION_PLUS_AUTO_RETRY://4
        MODE_SECONDARYPROTECTION_PLUS_Exec(1);
      break;

	  case MODE_MAINSWITCH_LVP_OVP://5
        MODE_LVP_OVP_Exec();
      break;

      case MODE_MAINSWITCH_LVP://6
        MODE_LVP_Exec();
      break;

      case MODE_MAINSWITCH_OVP://7
        MODE_OVP_Exec();
      break;




      default:
      printf("mode not yet implemented\n");

    }
  }
  
  /* USER CODE END 3 */
}

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

  __HAL_FLASH_SET_LATENCY(FLASH_LATENCY_0);

  /** 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.HSIDiv = RCC_HSI_DIV4;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  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_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
  RCC_ClkInitStruct.SYSCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_APB1_DIV1;

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

/* USER CODE BEGIN 4 */

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