#include "net.h"
#include "iec104.h"
#include "iec10x.h"

static err_t bms_test_process(int fd, void *data, int len)
{
    INT8U response[2] = {0xBB, 0xAA};
    if ((len == 2) && (((INT8U *)data)[0] == 0xAA) && (((INT8U *)data)[1] == 0xBB))
    {
        send(fd, (void *)response, sizeof(response), 0);
    }
    return 1;
}

static err_t bms_net_process(int fd)
{

    Iec10x_Scheduled(fd);
    Iec104_StateMachine();
    return 1;
}

void net_task(void)
{
    INT8U              buf[500];
    INT32S             ret    = 0;
    INT32S             sockfd = -1, newfd = -1;
    INT32U             len = 0;
    struct sockaddr_in svr_addr, clt_addr;

    INT16U Iec104_RecvLen;

    svr_addr.sin_family      = AF_INET;
    svr_addr.sin_port        = htons(TCP_PORT);
    svr_addr.sin_addr.s_addr = htons(INADDR_ANY);

    while (1)
    {
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            continue;
        }

        ret = bind(sockfd, (struct sockaddr *)&svr_addr, sizeof(svr_addr));
        if (ret < 0)
        {
            lwip_close(sockfd);
            sockfd = -1;
            continue;
        }

        ret = listen(sockfd, 1);
        if (ret < 0)
        {
            lwip_close(sockfd);
            continue;
        }

        len = sizeof(clt_addr);

        newfd = accept(sockfd, NULL, NULL);

        while (-1 != newfd)
        {
            ret = recv(newfd, buf, sizeof(buf) - 1, 0);
            if (ret <= 0)
            {
                printf("the other side has been closed (%d).\n", sizeof(buf) - 1);
                lwip_close(newfd);
                newfd = -1;
                break;
            }
            bms_net_process(newfd);
            LOG("#####################received \n");
            DumpHEX(buf, read(newfd, buf, 1500));
            Iex104_Receive(buf, read(newfd, buf, 1500));
        }

        lwip_close(sockfd);
        sockfd = -1;
        // OSTimeDly(10);
    }
}
