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

#include <stdio.h>
#include "net1.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| 77)	//        IP      addr
#define PN	23				//        port  number (telnet)

/*
 * SPIMS (SPI Made Simple) chip selects
 */
#define CS0	0x10000				// P0.16
#define CS1	0x20000				// P0.17
#define CS2	0x40000				// P0.18
#define CS3	0x80000				// P0.19

/*
 * The SPI is setup as master (CPOL =0, CPHA =0).
 *
 * Note: A pullup is needed for slave select (=P0.7), when
 * in master mode!
 */
static void
spi_init(void)
{
	Intern_pinsel0 |= 0x5500;		// enable SPI pins
	Intern_spcr     = 0x20;			// MSTR
	Intern_spccr    = 8;			// SCK =pclk/8
}

/*
 * The ethernet module channel 0 is initialized in TCP server mode.
 *
 * On connect, the program keeps listening for data which is simply
 * echoed (loopback).
 */
int
main(void)
{
	/*
	 * De-select all SPImS devices.
	 */
	Intern_ioset  = CS0|CS1|CS2|CS3;
	Intern_iodir |= CS0|CS1|CS2|CS3;

	spi_init();				// initialize SPI
	net_init(SN, GW, IP);			// initialize NET module

	printf("\n"
	       "NET1 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_rb(NET_SUBR), net_rb(NET_SUBR+1), net_rb(NET_SUBR+2), net_rb(NET_SUBR+3),
		net_rb(NET_GAR ), net_rb(NET_GAR +1), net_rb(NET_GAR +2), net_rb(NET_GAR +3),
		net_rb(NET_SIPR), net_rb(NET_SIPR+1), net_rb(NET_SIPR+2), net_rb(NET_SIPR+3)
	);

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

		int n;

		net_open(PN);			// initialize socket

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

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

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