/*
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
*/

/**
 * @file		ScatterWeb.Cmd.Comm.c
 * @brief		Command Engine Serialport I/O
 * @ingroup		cmd
 * @version		$Revision: 130 $
 *
 * <p>See <a href="group__cmd.html">Command Engine</a> for documentation.</p>
 *
 * $Id: ScatterWeb.Cmd.c 122 2007-10-30 11:56:54Z baar@PCPOOL.MI.FU-BERLIN.DE $
 */

/**
 * @addtogroup cmd
 * @{
 */
 
#include <string.h>
#include <ScatterWeb.System.h>
#include <ScatterWeb.Debuglog.h>

#include <string.h>
#include <ScatterWeb.System.h>
#include "ScatterWeb.Cmd.internal.h"

void Cmd_serialHandler(char* line) {

	switch( *line ) {
		case CHAR_NUL:
			return;
		case CMD_BINARY_IN_MARKER : {
			cmd_serial_header_t* sh = (cmd_serial_header_t*)line;
			//if( sh->protocol == CMD_PROTOCOL_BCMDREQUEST ) {
				cmd_header_t* cmd_header = (cmd_header_t*)(sh + 1);
				uint16_t headerlength = _Cmd_GetHeaderSize(cmd_header);
				char* args = ((char*)cmd_header) + headerlength;

				// test checksum
				char* checksum = ((char*)cmd_header) + sh->size;
				char  checksumtest = 0;
				char* d;
				for( d = line; d < checksum; d++ )
					checksumtest ^= *d;
				if( *checksum != checksumtest )
					LOG_LOW("(BCMD) ERR: checksum %#.2x %#.2x", checksum, checksumtest);

				_Cmd_BinarySerialRequest(
					(cmd_serial_header_t*)line,
					false,
					cmd_header,
					headerlength,
					args
				);
			//}
			} break;
	  #if CMD_ASCII_MODE
		default  :
		  	_Cmd_AsciiSerialRequest(line);
	  #endif
	}

	Comm_clear();
}

///////////////////////////////////////////////////////////////////////////////
// private helper functions
///////////////////////////////////////////////////////////////////////////////

uint16_t _Cmd_BinarySerialRequest(
	cmd_serial_header_t*	cmd_sh,
	bool					ascii_interface,
	cmd_header_t*			cmd_header,
	uint16_t				headerlength,
	char*					args
) {

	uint16_t	arglength = cmd_sh->size - headerlength;
	netaddr_t	addr = cmd_sh->destination;
	enum netaddr_compareresult	desttype = Net_compareAddress(&addr, true);
	if( desttype & (ADRCOMP_OTHER | ADRCOMP_BROADCAST) ) {
		// forward packet through radio
		// sends command + parameters + null-char
		_Cmd_Forward(
				&addr,
				cmd_header,
				args, arglength
		);
	}
	if( desttype & (ADRCOMP_THIS|ADRCOMP_BROADCAST) ) {
		// process command
		int	rpl_size;

		char*	rpl_buffer = _Cmd_GetBuffer();
		if( rpl_buffer == NULL )
			return 0;

		#if CMD_ENABLE_LOGGING
		_Cmd_logCommand(
			'q', &Configuration.id,
			cmd_header, cmd_sh->size
		);
		#endif

		rpl_size = Cmd_Run(cmd_header,
				args,
				cmd_sh->size,
				rpl_buffer,
				TERM_BUFSIZE,
				true
		);

		if( rpl_size != 0 ) {
			#if CMD_ENABLE_LOGGING
			_Cmd_logCommand(
				'r', &addr,
				(cmd_header_t*)rpl_buffer, rpl_size
			);
			#endif

			// print reply
			if( ascii_interface ) {
				_Cmd_AsciiPrintReply(NULL, rpl_size, (cmd_header_t*)rpl_buffer);
			} else {
				_Cmd_BinPrintReply(&addr, rpl_size, (cmd_header_t*)rpl_buffer);
			}
		}

		_Cmd_FreeBuffer(rpl_buffer);
		return rpl_size;
	}
	return 0;
}

#if CMD_ASCII_MODE
	uint16_t _Cmd_AsciiSerialRequest(char* line) {
		char*					args = line;
		cmd_serial_header_t		cmd_sh;
		char					buffer[CMD_ASCII_MAX_HEADER_LENGTH];

		cmd_header_t*			cmd_header = (cmd_header_t*)buffer;
		char*					cmd_name = ((char*)cmd_header) + CMD_ASCII_NAME_OFFSET;
		uint16_t				headerlength = CMD_ASCII_NAME_OFFSET;

		// get destination address
		cmd_sh.destination = Configuration.id;
		if( *args == CMD_ASCII_FWD_MARKER ) {
			args++;
			cmd_sh.destination = NETADDR_BROADCAST;
			if( *args != CMD_ASCII_FWD_BROADCAST ) {
				uint16_t node = String_parseUint16((uint8_t*)args, (uint8_t**)&args);
				cmd_sh.destination = node;
			} else {
				args++;
			}
			args++;
		}

		// command name and headerlength
		while( _Cmd_IsValidNameChar(*args) ) {
			*cmd_name = *args;
			cmd_name++;
			args++;
			headerlength++;
			if( headerlength > (CMD_ASCII_NAME_OFFSET+CMD_ASCII_MAX_NAME_LENGTH) ) {
				printf("return 0\r\n");
				return 0;
			}
		}
		*cmd_name = CHAR_NUL;

		// start of arguments
		while( *args == CHAR_SPC )
			args++;

		// flags
		cmd_header->flags = CMD_REQFLAG_REPLY | CMD_REQFLAG_ASCII;

		cmd_sh.size = headerlength + strlen(args) + 1;
		return _Cmd_BinarySerialRequest(&cmd_sh, true, cmd_header, headerlength, args);
	}

	/// print ascii command reply
	void _Cmd_AsciiPrintReply(
		const netaddr_t*			pSource,
		const uint16_t				size,
		const cmd_header_t (*const	rpl_header)
	) {
		// default reply values
		static const char _cmd_ascii_default_reply[] =
				"FAILED\0" "OK\0" "\3";

		const char*		name = ((char*)rpl_header) + CMD_ASCII_NAME_OFFSET;
		char*			reply;
		uint16_t		headerlength, replylength;

		// get position of command reply text
		headerlength = _Cmd_GetHeaderSize(rpl_header);
		reply = ((char*)rpl_header) + headerlength;
		replylength = size - headerlength;

		if( replylength <= CMD_SUCCESS ) {
			// no reply, select a default reply
			uint16_t index = ((rpl_header->flags & CMD_RPLFLAG_ERROR) == 0);

			// get default reply from stringtable
			reply = (char*)String_stringtableGet(_cmd_ascii_default_reply, index);
			replylength = strlen(reply);
		}

		putchar('[');
		if( pSource != NULL )
			printf("%u:", *pSource);
		printf("%s] %.*s\r\n", name, replylength, reply);
	}

#endif

void _Cmd_BinSerialWrite(
	const void (*const	data),
	const uint16_t		numchars
) {
	String_writeHex(Comm_writer, (uint8_t*)data, numchars);
}

void _Cmd_BinPrintReply(
	const netaddr_t*	source,
	const uint16_t		size,
	const cmd_header_t (*const 	header)
) {
	uint8_t protocol = CMD_PROTOCOL_BCMDRESPONSE;
	if( header->id.protocol == CMD_PROTOCOL_SYSTEM ) {
		// map command protocol 1 to different layer 1 protocol
		protocol = CMD_PROTOCOL_SYSINFO;
	}
	
	register uint8_t		checksum = CMD_BINARY_OUT_MARKER;
	register const uint8_t*	d = (const uint8_t*)header;
	register const uint8_t*	dmax = (const uint8_t*)header + size;
	checksum ^= size & 0x00FF;
	checksum ^= protocol;
	checksum ^= *((uint8_t*)source);
	for(; d < dmax; d++ ) {
		checksum ^= *d;
	}

	printf("%c%.2X%.2X%.4X",
		CMD_BINARY_OUT_MARKER,
		size, protocol, *source
	);
	String_writeHex(putchar, (uint8_t*)header, size);
	printf("%.2X\n", checksum);
}

/** @} */

