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

/** \file config.c
 ** \ingroup Firmware
 ** \brief Configuration data access, writing, first time configuration.
 **
 ** The configuration consists of the struct config_t defined in config.h.
 ** The variable ::Config is of that type and represents the current config in RAM
 ** and can be accessed directly everytime.
 **
 ** Changes to Config will only be made permanent (power-off & resets) with a 
 ** call to save_config(), which copies the content of Config to EEPROM[::EADR_CONFIG].
 **
 ** Initial loading from EEPROM[::EADR_CONFIG] is done by init_config() and has to be
 ** called on initialization in main().
 **
 ** First time configuration:
 ** Uncomment the following definition of firstTimeConfig and it will 
 ** get layed into Infomem (0x1000-0x1100, see .hex-File and/or linker map). 
 ** Before config_init() loads the regular config from EEPROM, it
 ** checks if the first int (which corresponds to the id) in Infomem is not 0xFFFF. If it is not, it
 ** copies the configuration from Infomem to EEPROM (clearing Infomem
 ** afterwards and loading the newly written data from EEPROM to Config).
 **/

#include "ScatterWeb.System.h"

/*
INFOMEM 
config_t firstTimeConfig = {    
  710,    // id 
  2000,    // rxReceiveLimit, best somewhere between 1900-2300
  99,      // transmitPower, 99 = max

#if defined(USB430) || defined(EWS430) || defined(THM430)
  00,       // boot_logLevel = DISABLED because of RTS/CTS Handshake
#else
  NO,       // boot_logLevel
#endif

  PANIC_ON_STACK_OVERFLOW + PANIC_ON_FULL_TIMERS + PANIC_ON_BAD_RESET + PANIC_DISABLES_APP, // panicFlags
  FF_PROGRAMMABLE + FF_DCOCHECKER                                              // firmwareFlags
};
*/

config_t Configuration; 

UINT16 config_readInt(UINT16 adr){
  UINT16 result;
  IO_read(adr, (UINT8*)&result, 2);
  return result;
}

UINT8 config_readChar(UINT16 adr){
  UINT8 result;
  IO_read(adr, (UINT8*)&result, 1);
  return result; 
}

/// First check if there is a first time configuration written into infofem for copying to eeprom, then load the config from eeprom.
bool Configuration_init(){
  void config_infomem_clear(); // FORWARD DECLARATION
  if( *((UINT16*)0x1000) != 0xFFFF){ // a config 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;
}

/// Write ::Config to EEPROM[::EADR_CONFIG].
bool Configuration_save(){
  IO_write(EADR_CONFIG, (UINT8*) &Configuration, sizeof(config_t));
  return True;
}

/// Helper used by config_init to clear a first time configuration int infomem.
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 Config is.
  FCTL1 = 0xA500;             // ERASE = 0 automatically done?!
  FCTL3 = 0xA510;             // Lock = 1 
  ////////////////////////////////
  /// EXIT //////////////////// 
  System_startWatchdog();           // 
  _EINT();                   // 
  IFG1 = 0x00;               // 
  IE1= ie1;                  // 
  /////////////////////////////
}

////////////////////////////////////////////////////////////////////////////////
///\name Configuration commands
///\ingroup Commands
//@{

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

COMMAND(scf, 0){
  Comm_print("Writing standard config....\r\n");
  Configuration.id = 79;
  Configuration.rxReceiveLimit = 2200;
  Configuration.transmitPower = 99;
  Configuration.boot_logLevel = 1;
  Configuration.panicFlags = 0;
  Configuration.firmwareFlags = FF_PROGRAMMABLE + 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

///< rlo <br> Read log level, see config.h for possible values.
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 ")))) )
  ); 
}   
    
///< slo xx <br> Set log level, see config.h for possible values.               
COMMAND(slo, 0){ 
  Comm_logLevel = String_fromHexToByte( &str[4]); 
  term_rlo(str);
}                     

///< Read boot log level, see config.h for possible values.
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 ")))) )
  );  
} 
               
///< Set boot log level, see config.h for possible values.
COMMAND(slb, 0){ 
  Configuration.boot_logLevel = String_fromHexToByte( &str[4]); Configuration_save();
  term_rlb(str); 
} 

///< Read panic flags, see config.h for possible values.
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 " : "")  
  ); 
}                    

///< Set panic flags, see config.h for possible values.
COMMAND(spf, 0){ 
  Configuration.panicFlags = String_fromHexToByte( &str[4]); 
  Configuration_save(); 
  term_rpf(str);
}    

/// rff <br> Reads firmware flags, see config.h for possible values.
COMMAND(rff, 0){ 
 String_write(term_reply, "%b [%s%s%s%s]", Configuration.firmwareFlags,
                          ((Configuration.firmwareFlags & FF_PROGRAMMABLE) ? "PROGRAMMABLE " : ""),
                          ((Configuration.firmwareFlags & FF_DCOCHECKER) ? "DCOCHECKER " : ""),
                          ((Configuration.firmwareFlags & FF_ROUTING) ? "ROUTING " : ""),
                          ((Configuration.firmwareFlags & FF_PACKETFILTER) ? "PFILTER " : "")
                          
  );
}                 

/// sff xx <br> Sets firmware flags, see config.h for possible values.
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!");
}

//@}

/// Prints configuration to serial port.
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);  
  Comm_print("| ImageData[FLASH ]: "); printImageData(&imageData); 
  Comm_print("| ImageData[EEPROM]: ");
  if(config_readChar(EADR_IMAGESTATE) & IMAGE_REPROGRAMMABLE) Comm_print("EMPTY\r\n");
  else {
    imageData_t i;
    IO_read(config_readInt(EADR_IMAGESTART), (UINT8*)&i, sizeof(imageData_t));
    printImageData(&i);
  }
  { 
    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;
}
