/* 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 "crc.h"
#include "usart.h"
#include "spi.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stdio.h"
#include "modbus_crc.h"
#include "ssd1306.h"
/* USER CODE END Includes */

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

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#define ENERGY_COST 0.9f  // per kWh
#define OLED_UPDATE_PERIOD 5000
#define HARDWARE_FLOW_CONTROL_RS485
/* USER CODE END PD */

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

/* USER CODE END PM */

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

/* USER CODE BEGIN PV */
uint8_t modbus_data_received_flag = 0;
uint8_t RxData[32];
uint8_t TxData[8];
uint8_t energy_meter_heartbeat = 0;
uint16_t EnergyData[3];

uint16_t crc;

char lcd_line[21];
uint32_t SoftTimerLCD;
/* USER CODE END PV */

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

/* USER CODE END PFP */

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

void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
{
	if (huart->Instance == UART5)
	{
		modbus_data_received_flag = 1;
		energy_meter_heartbeat = 1 - energy_meter_heartbeat; // toggle
	}
}

#ifdef HARDWARE_FLOW_CONTROL_RS485

void sendData(uint8_t *data)
{
	HAL_UART_Transmit(&huart5, data, 8, 500);
}

#else

void sendData(uint8_t *data)
{
	HAL_GPIO_WritePin(MAX3485_EN_GPIO_Port, MAX3485_EN_Pin, GPIO_PIN_SET);
//	HAL_Delay(1);
	HAL_UART_Transmit(&huart5, data, 8, 500);
//	HAL_Delay(1);
	HAL_GPIO_WritePin(MAX3485_EN_GPIO_Port, MAX3485_EN_Pin, GPIO_PIN_RESET);
}

#endif
/* 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_UART5_Init();
  MX_SPI2_Init();
  MX_CRC_Init();
  /* USER CODE BEGIN 2 */

	ssd1306_Init();
	HAL_Delay(250);

	// See e.g. https://www.youtube.com/watch?v=TBvcYIUUW0o
	TxData[0] = 107;  // slave address
	TxData[1] = 0x03;  // Function code for Read Holding Registers

	TxData[2] = 0;
	TxData[3] = 0x00; // starting address

	TxData[4] = 0;
	TxData[5] = 0x03; // number of registers to read: 3 * 2 bytes = 6 bytes to be read

	crc = modbus_rtu_crc(TxData, 6); // 6 bytes of data + 2 bytes of crc
	TxData[6] = crc & 0xFF;   // CRC LOW
	TxData[7] = (crc >> 8) & 0xFF;  // CRC HIGH

	HAL_UARTEx_ReceiveToIdle_IT(&huart5, (uint8_t*) (&RxData), 11); // pull-up resistor!!!
	sendData(TxData);
	HAL_Delay(250);

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

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

		if ((HAL_GetTick() - SoftTimerLCD) > OLED_UPDATE_PERIOD)
		{
			SoftTimerLCD = HAL_GetTick();

			if (1 == modbus_data_received_flag)
			{
				modbus_data_received_flag = 0;

				HAL_UARTEx_ReceiveToIdle_IT(&huart5, (uint8_t*) (&RxData), 11);
				sendData(TxData);

				EnergyData[0] = RxData[3] << 8 | RxData[4];
				EnergyData[1] = RxData[5] << 8 | RxData[6];
				EnergyData[2] = RxData[7] << 8 | RxData[8];

				float total_energy = ((float) (EnergyData[0] * 256 * 256
						+ EnergyData[1] * 256 + EnergyData[2])) / 100.0f;
				float total_cost = total_energy * ENERGY_COST;

				ssd1306_Fill(Black);
				ssd1306_SetCursor(5, 10);
				ssd1306_WriteString("Modbus Master STM32", Font_6x8, White);
				ssd1306_SetCursor(5, 20);
				ssd1306_WriteString("LE-01M Energy Meter", Font_6x8, White);
				ssd1306_SetCursor(5, 30);
				if (1 == energy_meter_heartbeat)
				{
					sprintf(lcd_line, "  ufnalski.edu.pl  *");
				}
				else
				{
					sprintf(lcd_line, "  ufnalski.edu.pl");
				}
				ssd1306_WriteString(lcd_line, Font_6x8, White);
				sprintf(lcd_line, "Energy: %.2f kWh", total_energy);
				ssd1306_SetCursor(5, 44);
				ssd1306_WriteString(lcd_line, Font_6x8, White);
				sprintf(lcd_line, "Cost:   %.2f PLN", total_cost);
				ssd1306_SetCursor(5, 55);
				ssd1306_WriteString(lcd_line, Font_6x8, White);

				ssd1306_UpdateScreen();
			}
		}

//  Toggle the light bulb
//	      TxData[0] = 13;  // slave address
//
//	      TxData[1] = 0x05;  // Force single coil
//
//	      TxData[2] = 0;  // coil address high
//	      TxData[3] = 0;  // coil address low
//
//	      TxData[4] = 0xFF;  // force data high
//	      TxData[5] = 0;
//
//	      crc = modbus_rtu_crc(TxData, 6);
//
//	      TxData[6] = crc&0xFF;   // CRC LOW
//	      TxData[7] = (crc>>8)&0xFF;  // CRC HIGH
//
//	      sendData((uint8_t *)(&TxData));
//
//	      HAL_Delay(2000);
//	      TxData[4] = 0;  // force data low
//
//	      crc = modbus_rtu_crc(TxData, 6);
//	      TxData[6] = crc&0xFF;   // CRC LOW
//	      TxData[7] = (crc>>8)&0xFF;  // CRC HIGH
//
//        sendData((uint8_t *)(&TxData));
//
//	      HAL_Delay(2000);

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

  /** 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 = RCC_PLLM_DIV1;
  RCC_OscInitStruct.PLL.PLLN = 10;
  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_2) != HAL_OK)
  {
    Error_Handler();
  }
}

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