/*
Copyright 2007, Freie Universitaet Berlin. All rights reserved.

These sources were developed at the Freie Universität Berlin, Computer
Systems and Telematics group.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

- Neither the name of Freie Universitaet Berlin (FUB) nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

This software is provided by FUB and the contributors on an "as is"
basis, without any representations or warranties of any kind, express
or implied including, but not limited to, representations or
warranties of non-infringement, merchantability or fitness for a
particular purpose. In no event shall FUB or contributors be liable
for any direct, indirect, incidental, special, exemplary, or
consequential damages (including, but not limited to, procurement of
substitute goods or services; loss of use, data, or profits; or
business interruption) however caused and on any theory of liability,
whether in contract, strict liability, or tort (including negligence
or otherwise) arising in any way out of the use of this software, even
if advised of the possibility of such damage.

This implementation was developed by the CST group at the FUB.

For documentation and questions please use the web site
http://scatterweb.mi.fu-berlin.de and the mailinglist
scatterweb@lists.spline.inf.fu-berlin.de (subscription via the Website).
Berlin, 2007
*/

#include <ScatterWeb.System.h>
#include <ScatterWeb.CC1020.h>
#include <string.h>
#include "constants.h"


uint8_t recv_s = 0;					/*Reception switch 0=off 1=on*/
uint8_t promiscous = 0;					/*Promiscous switch 0=off 1=on*/


/*Dumps header and content*/
/*args : radioHandler arg */
/*returns: -1=error 0=ok  */
uint8_t dump(struct netpacket_handler_args* args) {
uint8_t i = 0;

	if (!args) return -1;

	/*Dumping*/
	if (recv_s) {
		
		_Data_redOff();

		/*http://cst.mi.fu-berlin.de/projects/ScatterWeb/documentation/dmsb/trunkhtml/structnetpacket__handler__args.html*/

		/*Header fields*/
		printf(
		"Packet number: %u\n"
		"Flags: %u\n"
		"From: %u\n"
		"To: %u\n"
		"Size: %u\n"
		"Tx-power: %u\n"
		"Type: %u\n",
		args->netheader->_num,
		args->netheader->flags,
		args->netheader->from,
		args->netheader->to,
		args->netheader->size,
		args->netheader->txpower,
		args->netheader->type
		);

		printf("Payload (%d) : \n", args->payload_size);
		for (i=0; i < args->payload_size; i++)
			printf("%c ", *((uint8_t *)(args->payload+i)));

		_Data_redOn();
	}
	

return 0;
}

char p = 0;

bool Process_radioHandler(struct netpacket_handler_args* args)
{
	/*
		Notes: * The received packet data becomes invalid when this handler is completed.
	*/

	// Pass packet through command interface
	if ( Cmd_radioHandler( args ) ) {
		// packet handled by messaging module
		return true;
	}
	
	/*Dump in promiscous mode if asked*/
	if (promiscous) dump(args);

	if ( args->cpaResult == ADRCOMP_OTHER ) {
		// intercept packets for other nodes here
	} else if ( args->cpaResult == ADRCOMP_BROADCAST ) {
		// process broadcast packets here
	} else {

		if (!promiscous) dump(args);

		// process packets for this node here
		switch ( args->netheader->type ) {

			case PING_REQUEST_PACKET:
				// send back to receiver's address
				Net_sendPong(args->netheader->from);
				break;

			case PING_REPLY_PACKET:
				LOG_LOW( "PONG from %u", args->netheader->from );
				break;

			case USERDEFINED_PACKET+PROTOCOL_N:
				/*printf("Got packet from protocol %u\n", PROTOCOL_N);*/
				break;

			default:
				return false;		// packet not handled (unknown)
		}
		return true;				// packet handled
	}
	return false;					// packet not handled (other destination)
}

void Process_sensorHandler(void* sdata)
{

}

uint8_t led_s = 0;
void callMe() {

	/*(printf("Hallo guten morgen !\n");
	(!led_s)? (_Data_redOn(), led_s = 1) : (_Data_redOff(), led_s = 0);
	Timers_add(2*1024, callMe, 0xFFFF);*/

}

void Process_init()
{
	System_registerCallback( C_RADIO, ( fp_vp )Process_radioHandler );
	System_registerCallback( C_SENSOR, ( fp_vp )Process_sensorHandler );
	/*Timers_add(5*1024, callMe, 0xFFFF);*/
	_Data_redOn();
}

/**
 * @brief	Ping request
 *
 * Send a ping request to another node
 * Example: ping 24
 */
COMMAND( ping, 0, cmdargs )
{
	uint16_t node;

	node = String_parseUint16( cmdargs->args, NULL );
	if ( node > 0 ) {
		Net_sendPing((netaddr_t)node);
	}
}

/**
 * @brief Echo Arguments
 *
 * Testcase 1: long command name
 * Testcase 2: argument splitting
 */
COMMAND( echoargs, CMDFLAG_SERIAL, cmdargs )
{
	uint16_t i;
	uint16_t count = Cmd_SplitArgs( cmdargs->args );
	char* arg = (char*) cmdargs->args;

	for ( i = 1; i <= count; i++ ) {
		printf("%u: %*s\n", i, strlen(arg), arg);
		arg = ( char* )Cmd_GetNextArg( arg );
	}
	snprintf(cmdargs->response_args, cmdargs->response_bufsize, "%u args found", count );
}




/*New test command
Walking through the first steps :) */
uint8_t count = 0;
COMMAND(hello, CMDFLAG_SERIAL, cmdargs) {
	printf("Hello scattered world (%u) (ARG: %d)!", count++,  String_parseUint16(cmdargs->args, NULL));
}


/* Command to send a test packet*/
COMMAND(send_hello, CMDFLAG_SERIAL, cmdargs) {
uint8_t* data = "Hello world!";		
netpacket_send_args_t npsargs;

	Net_sendArgsInit(&npsargs);

	npsargs.netheader.to = ID_NODE0;
	npsargs.netheader.type = USERDEFINED_PACKET+PROTOCOL_N;
	npsargs.netheader.flags = 0;
	npsargs.payload[0].buffer = (uint8_t*) data;
	npsargs.payload[0].size = strlen(data);
	Net_send(&npsargs);

}



/**********EXERCISES*********/

/***Traffic generator***/

uint8_t traffic_s = 0;							/*Traffic switch 0=off 1=on*/
uint16_t time_w = 0, p_max = 0;

/*Sends a packet with hello world message*/
void send() {
uint8_t* data = "Hello world!";
netpacket_send_args_t npsargs;

	/*Only send and call itself again if switch is on and max is not reached*/
	if (traffic_s && p_max){

		Net_sendArgsInit(&npsargs);

		npsargs.netheader.to = ID_NODE0;
		npsargs.netheader.type = USERDEFINED_PACKET+PROTOCOL_N;
		npsargs.netheader.flags = 0;
		npsargs.payload[0].buffer = (uint8_t*) data;
		npsargs.payload[0].size = strlen(data);
		Net_send(&npsargs);
	
		printf("Packet sent (%u left)\n", p_max-1);
		printf("\n");

		Timers_add(time_w*1024, send,(void *) --p_max);
	}
	else if (!p_max) {
		printf("Maximum packets reached, stopping\n");
		p_max--;
	}

}

/*Traffic generator switch command*/
COMMAND(t_gen, CMDFLAG_SERIAL, cmdargs) {
char* arg = (char*) cmdargs->args;

	/*We first parse the parameters (at least 2)*/
	if (Cmd_SplitArgs(cmdargs->args) < 2) {
		printf("Usage: t_gen <time> <packets max>\n");
	}
	else {
		time_w = String_parseUint16(arg, NULL);
		arg = ( char* )Cmd_GetNextArg( arg );
		p_max = String_parseUint16(arg, NULL);

		/*Now we switch*/
		if (!traffic_s)  {
			Timers_add(time_w*1024, send, (void *)p_max);
			traffic_s = 1;
			printf("Periodic traffic enabled (every %u seconds)\n", time_w);
		}
		else{
			traffic_s = 0;
			Timers_add(time_w*1024, send, (void *)0);
			printf("Periodic traffic disabled\n");
		}
	}

}



/****Dump network traffic****/
/**See algo Process_radioHandler for PROTOCOL_N**/

/*Traffic dumping switch command*/
COMMAND(t_dump, CMDFLAG_SERIAL, cmdargs) {
char* arg = (char*) cmdargs->args;


	/*An argument is switching between promiscous or not (on demand)*/
	if (Cmd_SplitArgs(cmdargs->args) > 0) {

		switch (String_parseUint16(arg, NULL)) {
		
			case 0:		promiscous = 0;
					break;
			case 1:		promiscous = 1;
					break;
			default:	printf("Usage: t_dump [0/1]\n");
					break;
		}
		
	}
	else {

		/*Switch between on and off*/
		recv_s = recv_s? 0 : 1;
	}

	printf("Promiscous mode : [%s]\n", promiscous?"ON":"OFF");
	printf("Traffic dumping : [%s]\n", recv_s?"ON":"OFF");
}

// Software header.
APP(
    APPH_STATIC_APP,	// Application Type
    __APP_NAME,			// Application Name (8 chars)
    1, 0				// Aplication Version (2 bytes)
);
