#include "lwip/opt.h"
#include "lwip/sys.h"
#include "tcp_server.h"
#include <string.h>
#include <stdio.h>
#include "gd32f30x.h"
#include "main.h"
#include "lwip/tcp.h"
#include "lwip/memp.h"
#include "lwip/api.h"
#include "sockets.h"
#include "log.h"

void tcp_server_task(void *pvParameters)
{
    int ret,sockfd;
		int recv_size;
    struct sockaddr_in tcpServerSock;
    struct sockaddr_in client_sock;
    tcpServerSock.sin_family = AF_INET;
		inet_aton("192.168.2.222",&(tcpServerSock.sin_addr));
//    tcpServerSock.sin_addr.s_addr = htonl(IPADDR_ANY);
    tcpServerSock.sin_port = htons(8080);
tcp_server_begin:
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        goto tcp_server_begin;
    }
    ret = bind(sockfd, (struct sockaddr *)&tcpServerSock, sizeof(tcpServerSock));
    if (ret < 0)
    {
        lwip_close(sockfd);
        sockfd = -1;
        goto tcp_server_begin;
    }
    ret = listen(sockfd, 10);
    if (ret < 0)
    {
        lwip_close(sockfd);
        sockfd = -1;
        goto tcp_server_begin;
    }
		socklen_t len = sizeof(client_sock);
    int client_socket = accept(sockfd, (struct sockaddr*)&client_sock,&len);
		if (client_socket<0)
    {
      printf("error");
    }
		LOG_PRINT(LOG_INFO,"上位机连接成功");
    while (1)
    {
				vTaskDelay(1000);
				char *cmd=pvPortMalloc(1024);
				recv_size=recv(client_socket,cmd,1024,0);
				if(recv_size>0)
				{
					LOG_PRINT(LOG_INFO,"服务端recv:%s",cmd);					
				}
				else if(recv_size==0)
				{
					lwip_close(client_socket);
					vPortFree(cmd);
					LOG_PRINT(LOG_WARN,"上位机断连，重新等待连接");
					client_socket= accept(sockfd, (struct sockaddr*)&client_sock,&len);
				}
    }
    
}
/*!
    \brief      initialize the tcp_client application
    \param[in]  none
    \param[out] none
    \retval     none
*/
void tcp_server_init(void)
{
    xTaskCreate(tcp_server_task, "TCP_CLIENT", DEFAULT_THREAD_STACKSIZE, NULL, 4, NULL);
}
