/*
 * Copyright (C) 2020-2021 Aloysius Indrayanto
 *
 * This file is part of the eCxx library, see LICENSE file for the license details.
 */


#include <eCxx/eCxx_Server.h>

#include "NodeMCU_Common.h"


//
// The TCP server
//
static eCxx::TCPServer tcpServer(2323);


//
// The init function
//
void eCxx_user_init()
{
    // Initialize application
    initBasicNodeMCUApp();

    // There is no need to enable the 74LVC541 buffers on the eCxx NodeMCU development board because
    // the UART is only used for communication with the host PC

    // Initialize UART
    App::uart().begin(9600);

    // Intialize TCP server
    tcpServer.begin();
}


//
// The task function
//
void eCxx_user_task()
{
    // Process event
    eCxx::Application::processEvent();

    // For convenience
    auto& uart = App::uart();

    // Check for a new TCP client connection
    eCxx::TCPClient&& client = tcpServer.handleClient();
    if( !client.connected() ) return;

    uart.writeStringln( PGM_STR("TCP client connected") );

    // Handle the TCP client (this loop will block other non-essential network handling, including OTA programming!)
    while( client.connected() ) {
        while( client.canRead() > 0) {
            // Yield
            App::yield();
            // Read data from the connected client
            eCxx::uint8_t c;
            client.read(c);
            // Send it back (this is an echo server)
            client.write(c);
            // Write it to UART
            uart.write(c);
        }
    }

    // Disconnect the TCP client
    client.end();
    uart.writeStringln( PGM_STR("TCP client disconnected") );
}
