/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2022 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "can.h"
#include "dma.h"
#include "i2c.h"
#include "spi.h"
#include "tim.h"
#include "usart.h"
#include "usb_device.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "mcp23017.h"
#include <math.h>
#include "ads1115.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 PCF_ADDRESS 0x27

#define THERMISTORNOMINAL 10000
#define TEMPERATURENOMINAL 25
#define BCOEFFICIENT 3988
#define SERIESRESISTOR 10000
/* USER CODE END PD */

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

/* USER CODE END PM */

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

/* USER CODE BEGIN PV */
float temp=0;	// Variable to get Temperature

uint8_t PWM_O1 = 0;
uint8_t PWM_O3 = 100;

char buffer[32]={0};
uint8_t usb_buffer[64];
uint8_t usart1_buffer[64];
char buffer_uart[32]={0};
uint8_t usart1_rx_index;
uint8_t rx_data;

uint16_t meas_counter = 1;


uint16_t ads_config = 1;
float voltage_adc[4];
float Temp[5];

const float voltageConv = 6.114 / 32768.0;


uint8_t P_GPIOA = 0x00;
uint8_t P_GPIOB = 0x00;

const double kelvintemp = 273.15;                // 0°Celsius in Kelvin
const double Tn = 273.15 + 25;                 //Nenntemperatur in Kelvin
/* 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 SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

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

/**
 * Function to perform jump to system memory boot from user application
 *
 * Call function when you want to jump to system memory
 */
void JumpToBootloader(void) {
    void (*SysMemBootJump)(void);

    /**
     * Step: Set system memory address.
     *
     *       For STM32F429, system memory is on 0x1FFF 0000
     *       For other families, check AN2606 document table 110 with descriptions of memory addresses
     */
    volatile uint32_t addr = 0x1FFFD800;

    /**
     * Step: Disable RCC, set it to default (after reset) settings
     *       Internal clock, no PLL, etc.
     */
#if defined(USE_HAL_DRIVER)
    HAL_RCC_DeInit();
#endif /* defined(USE_HAL_DRIVER) */
#if defined(USE_STDPERIPH_DRIVER)
    RCC_DeInit();
#endif /* defined(USE_STDPERIPH_DRIVER) */

    /**
     * Step: Disable systick timer and reset it to default values
     */
    SysTick->CTRL = 0;
    SysTick->LOAD = 0;
    SysTick->VAL = 0;

    /**
     * Step: Disable all interrupts
     */
    __disable_irq();

    /**
     * Step: Remap system memory to address 0x0000 0000 in address space
     *       For each family registers may be different.
     *       Check reference manual for each family.
     *
     *       For STM32F4xx, MEMRMP register in SYSCFG is used (bits[1:0])
     *       For STM32F0xx, CFGR1 register in SYSCFG is used (bits[1:0])
     *       For others, check family reference manual
     */

    __HAL_SYSCFG_REMAPMEMORY_SYSTEMFLASH();    //Call HAL macro to do this for you

    /**
     * Step: Set jump memory location for system memory
     *       Use address with 4 bytes offset which specifies jump location where program starts
     */
    SysMemBootJump = (void (*)(void)) (*((uint32_t *)(addr + 4)));

    /**
     * Step: Set main stack pointer.
     *       This step must be done last otherwise local variables in this function
     *       don't have proper value since stack pointer is located on different position
     *
     *       Set direct address location which specifies stack pointer in SRAM location
     */
    __set_MSP(*(uint32_t *)addr);

    /**
     * Step: Actually call our function to jump to set location
     *       This will start system memory execution
     */
    SysMemBootJump();

    /**
     * Step: Connect USB<->UART converter to dedicated USART pins and test
     *       and test with bootloader works with STM32 Flash Loader Demonstrator software
     */
}


void uprintf(char *str)
{
	//HAL_UART_Transmit(&huart3, (uint8_t *) str, strlen(str), 100);
	CDC_Transmit_FS((uint8_t *) str, strlen(str));
	HAL_Delay(10);
}

void uprintf_usart1(char *str)
{
	HAL_UART_Transmit(&huart1, (uint8_t *) str, strlen(str), 100);
	HAL_UART_Transmit(&huart1, (uint8_t *) "\r", 1, 100);
	HAL_Delay(10);
}

float convert2celsius(float NTC_Spannung, float AUX0_Spannung)
{

	  float widerstandNTC;
	  float T;
	  widerstandNTC = SERIESRESISTOR*(((double)NTC_Spannung/AUX0_Spannung)/(1-((double)NTC_Spannung/AUX0_Spannung)));                   // berechne den Widerstandswert vom NTC
	  T = 1/((1/Tn)+((double)1/BCOEFFICIENT)*log((double)widerstandNTC/SERIESRESISTOR));                          // ermittle die Temperatur in Kelvin

	  T = T - kelvintemp;

	  return T;
}


#define MAX_LED 300
#define USE_BRIGHTNESS 1


uint8_t LED_Data[MAX_LED][4];
uint8_t LED_Mod[MAX_LED][4];  // for brightness

int datasentflag=0;

void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim)
{
	HAL_TIM_PWM_Stop_DMA(&htim15, TIM_CHANNEL_1);
	datasentflag=1;
}

void Set_LED (int LEDnum, int Red, int Green, int Blue)
{
	LED_Data[LEDnum][0] = LEDnum;
	LED_Data[LEDnum][1] = Green;
	LED_Data[LEDnum][2] = Red;
	LED_Data[LEDnum][3] = Blue;
}

#define PI 3.14159265

void Set_Brightness (int brightness)  // 0-45
{
#if USE_BRIGHTNESS

	if (brightness > 45) brightness = 45;
	for (int i=0; i<MAX_LED; i++)
	{
		LED_Mod[i][0] = LED_Data[i][0];
		for (int j=1; j<4; j++)
		{
			float angle = 90-brightness;  // in degrees
			angle = angle*PI / 180;  // in rad
			LED_Mod[i][j] = (LED_Data[i][j])/(tan(angle));
		}
	}

#endif

}

uint16_t pwmData[(24*MAX_LED)+50];

void WS2812_Send (void)
{
	uint32_t indx=0;
	uint32_t color;


	for (int i= 0; i<MAX_LED; i++)
	{
#if USE_BRIGHTNESS
		color = ((LED_Mod[i][1]<<16) | (LED_Mod[i][2]<<8) | (LED_Mod[i][3]));
#else
		color = ((LED_Data[i][1]<<16) | (LED_Data[i][2]<<8) | (LED_Data[i][3]));
#endif

		for (int i=23; i>=0; i--)
		{
			if (color&(1<<i))
			{
				pwmData[indx] = 60;  // 2/3 of 90
			}

			else pwmData[indx] = 30;  // 1/3 of 90

			indx++;
		}

	}

	for (int i=0; i<50; i++)
	{
		pwmData[indx] = 0;
		indx++;
	}

	HAL_TIM_PWM_Start_DMA(&htim15, TIM_CHANNEL_1, (uint32_t *)pwmData, indx);
	while (!datasentflag){};
	datasentflag = 0;
}

void Reset_LED (void)
{
	for (int i=0; i<MAX_LED; i++)
	{
		LED_Data[i][0] = i;
		LED_Data[i][1] = 0;
		LED_Data[i][2] = 0;
		LED_Data[i][3] = 0;
	}
}





MCP23017_HandleTypeDef hmcp;


void PWM_Init()
{
	HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_1);
	HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_2);
}

void PWM_O1_Set(uint8_t O1_PWM)
{
	htim3.Instance->CCR1 = O1_PWM;
}

void PWM_O3_Set(uint8_t O3_PWM)
{
	htim3.Instance->CCR2 = O3_PWM;
}


void MCP_setPinA(uint8_t pin, uint8_t state)
{
        if(state==1)
        {
        	P_GPIOA |= (1<<pin);
        }
        else if(state==0)
        {
        	P_GPIOA &= ~(1<<pin);
        }
  	  hmcp.gpio[MCP23017_PORTA] = P_GPIOA;
  	  mcp23017_write_gpio(&hmcp, MCP23017_PORTA);
}

void MCP_setPinB(uint8_t pin, uint8_t state)
{
        if(state==1)
        {
        	P_GPIOB |= (1<<pin);
        }
        else if(state==0)
        {
        	P_GPIOB &= ~(1<<pin);
        }
  	  hmcp.gpio[MCP23017_PORTB] = P_GPIOB;
  	  mcp23017_write_gpio(&hmcp, MCP23017_PORTB);
}

void LED_RGB_Init()
{
	HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1);
	HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_2);
	HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_3);
}

void LED_RGB_SetIntensity(uint8_t red, uint8_t green, uint8_t blue)
{
	htim2.Instance->CCR1 = 100 - red;
	htim2.Instance->CCR2 = 100 - green;
	htim2.Instance->CCR3 = 100 - blue;
}
/* 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_CAN_Init();
  MX_I2C1_Init();
  MX_TIM2_Init();
  MX_USB_DEVICE_Init();
  MX_DMA_Init();
  MX_TIM3_Init();
  MX_TIM15_Init();
  MX_USART3_UART_Init();
  MX_USART1_UART_Init();
  MX_SPI2_Init();
  /* USER CODE BEGIN 2 */

  //PWM_Init();
  //PWM_O1_Set(0);
  //PWM_O3_Set(0);


  //mcp23017_init(&hmcp, &hi2c1, MCP23017_ADDRESS_20);
  //mcp23017_iodir(&hmcp, MCP23017_PORTA, MCP23017_IODIR_ALL_OUTPUT);
  //mcp23017_iodir(&hmcp, MCP23017_PORTB, MCP23017_IODIR_ALL_OUTPUT);


/*
  Set_LED(0, 255, 0, 0);
  Set_LED(1, 0, 255, 0);
  Set_LED(2, 0, 0, 255);

  Set_LED(3, 46, 89, 128);

  Set_LED(4, 156, 233, 100);
  Set_LED(5, 102, 0, 235);
  Set_LED(6, 47, 38, 77);

  Set_LED(7, 255, 200, 0);

  Set_Brightness(10);
  WS2812_Send();
*/

	LED_RGB_Init();
	LED_RGB_SetIntensity(100,0,0);
	HAL_Delay(200);
	LED_RGB_SetIntensity(0,0,100);
	HAL_Delay(200);
	LED_RGB_SetIntensity(0,100,0);

	  SSD1306_Init();

	  SSD1306_GotoXY (10,2); // goto 10, 10
	  SSD1306_Puts ("Temp", &Font_16x26, 1); //
	  SSD1306_GotoXY (10,30); // goto 10, 10
	  SSD1306_Puts ("Sensor", &Font_16x26, 1); //
	  SSD1306_UpdateScreen(); // update screen

	  HAL_Delay(2000);


	  HAL_UART_Receive_IT(&huart1, &rx_data, 1);
  /* USER CODE END 2 */

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




/*
	  	  for (int i=0; i<46; i++)
	  	  {
	  		  Set_Brightness(i);
	  		  WS2812_Send();
	  		  HAL_Delay (50);
	  	  }

	  	  for (int i=45; i>=0; i--)
	  	  {
	  		  Set_Brightness(i);
	  		  WS2812_Send();
	  		  HAL_Delay (50);
	  	  }
*/


/*	  ***Differentielel Messung Batterie
	  ADS1115_init(&ads_config, ADS1115_ADDRESS, MUX_DIFF_1_3, PGA_6144);
	  ADS1115_start_conversion(&hi2c1, ADS1115_ADDRESS ,&ads_config);
	  HAL_Delay(20);
	  voltage_adc[1] = ADS1115_read(&hi2c1, ADS1115_ADDRESS)*voltageConv;

	  sprintf(buffer_uart, "%3.3f;", voltage_adc[1]);
	  uprintf(buffer_uart);
*/

	  //***Temp-Messung 4 fach
	  ADS1115_init(&ads_config, ADS1115_ADDRESS, MUX_SINGLE_0, PGA_6144);
	  ADS1115_start_conversion(&hi2c1, ADS1115_ADDRESS ,&ads_config);
	  HAL_Delay(50);
	  voltage_adc[0] = ADS1115_read(&hi2c1, ADS1115_ADDRESS)*voltageConv;

	  ADS1115_init(&ads_config, ADS1115_ADDRESS, MUX_SINGLE_1, PGA_6144);
	  ADS1115_start_conversion(&hi2c1, ADS1115_ADDRESS ,&ads_config);
	  HAL_Delay(50);
	  voltage_adc[1] = ADS1115_read(&hi2c1, ADS1115_ADDRESS)*voltageConv;

	  ADS1115_init(&ads_config, ADS1115_ADDRESS, MUX_SINGLE_2, PGA_6144);
	  ADS1115_start_conversion(&hi2c1, ADS1115_ADDRESS ,&ads_config);
	  HAL_Delay(50);
	  voltage_adc[2] = ADS1115_read(&hi2c1, ADS1115_ADDRESS)*voltageConv;

	  ADS1115_init(&ads_config, ADS1115_ADDRESS, MUX_SINGLE_3, PGA_6144);
	  ADS1115_start_conversion(&hi2c1, ADS1115_ADDRESS ,&ads_config);
	  HAL_Delay(50);
	  voltage_adc[3] = ADS1115_read(&hi2c1, ADS1115_ADDRESS)*voltageConv;

	  HAL_Delay(50);

	  uint8_t buffer_max[4];
	  HAL_GPIO_WritePin(SPI2_CS_GPIO_Port,SPI2_CS_Pin, GPIO_PIN_RESET);
	  HAL_SPI_Receive(&hspi2,buffer_max,4,100);
	  HAL_GPIO_WritePin(SPI2_CS_GPIO_Port,SPI2_CS_Pin, GPIO_PIN_SET);
	  HAL_Delay(50);



	  SSD1306_Clear();

	  sprintf(buffer, "T1: %3.2fC", Temp[1]); // @suppress("Float formatting support")
	  SSD1306_GotoXY (10,5); // goto 10, 10
	  SSD1306_Puts (buffer, &Font_7x10, 1);

	  sprintf(buffer, "T2: %3.2fC", Temp[2]); // @suppress("Float formatting support")
	  SSD1306_GotoXY (10,20); // goto 10, 10
	  SSD1306_Puts (buffer, &Font_7x10, 1);

	  sprintf(buffer, "T3: %3.2fC", Temp[3]); // @suppress("Float formatting support")
	  SSD1306_GotoXY (10,35); // goto 10, 10
	  SSD1306_Puts (buffer, &Font_7x10, 1);

	  sprintf(buffer, "T4: %3.2fC", Temp[4]); // @suppress("Float formatting support")
	  SSD1306_GotoXY (10,50); // goto 10, 10
	  SSD1306_Puts (buffer, &Font_7x10, 1);

	  SSD1306_UpdateScreen();

	  sprintf(buffer_uart, "%d;", meas_counter);
	  //uprintf(buffer_uart);
	  uprintf_usart1(buffer_uart);
	  meas_counter++;




	  for(int i = 1; i<=4; i++)
	  {
		  Temp[i] = convert2celsius(voltage_adc[i-1], 5.0);
		  sprintf(buffer_uart, "Temp %d: %3.2f;", i, Temp[i]);
		  //uprintf(buffer_uart);
		  uprintf_usart1(buffer_uart);

	  }

	  //CDC_Transmit_FS((uint8_t *) "\r", 1);





	  if (usb_buffer[0] == 7 || usart1_buffer[0] == 7)
	 {

		  JumpToBootloader();
		  LED_RGB_SetIntensity(0,0,100);
		  usb_buffer[0] = 0;

	 }

	  /*
  	  for (int i=0; i<MAX_LED; i++)
  	  {

  		Set_LED(i, 255, 0, 0);
  	  	WS2812_Send();


  	  }
*/



		HAL_Delay (1000);






/*
	  PWM_O1++;
	  PWM_O3++;


	  if(PWM_O1>=100)
	  {
		  PWM_O1 = 0;
	  }

	  if(PWM_O3>=100)
	  {
		  PWM_O3 = 0;
	  }


	  PWM_O1_Set(PWM_O1);
	  PWM_O3_Set(PWM_O3);
	  HAL_GPIO_TogglePin(OUT2_3V3_GPIO_Port, OUT2_3V3_Pin);
	  HAL_GPIO_TogglePin(OUT4_3V3_GPIO_Port, OUT4_3V3_Pin);


	  HAL_Delay(50);

	  for(uint8_t pin = 0; pin <=7; pin++)
	  {
		  MCP_setPinA(pin,1);
		  HAL_Delay(200);
	  }

	  for(uint8_t pin = 0; pin <=7; pin++)
	  {
		  MCP_setPinB(pin,1);
		  HAL_Delay(200);
	  }
*/

/*
	  hmcp.gpio[MCP23017_PORTA] = P_GPIOA;
	  mcp23017_write_gpio(&hmcp, MCP23017_PORTA);

	  P_GPIOA++;

	  hmcp.gpio[MCP23017_PORTB] = P_GPIOB;
	  mcp23017_write_gpio(&hmcp, MCP23017_PORTB);
	  P_GPIOB--;
*/

    /* 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};
  RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI|RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  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_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  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();
  }
  PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USB|RCC_PERIPHCLK_USART1
                              |RCC_PERIPHCLK_USART3|RCC_PERIPHCLK_I2C1;
  PeriphClkInit.Usart1ClockSelection = RCC_USART1CLKSOURCE_PCLK2;
  PeriphClkInit.Usart3ClockSelection = RCC_USART3CLKSOURCE_PCLK1;
  PeriphClkInit.I2c1ClockSelection = RCC_I2C1CLKSOURCE_HSI;
  PeriphClkInit.USBClockSelection = RCC_USBCLKSOURCE_PLL_DIV1_5;
  if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
	__NOP();

	if(huart->Instance==USART1)
	 {
		 // if the data is not being received, clear the buffer
		 if(usart1_rx_index==0)
		 {
			 for(int i=0;i<20;i++)
			 {
				 usart1_buffer[i]=0;
			 }

		 }
		 // if the character received is other than 'enter' ascii13, save the data in buffer
		 if(rx_data!=13)
		 {
			 usart1_buffer[usart1_rx_index++]=rx_data;
		 	 }
		 else
		 	 {
			 usart1_rx_index=0;
		 	 }
		 HAL_UART_Receive_IT(&huart1,&rx_data,1);// receive data (one character only)
	 	 }
}


void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
{
	__NOP();
}
/* 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 */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
