/*!
 * @file       main.c
 *
 * @brief      ETH Main program body
 *
 * @version    V1.0.0
 *
 * @date       2022-11-10
 *
 * @attention
 *
 *  Copyright (C) 2022 Geehy Semiconductor
 *
 *  You may not use this file except in compliance with the
 *  GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE).
 *
 *  The program is only for reference, which is distributed in the hope
 *  that it will be useful and instructional for customers to develop
 *  their software. Unless required by applicable law or agreed to in
 *  writing, the program is distributed on an "AS IS" BASIS, WITHOUT
 *  ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions
 *  and limitations under the License.
 */

/* Includes */
#include "main.h"
#include "board_DP83848.h"
#include <stdio.h>
#include <string.h>

/** @addtogroup Examples
  * @{
  */

/** @addtogroup ETH_Ping
  * @{
  */

/** @defgroup ETH_Ping_Macros Macros
  @{
*/

/* printf function configs to UART4 */
#define DEBUG_USART         UART4

/* Configurate local ETH information */
#define ETH_IP_ADDR         "169.254.90.123"
#define ETH_NET_MASK        "255.255.255.0"
#define ETH_GATEWAY         "169.254.90.1"

/**@} end of group ETH_Ping_Macros */

/** @defgroup ETH_Ping_Variables Variables
  * @{
  */

/* Global pointers on Rx descriptor used to transmit and receive descriptors */
extern ETH_DMADescConfig_T*  DMARxDescToGet;

/* current Ethernet LocalTime value */
volatile uint32_t ETHTimer = 0;
/* lwip network interface structure for ethernetif */
struct netif UserNetif;

/* TCP periodic Timer */
uint32_t TCPTimer = 0;
/* ARP periodic Timer */
uint32_t ARPTimer = 0;
/* MAC address */
uint8_t SetMACaddr[6] = {0, 0, 0, 0, 0, 8};

/* Menu title string*/
const char* menuTitleStr[] =
{
    "   ETH Raw Ping Example   ",
};

/* Menu bottom column string*/
const char* menuBottomColStr[] =
{
    "   GEEHY SEMICONDUCTOR   ",
};

/**@} end of group ETH_Ping_Variables */

/** @defgroup ETH_Ping_Functions Functions
  * @{
  */

/* Configure SysTick */
void ConfigSysTick(void);
/* User config the different system Clock */
void UserRCMClockConfig(void);
void APM_EVAL_Init(void);
void Menu_DisplayInit(void);

/*!
 * @brief     Main program
 *
 * @param     None
 *
 * @retval    None
 */
int main(void)
{
    APM_EVAL_Init();
    
    /* User config the different system Clock */
    UserRCMClockConfig();

    /* Configure SysTick */
    ConfigSysTick();
    
    printf("\r\nETH Raw Ping Demo.\r\n");

    /* Configure ethernet (GPIOs, clocks, MAC, DMA) */
    Ethernet_Config();

    /* Initilaize the LwIP stack */
    LwIP_Init();

    while (1)
    {
        /* check if any packet received */
        if (ETH_ReadRxPacketSize(DMARxDescToGet))
        {
            /* process received ethernet packet */
            LwIP_Pkt_Handle();
        }

        /* handle periodic timers for LwIP */
        LwIP_Periodic_Handle(ETHTimer);
    }
}

/*!
 * @brief       Init EVAL board
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
void APM_EVAL_Init(void)
{
    USART_Config_T usartConfigStruct;
    
    /* UART4 Config */
    usartConfigStruct.baudRate = 115200;
    usartConfigStruct.hardwareFlow = USART_HARDWARE_FLOW_NONE;
    usartConfigStruct.mode = USART_MODE_TX_RX;
    usartConfigStruct.parity = USART_PARITY_NONE;
    usartConfigStruct.stopBits = USART_STOP_BIT_1;
    usartConfigStruct.wordLength = USART_WORD_LEN_8B;
    APM_EVAL_COMInit(COM4, &usartConfigStruct);

    APM_LCDInit();
    LCD_Clear(0, 0, LCD_WIDTH, LCD_HEIGHT, LCD_BCOLOR);

    Menu_DisplayInit();
}

/*!
 * @brief       Initialize the Menu UI
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
void Menu_DisplayInit(void)
{
    char ipStr[24] = "IP: ";
    char maskStr[24] = "Mask: ";
    char gwStr[24] = "Gw: ";
    
    strcat(ipStr, ETH_IP_ADDR);
    strcat(maskStr, ETH_NET_MASK);
    strcat(gwStr, ETH_GATEWAY);
    
    /* Menu title */
    LCD_Clear(0, 0, LCD_WIDTH, 40, LCD_FCOLOR);
    LCD_DisplayString(20, LCD_LINE_TITLE, menuTitleStr[0], LCD_TEXT_SELECT_FC, LCD_TEXT_SELECT_BC, 16, 0);
    
    /* Menu item */
    LCD_DisplayString(10, LCD_LINE_2, "   Static IP address:   ", LCD_TEXT_FC, LCD_TEXT_BC, 16, 0);
    LCD_DisplayString(40, LCD_LINE_3, ipStr, LCD_TEXT_FC, LCD_TEXT_BC, 16, 0);
    LCD_DisplayString(40, LCD_LINE_4, maskStr, LCD_TEXT_FC, LCD_TEXT_BC, 16, 0);
    LCD_DisplayString(40, LCD_LINE_5, gwStr, LCD_TEXT_FC, LCD_TEXT_BC, 16, 0);
    
    /* Menu bottom */
    LCD_Clear(0, LCD_LINE_BOTTOM, LCD_WIDTH, LCD_HEIGHT, LCD_FCOLOR);
    LCD_DisplayString(20, LCD_LINE_BOTTOM, menuBottomColStr[0], LCD_TEXT_SELECT_FC, LCD_TEXT_SELECT_BC, 16, 0);
}

/*!
* @brief     Configure SysTick
*
* @param     None
*
* @retval    None
*/
void ConfigSysTick(void)
{
    if (SysTick_Config(SystemCoreClock / 100))
    {
        /* Capture error */
        while (1);
    }
}

/*!
 * @brief     This function initializes the lwIP stack
 *
 * @param     None
 *
 * @retval    None
 */
void LwIP_Init(void)
{
    struct ip_addr ipaddr;
    struct ip_addr netmask;
    struct ip_addr gw;

    int ipAddrTemp[4];
    int netMaskTemp[4];
    int gatewayTemp[4];

    /* Initializes the dynamic memory heap */
    mem_init();

    /* Initializes the memory pools */
    memp_init();

    sscanf(ETH_IP_ADDR, "%d.%d.%d.%d", &ipAddrTemp[0], &ipAddrTemp[1], &ipAddrTemp[2], &ipAddrTemp[3]);
    sscanf(ETH_NET_MASK, "%d.%d.%d.%d", &netMaskTemp[0], &netMaskTemp[1], &netMaskTemp[2], &netMaskTemp[3]);
    sscanf(ETH_GATEWAY, "%d.%d.%d.%d", &gatewayTemp[0], &gatewayTemp[1], &gatewayTemp[2], &gatewayTemp[3]);

    IP4_ADDR(&ipaddr, ipAddrTemp[0], ipAddrTemp[1], ipAddrTemp[2], ipAddrTemp[3]);
    IP4_ADDR(&netmask, netMaskTemp[0], netMaskTemp[1], netMaskTemp[2], netMaskTemp[3]);
    IP4_ADDR(&gw, gatewayTemp[0], gatewayTemp[1], gatewayTemp[2], gatewayTemp[3]);

    /* Config MAC Address */
    ETH_ConfigMACAddress(ETH_MAC_ADDRESS0, SetMACaddr);

    /* Add a network interface to the list of lwIP netifs */
    netif_add(&UserNetif, &ipaddr, &netmask, &gw, NULL, &ethernetif_init, &ethernet_input);

    /* Registers the default network interface */
    netif_set_default(&UserNetif);

    /* When the netif is fully configured this function must be called */
    netif_set_up(&UserNetif);

#ifdef MII_MODE
    printf("MII_MODE\r\n");
#elif defined RMII_MODE  /* Mode RMII */
    printf("RMII_MODE\r\n");
#endif
    printf("Static ETH Information:\r\n");
    printf("ETH_IP       : %d.%d.%d.%d\r\n", ipAddrTemp[0], ipAddrTemp[1], ipAddrTemp[2], ipAddrTemp[3]);
    printf("ETH_Net_Mask : %d.%d.%d.%d\r\n", netMaskTemp[0], netMaskTemp[1], netMaskTemp[2], netMaskTemp[3]);
    printf("ETH_Gateway  : %d.%d.%d.%d\r\n", gatewayTemp[0], gatewayTemp[1], gatewayTemp[2], gatewayTemp[3]);
}

/*!
 * @brief     This function received ethernet packet
 *
 * @param     None
 *
 * @retval    None
 */
void LwIP_Pkt_Handle(void)
{
    /* Read a received packet from the Ethernet buffers and send it to the lwIP for handling */
    ethernetif_input(&UserNetif);
}

/*!
 * @brief     This function LwIP periodic tasks
 *
 * @param     ETHTimer the current Ethernet Timer value
 *
 * @retval    None
 */
void LwIP_Periodic_Handle(__IO uint32_t ETHTimer)
{
#if LWIP_TCP

    /* TCP periodic process every 250 ms */
    if (ETHTimer - TCPTimer >= TCP_TMR_INTERVAL)
    {
        TCPTimer =  ETHTimer;
        tcp_tmr();
    }

#endif

    /* ARP periodic process every 5s */
    if ((ETHTimer - ARPTimer) >= ARP_TMR_INTERVAL)
    {
        ARPTimer =  ETHTimer;
        etharp_tmr();
    }
}

/*!
 * @brief     User config the different system Clock
 *
 * @param     None
 *
 * @retval    None
 */
void UserRCMClockConfig(void)
{
    SystemInit();
}

/*!
 * @brief     Redirect C Library function printf to serial port.
 *            After Redirection, you can use printf function.
 *
 * @param     ch:  The characters that need to be send.
 *
 * @param     *f:  pointer to a FILE that can recording all information
 *            needed to control a stream
 *
 * @retval    The characters that need to be send.
 */
int fputc(int ch, FILE* f)
{
    /* send a byte of data to the serial port */
    USART_TxData(DEBUG_USART, (uint8_t)ch);

    /* wait for the data to be send */
    while (USART_ReadStatusFlag(DEBUG_USART, USART_FLAG_TXBE) == RESET);

    return (ch);
}

/**@} end of group ETH_Ping_Functions */
/**@} end of group ETH_Ping */
/**@} end of group Examples */
