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

/* USER CODE END Includes */

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

typedef struct {
	int r2d : 1;
	int tson : 1;
	int racemode : 1;
	int sdc_in : 1;
	int sdc_out : 1;
} dash_tx_t;

typedef enum {
	TS_INACTIVE = 0,
	TS_ACTIVE = 1,
	TS_PRECHARGE = 2,
	TS_DISCHARGE = 3,
	TS_ERROR = 4,
} ams_state_t;

typedef enum {
	R2D_NONE = 0,
	R2D_TSMS = 1,
	R2D_TSActive = 2,
	R2D_Resetting_Nodes = 3,
	R2D_Resetting_Comms = 4,
	R2D_Waiting_Init = 5,
	R2D_Init_Stage1 = 6,
	R2D_Init_Stage2 = 7,
	R2D_Success = 0xF,
} r2d_progress_t;

typedef struct {
	ams_state_t ams_state;
	int imd_ok;
	int sdc_closed;
	r2d_progress_t r2d_progress;
} dash_rx_t;

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#define CAN_ID_TX 0x420
#define CAN_ID_RX_R2D 0x410
#define CAN_ID_RX_AMS 0x00A
/* USER CODE END PD */

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

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
CAN_HandleTypeDef hcan;

/* USER CODE BEGIN PV */
dash_tx_t				dash_tx;
CAN_TxHeaderTypeDef   	txHeader;
uint32_t              	txMailbox;

dash_rx_t				dash_rx;

uint32_t 				ams_last_tick = 0;
uint32_t  				last_send_can_tick = 0;


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

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

  txHeader.IDE = CAN_ID_STD;
  txHeader.StdId = CAN_ID_TX;
  txHeader.RTR = CAN_RTR_DATA;
  txHeader.DLC = 1;


  if (HAL_CAN_Start(&hcan) != HAL_OK)
  	Error_Handler();

  CAN_FilterTypeDef canfilterconfig;

  canfilterconfig.FilterActivation = CAN_FILTER_ENABLE;
  canfilterconfig.FilterBank = 0;
  canfilterconfig.FilterFIFOAssignment = CAN_FILTER_FIFO0;
  canfilterconfig.FilterIdHigh = CAN_ID_RX_AMS << (16 - 11);
  canfilterconfig.FilterIdLow = CAN_ID_RX_R2D << (16 - 11);
  canfilterconfig.FilterMaskIdHigh = 0x7FF << (16 - 11);
  canfilterconfig.FilterMaskIdLow = 0x7FF << (16 - 11);
  canfilterconfig.FilterMode = CAN_FILTERMODE_IDMASK;
  canfilterconfig.FilterScale = CAN_FILTERSCALE_32BIT;
  canfilterconfig.SlaveStartFilterBank = 14;

  if (HAL_CAN_ConfigFilter(&hcan, &canfilterconfig) != HAL_OK) {
    Error_Handler();
  }

  if (HAL_CAN_ActivateNotification(&hcan, CAN_IT_RX_FIFO0_MSG_PENDING) != HAL_OK)
    Error_Handler();

  // blink flags
  int blink_state = 0;

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

	  if ((HAL_GetTick() - last_send_can_tick ) > 200) {
		  if (HAL_CAN_AddTxMessage(&hcan, &txHeader, (uint8_t*) &dash_tx, &txMailbox) != HAL_OK) {
			  Error_Handler();
		  }
		 last_send_can_tick = HAL_GetTick();
	  }

	  // Inverted in hardware
	  if ((HAL_GetTick() - ams_last_tick) < 80) {
		  HAL_GPIO_WritePin(IMD_LED_GPIO_Port, IMD_LED_Pin, dash_rx.imd_ok);
		  HAL_GPIO_WritePin(AMS_LED_GPIO_Port, AMS_LED_Pin, dash_rx.ams_state != TS_ERROR);
		  HAL_GPIO_WritePin(TSOFF_LED_GPIO_Port, TSOFF_LED_Pin, dash_rx.ams_state == TS_INACTIVE);
	  } 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 (dash_rx.sdc_closed) {
		  switch (dash_rx.ams_state) {
		  	  case TS_INACTIVE:
		  		  r = g = 1;
		  		  break;
		  	  case TS_PRECHARGE:
		  		  // Gelb blink
		  		  br = bg = 1;
		  		  break;
		  	  case TS_ACTIVE:
		  		  g = 1;
		  		  break;
		  	  case TS_DISCHARGE:
		  		  // Blau blink
		  		  bb = 1;
		  		  break;
		  	  default:
		  		  r = 1;
		  		  break;
		  }
	  } else {
		  b = 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_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);
	  }

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

	  if (dash_rx.ams_state == TS_ACTIVE) {
		  switch (dash_rx.r2d_progress) {
			  case R2D_NONE:
			  case R2D_TSMS:
			  case R2D_TSActive:
				  r = g = 1;
				  break;
			  case R2D_Success:
				  g = 1;
				  break;
		  	  default:
		  		  // Gelb blink
		  		  bg = br = 1;
		  		  break;
		  }
	  } else {
		  b = 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_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_state = !blink_state;

	  HAL_Delay(50);

	  /*
	   * TODO:
	   * Farbveläufe
	   **/

  }
  /* 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_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL4;
  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_PLLCLK;
  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_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 */
// CAN RX interrupt handler
void HAL_CAN_RxFifo0MsgPendingCallback(CAN_HandleTypeDef *hcan) {

  CAN_RxHeaderTypeDef   rxHeader;
  uint8_t				rxData[8];

  // Read frame from HW into buffer
  if (HAL_CAN_GetRxMessage(hcan, CAN_RX_FIFO0, &rxHeader, rxData) != HAL_OK)
    Error_Handler();

  // Discard if it's not for us (shouldn't happen thanks to filter, but just to be sure)
  if (rxHeader.StdId == CAN_ID_RX_AMS) {
	  uint8_t ams_info = rxData[0];
	  uint8_t imd_info = rxData[6];

	  dash_rx.ams_state = ams_info & 0b01111111;
	  dash_rx.sdc_closed = ams_info >> 7;
	  dash_rx.imd_ok = imd_info >> 7;
	  ams_last_tick = HAL_GetTick();
  }


  if (rxHeader.StdId == CAN_ID_RX_R2D) {
	  uint8_t r2d_info = rxData[1];

	  dash_rx.r2d_progress = r2d_info & 0b00001111;
  }


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