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

/* Definitions for defaultTask */
osThreadId_t defaultTaskHandle;
const osThreadAttr_t defaultTask_attributes = {
  .name = "defaultTask",
  .stack_size = 1024 * 4,
  .priority = (osPriority_t) osPriorityNormal,
};
/* Definitions for SensorReading */
osThreadId_t SensorReadingHandle;
const osThreadAttr_t SensorReading_attributes = {
  .name = "SensorReading",
  .stack_size = 1024 * 4,
  .priority = (osPriority_t) osPriorityLow,
};
/* Definitions for Sensor2Reading */
osThreadId_t Sensor2ReadingHandle;
const osThreadAttr_t Sensor2Reading_attributes = {
  .name = "Sensor2Reading",
  .stack_size = 1024 * 4,
  .priority = (osPriority_t) osPriorityNormal,
};
/* Definitions for SensorQueue1 */
osMessageQueueId_t SensorQueue1Handle;
const osMessageQueueAttr_t SensorQueue1_attributes = {
  .name = "SensorQueue1"
};
/* USER CODE BEGIN PV */
MPU6050_HandleTypeDef hmpu1;
MPU6050_HandleTypeDef hmpu2;
MadgwickFilter Sensor1Quat;
MadgwickFilter Sensor2Quat;

char output[256];
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 *argument);
void StartSensorReading(void *argument);
void StartSensor2Reading(void *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 */

  /* Init scheduler */
  osKernelInitialize();

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

  /* Create the queue(s) */
  /* creation of SensorQueue1 */
  SensorQueue1Handle = osMessageQueueNew (5, sizeof(ProcessedData_HandleTypeDef), &SensorQueue1_attributes);

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

  /* Create the thread(s) */
  /* creation of defaultTask */
  defaultTaskHandle = osThreadNew(StartDefaultTask, NULL, &defaultTask_attributes);

  /* creation of SensorReading */
  SensorReadingHandle = osThreadNew(StartSensorReading, NULL, &SensorReading_attributes);

  /* creation of Sensor2Reading */
  Sensor2ReadingHandle = osThreadNew(StartSensor2Reading, NULL, &Sensor2Reading_attributes);

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

  /* USER CODE BEGIN RTOS_EVENTS */
  /* add events, ... */
  /* USER CODE END RTOS_EVENTS */

  /* 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 *argument)
{
  /* USER CODE BEGIN 5 */
	MadgwickFilter_Init(&Sensor1Quat, 20.0f, 0.1f);
	MadgwickFilter_Init(&Sensor2Quat, 20.0f, 0.1f);
	ProcessedData_HandleTypeDef RecievedData;
  /* Infinite loop */
  for(;;)
  {
	  osMessageQueueGet(SensorQueue1Handle, &RecievedData, NULL, osWaitForever);

	  // Update Madgwick filter with processed data
	  MadgwickFilter_Update(&Sensor1Quat, RecievedData.Sensor1Data[3], RecievedData.Sensor1Data[4], RecievedData.Sensor1Data[5], // Gx, Gy, Gz
			  RecievedData.Sensor1Data[0], RecievedData.Sensor1Data[1], RecievedData.Sensor1Data[2]);     // Ax, Ay, Az
	  MadgwickFilter_Update(&Sensor2Quat, RecievedData.Sensor2Data[3], RecievedData.Sensor2Data[4], RecievedData.Sensor2Data[5], // Gx, Gy, Gz
			  RecievedData.Sensor2Data[0], RecievedData.Sensor2Data[1], RecievedData.Sensor2Data[2]);     // Ax, Ay, Az


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

      sendQuat(&huart2, &hmpu1, &Sensor1Quat);
//      // Output orientation
//      sprintf(output, "Sensor 1 qw: %.4f qx: %.4f qy: %.4f qz: %.4f\n",
//    		  Sensor1Quat.q[0], Sensor1Quat.q[1], Sensor1Quat.q[2], Sensor1Quat.q[3]);
//  	  HAL_UART_Transmit(&huart2, (uint8_t*)output, strlen(output), 250);
//
//      sprintf(output, "Sensor 2 qw: %.4f qx: %.4f qy: %.4f qz: %.4f\n",
//    		  Sensor2Quat.q[0], Sensor2Quat.q[1], Sensor2Quat.q[2], Sensor2Quat.q[3]);
//  	  HAL_UART_Transmit(&huart2, (uint8_t*)output, strlen(output), 250);

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

	xSensorReadingTask = xTaskGetCurrentTaskHandle();

	// hold the sensor data
	uint8_t binarySensor1Data[14];
	uint8_t binarySensor2Data[14];
//	float processedData[6];
	ProcessedData_HandleTypeDef ProcessedData;

	// initialize and calibrate both sensors
	Init_MPU6050(&hmpu1, &huart2);
	calibrate_Sensor(&hmpu1, &huart2);

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

  /* Infinite loop */
  for(;;)
  {
	  read_dma(&hmpu1, binarySensor1Data);
	  read_dma(&hmpu1, binarySensor2Data);

	  process_binaryData(&hmpu1, binarySensor1Data, ProcessedData.Sensor1Data);
	  process_binaryData(&hmpu1, binarySensor2Data, ProcessedData.Sensor2Data);

	  osMessageQueuePut(SensorQueue1Handle, &ProcessedData, NULL, 5);

//	  // Update Madgwick filter with processed data
//	  MadgwickFilter_Update(&madgwick, processedData[3], processedData[4], processedData[5], // Gx, Gy, Gz
//			  processedData[0], processedData[1], processedData[2]);     // Ax, Ay, Az
//
//      // Get Euler angles
//      MadgwickFilter_GetEulerAngles(&madgwick, &roll, &pitch, &yaw);
//
//      // Output orientation
//      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);

//	  	      sprintf(output, "Roll: %.2f Pitch: %.2f Yaw: %.2f\n", roll, pitch, yaw);
//	  	      HAL_UART_Transmit(&huart2, (uint8_t*)output, strlen(output), 250);

      osDelay(50);
  }
  /* 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 *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 */
