/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body for GPS Navigation System
  ******************************************************************************
  * @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 */
#include <math.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
/* USER CODE END Includes */

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

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

#define CAMP_LATITUDE       18.556283  // Camp Latitude (destination)
#define CAMP_LONGITUDE      73.955067  // Camp Longitude (destination)
#define EARTH_RADIUS_KM     6371       // Earth's radius in kilometers
#define UART_BUFFER_SIZE    30         // Size of UART receive buffer
#define MAX_DISTANCE_STR    20         // Max characters for distance string
#define MAX_MESSAGE_LENGTH  100        // Max characters for output message

/* USER CODE END PD */

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

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
UART_HandleTypeDef huart2;

/* USER CODE BEGIN PV */

static uint8_t uartRxByte;                     // Single received byte via UART
static char uartRxBuffer[UART_BUFFER_SIZE];    // Buffer to store complete UART string
static uint8_t uartRxIndex = 0;                // Index for UART buffer
static bool isStringReceived = false;          // Flag indicating complete string received

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART2_UART_Init(void);
/* USER CODE BEGIN PFP */

static void trimString(char *str);
static void processReceivedString(void);
static void startUartReception(void);
static void floatToString(float value, char* buffer, uint8_t decimalPlaces);
static void printToSerial(const char *message);
static bool parseGpsCoordinates(char* gpsString, double* latitude, double* longitude);
static double calculateHaversineDistance(double lat1, double lon1, double lat2, double lon2);
static const char* calculateCompassDirection(double lat1, double lon1, double lat2, double lon2);
static inline double radiansToDegrees(double radians);
static inline double degreesToRadians(double degrees);

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/**
  * @brief  Prints a string to the serial monitor
  * @param  message: Pointer to the null-terminated string to send
  * @retval None
  */
static void printToSerial(const char *message) {
    HAL_UART_Transmit(&huart2, (uint8_t*)message, strlen(message), HAL_MAX_DELAY);
}

/**
  * @brief  Converts a float to a string with specified decimal places
  * @param  value: The float value to convert
  * @param  buffer: Pointer to the output buffer
  * @param  decimalPlaces: Number of decimal places to show
  * @retval None
  */
static void floatToString(float value, char* buffer, uint8_t decimalPlaces) {
    // Handle negative numbers
    bool isNegative = value < 0;
    if (isNegative) {
        value = -value;
    }

    // Extract integer part
    int32_t integerPart = (int32_t)value;
    float fractionalPart = value - integerPart;

    // Convert integer part to string
    char* ptr = buffer;
    if (isNegative) {
        *ptr++ = '-';
    }

    if (integerPart == 0) {
        *ptr++ = '0';
    } else {
        // Reverse the integer digits temporarily
        char temp[10];
        uint8_t i = 0;
        while (integerPart > 0) {
            temp[i++] = (integerPart % 10) + '0';
            integerPart /= 10;
        }

        // Write them in correct order
        while (i > 0) {
            *ptr++ = temp[--i];
        }
    }

    // Add decimal point
    *ptr++ = '.';

    // Convert fractional part
    for (uint8_t d = 0; d < decimalPlaces; d++) {
        fractionalPart *= 10;
        uint8_t digit = (uint8_t)fractionalPart;
        *ptr++ = digit + '0';
        fractionalPart -= digit;
    }

    *ptr = '\0'; // Null-terminate
}

/**
  * @brief UART RX Complete Callback
  * @param huart: Pointer to UART handle
  * @retval None
  */
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
    if (huart->Instance == USART2) {
        if (uartRxByte == '\r' || uartRxByte == '\n') {
            // End of input: Null terminate and process
            uartRxBuffer[uartRxIndex] = '\0';
            processReceivedString();
            uartRxIndex = 0;
        } else if (uartRxIndex < sizeof(uartRxBuffer) - 1) {
            // Store character in buffer
            uartRxBuffer[uartRxIndex++] = uartRxByte;
        }
        // Restart reception for next byte
        startUartReception();
    }
}

/**
  * @brief Starts UART reception in interrupt mode
  * @retval None
  */
static void startUartReception() {
    HAL_UART_Receive_IT(&huart2, &uartRxByte, 1);
}

/**
  * @brief Processes the received string
  * @retval None
  */
static void processReceivedString() {
    isStringReceived = true;
}

/**
  * @brief Trims whitespace and control characters from string
  * @param str: Pointer to the string to trim
  * @retval None
  */
static void trimString(char *str) {
    int i = strlen(str) - 1;
    while (i >= 0 && (str[i] == '\r' || str[i] == '\n' || str[i] == ' ')) {
        str[i] = '\0';
        i--;
    }
}

/**
  * @brief Convert radians to degrees
  * @param radians: Angle in radians
  * @retval Angle in degrees
  */
static inline double radiansToDegrees(double radians) {
    return radians * (180.0 / M_PI);
}

/**
  * @brief Convert degrees to radians
  * @param degrees: Angle in degrees
  * @retval Angle in radians
  */
static inline double degreesToRadians(double degrees) {
    return degrees * (M_PI / 180.0);
}

/**
  * @brief Parses GPS coordinates from a custom-formatted string
  * @param gpsString: Input string containing coordinates
  * @param latitude: Pointer to store parsed latitude
  * @param longitude: Pointer to store parsed longitude
  * @retval true if parsing succeeded, false otherwise
  */
static bool parseGpsCoordinates(char* gpsString, double* latitude, double* longitude) {
    char* latMarker = strstr(gpsString, "X=");
    char* lonMarker = strstr(gpsString, ",Y=");

    if (latMarker == NULL || lonMarker == NULL) {
        printToSerial("Error: Invalid GPS format\r\n");
        return false;
    }

    // Extract latitude (skip "X=")
    *latitude = atof(latMarker + 2);

    // Extract longitude (skip ",Y=")
    *longitude = atof(lonMarker + 3);

    return true;
}

/**
  * @brief Calculates the great-circle distance using Haversine formula
  * @param lat1: Latitude of point 1
  * @param lon1: Longitude of point 1
  * @param lat2: Latitude of point 2
  * @param lon2: Longitude of point 2
  * @retval Distance in kilometers between the two points
  */
static double calculateHaversineDistance(double lat1, double lon1, double lat2, double lon2) {
    double dLat = degreesToRadians(lat2 - lat1);
    double dLon = degreesToRadians(lon2 - lon1);
    lat1 = degreesToRadians(lat1);
    lat2 = degreesToRadians(lat2);

    double a = sin(dLat / 2) * sin(dLat / 2) +
               cos(lat1) * cos(lat2) * sin(dLon / 2) * sin(dLon / 2);
    double c = 2 * atan2(sqrt(a), sqrt(1 - a));

    return EARTH_RADIUS_KM * c;
}

/**
  * @brief Calculates compass direction from point 1 to point 2
  * @param lat1: Latitude of starting point
  * @param lon1: Longitude of starting point
  * @param lat2: Latitude of destination point
  * @param lon2: Longitude of destination point
  * @retval Compass direction as string (N, NE, E, SE, S, SW, W, NW)
  */
static const char* calculateCompassDirection(double lat1, double lon1, double lat2, double lon2) {
    double dLon = degreesToRadians(lon2 - lon1);
    lat1 = degreesToRadians(lat1);
    lat2 = degreesToRadians(lat2);

    double y = sin(dLon) * cos(lat2);
    double x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon);
    double bearing = atan2(y, x);
    bearing = radiansToDegrees(bearing);

    // Normalize bearing to 0-360 degrees
    bearing = fmod(bearing + 360.0, 360.0);

    // Convert bearing to compass direction
    const double sectorSize = 45.0;
    const char* directions[] = {"N", "NE", "E", "SE", "S", "SW", "W", "NW"};
    int index = (int)((bearing + sectorSize/2) / sectorSize) % 8;

    return directions[index];
}

/* 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_USART2_UART_Init();
  /* USER CODE BEGIN 2 */
  startUartReception();
  /* USER CODE END 2 */

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

    /* USER CODE BEGIN 3 */
    if(isStringReceived) {
        double currentLatitude, currentLongitude;
        char distanceString[MAX_DISTANCE_STR];
        char outputMessage[MAX_MESSAGE_LENGTH];

        // Trim any whitespace from the received string
        trimString(uartRxBuffer);

        // Parse the coordinates from the received string
        if(parseGpsCoordinates(uartRxBuffer, &currentLatitude, &currentLongitude)) {
            // Calculate distance to camp (in km)
            double distance = calculateHaversineDistance(
                currentLatitude, currentLongitude,
                CAMP_LATITUDE, CAMP_LONGITUDE);

            // Get compass direction to camp
            const char* direction = calculateCompassDirection(
                currentLatitude, currentLongitude,
                CAMP_LATITUDE, CAMP_LONGITUDE);

            // Convert distance to string with 2 decimal places
            floatToString((float)distance, distanceString, 2);

            // Prepare and send the output messages
            snprintf(outputMessage, sizeof(outputMessage),
                    "Distance to camp: %s km\r\n", distanceString);
            printToSerial(outputMessage);

            snprintf(outputMessage, sizeof(outputMessage),
                    "Direction to camp: %s\r\n", direction);
            printToSerial(outputMessage);
        } else {
            // If parsing failed, send error message
            printToSerial("Error: Invalid GPS format\r\n");
        }

        // Reset the flag for next reception
        isStringReceived = false;
    }
  }
  /* 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_DIV2;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL16;
  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 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 = 9600;
  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 */

}

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

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