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

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include <stdio.h>
#include <string.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 ---------------------------------------------------------*/
ADC_HandleTypeDef hadc;

CAN_HandleTypeDef hcan;

UART_HandleTypeDef huart1;

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_ADC_Init(void);
//static void MX_CAN_Init(void);
static void MX_USART1_UART_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_ADC_Init();
//  MX_CAN_Init();
	MX_USART1_UART_Init();
	/* USER CODE BEGIN 2 */

	//load flash copy of config to RAM
	// memcpy((void*)&config_ram,(void*)(0x0800F000), sizeof(config_t));
	memcpy((void*) &config_ram, (void*) &config_flash, sizeof(config_t));
	config = &config_ram;

	//calculate gain and offset for PPS and TPS calc
	Apply_Sensor_Calibration();
	config->config_bits &= ~CONFIG_TESTMODE_F;

//clear momms
	memset((void*) &var, 0, sizeof(var_t));
	//Initialize TS Comms
	Comms_Init();
	NVIC_EnableIRQ(USART1_IRQn);

// check if safety features are enabled
	if (config->config_bits & CONFIG_SAFETY_FEATURES_F) {
		Check_Safety_Limits();
		Safety_TPS_Safety_Timer_Start();
		//TODO Watch_Dog_Init();
		// change status
		var.status1 |= DBW_STATUS1_SAFETY_F;
	}
// if not change status to safy disabled
	else
		var.status1 &= ~DBW_STATUS1_SAFETY_F;

// Check if CAN has to be initialized
	if ((config->pps2tps_option == PPS2TPS_OPTION_MS3_CAN)
			|| (config->idle_input_option == IDLE_OPTION_MS_CAN)
			|| config->can_ms29bit_options == 0x01) {
//		Can_Init();

	}
	if (config->idle_input_option == IDLE_OPTION_PWM_INPUT1) {
		TIM3_Init();
	}
	if (1) {
		TIM14_Init(); //rpm input init
		TIM16_Init(); // vss out init
		TIM17_Init(); //Mazda rx8 can message init
	}
	Adc_Init();
	DBW_Init();
	DBW_Pwm_Init();

//check if program flash is write protected and set status
	if (FLASH->WRPR & 0x00003FFF)
		var.status0 |= DBW_STATUS0_UNPROTECTED_F;
	else
		var.status0 &= ~DBW_STATUS0_UNPROTECTED_F;

//check if agreement is set if so start DBW drive
	if (config->config_bits & CONFIG_AGREEMENT_F) {
		var.status0 |= DBW_STATUS0_AGREEMENT_F;
	} else
		var.status0 &= ~DBW_STATUS0_AGREEMENT_F;

// check if TPS and PPS are calibrated

	if (config->config_bits & CONFIG_SENSORS_CALIBRATED_F) {
		var.status0 |= DBW_STATUS0_SENSOR_CAL_F;
	}

	else {
		var.status0 &= ~DBW_STATUS0_SENSOR_CAL_F;
	}

// start DBW if sensors are calibrated and agreement is accepted
	if ((var.status0 & DBW_STATUS0_AGREEMENT_F)
			&& (var.status0 & DBW_STATUS0_SENSOR_CAL_F)) {
		DBW_Start();
	} else
		DBW_Stop();

	/* USER CODE END 2 */

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

// is something to be transmitted on serial
		Poll_Tx();

// Update WDT and check ADC range if safety features are enabled
		if ((var.status1 & DBW_STATUS1_SAFETY_F) && var.clock > 1000) {
			//TODO Watch_Dog_Update();
			Check_Adc_Range();
			Check_TPS_Target();
		}

//check if tesmode is turned on
		if (config->config_bits & CONFIG_TESTMODE_F) {
			var.status0 &= ~DBW_STATUS0_READY_F;
			DBW_TPS_AutoCal();
			DBW_Read_sensors();
		} else {
			DBW_Process();
		}

		CAN_Send_TX_Buffer();
		if (1) {
		MAZDA_CAN_Read();
		}
		/* 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 };

	/** Initializes the CPU, AHB and APB busses clocks
	 */
	RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI14
			| RCC_OSCILLATORTYPE_HSE;
	RCC_OscInitStruct.HSEState = RCC_HSE_ON;
	RCC_OscInitStruct.HSI14State = RCC_HSI14_ON;
	RCC_OscInitStruct.HSI14CalibrationValue = 16;
	RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
	RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
	RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL12;
	RCC_OscInitStruct.PLL.PREDIV = RCC_PREDIV_DIV2;
	if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
		Error_Handler();
	}
	/** Initializes the CPU, AHB and APB busses clocks
	 */
	RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK
			| RCC_CLOCKTYPE_PCLK1;
	RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
	RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
	RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;

	if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK) {
		Error_Handler();
	}
	PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USART1;
	PeriphClkInit.Usart1ClockSelection = RCC_USART1CLKSOURCE_PCLK1;
	if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK) {
		Error_Handler();
	}
}

/**
 * @brief ADC Initialization Function
 * @param None
 * @retval None
 */
static void MX_ADC_Init(void) {

	/* USER CODE BEGIN ADC_Init 0 */

	/* USER CODE END ADC_Init 0 */

	ADC_ChannelConfTypeDef sConfig = { 0 };

	/* USER CODE BEGIN ADC_Init 1 */

	/* USER CODE END ADC_Init 1 */
	/** Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion)
	 */
	hadc.Instance = ADC1;
	hadc.Init.ClockPrescaler = ADC_CLOCK_ASYNC_DIV1;
	hadc.Init.Resolution = ADC_RESOLUTION_12B;
	hadc.Init.DataAlign = ADC_DATAALIGN_RIGHT;
	hadc.Init.ScanConvMode = ADC_SCAN_DIRECTION_FORWARD;
	hadc.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
	hadc.Init.LowPowerAutoWait = DISABLE;
	hadc.Init.LowPowerAutoPowerOff = DISABLE;
	hadc.Init.ContinuousConvMode = DISABLE;
	hadc.Init.DiscontinuousConvMode = DISABLE;
	hadc.Init.ExternalTrigConv = ADC_SOFTWARE_START;
	hadc.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
	hadc.Init.DMAContinuousRequests = DISABLE;
	hadc.Init.Overrun = ADC_OVR_DATA_PRESERVED;
	if (HAL_ADC_Init(&hadc) != HAL_OK) {
		Error_Handler();
	}
	/** Configure for the selected ADC regular channel to be converted.
	 */
	sConfig.Channel = ADC_CHANNEL_0;
	sConfig.Rank = ADC_RANK_CHANNEL_NUMBER;
	sConfig.SamplingTime = ADC_SAMPLETIME_1CYCLE_5;
	if (HAL_ADC_ConfigChannel(&hadc, &sConfig) != HAL_OK) {
		Error_Handler();
	}
	/** Configure for the selected ADC regular channel to be converted.
	 */
	sConfig.Channel = ADC_CHANNEL_1;
	if (HAL_ADC_ConfigChannel(&hadc, &sConfig) != HAL_OK) {
		Error_Handler();
	}
	/** Configure for the selected ADC regular channel to be converted.
	 */
	sConfig.Channel = ADC_CHANNEL_2;
	if (HAL_ADC_ConfigChannel(&hadc, &sConfig) != HAL_OK) {
		Error_Handler();
	}
	/** Configure for the selected ADC regular channel to be converted.
	 */
	sConfig.Channel = ADC_CHANNEL_3;
	if (HAL_ADC_ConfigChannel(&hadc, &sConfig) != HAL_OK) {
		Error_Handler();
	}
	/** Configure for the selected ADC regular channel to be converted.
	 */
	sConfig.Channel = ADC_CHANNEL_4;
	if (HAL_ADC_ConfigChannel(&hadc, &sConfig) != HAL_OK) {
		Error_Handler();
	}
	/** Configure for the selected ADC regular channel to be converted.
	 */
	sConfig.Channel = ADC_CHANNEL_5;
	if (HAL_ADC_ConfigChannel(&hadc, &sConfig) != HAL_OK) {
		Error_Handler();
	}
	/* USER CODE BEGIN ADC_Init 2 */

	/* USER CODE END ADC_Init 2 */

}

/**
 * @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 = 16;
//	hcan.Init.Mode = CAN_MODE_NORMAL;
//	hcan.Init.SyncJumpWidth = CAN_SJW_1TQ;
//	hcan.Init.TimeSeg1 = CAN_BS1_1TQ;
//	hcan.Init.TimeSeg2 = CAN_BS2_1TQ;
//	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 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 = 115200;
	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(GPIOB,
			PWM1_Pin | PWM2_Pin | FAULT_Pin | D2_Pin | D1_Pin | GPO1_Pin
					| GPO2_1_Pin | GPO2_2_Pin, GPIO_PIN_RESET);

	/*Configure GPIO pins : IN1_Pin IN2_Pin STATUS_FLAG_Pin */
//  GPIO_InitStruct.Pin = IN1_Pin|IN2_Pin|STATUS_FLAG_Pin;
//  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
//  GPIO_InitStruct.Pull = GPIO_NOPULL;
//  HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
	/*Configure GPIO pins : PWM1_Pin PWM2_Pin FAULT_Pin D2_Pin
	 D1_Pin GPO1_Pin GPO2_1_Pin GPO2_2_Pin */
	GPIO_InitStruct.Pin = PWM1_Pin | PWM2_Pin | FAULT_Pin | D2_Pin | D1_Pin
			| GPO1_Pin | GPO2_1_Pin | GPO2_2_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);

}

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