/*
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: Thomas Pietsch, 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"

#define EADR_CONFIG     (0x0F00)

config_t Configuration; 

COMMAND(rcf, SERIALONLY) { Configuration_print(); } // rcf <br> Prints complete configuration.   

COMMAND(scf, 0) {
  Comm_print("Writing standard Configuration....\r\n");
  Configuration.id = 79;
  Configuration.rxReceiveLimit = 2200;
  Configuration.transmitPower = 99;
  Configuration.boot_logLevel = 1;
  Configuration.panicFlags = 0;
  Configuration.firmwareFlags = FF_DCOCHECKER;
  Configuration_save();
  term_rcf(str);
  Comm_print("Hint: USB Stick should have boot_logLevel at 0 (slb 00)\r\nResetting now...\r\n\r\n  ");
  System_reset();
}

COMMAND(rid, 0) { String_write(term_reply, "%i", Configuration.id); }                   // rid <br> Prints ID of the sensor board.

COMMAND(sid, 0) { Configuration.id = String_parseInt(& str[4], NULL); Configuration_save(); }  // sid nnnn <br> Sets ID of the sensor board. Value range: 0000-9999, Ex: sid 4711

COMMAND(rlo, 0) { 
  UINT8 l = Comm_logLevel & 0x0F;
  String_write(term_reply, "%b [%s%s%s]", Comm_logLevel,
                      ((Comm_logLevel & DEBUG_RADIO) ? "RADIO " : ""),
                      ((Comm_logLevel & DEBUG_DCO) ? "DCO " : ""),
                      ( l==0 ? "DISABLED" : ( l==NO ? "NO" : ( l==LOW ? "LOW" : ( l==MEDIUM ? "MEDIUM" : ( l==HIGH ? "HIGH" : "VERBOSE ")))) )
  ); 
}   
    
COMMAND(slo, 0) { 
  Comm_logLevel = String_fromHexToByte( &str[4]); 
  term_rlo(str);
}                     

COMMAND(rlb, 0) {   
  UINT8 l = Configuration.boot_logLevel & 0x0F;
  String_write(term_reply, "%b [%s%s%s]", Configuration.boot_logLevel,
                      ((Configuration.boot_logLevel & DEBUG_RADIO) ? "RADIO " : ""),
                      ((Configuration.boot_logLevel & DEBUG_DCO) ? "DCO " : ""),
                      ( l==0 ? "DISABLED" : ( l==NO ? "NO" : ( l==LOW ? "LOW" : ( l==MEDIUM ? "MEDIUM" : ( l==HIGH ? "HIGH" : "VERBOSE ")))) )
  );  
} 
               
COMMAND(slb, 0) { 
  Configuration.boot_logLevel = String_fromHexToByte( &str[4]); Configuration_save();
  term_rlb(str); 
} 

COMMAND(rpf, 0) { 
  String_write(term_reply, "%b [%s%s%s%s]", Configuration.panicFlags,
                          ((Configuration.panicFlags & PANIC_ON_STACK_OVERFLOW) ? "POST " : ""),
                          ((Configuration.panicFlags & PANIC_ON_FULL_TIMERS) ? "POFT " : ""),
                          ((Configuration.panicFlags & PANIC_ON_BAD_RESET) ? "POBR " : ""),
                          ((Configuration.panicFlags & PANIC_DISABLES_APP) ? "PDA " : "")  
  ); 
}               
     
COMMAND(spf, 0) { 
  Configuration.panicFlags = String_fromHexToByte(&str[4]); 
  Configuration_save(); 
  term_rpf(str);
}    

COMMAND(rff, 0) { 
 String_write(term_reply, "%b [%s]", Configuration.firmwareFlags,
                          ((Configuration.firmwareFlags & FF_DCOCHECKER) ? "DCOCHECKER " : "")
  );
}                 

COMMAND(sff, 0) { 
  Configuration.firmwareFlags = String_fromHexToByte( &str[4]); 
  Configuration_save(); 
  term_rff(str);
} 

COMMAND(prr, 0) {
  UINT8* pr = System_panicReason(0);
  if(pr != 0)  String_write(term_reply, "Panic[0]: %s", pr);
  else         String_write(term_reply, "No panic!");
}

void config_infomem_clear() {
  UINT8 ie1 = IE1;
  /// INIT //////////////////// disable all interrupts
  IFG1=0;                     // clear interrupt flag1 
  WDTCTL=0x5A80;              // stop WD 
                              // DCO(SMCLK) is 2,4576MHz, /6 = 409600 Hz 
  FCTL2=0xA5C5;               // select SMCLK for flash timing, divider 5+1 
  _DINT();                    // disable all interrupts to protect CPU 
                              // during programming from system crash 
  IE1=0x00;                   // disable all NMI-Interrupt sources
  /// ERASE ////////////////////
  FCTL3 = 0xA500;             // Lock = 0   
  while(FCTL3 & 0x0001) nop();// Wait for BUSY = 0, not needed unless run from RAM
  FCTL1 = 0xA502;             // ERASE = 1 
  *((UINT16*)0x1000) = 0xFFFF;         // erase Flash segment where Configuration is.
  FCTL1 = 0xA500;             // ERASE = 0 automatically done?!
  FCTL3 = 0xA510;             // Lock = 1 
  ////////////////////////////////
  /// EXIT //////////////////// 
  System_startWatchdog();    // 
  _EINT();                   // 
  IFG1 = 0x00;               // 
  IE1= ie1;                  // 
  /////////////////////////////
}

bool Configuration_init() {
  void config_infomem_clear(); // FORWARD DECLARATION
  if( *((UINT16*)0x1000) != 0xFFFF) { // a Configuration was written into infomem
    IO_write(EADR_CONFIG, (UINT8*) 0x1000, sizeof(config_t));
    config_infomem_clear();
  }
  IO_read(EADR_CONFIG, (UINT8*) &Configuration, sizeof(config_t));
  return True;
}

bool Configuration_save() {
  IO_write(EADR_CONFIG, (UINT8*) &Configuration, sizeof(config_t));
  return True;
}

bool Configuration_print() {
  Comm_print("\r\n+==============================================================\r\n");
  Comm_print("| DCO: %b BCS: %b    Reset: [%s]\r\n", DCOCTL, BCSCTL1, System_resetReason());  
  Comm_print("| Id: %i\r\n", Configuration.id);
  Comm_print("| transmitPower: %i  rxReceiveLimit: %i\r\n", Configuration.transmitPower, Configuration.rxReceiveLimit);
  term_rlo(NULL); Comm_print("| logLevel:      %s", term_reply);
  term_rlb(NULL); Comm_print(" (%s)\r\n", term_reply);
  term_rff(NULL); Comm_print("| firmwareFlags: %s\r\n", term_reply);
  term_rpf(NULL); Comm_print("| panicFlags:    %s\r\n", term_reply);  
  UINT16 i;
  UINT8* str;
  i=0;
  while( (str = System_panicReason(i)) != NULL){
    Comm_print("| Panic[%i]: %s\r\n", i, str); 
    i++;   
  }
  Comm_print("+==============================================================\r\n");
  term_reply[0] = '\0';
  return True;
}
