#include "system.h"
#include "altera_avalon_pio_regs.h"
#include "sys/alt_stdio.h"
#include "wiring.h"
#include "adb.h"
#include <stdio.h>
#include <string.h>

// Adb connection.
static Connection *connection;
static long lastTime;
static uint16_t count;

typedef union {
	uint32_t data32;
	uint8_t data8[4];
} RDATA;

// Event handler for the shell connection. 
static void adbEventHandler(Connection * connection, adb_eventType event, uint16_t length, uint8_t * data)
{
	RDATA rdata;
	int i, j, offset;

	if( event == ADB_CONNECTION_RECEIVE ) {
			for(i=0; i<16; i++) {
				offset = i << 2;
				for (j=0; j<4; j++) {
					rdata.data8[3-j] = data[offset+j];
				}
				IOWR_32DIRECT(MATRIX_LED_CTRL_0_BASE, offset, rdata.data32);
			}
	} else if( event == ADB_CONNECTION_OPEN ) {
		alt_putstr("connect\n");
	} else if( event == ADB_CONNECTION_CLOSE ) {
		alt_putstr("disconnect\n");
	}
}

static void setup( void )
{
	// Initialize the ADB subsystem.
	while( adbInit() ) {
		delay( 100 );
	}

	while( 1 ) {
		connection = adbAddConnection( "tcp:6000", true, adbEventHandler );
		if( connection != NULL ) {
			break;
		}
		delay( 10 );
	}

}

static void loop( void )
{
	// Poll the ADB subsystem.
	adbPoll();
}

int main( void )
{ 
	int i, j;
	int dd = 0x1;

	alt_putstr("Start\n");
	setup();

	for (j=0; j<=32; j++){
		for(i=0; i<64; i+=4) {
			IOWR_32DIRECT(MATRIX_LED_CTRL_0_BASE, i, dd);
		}
		dd <<= 1;
		delay(20);
	}
	for(i=0; i<64; i+=4) {
		IOWR_32DIRECT(MATRIX_LED_CTRL_0_BASE, i, 0xffffffff);
		delay(20);
		IOWR_32DIRECT(MATRIX_LED_CTRL_0_BASE, i, 0x0);
	}

	/* Event loop never exits. */
	while (1) {
		loop();
	}
}

