/*
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.System.Commands.c
 * @brief			Commands that do not relate to a specific module
 * @ingroup	cmd
 * @version	$Revision: 241 $
 * @since		1.1
 *
 * $Id$
 */

#include <string.h>
#include <ScatterWeb.System.h>

command_t* _System_firstCommand() {
	extern command_t __term_start;
	return &__term_start;
}
command_t* _System_lastCommand() {
	extern command_t __term_end;
	return &__term_end;
}

#if SYSTEM_CMDLEVEL >= LOW
	/**
	 * @brief Reset <code>reset</code>
	 * @ingroup commands
	 *
	 * Resets the MSB-430
	 */
	COMMAND(reset, 0, cmdargs) {
		System_reset(WDS_SWRESET);
	}

	/**
	 * @brief	Time command: <code>time [newtime]</code>
	 * @ingroup	commands
	 * @param	newtime UNIX timestamp (seconds since 1970 or string
	 * in the format [yy-mm-dd hh:mm:ss]) (optional)
	 *
	 * Example:<br>
	 * <code>time 1190201523<br>
	 * [time] 211897923,0 2007-09-19#12:32:03<br>
	 * time 2007-09-19 13:12<br>
	 * [time] 211897923,0 2007-09-19#13:12:00</code>
	 */
	COMMAND(time, 0, cmdargs) {
		btime_t btime;
		time_t time;
		uint32_t seconds;
		
		if( cmdargs->arg_size > 0 ) {
			// set time
			// try unix timestamp
			seconds = strtoul(cmdargs->args, NULL, 0);	
			if( seconds > 3000 ) {
				// unix timestamp
				seconds -= UTC_OFFSET_SECONDS;
				time.secs = seconds;
				time.millis = 0;
			} else {	
				// format [yy-mm-dd hh:mm:ss]
				Time_read(cmdargs->args, &btime);
				Time_convertBtime(&btime, &time);
			}
			Time_set(&time);				
		}
		// output of current time
		time = CURRENT_TIME;
		Time_convertTime(&time, &btime);
		seconds = time.secs + UTC_OFFSET_SECONDS;

		Time_write(cmdargs->response_args, &btime);		
		char* outbuf = cmdargs->response_args + strlen(cmdargs->response_args);
		sprintf(outbuf, " (%lu,%u)",
				seconds, time.millis);
	}
#endif

#if SYSTEM_CMDLEVEL >= HIGH
	/**
	 * @brief	List command: <code>commands</code>
	 * @ingroup	commands
	 * 
	 * Prints all available commands to stdout.
	 * <p>Format: <code>[name] @:[pointer to handler] F:[flags]</code>
	 */
	COMMAND(commands, CMDFLAG_SERIAL, cmdargs) {
	  extern command_t __term_start;  // __term_start is provided by the linker script, start of .commands segment.
	  extern command_t __term_end;    // __term_end is provided by the linker script, end of .commands segment.
	  command_t* c = &__term_start;
	  int l;
	  
	  printf("[lst] {\r\n");
	  while(c < &__term_end){ //and then loops through the command_t list
	  	if( c->flags & CMDFLAG_ASCII )
	    	l = printf("%s", c->id.ascName);
	    else
	    	l = printf("%.2X.%.2X", c->id.binId.protocol, c->id.binId.function);
		String_writeChar( putchar, CHAR_SPC, CMD_ASCII_MAX_NAME_LENGTH + 2 - l);
		printf("@:%p F:%#.2x,\r\n", c->delegate.ascii, c->flags);
	    c++;
	  }
	  printf("}\r\n");
	  snprintf(cmdargs->response_args, cmdargs->response_bufsize, "%u",
			  (uint16_t)(&__term_end - &__term_start));
	}	
#endif

#if SYSTEM_CMDLEVEL >= VERBOSE
	/**
	 * @brief	Dump Memory: <code>mem [start] [end]</code>
	 * @ingroup	commands
	 * @param	start	Address of first byte
	 * @param	end		Address of last byte
	 */
	COMMAND(mem, CMDFLAG_SERIAL, cmdargs) {
		const char* arg;
		uint8_t *fromad, *toad;
	
		arg = cmdargs->args;
		fromad = (uint8_t*)String_parseUint16(arg, (uint8_t**)&arg); arg++;
		toad = (uint8_t*)String_parseUint16(arg, (uint8_t**)&arg);

		System_memoryDump(fromad, toad);
	}
	
	/**
	 * @brief Read PC
	 * @ingroup commands
	 *
	 * Read the program counter.
	 */
	COMMAND(rpc, 0, cmdargs) {
		snprintf(cmdargs->response_args, cmdargs->response_bufsize,
				"%p", (void*)READ_PC);
	}
	
	/**
	 * @brief	Prints stack and returns stack pointer
	 * @ingroup	commands
	 * @return	position of stack pointer
	 */
	COMMAND(stack, CMDFLAG_SERIAL, cmdargs) {
		extern int __stack;
		snprintf(cmdargs->response_args, cmdargs->response_bufsize,
				"%p <- %p", (void*)READ_SP, &__stack);
		System_printStack();
	}

	/**
	 * @brief	simulate panic
	 * @ingroup	commands
	 * @param[in]	reason		reset reason (see #reset_reason)
	 * @param[in]	message		debug message
	 */
	COMMAND( panic, 0, cmdargs ) {
		const uint8_t* c = (const uint8_t*)cmdargs->args;
		uint16_t reason;
		reason = String_parseUint16(c, (uint8_t**)&c);
		if( *c != 0 ) c++;
		System_panic(reason, (char*)c);
	}

	/**
	 * @brief Print linked libraries
	 * @ingroup commands
	 *
	 * Prints the libraries linked to the firmware to stdout.
	 */	
	COMMAND( libraries, CMDFLAG_SERIAL, cmdargs ) {
		int i=0;
		while(i < library_count) {
			if(i)
				printf(", ");
			printf("%s", library_names[i]);
			i++;
		}
		printf("\r\n");
	}
#endif

