#include "custom_lcd.h"
#include "cmsis_os.h"
#include <stdio.h>
#include "iwdg.h"

extern unsigned tim1_cnt;
extern I2C_HandleTypeDef hi2c1;
uint16_t LCD_adr;

extern struct flags FLAGS;
//extern struct var_result VAR_RESULT;
//LCD Delays (Delay1 - )

void LCD_Reinit(void)
{
	LCD_Init(); 
	FLAGS.LCD_REINIT=0; 
	osDelay(1000); 
}
void LCD_Check(void)
{
	if(FLAGS.LCD_REINIT) LCD_Reinit();
}

void LCD_Send_CMD (char cmd)
{
	char data_up, data_low;
	uint8_t data_t[4];
	data_up = (cmd&0xf0);
	data_low=((cmd<<4)&0xf0);
	data_t[0]=data_up|0x0C; //en=1, rs=0
	data_t[1]=data_up|0x08; //en=0, rs=0
	data_t[2]=data_low|0x0C; //en=1, rs=0
	data_t[3]=data_low|0x08; //en=0, rs=0
	HAL_I2C_Master_Transmit(&hi2c1, LCD_adr, (uint8_t *)data_t, 4, HAL_MAX_DELAY);
}

void LCD_Send_DATA (char data)
{
	char data_up, data_low;
	uint8_t data_t[4];
	data_up = (data&0xf0);
	data_low=((data<<4)&0xf0);
	data_t[0]=data_up|0x0D; //en=1, rs=1
	data_t[1]=data_up|0x09; //en=0, rs=1
	data_t[2]=data_low|0x0D; //en=1, rs=1
	data_t[3]=data_low|0x09; //en=0, rs=1
	HAL_I2C_Master_Transmit(&hi2c1, LCD_adr, (uint8_t *)data_t, 4, HAL_MAX_DELAY);
}

void LCD_Send_STRING(char *str)
{
	while (*str) LCD_Send_DATA (*str++);
}

void LCD_Send_INT(int int_to_string)
{
	char string_from_int[10];
	snprintf(string_from_int, sizeof(string_from_int), "%d", int_to_string);
	LCD_Send_STRING(string_from_int);
}

void LCD_Send_NUMB(float numb_to_string)
{
	char string_from_numb[10];
	snprintf(string_from_numb, sizeof(string_from_numb), "%.3f", numb_to_string);
	LCD_Send_STRING(string_from_numb);
}


void LCD_Init(void)
{
	for (LCD_adr = 0; LCD_adr < 128; LCD_adr++)
	{
		if(HAL_I2C_IsDeviceReady(&hi2c1, LCD_adr << 1, 1, HAL_MAX_DELAY)==HAL_OK)  break; // scan i2c adresses
	}	
	LCD_adr = LCD_adr << 1;
	
	osDelay(500);
	LCD_Send_CMD(0x30);
	osDelay(5);
	LCD_Send_CMD(0x30);
	osDelay(1);
	LCD_Send_CMD(0x30);
	osDelay(10);
	LCD_Send_CMD(0x20); // 4bit mode
	osDelay(10);

	//dislay initialisation
	LCD_Send_CMD(0x28); // display off
	osDelay(1);
	LCD_Send_CMD(0x08); // display off
	osDelay(50);
	LCD_Send_CMD(0x01); // clear display
	osDelay(10);
	osDelay(10);
	LCD_Send_CMD(0x06); // direction of cursor
	osDelay(1); 
	LCD_Send_CMD(0x0C); // display on / cursor off
}

void LCD_Start(void)
{
	if(!(FLAGS.LCD_ON))
	{
		osDelay(3000);
		LCD_Init();
		MX_IWDG_Init();
		FLAGS.LCD_ON = 1;
	}
}

void LCD_IWDG_Reset(void)
{
	HAL_IWDG_Refresh(&hiwdg);
}
