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

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

#include "measurement.h"
#include "ssd1306.h"
#include "display.h"
#include "stm32f0xx_it.h"
#include "bbb.h"
#include "SpotWelder.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 */

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

#define BEEPDUR								50
#define MIN_VBAT_MV							8000
#define MAX_VBAT_MV							41000
#define MINIMUM_CAP_VOLTAGE_MV				2000
#define DELAY_BEFORE_WELD_MS				1000
#define DISCHENERGY_STEP_MJ					5
#define MIN_DISCH_ENERGY_MJ					5
#define DELAY_AFTER_PLACING_ELECTRODE_MS	500
#define WELDING_DURATION_MS					90
#define CAPCHARGVOLTAGEDROP_MV				2000

int8_t IsSticked = 0;
int8_t ReqEnergy_mJ = 5;
uint8_t WeldResult;



uint16_t GetReqEnergy(void){
	return ReqEnergy_mJ;
}


uint16_t GetCapEnergy(void){
	return sw_GetEnergy(meas_GetVcap());
}


uint16_t GetMaxCapEnergy(void){
	return sw_GetEnergy( meas_GetVbat() - CAPCHARGVOLTAGEDROP_MV );
}

/* USER CODE END 0 */

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

	for(volatile uint32_t i=0; i<500000; i++);

  /* USER CODE END 1 */

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

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  

  LL_APB1_GRP2_EnableClock(LL_APB1_GRP2_PERIPH_SYSCFG);
  LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_PWR);

  /* System interrupt 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_ADC_Init();
  MX_I2C1_Init();
  MX_TIM16_Init();
  MX_TIM1_Init();
  MX_TIM3_Init();
  /* USER CODE BEGIN 2 */

  //MX_USART1_UART_Init();

  LL_DBGMCU_APB1_GRP2_FreezePeriph(LL_DBGMCU_APB1_GRP2_TIM1_STOP);
  LL_DBGMCU_APB1_GRP1_FreezePeriph(LL_DBGMCU_APB1_GRP2_TIM16_STOP);//__HAL_DBGMCU_FREEZE_TIM1();
  LL_SYSTICK_EnableIT();

  sw_Init();
  bbb_Init();												//Initialize battery, button, buzzer module
  meas_Init();												//Initialize measurement module
  ssd1306_Init();											//Initialize the screen


  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */


  disp_DrawInitScreen();
  bbb_Melody3(1, 2, 3, BEEPDUR);
  bbb_WaitSync(1000);
  while (1)
  {


	  if(IsSticked){
		  disp_DrawResultsScreen(WeldResult);
	  }
	  else{
		  disp_DrawDefScreen("READY");
	  }

	  while(meas_GetVbat() > MAX_VBAT_MV){													//Check overvoltage error
		  disp_DrawDefScreen("OVERVOLT");
		  bbb_Melody3(3, 3, 3, BEEPDUR);
		  bbb_WaitSync(100);
	  }

	  while(meas_GetVbat() < MIN_VBAT_MV){													//Check undervoltage error
		  disp_DrawDefScreen("UNDERVOLT");
		  bbb_Melody3(1, 1, 1, BEEPDUR);
		  bbb_WaitSync(100);
	  }

	  if(meas_GetVcap() < MINIMUM_CAP_VOLTAGE_MV) sw_Charge(MINIMUM_CAP_VOLTAGE_MV);		//Some voltage must be maintained in order to be able to detect electrode placement

	  if( bbb_Update() ){
		  if( Btn2.PrevBtnEvt == bbb_EvtTd_Released ){										//Energy decrease button pressed
			  int8_t EPrev = ReqEnergy_mJ;													//Save currently set value to be able to revert back
			  ReqEnergy_mJ -= DISCHENERGY_STEP_MJ;											//Decrement by desired value

			  int8_t CapEnergy = sw_GetEnergy(meas_GetVcap());								//Get energy stored currently in capacitor

			  if(ReqEnergy_mJ < MIN_DISCH_ENERGY_MJ){										//If desired energy is below specified minimum
				  ReqEnergy_mJ = MIN_DISCH_ENERGY_MJ;										//Saturate it
				  bbb_Beep(2, 3*BEEPDUR);													//Indicate issue
			  }
			  else if(ReqEnergy_mJ < CapEnergy){											//If energy in capacitor bank is higher than desired (for instance after failed discharge)
				  ReqEnergy_mJ = EPrev;														//Do not change it to lower value (keep previous)
				  bbb_Melody3(2, 2, 2, BEEPDUR);											//Indicate issue
			  }
			  else{
				  bbb_Melody2(2, 1, BEEPDUR);												//If everything is OK just set new value
			  }
		  }

		  if( Btn1.PrevBtnEvt == bbb_EvtTd_Released ){
			  volatile uint8_t MaxE = sw_GetEnergy( meas_GetVbat() - CAPCHARGVOLTAGEDROP_MV );	//Energy increase button pressed

			  ReqEnergy_mJ += DISCHENERGY_STEP_MJ;
			  if(ReqEnergy_mJ > MaxE){														//If vbat voltage does not allow such high energy
				  ReqEnergy_mJ = MaxE;														//Set maximum possible discharge energy
				  bbb_Beep(2, 3*BEEPDUR);													//And indicate issue
			  }
			  else{
				  bbb_Melody2(2, 3, BEEPDUR);												//Else just set new value
			  }
		  }
	  }

	  if( ((3*meas_GetVe2())>>1) > meas_GetVcap()){											//When electrodes are connected
		  if(IsSticked == 0){																//And it is not just sticked electrode from previous welding
			  sw_ResetReport();
			  disp_DrawDefScreen("TRIGGERED");
			  bbb_Melody3(3, 3, 3, BEEPDUR);												//Indicate start of welding process
			  bbb_WaitSync(DELAY_AFTER_PLACING_ELECTRODE_MS);								//Wait for some time to allow for electrode placement
			  disp_DrawDefScreen("CHARGING");
			  int8_t ChargStatus = sw_Charge(sw_CalcCapVoltageFromEnergy(ReqEnergy_mJ));	//Start charging

			  if(ChargStatus == 0){															//If charging was successful
				  disp_DrawDefScreen("WELDING");
				  sw_Weld(WELDING_DURATION_MS);												//Start discharging
				  bbb_WaitSync(100);														//Just wait some more

				  if( meas_GetVcap() > 3000 ){												//If capacitor voltage reached low threshold
					  WeldResult = 2;	//Discharge failed
					  bbb_Melody3(3, 2, 1, BEEPDUR);										//Else discharge failed
				  }
				  else{
					  WeldResult = 0;	//Discharge OK
					  bbb_Melody3(1, 2, 3, BEEPDUR);										//Discharge was successful
				  }

			  }
			  else{																			//Else charging of capacitor failed
				  WeldResult = 1;	//Charging failed
				  bbb_Melody3(2, 2, 2, BEEPDUR);
			  }
			  IsSticked = 1;															//Anyway electrode is presumed to be sticked until disconnected and connected again
		  }
	  }
	  else{
		  IsSticked = 0;
		  bbb_WaitSync(100);
	  }

    /* USER CODE END WHILE */

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

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  LL_FLASH_SetLatency(LL_FLASH_LATENCY_1);

  if(LL_FLASH_GetLatency() != LL_FLASH_LATENCY_1)
  {
  Error_Handler();  
  }
  LL_RCC_HSE_Enable();

   /* Wait till HSE is ready */
  while(LL_RCC_HSE_IsReady() != 1)
  {
    
  }
  LL_RCC_HSI14_Enable();

   /* Wait till HSI14 is ready */
  while(LL_RCC_HSI14_IsReady() != 1)
  {
    
  }
  LL_RCC_HSI14_SetCalibTrimming(16);
  LL_RCC_PLL_ConfigDomain_SYS(LL_RCC_PLLSOURCE_HSE_DIV_1, LL_RCC_PLL_MUL_6);
  LL_RCC_PLL_Enable();

   /* Wait till PLL is ready */
  while(LL_RCC_PLL_IsReady() != 1)
  {
    
  }
  LL_RCC_SetAHBPrescaler(LL_RCC_SYSCLK_DIV_1);
  LL_RCC_SetAPB1Prescaler(LL_RCC_APB1_DIV_1);
  LL_RCC_SetSysClkSource(LL_RCC_SYS_CLKSOURCE_PLL);

   /* Wait till System clock is ready */
  while(LL_RCC_GetSysClkSource() != LL_RCC_SYS_CLKSOURCE_STATUS_PLL)
  {
  
  }
  LL_Init1msTick(48000000);
  LL_SetSystemCoreClock(48000000);
  LL_RCC_HSI14_EnableADCControl();
  LL_RCC_SetI2CClockSource(LL_RCC_I2C1_CLKSOURCE_SYSCLK);
}

/* 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 */
  /* 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,
     tex: 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****/
