/* 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"
#include "cmsis_os.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include <stdio.h>
#include <string.h>
#include "mpu6050.h"
#include "madgwick.h"

/* USER CODE END Includes */

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

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#define GYR1_Add 0x68 << 1 // 7-Bit Adresse und 8. Bit gesetzt als write (0 write, 1 read)
#define GYR2_Add 0x69 << 1

/* USER CODE END PD */

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

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
I2C_HandleTypeDef hi2c1;
DMA_HandleTypeDef hdma_i2c1_rx;

UART_HandleTypeDef huart2;

osThreadId defaultTaskHandle;
osThreadId SensorReadingHandle;
osThreadId Sensor2ReadingHandle;
/* USER CODE BEGIN PV */
MPU6050_HandleTypeDef hmpu1;
MPU6050_HandleTypeDef hmpu2;
MadgwickFilter madgwick;

// sensor reading flags
uint8_t sensor1_flag = 0;
uint8_t sensor2_flag = 0;


char output[128];
int16_t copy_raw_data[6];			//[ax, ay, az, gx, gy, gz]
float processed_data[6];			//[Ax, Ay, Az, Gx, Gy, Gz]

uint32_t last_transmit = 0;
uint32_t now = 0;

float roll, pitch, yaw; 			// Madgwick euler angles



/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_DMA_Init(void);
static void MX_USART2_UART_Init(void);
static void MX_I2C1_Init(void);
void StartDefaultTask(void const * argument);
void StartSensorReading(void const * argument);
void StartSensor2Reading(void const * argument);

/* 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_DMA_Init();
  MX_USART2_UART_Init();
  MX_I2C1_Init();
  /* USER CODE BEGIN 2 */




  /* USER CODE END 2 */

  /* USER CODE BEGIN RTOS_MUTEX */
  /* add mutexes, ... */
  /* USER CODE END RTOS_MUTEX */

  /* USER CODE BEGIN RTOS_SEMAPHORES */
  /* add semaphores, ... */
  /* USER CODE END RTOS_SEMAPHORES */

  /* USER CODE BEGIN RTOS_TIMERS */
  /* start timers, add new ones, ... */
  /* USER CODE END RTOS_TIMERS */

  /* USER CODE BEGIN RTOS_QUEUES */
  /* add queues, ... */
  /* USER CODE END RTOS_QUEUES */

  /* Create the thread(s) */
  /* definition and creation of defaultTask */
  osThreadDef(defaultTask, StartDefaultTask, osPriorityNormal, 0, 1024);
  defaultTaskHandle = osThreadCreate(osThread(defaultTask), NULL);

  /* definition and creation of SensorReading */
  osThreadDef(SensorReading, StartSensorReading, osPriorityIdle, 0, 1024);
  SensorReadingHandle = osThreadCreate(osThread(SensorReading), NULL);

  /* definition and creation of Sensor2Reading */
  osThreadDef(Sensor2Reading, StartSensor2Reading, osPriorityNormal, 0, 1024);
  Sensor2ReadingHandle = osThreadCreate(osThread(Sensor2Reading), NULL);

  /* USER CODE BEGIN RTOS_THREADS */
  /* add threads, ... */
  /* USER CODE END RTOS_THREADS */

  /* Start scheduler */
  osKernelStart();

  /* We should never get here as control is now taken by the scheduler */

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

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

  /** Configure the main internal regulator output voltage
  */
  __HAL_RCC_PWR_CLK_ENABLE();
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE3);

  /** 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.PLLM = 16;
  RCC_OscInitStruct.PLL.PLLN = 336;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV4;
  RCC_OscInitStruct.PLL.PLLQ = 2;
  RCC_OscInitStruct.PLL.PLLR = 2;
  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_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
  * @brief I2C1 Initialization Function
  * @param None
  * @retval None
  */
static void MX_I2C1_Init(void)
{

  /* USER CODE BEGIN I2C1_Init 0 */

  /* USER CODE END I2C1_Init 0 */

  /* USER CODE BEGIN I2C1_Init 1 */

  /* USER CODE END I2C1_Init 1 */
  hi2c1.Instance = I2C1;
  hi2c1.Init.ClockSpeed = 100000;
  hi2c1.Init.DutyCycle = I2C_DUTYCYCLE_2;
  hi2c1.Init.OwnAddress1 = 0;
  hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
  hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
  hi2c1.Init.OwnAddress2 = 0;
  hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
  hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
  if (HAL_I2C_Init(&hi2c1) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN I2C1_Init 2 */

  /* USER CODE END I2C1_Init 2 */

}

/**
  * @brief USART2 Initialization Function
  * @param None
  * @retval None
  */
static void MX_USART2_UART_Init(void)
{

  /* USER CODE BEGIN USART2_Init 0 */

  /* USER CODE END USART2_Init 0 */

  /* USER CODE BEGIN USART2_Init 1 */

  /* USER CODE END USART2_Init 1 */
  huart2.Instance = USART2;
  huart2.Init.BaudRate = 115200;
  huart2.Init.WordLength = UART_WORDLENGTH_8B;
  huart2.Init.StopBits = UART_STOPBITS_1;
  huart2.Init.Parity = UART_PARITY_NONE;
  huart2.Init.Mode = UART_MODE_TX_RX;
  huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart2.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart2) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART2_Init 2 */

  /* USER CODE END USART2_Init 2 */

}

/**
  * Enable DMA controller clock
  */
static void MX_DMA_Init(void)
{

  /* DMA controller clock enable */
  __HAL_RCC_DMA1_CLK_ENABLE();

  /* DMA interrupt init */
  /* DMA1_Stream0_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(DMA1_Stream0_IRQn, 5, 0);
  HAL_NVIC_EnableIRQ(DMA1_Stream0_IRQn);

}

/**
  * @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_GPIOC_CLK_ENABLE();
  __HAL_RCC_GPIOH_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(LD2_GPIO_Port, LD2_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin : B1_Pin */
  GPIO_InitStruct.Pin = B1_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(B1_GPIO_Port, &GPIO_InitStruct);

  /*Configure GPIO pin : LD2_Pin */
  GPIO_InitStruct.Pin = LD2_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(LD2_GPIO_Port, &GPIO_InitStruct);

  /* USER CODE BEGIN MX_GPIO_Init_2 */

  /* USER CODE END MX_GPIO_Init_2 */
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/* USER CODE BEGIN Header_StartDefaultTask */
/**
  * @brief  Function implementing the defaultTask thread.
  * @param  argument: Not used
  * @retval None
  */
/* USER CODE END Header_StartDefaultTask */
void StartDefaultTask(void const * argument)
{
  /* USER CODE BEGIN 5 */
	// Initialize MPU struct
	hmpu1.address = GYR1_Add;
	hmpu1.hi2c = &hi2c1;
	hmpu1.accel_range = 0x02;
	hmpu1.gyro_range = 0x02;
	hmpu1.accel_factor = 4096.0;
	hmpu1.gyro_factor = 32.8;
	hmpu1.calibrate = 0;


	data_ready = 0;
	dma_ready = 1;


	Init_MPU6050(&hmpu1, &huart2);
	Calibrate_MPU(&hmpu1, &huart2);

	MadgwickFilter_Init(&madgwick, 125.0f, 0.1f);
	start_dma_transfer(&hmpu1);

  /* Infinite loop */
  for(;;)
  {
	  if (data_ready){
		  // copy the data so it doesnt get changed while working on it
		  // accelerometer
		  copy_raw_data[0] = raw_data[0];
		  copy_raw_data[1] = raw_data[1];
		  copy_raw_data[2] = raw_data[2];
		  // gyro
		  copy_raw_data[3] = raw_data[3];
		  copy_raw_data[4] = raw_data[4];
		  copy_raw_data[5] = raw_data[5];

		  // DEBUG
		  //sprintf(output, "RAW: %02X %02X %02X %02X %02X %02X\n", ax_copy, ay_copy, az_copy, gx_copy, gy_copy, gz_copy);

		  data_ready = 0;

		  processed_data[0] = (float)copy_raw_data[0]/hmpu->accel_factor;
		  processed_data[1] = (float)copy_raw_data[1]/hmpu->accel_factor;
		  processed_data[2] = (float)copy_raw_data[2]/hmpu->accel_factor;
		  processed_data[3] = (float)copy_raw_data[3]/hmpu->gyro_factor;
		  processed_data[4] = (float)copy_raw_data[4]/hmpu->gyro_factor;
		  processed_data[5] = (float)copy_raw_data[5]/hmpu->gyro_factor;

		  if(hmpu->calibrate) {
			  processed_data[0] -= hmpu->accel_bias[0];
			  processed_data[1] -= hmpu->accel_bias[1];
			  processed_data[2] -= hmpu->accel_bias[2];
			  processed_data[3] -= hmpu->gyro_bias[0];
			  processed_data[4] -= hmpu->gyro_bias[1];
			  processed_data[5] -= hmpu->gyro_bias[2];
		  }

		  start_dma_transfer(&hmpu1);
	      // Update Madgwick filter with processed data
	      MadgwickFilter_Update(&madgwick, processed_data[3], processed_data[4], processed_data[5], // Gx, Gy, Gz
	                           processed_data[0], processed_data[1], processed_data[2]);     // Ax, Ay, Az

	      // Get Euler angles
	      MadgwickFilter_GetEulerAngles(&madgwick, &roll, &pitch, &yaw);

	      // Output orientation
	      now = HAL_GetTick();
	      if (now - last_transmit >= 50) { // Limit to 5 Hz (every 50ms)
	        sprintf(output, "qw: %.4f qx: %.4f qy: %.4f qz: %.4f\n",
	                madgwick.q[0], madgwick.q[1], madgwick.q[2], madgwick.q[3]);
	        HAL_UART_Transmit(&huart2, (uint8_t*)output, strlen(output), 250);
	        last_transmit = now;
	      }
//	      sprintf(output, "Roll: %.2f Pitch: %.2f Yaw: %.2f\n", roll, pitch, yaw);
//	      HAL_UART_Transmit(&huart2, (uint8_t*)output, strlen(output), 250);

		  start_dma_transfer(&hmpu1);
	  }
  }
  /* USER CODE END 5 */
}

/* USER CODE BEGIN Header_StartSensorReading */
/**
* @brief Function implementing the SensorReading thread.
* @param argument: Not used
* @retval None
*/
/* USER CODE END Header_StartSensorReading */
void StartSensorReading(void const * argument)
{
  /* USER CODE BEGIN StartSensorReading */
	// set the sensor struct
	hmpu1.address = GYR1_Add;
	hmpu1.hi2c = &hi2c1;
	hmpu1.accel_range = 0x02;
	hmpu1.gyro_range = 0x02;
	hmpu1.accel_factor = 4096.0;
	hmpu1.gyro_factor = 32.8;
	hmpu1.calibrate = 0;

	hmpu2.address = GYR2_Add;
	hmpu2.hi2c = &hi2c1;
	hmpu2.accel_range = 0x02;
	hmpu2.gyro_range = 0x02;
	hmpu2.accel_factor = 4096.0;
	hmpu2.gyro_factor = 32.8;
	hmpu2.calibrate = 0;
	// initialize and calibrate both sensors
	Init_MPU6050(&hmpu1, &huart2);
	Calibrate_MPU(&hmpu1, &huart2);

	Init_MPU6050(&hmpu2, &huart2);
	Calibrate_MPU(&hmpu2, &huart2);

	// hold the sensor data
	uint8_t binarySensorData[14];
	int16_t rawData[6];

  /* Infinite loop */
  for(;;)
  {

    osDelay(1);
  }
  /* USER CODE END StartSensorReading */
}

/* USER CODE BEGIN Header_StartSensor2Reading */
/**
* @brief Function implementing the Sensor2Reading thread.
* @param argument: Not used
* @retval None
*/
/* USER CODE END Header_StartSensor2Reading */
void StartSensor2Reading(void const * argument)
{
  /* USER CODE BEGIN StartSensor2Reading */
	// Initialize MPU struct
	hmpu2.address = GYR2_Add;
	hmpu2.hi2c = &hi2c1;
	hmpu2.accel_range = 0x02;
	hmpu2.gyro_range = 0x02;
	hmpu2.accel_factor = 4096.0;
	hmpu2.gyro_factor = 32.8;
	hmpu2.calibrate = 0;

	// init, calibrate and start mpu
	Init_MPU6050(&hmpu2, &huart2);
	Calibrate_MPU(&hmpu2, &huart2);
	start_dma_transfer(&hmpu2);
  /* Infinite loop */
  for(;;)
  {
    osDelay(1);
  }
  /* USER CODE END StartSensor2Reading */
}

/**
  * @brief  Period elapsed callback in non blocking mode
  * @note   This function is called  when TIM6 interrupt took place, inside
  * HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment
  * a global variable "uwTick" used as application time base.
  * @param  htim : TIM handle
  * @retval None
  */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
  /* USER CODE BEGIN Callback 0 */

  /* USER CODE END Callback 0 */
  if (htim->Instance == TIM6)
  {
    HAL_IncTick();
  }
  /* USER CODE BEGIN Callback 1 */

  /* USER CODE END Callback 1 */
}

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