/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2021 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"
#include "adc.h"
#include "comp.h"
#include "dac.h"
#include "dma.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "led.h"
#include "output.h"
#include "meas.h"
#include "sysdata.h"
#include "balancer.h"
#include "modbus.h"
#include "eeprom.h"
#include "bms.h"
#include <stdio.h>
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
#define LED_INTERVALL                 1
#define BALANCER_EXEC_INTERVALL       1
#define COMMUNICATION_TIMEOUT  (300000) //in ms --> 5 Minuten
/* 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 */
modbus_t modbusData;
uint32_t communicationTimeoutCounter = 0;
uint16_t keyAccepted=0;
uint16_t savedLockKey;

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
bool SetFlashReadProtection(bool state);
bool SetBootFromFlashAndReadOutProtection(void);
void applyMBParameter(void);
void resetCounters(void);
void resetMinMaxValues(void);
void mb_save_lock_key(void);
/* 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 */
  uint32_t ledExecTime = 0;
 // uint32_t balancerCheckTime = 0;
  uint32_t balancerExecTime = 0;
  uint32_t oldTime=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_COMP1_Init();
  MX_COMP2_Init();
  MX_DAC1_Init();
  MX_TIM1_Init();
  MX_USART1_UART_Init();
  /* USER CODE BEGIN 2 */
  HAL_Delay(100);
  SYSDATA_Init();
  if(EEPROM_isFirstStart())
  {
    // zurücksetzen aller Werte 
    printf("full restore...\n");
    EEPROM_fullRestore(&sysData,false);
    EEPROM_ResetLogData();
  }

  if(HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_3) == GPIO_PIN_RESET)
  {
    // zurücksetzen auf Werkseinsellung
    printf("factore restore (Pin)...\n");
    EEPROM_fullRestore(&sysData,true);    
  }

  // Lade gespeicherte Einstellungen
  printf("read config...\n");
  EEPROM_readConfig(&sysData);
  EEPROM_readLogData();


  //Display Address with Error LED blinks
  int n;
  for (n=0; n<sysData.s.slaveAddress; n++)
  {
    LED_ErrorOn();
    HAL_Delay(350);
    LED_ErrorOff();
    HAL_Delay(350);
  }



  LED_FunctionStartBlink(100,900);
  OUTPUT_LVP_Disable();
  OUTPUT_OVP_Disable();
  BALANCER_Init();
  MEAS_Init();

  // Modbus Initialisierung
  mbInit(&modbusData, sysData.s.baudrate, sysData.s.parityMode, &huart1, accessModeTable, &keyAccepted);
  

  /* USER CODE END 2 */

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


    if (HAL_GetTick() >= (ledExecTime + LED_INTERVALL))
    {
      LED_Exec();
      ledExecTime = HAL_GetTick();
    }


    if (HAL_GetTick() >= (balancerExecTime + BALANCER_EXEC_INTERVALL))
    {
      
      balancerExecTime = HAL_GetTick();
      MEAS_Exec();
      BMS_Exec();
      BALANCER_Exec();    
    }
    
        

    if (HAL_GetTick() > oldTime)
    {
      //1ms Intervall
      oldTime = HAL_GetTick();

      if (communicationTimeoutCounter) 
      {
        communicationTimeoutCounter--;
        if (communicationTimeoutCounter==0)
        {
          sysData.s.masterMode=0;
        }

      }
    }

    if (sysData.s.command != 0) 
    {   
      if  (modbusData.current_query ==  MB_QUERY_NOTHING)
      {
        //printf("CMD = %d\n", sys_data.s.parameter.command);
        switch (sysData.s.command )
        {
          case CMD_SAVE_PARAMETER_TO_EEPROM: 
            printf("EXE: Store parameter\n");
            EEPROM_storeConfig(&sysData,0,false);
            break;
          case CMD_RESET_FACTORY:
            printf("EXEC: Factory Restore\n");
            EEPROM_fullRestore(&sysData,1);
            break;
          case CMD_SAVE_SN:
            printf("EXEC: Store with sn\n");
             EEPROM_storeConfig(&sysData,1,false);
            break;
          case CMD_RESET:
            printf("EXEC: RESTART\n");
            NVIC_SystemReset();
            break;
          case CMD_APPLY_MB_PARAMETER:
            printf("EXEC: Apply MB Parameter\n");
            applyMBParameter();
            break;
          case CMD_RESET_COUNTERS:
            printf("EXEC: Reset Counters\n");
            resetCounters();
            break;
          case CMD_RESET_MIN_MAX_VALUES:
            printf("EXEC: Reset Min and Max Values\n");
            resetMinMaxValues();
            break;
           case CMD_SAVE_LOCK_KEY:
            printf("EXEC: Save lock key\n");
            mb_save_lock_key();
            break;
          default:
              printf("UNKNOWN COMMAND\n");
         
        }
        sysData.s.command = 0;
      }
      else
      {
        //printf("wait with execution till modbus communnikation finished\n");
      }
    }



    // Modbus Kommunikation
    if (mbGetFrameComplete(&modbusData) == true)
    {
      //printf("RX frame complete\n");
      if (mbSlaveCheckModbusRtuQuery(&modbusData) == RESPOND_TO_QUERY) 
      {
        //printf("->send response...\n");
        mbSlaveProcessRtuQuery(&modbusData);    

        //Prüfe KEY 
        if (sysData.s.lockKey == savedLockKey)
        {
          sysData.s.keyAccepted = 1;  
          keyAccepted = 1;        
        }
        else
        {
          sysData.s.keyAccepted = 0;
          keyAccepted = 0;
        }

        //Wenn Ausgleichsspannungsregister von einem Mastergerät geändert wird. In den Master Modus gehen
        if (sysData.s.balancerVoltageRemote != 0)
        {
          communicationTimeoutCounter = COMMUNICATION_TIMEOUT;
          sysData.s.masterMode = 1;        
          sysData.s.balancerVoltage = sysData.s.balancerVoltageRemote;
        }

      }
      else
      {
        //printf("->don't respond...\n");
        modbusData.uart->RxState = HAL_UART_STATE_BUSY_RX;
      }
    }
    else
    {
      if (sysData.s.balancerPower == 0)
      {
  //      HAL_PWR_EnterSLEEPMode(PWR_MAINREGULATOR_ON,PWR_SLEEPENTRY_WFI);
      }
    }
  

    /* 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};
  RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};

  /** Configure the main internal regulator output voltage
  */
  HAL_PWREx_ControlVoltageScaling(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_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_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSE;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
  {
    Error_Handler();
  }
  /** Initializes the peripherals clocks
  */
  PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USART1|RCC_PERIPHCLK_ADC
                              |RCC_PERIPHCLK_TIM1;
  PeriphClkInit.Usart1ClockSelection = RCC_USART1CLKSOURCE_PCLK1;
  PeriphClkInit.AdcClockSelection = RCC_ADCCLKSOURCE_SYSCLK;
  PeriphClkInit.Tim1ClockSelection = RCC_TIM1CLKSOURCE_PCLK1;
  if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */
void mb_save_lock_key()
{
  if (sysData.s.lockKey == savedLockKey)
  {
    EEPROM_storeConfig(&sysData,false,true);
    savedLockKey = sysData.s.newLockKey;
    sysData.s.lockKey = savedLockKey;
  }

  if (savedLockKey != 0)
  {
    sysData.s.writeLocked = 1;
  }
  else
  {
    sysData.s.writeLocked = 0;
  }
}

void applyMBParameter()
{
  HAL_UART_DeInit(&huart1);
  mbInit(&modbusData, sysData.s.baudrate, sysData.s.parityMode, &huart1, accessModeTable, &keyAccepted);
}

void resetCounters()
{
  if (sysData.s.lockKey == savedLockKey)
  {
    sysData.s.criticalOverTempTime = 0;
    sysData.s.criticalUnderTempTime = 0;
    sysData.s.criticalOverVoltageTime = 0;
    sysData.s.criticalUnderVoltageTime = 0;
    sysData.s.cycleCounter = 0;
    EEPROM_storeLogData();
   }
   else
   {
    printf("not allowed, paramter locked!\n");
   }
}

void resetMinMaxValues()
{
  if (sysData.s.lockKey == savedLockKey)
  {
    sysData.s.minTemperature = sysData.s.cellTemperature;
    sysData.s.maxTemperature = sysData.s.cellTemperature;
    sysData.s.minVoltage = sysData.s.cellVoltage;
    sysData.s.maxVoltage = sysData.s.cellVoltage;  
    EEPROM_storeLogData();
   }
   else
   {
    printf("not allowed, paramter locked!\n");
   }
}

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