/*
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://scatterweb.mi.fu-berlin.de and the mailinglist
scatterweb@lists.spline.inf.fu-berlin.de (subscription via the Website).
Berlin, 2003/2004/2005
*/

#include "ScatterWeb.System.h"

UINT8 term_reply[TERM_BUFSIZE]; 

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);
}

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);   
}

COMMAND(rlg, 0) {
  #if defined(ESB430) || defined(EYE430) || defined(ESF430) || defined(ESS430)
  String_write(term_reply, "%i", (GREENSTATE ? 0 : 1));  ///< rlg <br> Reads state of the red LED. 0 - OFF, 1 - ON 
  #else
  String_write(term_reply, "NOT SUPPORTED: %s (wrong platform)", str);
  #endif  
}

COMMAND(rly, 0) {
  #if defined(ESB430) || defined(EYE430) || defined(ESF430) || defined(ESS430)
  String_write(term_reply, "%i", (YELLOWSTATE ? 0 : 1)); ///< rly <br> Reads state of the red LED. 0 - OFF, 1 - ON 
  #else
  String_write(term_reply, "NOT SUPPORTED: %s (wrong platform)", str); 
  #endif  
}
COMMAND(slg, 0) {
  #if defined(ESB430) || defined(EYE430) || defined(ESF430) || defined(ESS430)
  if(str[4]=='1') Data_greenOn();  else Data_greenOff();        ///< slg [0-1] <br> Switches green LED. 0 - OFF, 1 - ON
  #else
  String_write(term_reply, "NOT SUPPORTED: %s (wrong platform)", str); 
  #endif  
}

COMMAND(sly, 0) {
  #if defined(ESB430) || defined(EYE430) || defined(ESF430) || defined(ESS430)
  if(str[4]=='1') Data_yellowOn(); else Data_yellowOff();      ///< sly [0-1] <br> Switches yellow LED. 0 - OFF, 1 - ON
  #else
  String_write(term_reply, "NOT SUPPORTED: %s (wrong platform)", str); 
  #endif  
}

COMMAND(swg, 0) {
  #if defined(ESB430) || defined(EYE430) || defined(ESF430) || defined(ESS430)
  Data_greenToggle();	                              ///< Toggles green led.
  #else
  String_write(term_reply, "NOT SUPPORTED: %s (wrong platform)", str); 
  #endif  
}

COMMAND(swy, 0) {
  #if defined(ESB430) || defined(EYE430) || defined(ESF430) || defined(ESS430)
  Data_yellowToggle();                               ///< Toggles yellow led.
  #else
  String_write(term_reply, "NOT SUPPORTED: %s (wrong platform)", str); 
  #endif  
}

COMMAND(stp, 0) {
  #if !defined(ESS430)
  Net_setTxPower( String_parseInt((char*) &str[4], NULL));             ///< stp nn <br> sets transceiver transmission power. value range: 00-99 Ex: stp 99
  #else
  String_write(term_reply, "NOT SUPPORTED: %s (wrong platform)", str); 
  #endif    
}
  
COMMAND(rrp, 0){ String_write(term_reply, "%i", rxpTemp);  }                           ///< rrp <br> Reads AD value of the transceiver receive power.
COMMAND(rtp, 0){ String_write(term_reply, "%i", Configuration.transmitPower); }               ///< rtp <br> Reads transceiver transmission power.
COMMAND(rlr, 0){ String_write(term_reply, "%i", (REDSTATE ? 0 : 1)); }    ///< rlr <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(swr, 0){ Data_redToggle(); }                                 ///< Toggles red led.
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(RST, 0){ System_reset(); }    ///< RST <br> Resets the MSP.                                                   
COMMAND(rsp, 0){ String_write(term_reply, "%x", READ_SP); } ///< Prints stack pointer.
COMMAND(pan, 0){ System_panic("Test: %s", &str[4]); }
COMMAND(pcl, 0){ System_panicClear(); System_reset(); }

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);
}

COMMAND(tis, 0){ 
  time_t time;
  time.secs = String_parseLongInt(& str[4], NULL);
  time.millis = 0;
  Time_setSystemTime(&time);
}

COMMAND(tiz, 0){ 
  btime_t btime;
  time_t time;
  Time_readTime(&str[4], &btime);
  Time_convertTime(&btime, &time);
  Time_setSystemTime(&time);
  Time_convertSystemTime(&time, &btime);
  String_write(term_reply, "OK %t", &btime);
}

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) );  
}

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));
}

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
    //Comm_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);
}

COMMAND(rbu, 0) {
  #if defined(ESB430) || defined(EYE430)
  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(ESB430) || defined(EYE430)
  String_write(term_reply, "%i", BATTERYVOLTAGE);
  #else
  String_write(term_reply, "NOT SUPPORTED: %s (wrong platform)", str);
  #endif
}
COMMAND(rve, 0) {
  #if defined(ESB430) || defined(EYE430)
  String_write(term_reply, "%i", EXTERNVOLTAGE);
  #else
  String_write(term_reply, "NOT SUPPORTED: %s (wrong platform)", str);
  #endif
}

COMMAND(rmm, 0) {
  #if defined(ESB430) || defined(EYE430)
  String_write(term_reply, "%i", MICVOLTAGE);
  #else
  String_write(term_reply, "NOT SUPPORTED: %s (wrong platform)", str);
  #endif
}

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 if(str[0]=='$'){
    UINT16 length;
    length++;
    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){
  UINT16 length;
  doCommand(data, 0);
  for(length=0; term_reply[length] != '\0'; length++);
  length++;
  return True;
}

bool Messaging_enable() {
  System_registerCallback(C_SERIAL, Messaging_serialHandler);         
  return True;
}

bool Messaging_disable() {
  System_registerCallback(C_SERIAL, 0);         
  return True;
}
