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

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ssd1306.h"
#include "SGP40.h"
#include "SHT31.h"
/* USER CODE END Includes */

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

/* USER CODE END PTD */

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

//#define SET_BUILTIN_RTC
#define OLED_UPDATE_PERIOD 1000

/* 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 softTimerOLED;
char lcd_line[32];
const char *day_of_week[] =
{ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };

float t_ambient;
float rh_ambient;
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
void GetCompilationTime(RTC_TimeTypeDef *timePtr);
void GetCompilationDate(RTC_DateTypeDef *datePtr);
void CalculateDayOfWeek(RTC_DateTypeDef *datePtr);

#ifdef __GNUC__
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif

PUTCHAR_PROTOTYPE
{
	HAL_UART_Transmit(&hlpuart1, (uint8_t*) &ch, 1, HAL_MAX_DELAY);
	return ch;
}
/* 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_LPUART1_UART_Init();
	MX_I2C1_Init();
	MX_RTC_Init();
	MX_SPI2_Init();
	/* USER CODE BEGIN 2 */
	SHT31_Config(SHT31_ADDRESS_A, &hi2c1);
	HAL_Delay(2000);

	printf("SGP40 VOC Sensor test\r\n");
	DEV_ModuleInit();

	if (SGP40_Init() != 0)
	{
		printf("init err!!!");
		return 0;
	}

	ssd1306_Init();

#ifdef SET_BUILTIN_RTC
	GetCompilationDate(&dateNow);
	CalculateDayOfWeek(&dateNow);
	HAL_RTC_SetDate(&hrtc, &dateNow, RTC_FORMAT_BIN);
	GetCompilationTime(&timeNow);
	HAL_RTC_SetTime(&hrtc, &timeNow, RTC_FORMAT_BIN);
#endif
	/* USER CODE END 2 */

	/* Infinite loop */
	/* USER CODE BEGIN WHILE */
	softTimerOLED = HAL_GetTick();
	UWORD voc1 = 0;
	UWORD voc2 = 0;
	while (1)
	{
		if ((HAL_GetTick() - softTimerOLED) > OLED_UPDATE_PERIOD)
		{
			softTimerOLED = HAL_GetTick();
			HAL_RTC_GetTime(&hrtc, &timeNow, RTC_FORMAT_BIN);
			HAL_RTC_GetDate(&hrtc, &dateNow, RTC_FORMAT_BIN);

			if (SHT31_GetData(SHT31_Periodic, SHT31_Medium, SHT31_NON_Stretch,
					SHT31_1) == SHT31_OK)
			{
				t_ambient = SHT31_GetTemperature();
				rh_ambient = SHT31_GetHumidity();
			}

			voc1 = SGP40_MeasureRaw(t_ambient, rh_ambient);
			voc2 = SGP40_MeasureVOC(t_ambient, rh_ambient);
			printf("SGP40_MeasureRaw voc = %d\r\n", voc1);
			printf("SGP40_MeasureVOC voc = %d\r\n", voc2);

			ssd1306_Fill(Black);
			ssd1306_SetCursor(20, 0);
			sprintf(lcd_line, "SGP40 + SHT31");
			ssd1306_WriteString(lcd_line, Font_6x8, White);
			ssd1306_SetCursor(40, 10);
			sprintf(lcd_line, "%02d:%02d:%02d", timeNow.Hours, timeNow.Minutes,
					timeNow.Seconds);
			ssd1306_WriteString(lcd_line, Font_6x8, White);
			ssd1306_SetCursor(0, 20);
			sprintf(lcd_line, "%s, %02d.%02d.%04d",
					day_of_week[dateNow.WeekDay - 1], dateNow.Date,
					dateNow.Month, (2000 + dateNow.Year));
			ssd1306_WriteString(lcd_line, Font_6x8, White);

			ssd1306_SetCursor(20, 30);
			sprintf(lcd_line, "T_amb = %.1f *C", t_ambient);
			ssd1306_WriteString(lcd_line, Font_6x8, White);

			ssd1306_SetCursor(20, 40);
			sprintf(lcd_line, "RH_amb = %.1f%%", rh_ambient);
			ssd1306_WriteString(lcd_line, Font_6x8, White);

			ssd1306_SetCursor(20, 55);
			sprintf(lcd_line, "VOC_index = %d", voc2);
			ssd1306_WriteString(lcd_line, Font_6x8, White);

			ssd1306_UpdateScreen();
		}
		/* 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_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1_BOOST);

	/** 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_HSI
			| RCC_OSCILLATORTYPE_LSE;
	RCC_OscInitStruct.LSEState = RCC_LSE_ON;
	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 = RCC_PLLM_DIV4;
	RCC_OscInitStruct.PLL.PLLN = 85;
	RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
	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();
	}
}

/* USER CODE BEGIN 4 */
void GetCompilationTime(RTC_TimeTypeDef *timePtr)
{
	char temp[] = __TIME__;

	timePtr->Seconds = atoi(temp + 6);
	*(temp + 5) = 0;
	timePtr->Minutes = atoi(temp + 3);
	*(temp + 2) = 0;
	timePtr->Hours = atoi(temp);
}

void GetCompilationDate(RTC_DateTypeDef *datePtr)
{
	const char *months[] =
	{ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct",
			"Nov", "Dec" };
	char temp[] = __DATE__;
	uint8_t i;

	datePtr->Year = atoi(temp + 9);
	*(temp + 6) = 0;
	datePtr->Date = atoi(temp + 4);
	*(temp + 3) = 0;
	for (i = 0; i < 12; i++)
	{
		if (!strcmp(temp, months[i]))
		{
			datePtr->Month = i + 1;
			return;
		}
	}
}

// https://www.geeksforgeeks.org/find-day-of-the-week-for-a-given-date/
void CalculateDayOfWeek(RTC_DateTypeDef *datePtr)
{
	const int16_t t[] =
	{ 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };
	int16_t y, m, d;
	m = datePtr->Month;
	y = (datePtr->Year) + 2000 - (m < 3);
	d = datePtr->Date;
	datePtr->WeekDay = (y + y / 4 - y / 100 + y / 400 + t[m - 1] + d) % 7;
	if (datePtr->WeekDay == 0)
	{
		datePtr->WeekDay = 7;
	}
}
/* 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 */
