/*
Copyright 2003/2004, 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.
Contributors: Bjoern Lichtblau

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

/** \file terminal.c
\ingroup Firmware
\brief Implementation of terminal program (better name would be command shell) for uart&radio. 

Control the MSP via RS232 or radio with simple ascii commands.
A description of all terminal commands can be found below. <br>

\image html tss.jpg "Interfacing an ESB with TeraTerm: Serial port setup"

<h2>Remote command execution</h2>

To issue an command over radio write @[id], answers will get [id] prepended.
\code
@85 rid
[85] 85
@85 tim
[85] 23080608,984 2001-09-25 03:16:48
\endcode   
<br>


<h2>Command creation</h2>

Use the COMMAND macro to easily create a new terminal command.
The first argument to the Macros is always the three digit terminal command code.
The second argument to the Macros is a 8bit flag field.
For example the following:
\code
COMMAND(xxx, 0){ print("test\r\n"); }
\endcode
will evaluate to
\code
void term_xxx (const UINT8* str);
__attribute__((section(".commands"))) const command_t com_xxx = { term_xxx, "xxx", 0 }; \
void term_xxx (const UINT8* str){ print("test\r\n"); }
\endcode

Besides creating the function header it first creates a forward declaration which
is then needed in the following definition of a const command_t com_xxx struct in the 
.commands segment. com_xxx contains a pointer to the function, the three digit function code
and a flag field. 
Because all those command_t entries are put into a special segment (.commands),
the function doCommand can easily loop through this segment (going from __term_start to __term_end
also provied by the linker script) and search for the command. <br>
This even makes it possible, to declare terminal commands 
where needed, not only in terminal.c! (The firmware commands will still stay
centralized in terminal.c to have code & documentation of the firmware commands in one place.) <br>

The needed modifications of the linker script can be seen in firmware/ldscript.x:
\dontinclude ldscript.x
\skip .text :
\until   }  > text
<br>

All commands must write their answer to term_reply and it should not be longer than TERM_BUFSIZE.
If nothing is written to term_reply automatically an "OK" is generated.

The only exception to that is when the bit ::SERIALONLY in the flag field is set.
That means that the terminal command uses the sendRS232 functions directly (not writing
its answer to term_reply) and can't be called over radio.

**/

#include "ScatterWeb.System.h"

/** \defgroup Commands Terminal Commands
 ** \copydoc terminal.c
 ** @{
 **/ 

COMMAND(png, SERIALONLY){ 
  packet_t packet;
  packet.to = String_parseInt(&str[4], NULL);   packet.type = PING_PACKET;
  packet.header_length = 0;                     packet.header = NULL;
  packet.data_length = 0;                       packet.data = NULL;
  Net_send(&packet, NULL);
  Comm_print("PING to %i\r\n", String_parseInt(&str[4], NULL));   
}

////////////////////////////////////////////////////////////////////////////////
///\name Terminal Commands: LEDs & Beeper
//@{
COMMAND(rlr, 0){ String_write(term_reply, "%i", (REDSTATE ? 0 : 1)); }    ///< rlr <br> Reads state of the red LED. 0 - OFF, 1 - ON 
COMMAND(rlg, 0){ String_write(term_reply, "%i", (GREENSTATE ? 0 : 1)); }  ///< rlg <br> Reads state of the red LED. 0 - OFF, 1 - ON 
COMMAND(rly, 0){ String_write(term_reply, "%i", (YELLOWSTATE ? 0 : 1)); } ///< rly <br> Reads state of the red LED. 0 - OFF, 1 - ON 
COMMAND(slr, 0){ if(str[4]=='1') Data_redOn();    else Data_redOff(); }         ///< slr [0-1] <br> Switches red LED. 0 - OFF, 1 - ON
COMMAND(slg, 0){ if(str[4]=='1') Data_greenOn();  else Data_greenOff(); }       ///< slg [0-1] <br> Switches green LED. 0 - OFF, 1 - ON
COMMAND(sly, 0){ if(str[4]=='1') Data_yellowOn(); else Data_yellowOff(); }      ///< sly [0-1] <br> Switches yellow LED. 0 - OFF, 1 - ON
COMMAND(swr, 0){ Data_redToggle(); }                                 ///< Toggles red led.
COMMAND(swg, 0){ Data_greenToggle(); }	                              ///< Toggles green led.
COMMAND(swy, 0){ Data_yellowToggle();}                               ///< Toggles yellow led.

//COMMAND(sbp, 0){ if(str[4]=='1') BEEPERON : BEEPEROFF ); }     ///< sbp [0-1] <br> Switches beeper. 0 - OFF, 1 - ON      

//@}

////////////////////////////////////////////////////////////////////////////////
///\name Terminal Commands: Transceiver
//@{
COMMAND(rtp, 0){ String_write(term_reply, "%i", Configuration.transmitPower); }               ///< rtp <br> Reads transceiver transmission power.
COMMAND(stp, 0){ Net_setTxPower( String_parseInt((char*) &str[4], NULL), 1); }             ///< stp nn <br> sets transceiver transmission power. value range: 00-99 Ex: stp 99
COMMAND(rfr, 0){ String_write(term_reply, "%i", Configuration.rxReceiveLimit); }              ///< rfr <br> Reads transceiver reception threshold.
COMMAND(sfr, 0){ Configuration.rxReceiveLimit = String_parseInt((char*) &str[4], NULL); Configuration_save(); }///< sfr nnnn <br> sets transceiver reception threshold. Value range: 0000-4096 Ex: sfr 2000
COMMAND(rrp, 0){ String_write(term_reply, "%i", rxpTemp);  }                           ///< rrp <br> Reads AD value of the transceiver receive power.
//@}

////////////////////////////////////////////////////////////////////////////////
///\name Terminal Commands: Rest (New, Testing, Temporary, ...)
//@{

COMMAND(RST, 0){ System_reset(); }    ///< RST <br> Resets the MSP.                                                   

COMMAND(rsp, 0){ Comm_print("%x\r\n", READ_SP); } ///< Prints stack pointer.

COMMAND(upd, SERIALONLY){ 
  System_reprogram(); 

}  ///< Updates this device with the current content in EEPROM.

/// dco[+-]<br> Displays current DCO Setting (DCOCTL, BCSCTL1, dcoDiff). For manipulating the DCO manually with dco+ and dco- the DCOChecker should be disabled.
COMMAND(dco, 0){
  extern int dcoDiff;
  if(str[3]=='-'){
      String_write(term_reply, "SET-- ");
      DCOCTL--;
      if (DCOCTL == 0xFF){
         if(!((BCSCTL1 & 0x07) == 0x00)){
           Comm_print("Frequency too low!!!\r\n");
           WDTCTL = 0xDEAD;
         }      
         BCSCTL1--;     // Did DCO role under? -> Select next lower RSEL
      }
  } else if(str[3]=='+'){
      String_write(term_reply, "SET++ ");
      DCOCTL++;
      if (DCOCTL == 0x00){
         if((BCSCTL1 & 0x07) == 0x07){
           Comm_print("Frequency too high!!!\r\n");
           WDTCTL = 0xDEAD;
         }      
         BCSCTL1++;     // Did DCO role over? // -> Select next higher RSEL
      }
  }
  if(term_reply[0]==0) String_write(&term_reply[0], "%b %b >%i", DCOCTL, BCSCTL1, dcoDiff);   
  else                 String_write(&term_reply[6], "%b %b >%i", DCOCTL, BCSCTL1, dcoDiff);   
}

/// Prints current time in seconds,milliseconds and broken down time.
COMMAND(tim, 0){
  btime_t btime;
  time_t time = CURRENT_TIME;
  Time_convertSystemTime(&time, &btime);
  String_write(term_reply, "%l,%i %t", time.secs, time.millis, &btime);
}

/// Sets current time as a long of seconds.
COMMAND(tis, 0){ 
  time_t time;
  time.secs = String_parseLongInt(& str[4], NULL);
  time.millis = 0;
  Time_setSystemTime(&time);
}

/// Sets current time in broken down time format [yy-mm-dd hh:mm:ss].
COMMAND(tiz, 0){ 
  btime_t btime;
  time_t time;
  Time_readTime(&str[4], &btime);
  //print("parsed: %t\r\n", &btime);
  Time_convertTime(&btime, &time);
  //currentTime = time;
  Time_setSystemTime(&time);
  Time_convertSystemTime(&time, &btime);
  String_write(term_reply, "OK %t", &btime);
}

/// Prints DATA and STACK usage and free bytes between them.
COMMAND(mem, 0){
  extern UINT16 __noinit_end;
  UINT16* p = & __noinit_end;
  while(*p==0xABCD) p++;
  String_write(term_reply, "DATA[0200-%x] STACK[%x-09FF] free: %i bytes", &__noinit_end, p, 
    ((UINT16)p)-((UINT16)&__noinit_end) );  
}

/// Clears all panics and does a reset.
COMMAND(pcl, 0){ System_panicClear(); System_reset(); }

/// Lists all available commands.
COMMAND(lst, SERIALONLY){
  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;
  while(c < &__term_end){ /// and then loops through the command_t list
    Comm_print("%c%c%c(%x, %b)  ", c->code[0], c->code[1], c->code[2], c->function, c->flags);
    if((c-&__term_start)%5==4) Comm_print("\r\n");
    c++;
  }
  Comm_print("\r\n%i commands alltogether.\r\n", (&__term_end - &__term_start));
}
//@}

////////////////////////////////////////////////////////////////////////////////
/// \name ESB specific commands
//@{
COMMAND(rbu, 0) {
  #if defined(ESB) || defined(EYE)
  String_write(term_reply, "%i", (P2IN&0x80 ? 0 : 1));
  #else
  String_write(term_reply, "NOT SUPPORTED: %s (wrong platform)", str);
  #endif
}
COMMAND(rvb, 0) {
  #if defined(ESB) || defined(EYE)
  String_write(term_reply, "%i", BATTERYVOLTAGE);
  #else
  String_write(term_reply, "NOT SUPPORTED: %s (wrong platform)", str);
  #endif
}
COMMAND(rve, 0) {
  #if defined(ESB) || defined(EYE)
  String_write(term_reply, "%i", EXTERNVOLTAGE);
  #else
  String_write(term_reply, "NOT SUPPORTED: %s (wrong platform)", str);
  #endif
}

COMMAND(rmm, 0) {
  #if defined(ESB) || defined(EYE)
  String_write(term_reply, "%i", MICVOLTAGE);
  #else
  String_write(term_reply, "NOT SUPPORTED: %s (wrong platform)", str);
  #endif
}            /// rmm <br> Microphone: Reads counter of the microphone.

/// si2 xxxx <br> IR Diode: Sends an NEC code via the IR sender diode.
COMMAND(si2, 0){ 	
    #if defined(ESB) || defined(EYE)	                            
    UINT8 high;
    UINT8 low;
    UINT16 data;
    high = String_fromHexToByte((char*) &str[4]);
    low = String_fromHexToByte((char*) &str[6]);
    data = high;
    data = (data << 8) + low;
    Data_RC5SendNEC(0x1CE3, 0x807F); 
    String_write(term_reply, " %x gesendet. \r\n", data); 
    #else
    String_write(term_reply, "NOT SUPPORTED: %s (wrong platform)", str);
    #endif
}
//@}

// End of commands group
//@}

/** \name Interface functions.
 ** Global term_reply var, generic search&execute function and serial and radio interface.
 */
//@{

UINT8 term_reply[TERM_BUFSIZE]; 

/** \brief Search & execute a given command.
 **
 ** If flag SERIAL_ONLY is set and a SERIAL_ONLY command is called nothing
 ** will be written to term_reply!
 ** If no flag is set term_reply will always contain some string after doCommand.
 */ 
void doCommand(const UINT8* str, UINT8 flags){
  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.
  /// The list of command_t structs automatically with the COMMAND Macro
  /// begins at __term_start, which is provided by the linker script.
  command_t* c = &__term_start;
  /// The algorithm first clears term_reply[0] 
  term_reply[0] = '\0';
  while(c < &__term_end){ /// and then loops through the command_t list
    //print("testing %c%c%c(%x)\r\n", command->code[0], command->code[1], command->code[2], command->function );
    if( (str[0] == c->code[0]) && (str[1] == c->code[1]) && (str[2] == c->code[2]) ){ /// until a matching command is found.
      if(c->flags & SERIALONLY){ /// If it is serial only command
         /// and SERIAL_ONLY in flags is set, the function is simply executed. This
         /// is currently the only case when nothing is written to term_reply.
         if(flags & SERIALONLY) c->function(str);
         /// Otherwise a "Not supported" answer is generated.
         else String_write(term_reply, "NOT SUPPORTED: %s (serial only)", str);
      }
      else { /// If it is a standard command (not serial only) which writes its reply to term_reply
        /// the function is called.
        c->function(str);
        /// Standard commands can leave term_reply untouched, if that is the case
        /// a standard "OK" is generated.
        if(term_reply[0] == '\0') String_write(term_reply, "OK");        
      }
      return;
    }
    c++;       
  }
  /// If no command exists a "UNKNOWN COMMAND" reply is generated.
  String_write(term_reply, "UNKNOWN COMMAND: %s\r\n", str);
}

void Messaging_serialHandler(void* line){
  UINT8* str = (UINT8*) line;
  if(str[0]=='@'){
    packet_t packet;
    packet.to = String_parseInt(&str[1], &packet.data);
    packet.data++; // packet.data is now on first byte of remote terminal command
    for(packet.data_length=0; packet.data[packet.data_length] != '\0'; packet.data_length++);
    packet.data_length++;
    packet.type = MESSAGING_REQ_PACKET;
    packet.header = 0;
    packet.header_length = 0;
    Net_send(&packet, NULL);   
    Comm_clear();    
  } 
  else {
    doCommand(str, SERIALONLY);
    if(term_reply[0]!='\0') Comm_print("%s\r\n", term_reply);
    Comm_clear();
  }
}

bool Messaging_requestHandler(){
  packet_t packet;
  packet.to = rxPacket.from;  
  packet.type = MESSAGING_ANS_PACKET;
  packet.header = 0;   
  packet.header_length = 0;
  doCommand(rxPacket.data, 0);  
  // Count length and send data  
  packet.data = term_reply;         
  for(packet.data_length=0; packet.data[packet.data_length] != '\0'; packet.data_length++);
  packet.data_length++;
  Net_send(&packet, 0);     
  return True;
}

bool Messaging_answerHandler(){
  Comm_print("[%i] %s\r\n", rxPacket.from, rxPacket.data);
  return True;
}

bool Messaging_requestDataHandler(UINT8* data){
  packet_t packet;
  packet.to = rxPacket.from;  
  packet.type = MESSAGING_ANS_PACKET;
  packet.header = 0;   
  packet.header_length = 0;
  doCommand(rxPacket.data, 0);  
  // Count length and send data  
  packet.data = term_reply;         
  for(packet.data_length=0; packet.data[packet.data_length] != '\0'; packet.data_length++);
  packet.data_length++;
  Net_send(&packet, 0);     
  return True;
}

//@}
