/*
 * gps_parser.c
 *
 *  Created on: Dec 15, 2023
 *      Author: user
 */

#include "gps_parser.h"
#include "dma.h"
#include "usart.h"
#include "math.h"
#include <stdlib.h>

uint8_t GpsRxBuf[GpsRxBuf_SIZE];
extern DMA_HandleTypeDef hdma_usart1_rx;

void StartReadingGps(void)
{
	HAL_UARTEx_ReceiveToIdle_DMA(&huart1, GpsRxBuf, GpsRxBuf_SIZE);
	__HAL_DMA_DISABLE_IT(&hdma_usart1_rx, DMA_IT_HT);
//	__HAL_DMA_DISABLE_IT(&hdma_usart1_rx, DMA_IT_TC);
//	__HAL_DMA_DISABLE_IT(&hdma_usart1_rx, DMA_IT_TE);
}

uint8_t ParseGpsData(float *latitude, float *longitude)
{
	// https://www.rfwireless-world.com/Terminology/GPS-sentences-or-NMEA-sentences.html
	uint16_t inx = 0;
	uint8_t buff[16];

	if ((GpsRxBuf[0] == '$') && (GpsRxBuf[1] == 'G') && (GpsRxBuf[2] == 'P')
			&& (GpsRxBuf[3] == 'R') && (GpsRxBuf[4] == 'M')
			&& (GpsRxBuf[5] == 'C'))
	{
		// $GPRMC
		inx = 7;
		while (GpsRxBuf[inx] != ',')
		{
			inx++;
		}  // UTC time
		inx++;
		if (GpsRxBuf[inx] == 'A') // Status (A = valid data)
		{
			inx++;
			inx++;
			uint8_t inx_latitude = 0;
			while (GpsRxBuf[inx] != ',')
			{
				buff[inx_latitude] = GpsRxBuf[inx];
				inx_latitude++;
				inx++;
			}
			buff[inx_latitude] = '\0';
			*latitude = ConvertDDMMdotMMMM2DDdotDDDDDD(atoff((char*) buff));
			inx++;
			inx++;
			inx++;
			uint8_t inx_longitude = 0;
			while (GpsRxBuf[inx] != ',')
			{
				buff[inx_longitude] = GpsRxBuf[inx];
				inx_longitude++;
				inx++;
			}
			buff[inx_longitude] = '\0';
			*longitude = ConvertDDMMdotMMMM2DDdotDDDDDD(atoff((char*) buff));
			return 1;
		}
		else
		{
			StartReadingGps();
			return 0;
		}
	}
	else
	{
		StartReadingGps();
		return 0;
	}
}

float ConvertDDMMdotMMMM2DDdotDDDDDD(float gprmc_number)
{
	float before_dot = floor(gprmc_number / 100.0f);
	float after_dot = ((gprmc_number / 100.0f) - before_dot) * 100.0f / 60.0f;
	return before_dot + after_dot;
}
