/**
  ******************************************************************************
  * @file    USART/HyperTerminal_Interrupt/main.c
  * @author  MCD Application Team
  * @version V1.0.0
  * @date    18-May-2012
  * @brief   Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; COPYRIGHT 2012 STMicroelectronics</center></h2>
  *
  * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License");
  * You may not use this file except in compliance with the License.
  * You may obtain a copy of the License at:
  *
  *        http://www.st.com/software_license_agreement_liberty_v2
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  *
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "stm32f0xx.h"
#include "stm32f0xx_rcc.h"
#include "stm32f0xx_gpio.h"
#include "stm32f0xx_misc.h"
#include "stm32f0xx_usart.h"
#include <stdio.h>
#include "ugui.h"
#include "ESP8266.h"
#include "LEDS.h"
/** @addtogroup STM32F0xx_StdPeriph_Examples
  * @{
  */

/** @addtogroup HyperTerminal_Interrupt
  * @{
  */

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
#define TXBUFFERSIZE   150
#define RXBUFFERSIZE   1300

/* Private macro -------------------------------------------------------------*/
#define countof(a)   (sizeof(a) / sizeof(*(a)))

/* Private variables ---------------------------------------------------------*/
uint8_t *TxBuffer=NULL;//[TXBUFFERSIZE] = "AT+RST\r\n";
USART_InitTypeDef USART_InitStructure;
uint8_t RxBuffer[RXBUFFERSIZE];
volatile uint32_t NbrOfDataToTransfer = 0;
volatile uint32_t NbrOfDataToRead = RXBUFFERSIZE;
volatile uint32_t TxCount = 0;
volatile uint32_t RxCount = 0;



uint32_t prijem=0;
uint32_t new_data=0;

/* Private function prototypes -----------------------------------------------*/
void NVIC_Config(void);
void USARTInit(void);
void RxBuffer_clear (void);

/* Private functions ---------------------------------------------------------*/

void ESP8266_Init(void)
{
	 // NVIC configuration
	  NVIC_Config();

	  // USARTx configuration
	  USARTInit();

	  GPIO_ResetBits(GPIOA,GPIO_Pin_8);
	  for (uint32_t var = 0; var < 0xffff; ++var);
	  GPIO_SetBits(GPIOA,GPIO_Pin_8);
	  for (uint32_t var = 0; var < 0xffffff; ++var);

}





/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
void HyperTerminal_Interrupt(void)
{
  /*!< At this stage the microcontroller clock setting is already configured,
  this is done through SystemInit() function which is called from startup
  file (startup_stm32f0xx.s) before to branch to application main.
  To reconfigure the default setting of SystemInit() function, refer to
  system_stm32f0xx.c file
  */





 //ESP8266_send_cmd("AT+RST\r\n",8);





  while(1);
  /* Enable the USART1 Transmoit interrupt: this interrupt is generated when the
  USART1 transmit data register is empty */
  USART_ITConfig(USART1, USART_IT_TXE, ENABLE);

  /* Wait until USART1 send the TxBuffer */
  while(TxCount < NbrOfDataToTransfer)
  {}

  /* The software must wait until TC=1. The TC flag remains cleared during all data
  transfers and it is set by hardware at the last frame's end of transmission*/
  while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET)
  {}

  /* Enable the USART1 Receive interrupt: this interrupt is generated when the
  USART1 receive data register is not empty */
  USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);

  /* Wait until USART1 receive the RxBuffer */
  while(RxCount < NbrOfDataToRead)
  {}

      	UG_PutString(1,5,"Data Receive Completed!\n");
      	    	update_display();


  /* Infinite loop */
  while (1)
  {
  }
}


void NVIC_Config(void)
{
  NVIC_InitTypeDef NVIC_InitStructure;

  /* Enable the USART2 Interrupt */
  NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);
}

void USARTInit(void)
{
    GPIO_InitTypeDef GPIO_InitStructure;
    USART_InitTypeDef USART_InitStructure;

    USART_InitStructure.USART_BaudRate = 115200;
    USART_InitStructure.USART_WordLength = USART_WordLength_8b;
    USART_InitStructure.USART_StopBits = USART_StopBits_1;
    USART_InitStructure.USART_Parity = USART_Parity_No;
    USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
    USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;

    /* Enable GPIO clock */
    RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);

    /* Enable USART clock */
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);

    /* Connect PXx to USARTx_Tx */
    GPIO_PinAFConfig(GPIOA, GPIO_PinSource9, GPIO_AF_1);

    /* Connect PXx to USARTx_Rx */
    GPIO_PinAFConfig(GPIOA, GPIO_PinSource10, GPIO_AF_1);

    /* Configure USART Tx, Rx as alternate function push-pull */
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_10;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
    GPIO_Init(GPIOA, &GPIO_InitStructure);

    /* USART configuration */
    USART_Init(USART1, &USART_InitStructure);

    /* Enable USART */
    USART_Cmd(USART1, ENABLE);

}

void USART1_IRQHandler(void)
{
	if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)
	{
		USART_ClearITPendingBit(USART1, USART_IT_RXNE);
		RxBuffer[RxCount++] = USART_ReceiveData(USART1) & 0xFF;
		if(RxCount == RXBUFFERSIZE) RxBuffer_clear();
	}

	if(USART_GetITStatus(USART1, USART_IT_TXE) != RESET)
	{
		USART_SendData(USART1, *(TxBuffer+TxCount));
		TxCount++;
		if(TxCount == NbrOfDataToTransfer)
		{
			USART_ITConfig(USART1, USART_IT_TXE, DISABLE);
		}
	}
	USART_ClearFlag(USART1,USART_FLAG_ORE);
}

void RxBuffer_clear (void)
{
	RxCount = 0;
	for(uint32_t i=0;i<RXBUFFERSIZE;i++)
	{
		RxBuffer[i]=0;
	}
}

uint32_t ESP8266_send_cmd(uint8_t *cmd, uint32_t resp_cnt, ...)
{
	uint32_t bez_odezvy=0;
	va_list ap;

	uint8_t *resp[resp_cnt];

	if (resp_cnt == 0)bez_odezvy=1;

	va_start(ap, resp_cnt);
	for(uint32_t i=0;i<resp_cnt;i++)
	{
		resp[i]=va_arg(ap, uint8_t*);
	}
	va_end(ap);

	NbrOfDataToTransfer=strlen(cmd);
	TxCount=0;
	TxBuffer=cmd;
	if(!bez_odezvy)
	{
		RxBuffer_clear();
		USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
	}
	USART_ITConfig(USART1, USART_IT_TXE, ENABLE);

	while(TxCount < NbrOfDataToTransfer);	// Wait until USART1 send the TxBuffer

	volatile uint32_t ret_val=0;
	if(!bez_odezvy)
	{

		volatile uint32_t timeout=millis()+10000;	//10000ms
		while(!ret_val)	//cekani na odezvu
		{
			for(uint32_t i=0;i<resp_cnt;i++)
			{
				if(strstr(RxBuffer,resp[i]))
				{
					ret_val=i+1;
					break;
				}
			}
		if(timeout<millis()) break;
		}
		USART_ITConfig(USART1, USART_IT_RXNE, DISABLE);
	}
	return ret_val;
}

void ESP8266_transfer(uint8_t* send_buff, uint8_t* rece_buff)
{

	NbrOfDataToTransfer=strlen(send_buff);
	TxCount=0;
	TxBuffer=send_buff;
	RxBuffer_clear();
	USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
	USART_ITConfig(USART1, USART_IT_TXE, ENABLE);

	while(TxCount < NbrOfDataToTransfer);	// Wait until USART1 send the TxBuffer

	volatile uint32_t ret_val=0;

	volatile uint32_t timeout=millis()+10000;	//10000ms
	while(!ret_val)	//cekani na odezvu
	{
		if(strstr(RxBuffer,"SUCCESS\r\n0\r\n\r\n\r\nOK\r\n"))
		{
			ret_val=1;
		}
		if(timeout<millis()) break;
	}
	USART_ITConfig(USART1, USART_IT_RXNE, DISABLE);
	if(ret_val==1)
	{
		//zpracovani prijate zpravy
		uint8_t* mess_start=strstr(RxBuffer,"MESSAGE")+sizeof("MESSAGE")-1;
		uint8_t* mess_stop=strstr(RxBuffer,"SUCCESS");
		for(uint32_t i=0;i<(mess_stop-mess_start);i++)
		{
			*(rece_buff+i)=*(mess_start+i);;
		}
		*(rece_buff+(mess_stop-mess_start))=0;
	}
	return ret_val;
}

void ESP8266_get_response(uint8_t *cmd, uint32_t length)
{
	NbrOfDataToTransfer=length;
	TxBuffer=cmd;
	USART_ITConfig(USART1, USART_IT_TXE, ENABLE);

	/* Wait until USART1 send the TxBuffer */
	while(TxCount < NbrOfDataToTransfer);
	TxCount=0;
}



uint32_t  findintext(uint8_t *str1, uint8_t *str2)
{
	int len1=strlen(str1);
	int len2=strlen(str2);
	char success=0;

	for(int i=0;i<len1-len2;i++)
	{
		for(int n=0;n<len2;n++)
		{
			if(str1[i+n]==str2[n]) success=1;
			else
			{
				success=0;
				break;
			}
		}
		if(success) return (i);
	}
	return (0);
}

void USART2_IRQHandler(void)
{
	if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)
		{
			USART_ClearITPendingBit(USART1, USART_IT_RXNE);
			uint8_t ch = (USART_ReceiveData(USART1) & 0xFF);
			if((ch!='\n')&&(ch!='\r'))
			{
				// Read one byte from the receive data register
				RxBuffer[RxCount++] = ch;

				if(RxCount == NbrOfDataToRead)
				{
					prijem = 0;
					// Disable the USART1 Receive interrupt
					if(RxBuffer[RXBUFFERSIZE-1]==254)
					{
						USART_ITConfig(USART1, USART_IT_RXNE, DISABLE);
						RxCount = 0;

					}
					else RxCount=0;
				}
			}
			else
			{
				//prijata zprava
				if(RxCount>2)
				{
					//zpracovaní
					new_data = 1;
				}
				else
				{
					//prijat pouze ukoncovaci znak
					RxCount = 0;
				}
			}
		}

  if(USART_GetITStatus(USART1, USART_IT_TXE) != RESET)
  {
    /* Write one byte to the transmit data register */
    USART_SendData(USART1, *(TxBuffer+TxCount));
    TxCount++;
    if(TxCount == NbrOfDataToTransfer)
    {
      /* Disable the USART1 Transmit interrupt */
      USART_ITConfig(USART1, USART_IT_TXE, DISABLE);
    }
  }
}

/*void ESP8266_send_cmd(uint8_t *cmd, uint32_t length)
{
	NbrOfDataToTransfer=length;
	TxBuffer=cmd;
	USART_ITConfig(USART1, USART_IT_TXE, ENABLE);

	// Wait until USART1 send the TxBuffer
	while(TxCount < NbrOfDataToTransfer);
	TxCount=0;
}*/

/*Format odesilanych dat pro SmartPlug:

hlavni datovy stream:
* obsahuje U,I,P,Q,S,ny,datum,cas
* elektricke veliciny maji kazda 5 digitu
* casove veliciny maji 6 digitu, aby mohlo diji k odeslani 15:24:31 nebo 24.10.16
* poradi (pro prehlednost jsou jednotlive udaje oddeleny mezerou):

UUUUU IIIII PPPPP QQQQQ SSSSS nnnnn tttttt dddddd

(n predstavuje ny - ucinnost; t predstavuje cas a d predstavuje datum)


pro odelani na skutecny server je nutne se pripojit na server:

smartplug.smartsys.cz

a pro odeslani hodnot (datoveho streamu):

GET /receiver.php?data=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
