
#include "lwip/mem.h"
#include "lwip/memp.h"
#include "lwip/dhcp.h"
#include "ethernetif.h"
#include "common_config.h"
#include "netconf.h"
#include "tcpip.h"
#include "main.h"
#include "settings_api.h"
#include "parameters.h"
#include "stm32f4x7_eth.h"

#ifdef PRINTF_STDLIB
#include <stdio.h>
#endif
#ifdef PRINTF_CUSTOM
#include "tinystdio.h"
#endif
#include <string.h>


#define MAX_DHCP_TRIES 3

#define TIME_COUNTER_10_MIN   600
#define TIME_COUNTER_1_MIN    60

/**
  * @brief  Network interface structure
  */
struct netif xnetif; 

/**
  * @brief  Задача получения сетевый параметров по DHCP протоколу
  */
TaskHandle_t xHandleDHCP = NULL;


void LwIP_Init(void)
{
  struct ip_addr ipaddr;
  struct ip_addr netmask;
  struct ip_addr gw;
  uint16_t reg = 0;
  
  tcpip_init( NULL, NULL );	
  
  ipaddr.addr = 0;
  netmask.addr = 0;
  gw.addr = 0;
	
  netif_add(&xnetif, &ipaddr, &netmask, &gw, NULL, &ethernetif_init, &tcpip_input);
  netif_set_default(&xnetif);
  netif_set_up(&xnetif); 
    	  
  /* Проверяем наличие линка */
  reg = ETH_ReadPHYRegister(0, 1);

 // if (reg & 4)
    xTaskCreate(LwIP_DHCP_task, "DHCPClient", configMINIMAL_STACK_SIZE * 2, NULL,
                tskIDLE_PRIORITY + 2, &xHandleDHCP);
}

/**
  * @brief  LwIP_DHCP_Process_Handle
  * @param  None
  * @retval None
  */
void LwIP_DHCP_task(void * pvParameters)
{
  struct ip_addr ipaddr;
  struct ip_addr netmask;
  struct ip_addr gw;
  uint8_t DHCP_state;  
  DHCP_state = DHCP_START;

  for (;;)
  {
    switch (DHCP_state)
    {
      case DHCP_START:
      {
        dhcp_start(&xnetif);
        DHCP_state = DHCP_WAIT_ADDRESS;
        //PRINT_USART("\n\rLooking for DHCP server please wait...\n\r");
      }
      break;

      case DHCP_WAIT_ADDRESS:
      {
        /* Read the new IP address */
        ipaddr = xnetif.ip_addr;
        netmask = xnetif.netmask;
        gw = xnetif.gw;
        	
		
		
        if (ipaddr.addr != 0) 
        {
          DHCP_state = DHCP_ADDRESS_ASSIGNED;	
          dhcp_stop(&xnetif);
          
		  PRINT_USART("Parameters assigned by a DHCP server:\n\r     IP:   ");
          PRINT_USART(ipaddr_ntoa(&ipaddr));
		  
		  PRINT_USART("\n\r");
          
		  PRINT_USART("Netmask:   ");
		  PRINT_USART(ipaddr_ntoa(&netmask));
		  PRINT_USART("\n\r");
		  
		  PRINT_USART("Gateway:   ");
		  PRINT_USART(ipaddr_ntoa(&gw));
		  PRINT_USART("\n\r");
          
		  printf("ETH OK\r\n");
		  
          vTaskDelete(xHandleDHCP);
        }
        else
        {
          /* DHCP timeout */
          if (xnetif.dhcp->tries > MAX_DHCP_TRIES)
          {
            DHCP_state = DHCP_TIMEOUT;

            /* Stop DHCP */
            dhcp_stop(&xnetif);
			
			/* Сообщение о неудачной попытке получить IP */
			printf("ETH FAIL\r\n");
			
			vTaskDelete(xHandleDHCP);
          }
        }
      }
      break;

      default: break;
    }

    vTaskDelay(250);
  }   
}

/*********** Portions COPYRIGHT 2012 Embest Tech. Co., Ltd.*****END OF FILE****/
