/*
 * Copyright(C) Paul und Scherer (mct.de/mct.net)
 *
 * This example demonstrates how to...
 *
 *  ... communicate with the ethernet
 *      device via telnet (port #23).
 */

#include <stdio.h>
#include <target.h>
#include "net.h"

#define SN	(255L<<24|255L<<16|255L<<8|192)	// choose subnet  mask
#define GW	(194L<<24| 64L<<16|159L<<8| 65)	//        gateway addr
#define IP	(194L<<24| 64L<<16|159L<<8| 79)	//        IP      addr
#define PN	23				//        port  number (telnet)

/*
 * The ethernet device channel 0 is initialized in TCP server mode.
 *
 * On connect, the program keeps listening for data which is simply
 * echoed (loopback).
 */
int
main(void)
{
	/*
	 * Initialize bus interface.
	 */
	Intern_gp0con = 0x00000220;
	Intern_gp1con = 0x02222211;
	Intern_gp2con = 0x22222220;
	Intern_gp3con = 0x22222222;
	Intern_gp4con = 0x22222222;
	Intern_xmcfg  = 1;
	Intern_xm0con = 3;
	Intern_xm1con = 3;
	Intern_xm2con = 3;
	Intern_xm3con = 1;
	Intern_xm0par = 0x722;
	Intern_xm1par = 0x722;
	Intern_xm2par = 0x722;
	Intern_xm3par = 0x722;
	puts("Bus interface initialized.");

	net_init(SN, GW, IP);			// initialize NET device

	printf("\n"
	       "LC7026 TCP server\n"
	       "=================\n\n"
	       "     Subnet mask : %3d.%3d.%3d.%3d\n"
	       " Gateway address : %3d.%3d.%3d.%3d\n"
	       "      IP address : %3d.%3d.%3d.%3d\n",
		net_rh(NET_SUBR), net_rb(NET_SUBR), net_rh(NET_SUBR+2), net_rb(NET_SUBR+2),
		net_rh(NET_GAR ), net_rb(NET_GAR ), net_rh(NET_GAR +2), net_rb(NET_GAR +2),
		net_rh(NET_SIPR), net_rb(NET_SIPR), net_rh(NET_SIPR+2), net_rb(NET_SIPR+2)
	);

	while (1) {
		static char buf[1460];		// r/w buffer

		int n;

		net_open(PN, 0);		// initialize socket (listen)

		printf("\nDisconnected, waiting for connection (port #%d)...\n", net_rw(NET_S0_PORTR));

		while (net_rb(NET_S0_SSR) != NET_SE) ;	// wait for sock_established

		printf("Connected (%3d.%3d.%3d.%3d), received data is echoed...\n",
			net_rh(NET_S0_DIPR  ), net_rb(NET_S0_DIPR  ),
			net_rh(NET_S0_DIPR+2), net_rb(NET_S0_DIPR+2)
		);
		while ((n = net_read(buf, sizeof(buf)))) net_write(buf, n);
		net_close();
	}
}

