/* USER CODE BEGIN Header */
/**
 ******************************************************************************
 * @file           : main.c
 * @brief          : Main program body
 ******************************************************************************
 * @attention
 *
 * Copyright (c) 2022 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 "dma.h"
#include "rtc.h"
#include "sai.h"
#include "spi.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "math.h"
#include "stdio.h"
#include "dispcolor.h"
#include "clock.h"
#include "constants.h"
/* USER CODE END Includes */

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

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#define SAI_SAMPLES 1024
#define UART_SAMPLES 16
#define LCD_REFRESH_PERIOD 5000  // ms
#define DEBUG_VIA_UART 1

#define BYTE_TO_BINARY(byte)  \
  (byte & 0x80 ? '1' : '0'), \
  (byte & 0x40 ? '1' : '0'), \
  (byte & 0x20 ? '1' : '0'), \
  (byte & 0x10 ? '1' : '0'), \
  (byte & 0x08 ? '1' : '0'), \
  (byte & 0x04 ? '1' : '0'), \
  (byte & 0x02 ? '1' : '0'), \
  (byte & 0x01 ? '1' : '0')

/* USER CODE END PD */

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

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
RTC_TimeTypeDef timeNow;
RTC_DateTypeDef dateNow;

uint32_t AxisBufferX[SAI_SAMPLES];
float MicrophoneXAvgL;
float MicrophoneXAvgR;
float MicrophoneX[SAI_SAMPLES];
volatile uint8_t SaiSamplesReadyX;
uint32_t AxisBufferY[SAI_SAMPLES];
float MicrophoneYAvgL;
float MicrophoneYAvgR;
float MicrophoneY[SAI_SAMPLES];
volatile uint8_t SaiSamplesReadyY;

float RmsXL;
float RmsXR;
float RmsYL;
float RmsYR;
float AcousticAngle;

uint16_t i;

uint32_t SoftTimerLCD;

uint8_t UartMessage[256];
uint16_t MessageLength;

union Uint32Bytes
{
	uint32_t int32;
	struct
	{
		uint8_t b0;
		uint8_t b1;
		uint8_t b2;
		uint8_t b3;
	} Bytes;
};

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
void PeriphCommonClock_Config(void);
/* USER CODE BEGIN PFP */
int32_t Convert_24bit_I2S(uint32_t x); // reading from I2S mic is a signed(!!!) integer
int32_t Convert_18bit_I2S(uint32_t x);
float Mean_Value(float *SampleValues, uint16_t NumOfSamples, char AudioChannel);
void Mean_Remove(float *SampleValues, float MeanValue, uint16_t NumOfSamples,
		char AudioChannel);
float RMS_Value(float *SampleValues, uint16_t NumOfSumples, char AudioChannel);
/* 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();

	/* Configure the peripherals common clocks */
	PeriphCommonClock_Config();

	/* USER CODE BEGIN SysInit */

	/* USER CODE END SysInit */

	/* Initialize all configured peripherals */
	MX_GPIO_Init();
	MX_DMA_Init();
	MX_USART2_UART_Init();
	MX_RTC_Init();
	MX_SPI3_Init();
	MX_SAI1_Init();
	MX_SAI2_Init();
	/* USER CODE BEGIN 2 */

	HAL_GPIO_WritePin(SAI1_LR_A_WHITE_GPIO_Port, SAI1_LR_A_WHITE_Pin,
			GPIO_PIN_RESET);
	HAL_GPIO_WritePin(SAI1_LR_A_GREEN_GPIO_Port, SAI1_LR_A_GREEN_Pin,
			GPIO_PIN_SET);
	HAL_GPIO_WritePin(SAI2_LR_A_RED_GPIO_Port, SAI2_LR_A_RED_Pin,
			GPIO_PIN_RESET);
	HAL_GPIO_WritePin(SAI2_LR_A_YELLOW_GPIO_Port, SAI2_LR_A_YELLOW_Pin,
			GPIO_PIN_SET);

	timeNow.Hours = 20;
	timeNow.Minutes = 51;
	timeNow.Seconds = 0;
	HAL_RTC_SetTime(&hrtc, &timeNow, RTC_FORMAT_BIN);
	HAL_Delay(10);

	dispcolor_Init(240, 240);

	DrawClock(0, timeNow.Hours, timeNow.Minutes, timeNow.Seconds, 0, 0);

	HAL_SAI_Receive_DMA(&hsai_BlockA1, (uint8_t*) AxisBufferX, SAI_SAMPLES);
	HAL_SAI_Receive_DMA(&hsai_BlockA2, (uint8_t*) AxisBufferY, SAI_SAMPLES);

	SoftTimerLCD = HAL_GetTick();
	/* USER CODE END 2 */

	/* Infinite loop */
	/* USER CODE BEGIN WHILE */

	while (1)
	{
		if ((SaiSamplesReadyX == 1) && (SaiSamplesReadyY == 1))
		{
			for (i = 0; i < SAI_SAMPLES; i++)
			{
				MicrophoneX[i] =
						(float) (Convert_24bit_I2S(AxisBufferX[i] >> 8));
			}
			SaiSamplesReadyX = 0;

			MicrophoneXAvgL = Mean_Value(MicrophoneX, SAI_SAMPLES, 'L');
			MicrophoneXAvgR = Mean_Value(MicrophoneX, SAI_SAMPLES, 'R');

			Mean_Remove(MicrophoneX, MicrophoneXAvgL, SAI_SAMPLES, 'L');
			Mean_Remove(MicrophoneX, MicrophoneXAvgR, SAI_SAMPLES, 'R');

			RmsXL = RMS_Value(MicrophoneX, SAI_SAMPLES, 'L');
			RmsXR = RMS_Value(MicrophoneX, SAI_SAMPLES, 'R');

			for (i = 0; i < SAI_SAMPLES; i++)
			{
				MicrophoneY[i] =
						(float) (Convert_24bit_I2S(AxisBufferY[i] >> 8));
			}
			SaiSamplesReadyY = 0;

			MicrophoneYAvgL = Mean_Value(MicrophoneY, SAI_SAMPLES, 'L');
			MicrophoneYAvgR = Mean_Value(MicrophoneY, SAI_SAMPLES, 'R');

			Mean_Remove(MicrophoneY, MicrophoneYAvgL, SAI_SAMPLES, 'L');
			Mean_Remove(MicrophoneY, MicrophoneYAvgR, SAI_SAMPLES, 'R');

			RmsYL = RMS_Value(MicrophoneY, SAI_SAMPLES, 'L');
			RmsYR = RMS_Value(MicrophoneY, SAI_SAMPLES, 'R');

			//AcousticAngle = atan2f(RmsYR - RmsYL, RmsXR - RmsXL); // atan2(y,x) but here rotated to fit the hardware
			AcousticAngle = atan2f((RmsXR - RmsXL), -(RmsYR - RmsYL));

			if (HAL_GetTick() - SoftTimerLCD > LCD_REFRESH_PERIOD)
			{
				SoftTimerLCD = HAL_GetTick();
				HAL_RTC_GetTime(&hrtc, &timeNow, RTC_FORMAT_BIN);
				HAL_RTC_GetDate(&hrtc, &dateNow, RTC_FORMAT_BIN);
				DrawClock(AcousticAngle, timeNow.Hours, timeNow.Minutes,
						timeNow.Seconds, 0, 0);

				if (DEBUG_VIA_UART)
				{
					for (i = 1; i < UART_SAMPLES; i++)
					{
						if (i % 2)
						{
							MessageLength =
									sprintf((char*) UartMessage,
											"axis X channel L raw I2S reading: 0b %c%c%c%c%c%c%c%c %c%c%c%c%c%c%c%c %c%c%c%c%c%c%c%c %c%c%c%c%c%c%c%c\r\n",
											BYTE_TO_BINARY(
													((union Uint32Bytes )(AxisBufferX[i])).Bytes.b3),
											BYTE_TO_BINARY(
													((union Uint32Bytes )(AxisBufferX[i])).Bytes.b2),
											BYTE_TO_BINARY(
													((union Uint32Bytes )(AxisBufferX[i])).Bytes.b1),
											BYTE_TO_BINARY(
													((union Uint32Bytes )(AxisBufferX[i])).Bytes.b0)
											);
						}
						else
						{
							MessageLength =
									sprintf((char*) UartMessage,
											"axis X channel R raw I2S reading: 0b %c%c%c%c%c%c%c%c %c%c%c%c%c%c%c%c %c%c%c%c%c%c%c%c %c%c%c%c%c%c%c%c\r\n",
											BYTE_TO_BINARY(
													((union Uint32Bytes )(AxisBufferX[i])).Bytes.b3),
											BYTE_TO_BINARY(
													((union Uint32Bytes )(AxisBufferX[i])).Bytes.b2),
											BYTE_TO_BINARY(
													((union Uint32Bytes )(AxisBufferX[i])).Bytes.b1),
											BYTE_TO_BINARY(
													((union Uint32Bytes )(AxisBufferX[i])).Bytes.b0)
											);
						}
						HAL_UART_Transmit(&huart2, UartMessage, MessageLength,
								100);
					}
					MessageLength = sprintf((char*) UartMessage, "\r\n");
					HAL_UART_Transmit(&huart2, UartMessage, MessageLength, 100);
				}
			}

			HAL_SAI_Receive_DMA(&hsai_BlockA1, (uint8_t*) AxisBufferX,
			SAI_SAMPLES);
			HAL_SAI_Receive_DMA(&hsai_BlockA2, (uint8_t*) AxisBufferY,
			SAI_SAMPLES);

		}
		/* 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
	 */
	if (HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1) != HAL_OK)
	{
		Error_Handler();
	}

	/** Configure LSE Drive Capability
	 */
	HAL_PWR_EnableBkUpAccess();
	__HAL_RCC_LSEDRIVE_CONFIG(RCC_LSEDRIVE_LOW);

	/** Initializes the RCC Oscillators according to the specified parameters
	 * in the RCC_OscInitTypeDef structure.
	 */
	RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI
			| RCC_OSCILLATORTYPE_LSE | RCC_OSCILLATORTYPE_MSI;
	RCC_OscInitStruct.LSEState = RCC_LSE_ON;
	RCC_OscInitStruct.LSIState = RCC_LSI_ON;
	RCC_OscInitStruct.MSIState = RCC_MSI_ON;
	RCC_OscInitStruct.MSICalibrationValue = 0;
	RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_6;
	RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
	RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_MSI;
	RCC_OscInitStruct.PLL.PLLM = 1;
	RCC_OscInitStruct.PLL.PLLN = 40;
	RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV7;
	RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
	RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
	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_4) != HAL_OK)
	{
		Error_Handler();
	}

	/** Enable MSI Auto calibration
	 */
	HAL_RCCEx_EnableMSIPLLMode();
}

/**
 * @brief Peripherals Common Clock Configuration
 * @retval None
 */
void PeriphCommonClock_Config(void)
{
	RCC_PeriphCLKInitTypeDef PeriphClkInit =
	{ 0 };

	/** Initializes the peripherals clock
	 */
	PeriphClkInit.PeriphClockSelection =
	RCC_PERIPHCLK_SAI1 | RCC_PERIPHCLK_SAI2;
	PeriphClkInit.Sai1ClockSelection = RCC_SAI1CLKSOURCE_PLLSAI1;
	PeriphClkInit.Sai2ClockSelection = RCC_SAI2CLKSOURCE_PLLSAI1;
	PeriphClkInit.PLLSAI1.PLLSAI1Source = RCC_PLLSOURCE_MSI;
	PeriphClkInit.PLLSAI1.PLLSAI1M = 1;
	PeriphClkInit.PLLSAI1.PLLSAI1N = 16;
	PeriphClkInit.PLLSAI1.PLLSAI1P = RCC_PLLP_DIV7;
	PeriphClkInit.PLLSAI1.PLLSAI1Q = RCC_PLLQ_DIV2;
	PeriphClkInit.PLLSAI1.PLLSAI1R = RCC_PLLR_DIV2;
	PeriphClkInit.PLLSAI1.PLLSAI1ClockOut = RCC_PLLSAI1_SAI1CLK;
	if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
	{
		Error_Handler();
	}
}

/* USER CODE BEGIN 4 */
void HAL_SAI_RxCpltCallback(SAI_HandleTypeDef *hsai)
{
	if (hsai->Instance == SAI1_Block_A)
	{
		SaiSamplesReadyX = 1;
	}
	if (hsai->Instance == SAI2_Block_A)
	{
		SaiSamplesReadyY = 1;
	}
}

int32_t Convert_24bit_I2S(uint32_t x) // INMP441 >> 8
{
	int32_t t = x & 0x00FFFFFF;
	return t - (t >> 23 << 24);
}

int32_t Convert_18bit_I2S(uint32_t x)  //  SPH0645LM4H-B >> 14
{
	int32_t t = x & 0x003FFFF;
	return t - (t >> 17 << 18);
}

float Mean_Value(float *SampleValues, uint16_t NumOfSamples, char AudioChannel)
{
	float SumValue = 0;
	if (AudioChannel == 'L')
	{
		for (uint16_t i = 0; i < NumOfSamples; i += 2)
		{
			SumValue += SampleValues[i];
		}
		return SumValue * 2 / (float) NumOfSamples;
	}

	if (AudioChannel == 'R')
	{
		for (uint16_t i = 1; i < NumOfSamples; i += 2)
		{
			SumValue += SampleValues[i];
		}
		return SumValue * 2 / (float) NumOfSamples;
	}
	return 0;
}

void Mean_Remove(float *SampleValues, float MeanValue, uint16_t NumOfSamples,
		char AudioChannel)
{
	if (AudioChannel == 'L')
	{
		for (uint16_t i = 0; i < NumOfSamples; i += 2)
		{
			SampleValues[i] -= MeanValue;
		}
	}

	if (AudioChannel == 'R')
	{
		for (uint16_t i = 1; i < NumOfSamples; i += 2)
		{
			SampleValues[i] -= MeanValue;
		}
	}
}

float RMS_Value(float *SampleValues, uint16_t NumOfSamples, char AudioChannel)
{
	float RMSValue = 0;
	if (AudioChannel == 'L')
	{
		for (uint16_t i = 0; i < NumOfSamples; i += 2)
		{
			RMSValue += SampleValues[i] * SampleValues[i];
		}
		return sqrt(RMSValue);
	}

	if (AudioChannel == 'R')
	{
		for (uint16_t i = 1; i < NumOfSamples; i += 2)
		{
			RMSValue += SampleValues[i] * SampleValues[i];
		}
		return sqrt(RMSValue);
	}
	return 0;
}
/* 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 */
