/*
 * echo_server.c
 *
 *  Created on: Jun 9, 2024
 *      Author: jakubski
 */
#include <stdio.h>

#include "lwip/opt.h"
#include "lwip/arch.h"
#include "lwip/api.h"

#include "cmsis_os.h"
#define ECHOSERVER_THREAD_PRIO    ( tskIDLE_PRIORITY + 4 )

void echo_server_thread(void *arg)
{
	struct netconn *conn, *newconn;
	err_t err, recv_err;
	struct netbuf *inbuf;
	void *data;
	u16_t len;
	LWIP_UNUSED_ARG(arg);

	/* Create a new TCP connection handle */
	/* Bind to port 80 (HTTP) with default IP address */
	conn = netconn_new(NETCONN_TCP);
	LWIP_ERROR("echo_server: invalid conn", (conn != NULL), return;);

	err = netconn_bind(conn, IP_ADDR_ANY, 7);
	if (err == ERR_OK)
	{
		/* Put the connection into LISTEN state */
		netconn_listen(conn);

		do
		{
			err = netconn_accept(conn, &newconn);
			if (err == ERR_OK)
			{
				while (( recv_err = netconn_recv(newconn, &inbuf)) == ERR_OK)
				{
					do
					{
						netbuf_data(inbuf, &data, &len);
						netconn_write(newconn, data, len, NETCONN_COPY);
						printf("Echoed %d bytes\r\n", len);
						fflush(stdout);
					}
					while (netbuf_next(inbuf) >= 0);

					netbuf_delete(inbuf);
				}
				netconn_close(newconn);
				netconn_delete(newconn);
			}
			else
			{
				netconn_delete(newconn);
			}
		}
		while (err == ERR_OK);

//		LWIP_DEBUGF(HTTPD_DEBUG, ("echo_server_netconn_thread: netconn_accept received error %d, shutting down", err));
		netconn_close(conn);
		netconn_delete(conn);
	}
}

/** Initialize the ECHO server (start its thread) */
void echo_server_netconn_init(void)
{
  sys_thread_new("echo_server_netconn", echo_server_thread, NULL, DEFAULT_THREAD_STACKSIZE, ECHOSERVER_THREAD_PRIO);
}
