/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2023 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 "usb_device.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "math.h"
#define OPAMPGAIN 10
#define ADCCONVFACTOR (5.0/4096)
#define MAGICCONVFACTOR 0.1
/* 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 ---------------------------------------------------------*/
ADC_HandleTypeDef hadc1;

OPAMP_HandleTypeDef hopamp1;

UART_HandleTypeDef huart1;

/* USER CODE BEGIN PV */
typedef struct
{
	uint8_t overvoltage;
	uint8_t undervoltage;
	uint8_t overload;
	uint8_t overtemp;
} warningflags;
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_ADC1_Init(void);
static void MX_OPAMP1_Init(void);
static void MX_USART1_UART_Init(void);
/* USER CODE BEGIN PFP */

void activateIsoDCDC();
void deactivateIsoDCDC();
void setStatusLED();
void resetStatusLED();
void activateRemote();
void deactivateRemote();
void CS_High();
void CS_Low();
void setDAC(uint16_t value, uint8_t active);
uint8_t readLimits(warningflags* flags);
void checkUSB();
void emuSPIsend(uint16_t data);
/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
#define USBTIMEOUT 1000U

extern uint8_t usb_cdc_init_cmplt;
extern volatile uint32_t usb_rx_available;
extern volatile uint8_t usb_rx_overflow;
uint8_t UsbTxBufferFS[256];
uint8_t UsbRxBufferFS[256];

warningflags flags;
/* 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_ADC1_Init();
  MX_OPAMP1_Init();
  MX_USART1_UART_Init();
  MX_USB_DEVICE_Init();
  /* USER CODE BEGIN 2 */

  activateIsoDCDC();
  CS_High();
  HAL_Delay(1);
  CS_Low();
  HAL_Delay(1);
  CS_High();
  HAL_GPIO_WritePin(SPI1_CLK_GPIO_Port, SPI1_CLK_Pin, GPIO_PIN_SET);
  resetStatusLED();
  deactivateRemote();

  setDAC(0x0000, 1);

  while(usb_cdc_init_cmplt == 0);


  activateRemote();
  setStatusLED();
  setDAC(0xF00, 1);

  //getUsbBuffers(UsbTxBufferFS,UsbRxBufferFS);
/*  if(CDC_Start_Receive(UsbRxBufferFS))
  {
	  HAL_UART_Transmit(&huart1, string2, 6, 1000);
  }*/
  HAL_GPIO_WritePin(Status_LED_GPIO_Port, Status_LED_Pin, GPIO_PIN_RESET);
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  uint32_t lastrx = 0;
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
	  if(usb_rx_available >= 2)
	  {

		  uint16_t rawvalue = (uint16_t)(UsbRxBufferFS[0]<<8 | UsbRxBufferFS[1]);
		  float outvolt = ((float)rawvalue)/10 * 1/(OPAMPGAIN*10) * 4096/5;
		  uint16_t outval = (uint16_t) outvolt;
		  setDAC(outval,1);
		  HAL_GPIO_WritePin(Status_LED_GPIO_Port, Status_LED_Pin, GPIO_PIN_SET);
		  usb_rx_available = 0;
		  lastrx = HAL_GetTick();

		  uint8_t txbuf[1];
		  txbuf[0] = (flags.overload<<3) | (flags.overtemp<<2) | (flags.overvoltage<<1) | flags.undervoltage;
		  VCOM_Transmit(txbuf, 1);
	  }

  	  if((HAL_GetTick()-lastrx) > USBTIMEOUT)
	  {
		  setDAC(0, 1);
	  	  HAL_GPIO_WritePin(Status_LED_GPIO_Port, Status_LED_Pin, GPIO_PIN_RESET);
	  }

	  readLimits(&flags);


	  //HAL_UART_Transmit(&huart1, txbuf, 1, 1000);


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

  /** 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.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL3;
  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_HSE;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  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();
  }
  PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USB|RCC_PERIPHCLK_USART1
                              |RCC_PERIPHCLK_ADC12;
  PeriphClkInit.Usart1ClockSelection = RCC_USART1CLKSOURCE_PCLK2;
  PeriphClkInit.Adc12ClockSelection = RCC_ADC12PLLCLK_DIV1;
  PeriphClkInit.USBClockSelection = RCC_USBCLKSOURCE_PLL;
  if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
  * @brief ADC1 Initialization Function
  * @param None
  * @retval None
  */
static void MX_ADC1_Init(void)
{

  /* USER CODE BEGIN ADC1_Init 0 */

  /* USER CODE END ADC1_Init 0 */

  ADC_MultiModeTypeDef multimode = {0};
  ADC_ChannelConfTypeDef sConfig = {0};

  /* USER CODE BEGIN ADC1_Init 1 */

  /* USER CODE END ADC1_Init 1 */

  /** Common config
  */
  hadc1.Instance = ADC1;
  hadc1.Init.ClockPrescaler = ADC_CLOCK_ASYNC_DIV1;
  hadc1.Init.Resolution = ADC_RESOLUTION_12B;
  hadc1.Init.ScanConvMode = ADC_SCAN_DISABLE;
  hadc1.Init.ContinuousConvMode = DISABLE;
  hadc1.Init.DiscontinuousConvMode = DISABLE;
  hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
  hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;
  hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  hadc1.Init.NbrOfConversion = 1;
  hadc1.Init.DMAContinuousRequests = DISABLE;
  hadc1.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
  hadc1.Init.LowPowerAutoWait = DISABLE;
  hadc1.Init.Overrun = ADC_OVR_DATA_OVERWRITTEN;
  if (HAL_ADC_Init(&hadc1) != HAL_OK)
  {
    Error_Handler();
  }

  /** Configure the ADC multi-mode
  */
  multimode.Mode = ADC_MODE_INDEPENDENT;
  if (HAL_ADCEx_MultiModeConfigChannel(&hadc1, &multimode) != HAL_OK)
  {
    Error_Handler();
  }

  /** Configure Regular Channel
  */
  sConfig.Channel = ADC_CHANNEL_3;
  sConfig.Rank = ADC_REGULAR_RANK_1;
  sConfig.SingleDiff = ADC_SINGLE_ENDED;
  sConfig.SamplingTime = ADC_SAMPLETIME_19CYCLES_5;
  sConfig.OffsetNumber = ADC_OFFSET_NONE;
  sConfig.Offset = 0;
  if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN ADC1_Init 2 */

  /* USER CODE END ADC1_Init 2 */

}

/**
  * @brief OPAMP1 Initialization Function
  * @param None
  * @retval None
  */
static void MX_OPAMP1_Init(void)
{

  /* USER CODE BEGIN OPAMP1_Init 0 */

  /* USER CODE END OPAMP1_Init 0 */

  /* USER CODE BEGIN OPAMP1_Init 1 */

  /* USER CODE END OPAMP1_Init 1 */
  hopamp1.Instance = OPAMP1;
  hopamp1.Init.Mode = OPAMP_FOLLOWER_MODE;
  hopamp1.Init.NonInvertingInput = OPAMP_NONINVERTINGINPUT_IO0;
  hopamp1.Init.TimerControlledMuxmode = OPAMP_TIMERCONTROLLEDMUXMODE_DISABLE;
  hopamp1.Init.UserTrimming = OPAMP_TRIMMING_FACTORY;
  if (HAL_OPAMP_Init(&hopamp1) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN OPAMP1_Init 2 */

  /* USER CODE END OPAMP1_Init 2 */

}

/**
  * @brief USART1 Initialization Function
  * @param None
  * @retval None
  */
static void MX_USART1_UART_Init(void)
{

  /* USER CODE BEGIN USART1_Init 0 */

  /* USER CODE END USART1_Init 0 */

  /* USER CODE BEGIN USART1_Init 1 */

  /* USER CODE END USART1_Init 1 */
  huart1.Instance = USART1;
  huart1.Init.BaudRate = 9600;
  huart1.Init.WordLength = UART_WORDLENGTH_8B;
  huart1.Init.StopBits = UART_STOPBITS_1;
  huart1.Init.Parity = UART_PARITY_NONE;
  huart1.Init.Mode = UART_MODE_TX_RX;
  huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart1.Init.OverSampling = UART_OVERSAMPLING_16;
  huart1.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
  huart1.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
  if (HAL_UART_Init(&huart1) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART1_Init 2 */

  /* USER CODE END USART1_Init 2 */

}

/**
  * @brief GPIO Initialization Function
  * @param None
  * @retval None
  */
static void MX_GPIO_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOF_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOA, Status_LED_Pin|SPI1_CLK_Pin|SPI1_DAT_Pin|SPI1_CS_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOB, Remote_CTRL_Pin|Iso_DCDC_Power_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pins : Status_LED_Pin SPI1_CLK_Pin SPI1_DAT_Pin SPI1_CS_Pin */
  GPIO_InitStruct.Pin = Status_LED_Pin|SPI1_CLK_Pin|SPI1_DAT_Pin|SPI1_CS_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  /*Configure GPIO pins : Remote_CTRL_Pin Iso_DCDC_Power_Pin */
  GPIO_InitStruct.Pin = Remote_CTRL_Pin|Iso_DCDC_Power_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

  /*Configure GPIO pins : OVERTEMP_Pin UNDERVOLTAGE_Pin OVERLOAD_Pin OVERVOLTAGE_Pin */
  GPIO_InitStruct.Pin = OVERTEMP_Pin|UNDERVOLTAGE_Pin|OVERLOAD_Pin|OVERVOLTAGE_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_PULLUP;
  HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

  /*Configure GPIO pin : PA9 */
  GPIO_InitStruct.Pin = GPIO_PIN_9;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

}

/* USER CODE BEGIN 4 */
void activateIsoDCDC()
{
	HAL_GPIO_WritePin(Iso_DCDC_Power_GPIO_Port, Iso_DCDC_Power_Pin, GPIO_PIN_SET);
}

void deactivateIsoDCDC()
{
	HAL_GPIO_WritePin(Iso_DCDC_Power_GPIO_Port, Iso_DCDC_Power_Pin, GPIO_PIN_RESET);
}

void setStatusLED()
{
	HAL_GPIO_WritePin(Status_LED_GPIO_Port, Status_LED_Pin, GPIO_PIN_SET);
}

void resetStatusLED()
{
	HAL_GPIO_WritePin(Status_LED_GPIO_Port, Status_LED_Pin, GPIO_PIN_RESET);
}

void activateRemote()
{
	HAL_GPIO_WritePin(Remote_CTRL_GPIO_Port, Remote_CTRL_Pin, GPIO_PIN_RESET);
}

void deactivateRemote()
{
	HAL_GPIO_WritePin(Remote_CTRL_GPIO_Port, Remote_CTRL_Pin, GPIO_PIN_SET);
}

void CS_High()
{
	HAL_GPIO_WritePin(SPI1_CS_GPIO_Port, SPI1_CS_Pin, GPIO_PIN_RESET);
}

void CS_Low()
{
	HAL_GPIO_WritePin(SPI1_CS_GPIO_Port, SPI1_CS_Pin, GPIO_PIN_SET);
}

void setDAC(uint16_t value, uint8_t active)
{
	if(active)
	{
		value &= 0x0FFF; //Bitmask 12 bit Value
		value |= 0x7000; //Set DAC A with buffered reference and Gain x1
	}
	else
	{
		value = 0x0000; //Set Value to Zero and Shutdown Flag
	}

	value = value^0xFFFF;

	CS_Low();
	HAL_GPIO_WritePin(SPI1_CLK_GPIO_Port, SPI1_CLK_Pin, GPIO_PIN_SET);
	HAL_Delay(1);
	emuSPIsend(value);
	HAL_Delay(1);
	CS_High();
}

uint8_t readLimits(warningflags* flags)
{
	flags->overload = HAL_GPIO_ReadPin(OVERLOAD_GPIO_Port, OVERLOAD_Pin);
	flags->overtemp = HAL_GPIO_ReadPin(OVERTEMP_GPIO_Port, OVERTEMP_Pin);
	flags->overvoltage = HAL_GPIO_ReadPin(OVERVOLTAGE_GPIO_Port, OVERVOLTAGE_Pin);
	flags->undervoltage = HAL_GPIO_ReadPin(UNDERVOLTAGE_GPIO_Port, UNDERVOLTAGE_Pin);

	uint8_t errorflag = (flags->overload + flags->overtemp + flags->undervoltage + flags->overvoltage) -4;
	return errorflag;
}

void emuSPIsend(uint16_t data)
{
	for(int n = 15; n >= 0; n--)
	{
		HAL_GPIO_WritePin(SPI1_DAT_GPIO_Port, SPI1_DAT_Pin, (0x1 & (data>>n)));
		HAL_Delay(1);
		HAL_GPIO_WritePin(SPI1_CLK_GPIO_Port, SPI1_CLK_Pin, GPIO_PIN_RESET);
		HAL_Delay(1);
		HAL_GPIO_WritePin(SPI1_CLK_GPIO_Port, SPI1_CLK_Pin, GPIO_PIN_SET);
		HAL_Delay(1);
	}
}

void checkUSB()
{
	if(usb_rx_available)
	{

	}
}

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