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

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "can.h"
/* USER CODE END Includes */

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

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* 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 ---------------------------------------------------------*/
CAN_HandleTypeDef hcan;

/* USER CODE BEGIN PV */

/* USER CODE END PV */

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

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
extern dash_tx_t dash_tx;
extern rx_acc acc_status;
uint8_t sdc_closed;
uint8_t blink_state;
uint8_t r2d_progress;
uint32_t blink_tick_tson;
uint32_t blink_tick_r2d;
uint32_t ams_last_tick;
uint32_t can_send_tick;
/* 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_CAN_Init();
  /* USER CODE BEGIN 2 */
  can_init(&hcan);

  blink_state = 0;
  sdc_closed = 0;
  blink_tick_tson = HAL_GetTick();
  blink_tick_r2d = HAL_GetTick();
  can_send_tick = HAL_GetTick();

  /* USER CODE END 2 */

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

    /* USER CODE BEGIN 3 */
	  dash_tx.tson = HAL_GPIO_ReadPin(TSON_BTN_GPIO_Port, TSON_BTN_Pin);
	  dash_tx.r2d = HAL_GPIO_ReadPin(R2D_BTN_GPIO_Port, R2D_BTN_Pin);
	  dash_tx.sdc_in = HAL_GPIO_ReadPin(SDC_In_3V3_GPIO_Port, SDC_In_3V3_Pin);
	  dash_tx.sdc_out = HAL_GPIO_ReadPin(SDC_Out_3V3_GPIO_Port, SDC_Out_3V3_Pin);
	  dash_tx.racemode = HAL_GPIO_ReadPin(RMode_Out_3V3_GPIO_Port, RMode_Out_3V3_Pin);

	  // Inverted in hardware
	  if ((HAL_GetTick() - ams_last_tick) < 350) { //master sendet aller 100ms, fürs testen erstmal auf 150ms gesetzt -> kann später wieder runter
	  	HAL_GPIO_WritePin(IMD_LED_GPIO_Port, IMD_LED_Pin, acc_status.led_status.imd_error);
	  	HAL_GPIO_WritePin(AMS_LED_GPIO_Port, AMS_LED_Pin, acc_status.led_status.ams_error);
	  	HAL_GPIO_WritePin(TSOFF_LED_GPIO_Port, TSOFF_LED_Pin,acc_status.led_status.ts_green);
	  } else {
		// Safe state: Error LEDs on, TSOFF off
	  	HAL_GPIO_WritePin(IMD_LED_GPIO_Port, IMD_LED_Pin, 0);
	  	HAL_GPIO_WritePin(AMS_LED_GPIO_Port, AMS_LED_Pin, 0);
	  	HAL_GPIO_WritePin(TSOFF_LED_GPIO_Port, TSOFF_LED_Pin, 0);
	  }

	  int r = 0, g = 0, b = 0;
	  int br = 0, bg = 0, bb = 0;

	  if(acc_status.ams_status.sdc_closed == 1){
		  if(acc_status.ams_status.ts_state == TS_INACTIVE){
			  r = g = 1;
		  }
		  if(acc_status.ams_status.ts_state == TS_PRECHARGE){
			  br = bg = 1;
		  }
		  if(acc_status.ams_status.ts_state == TS_ACTIVE){
			  g = 1;
		  }
		  if(acc_status.ams_status.ts_state == TS_DISCHARGE){
			  br = bb = 1;
		  }
		  if(acc_status.ams_status.ts_state == TS_ERROR){
			  r = 1;
		  }
	  }
	  else{
		  b = r = 1;
	  }

	  HAL_GPIO_WritePin(TSON_R_GPIO_Port, TSON_R_Pin, r);
	  HAL_GPIO_WritePin(TSON_G_GPIO_Port, TSON_G_Pin, g);
	  HAL_GPIO_WritePin(TSON_B_GPIO_Port, TSON_B_Pin, b);

	  if ((br || bg || bb) && ((HAL_GetTick() - blink_tick_tson) > 10u)) {
	  	HAL_GPIO_WritePin(TSON_R_GPIO_Port, TSON_R_Pin, br && blink_state);
	  	HAL_GPIO_WritePin(TSON_G_GPIO_Port, TSON_G_Pin, bg && blink_state);
	  	HAL_GPIO_WritePin(TSON_B_GPIO_Port, TSON_B_Pin, bb && blink_state);
	  	blink_tick_tson = HAL_GetTick();
	  }

	  r = g = b = 0;
	  br = bg = bb = 0;

	  if (acc_status.ams_status.ts_state == TS_ACTIVE) {
		  if((r2d_progress == R2D_TS_ACTIVE) || (r2d_progress == R2D_TSMS) || (r2d_progress == R2D_NONE)){
			  r = g = 1;
		  }
		  if((r2d_progress == R2D_RESETTING_NODES) || (r2d_progress == R2D_RESETTING_COMMS) || (r2d_progress == R2D_WAITING_INIT) || (r2d_progress == R2D_INIT_STAGE1) || (r2d_progress == R2D_INIT_STAGE2)){
			  br = bg = 1;
		  }
		  if(r2d_progress == R2D_INIT_SUCCESS){
			  g = 1;
		  }
	  } else {
		  b = r = 1;
	  }

	  HAL_GPIO_WritePin(R2D_R_GPIO_Port, R2D_R_Pin, r);
	  HAL_GPIO_WritePin(R2D_G_GPIO_Port, R2D_G_Pin, g);
	  HAL_GPIO_WritePin(R2D_B_GPIO_Port, R2D_B_Pin, b);


	  if ((br || bg || bb) && ((HAL_GetTick() - blink_tick_r2d) > 10u)) {
	  	HAL_GPIO_WritePin(R2D_R_GPIO_Port, R2D_R_Pin, br && blink_state);
	  	HAL_GPIO_WritePin(R2D_G_GPIO_Port, R2D_G_Pin, bg && blink_state);
	  	HAL_GPIO_WritePin(R2D_B_GPIO_Port, R2D_B_Pin, bb && blink_state);
	  	blink_tick_r2d = HAL_GetTick();
	  }

	  blink_state = !blink_state;

	  if ((HAL_GetTick() - can_send_tick) > 50u){
		  can_send();
		  can_send_tick = HAL_GetTick();
	  }

  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {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.HSIState = RCC_HSI_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_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();
  }
}

/**
  * @brief CAN Initialization Function
  * @param None
  * @retval None
  */
static void MX_CAN_Init(void)
{

  /* USER CODE BEGIN CAN_Init 0 */

  /* USER CODE END CAN_Init 0 */

  /* USER CODE BEGIN CAN_Init 1 */

  /* USER CODE END CAN_Init 1 */
  hcan.Instance = CAN;
  hcan.Init.Prescaler = 2;
  hcan.Init.Mode = CAN_MODE_NORMAL;
  hcan.Init.SyncJumpWidth = CAN_SJW_1TQ;
  hcan.Init.TimeSeg1 = CAN_BS1_13TQ;
  hcan.Init.TimeSeg2 = CAN_BS2_2TQ;
  hcan.Init.TimeTriggeredMode = DISABLE;
  hcan.Init.AutoBusOff = DISABLE;
  hcan.Init.AutoWakeUp = DISABLE;
  hcan.Init.AutoRetransmission = DISABLE;
  hcan.Init.ReceiveFifoLocked = DISABLE;
  hcan.Init.TransmitFifoPriority = DISABLE;
  if (HAL_CAN_Init(&hcan) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN CAN_Init 2 */

  /* USER CODE END CAN_Init 2 */

}

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

  /* 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, TSON_R_Pin|TSON_G_Pin|TSON_B_Pin|IMD_LED_Pin
                          |AMS_LED_Pin|TSOFF_LED_Pin|R2D_R_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOB, R2D_G_Pin|R2D_B_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pins : TSON_R_Pin TSON_G_Pin TSON_B_Pin IMD_LED_Pin
                           AMS_LED_Pin TSOFF_LED_Pin R2D_R_Pin */
  GPIO_InitStruct.Pin = TSON_R_Pin|TSON_G_Pin|TSON_B_Pin|IMD_LED_Pin
                          |AMS_LED_Pin|TSOFF_LED_Pin|R2D_R_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 : R2D_G_Pin R2D_B_Pin */
  GPIO_InitStruct.Pin = R2D_G_Pin|R2D_B_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 : TSON_BTN_Pin SDC_Out_3V3_Pin SDC_In_3V3_Pin R2D_BTN_Pin
                           RMode_Out_3V3_Pin */
  GPIO_InitStruct.Pin = TSON_BTN_Pin|SDC_Out_3V3_Pin|SDC_In_3V3_Pin|R2D_BTN_Pin
                          |RMode_Out_3V3_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

/* USER CODE BEGIN MX_GPIO_Init_2 */
/* USER CODE END MX_GPIO_Init_2 */
}

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