/*
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 eeprom.c
 ** \ingroup Firmware
 ** \brief Methods for writing/reading the EEPROM.
 **
 ** Most important functions for writing/reading the EEPROM are ::eeprom_write/::eeprom_read.
 **
 ** The EEPROM offers 64k memory (100000 write cycles) and is
 ** accessed with an I2C like bus (like RTC).
 ** 
 ** Currently use is storing configuration data (see config.c) 
 ** and temporary storage of a new software image before it 
 ** gets flashed (see flasher.c, programming.c).
 **
 ** ( DEVICE ADDRESSING:   Start | 1 0 1 0 A2 A1 A0 R/W | ... )
 **
 **
 ** EEPROM memory map:
 ** <table>
 ** <tr><th>Region          </th><th> Usage </th>
 ** <tr><td>0x0000 - 0x0CFF </td><td> Free for use. </td></tr>
 ** <tr><td>0x0D00 - 0x0DFF </td><td> Application config (::EADR_APPCONFIG).
 ** <tr><td>0x0E00 - 0x0EFF </td><td> Used by flasher.c / ::EADR_FLASHERBUF: 
 **                                   Free for use only if flasher_state==IDLE</td></tr>
 ** <tr><td>0x0F00 - 0x0FFF </td><td> Never change something here. Used for configuration
 **                                   data (config.c, ::EADR_CONFIG) and some reprogramming 
 **                                   variables () (see programming.h).</td></tr>
 ** <tr><td>0x1000 - 0xFFFF </td><td> Programming image storage or other big data.
 **                                   Use according to EEPROM[::EADR_IMAGESTATE], 
 **                                   see programming.c.</td></tr>
 ** </table>
 **                        
 **/

#include "ScatterWeb.System.h"

/// \name EEPROM clock&data line macros. Data is on P56 and clock on P57.
//@{
#define SDA_HIGH (P5OUT |= 0x04) ///< EEPROM data line high
#define SDA_LOW (P5OUT &= 0xFB)  ///< EEPROM data line low
#define SCL_HIGH (P5OUT |= 0x08) ///< EEPROM clock line high 
#define SCL_LOW (P5OUT &= 0xF7)  ///< EEPROM clock line low
//@}

/// \name Basic functions for interfacing i2c-like eeprom bus.
//@{

/// Puts the start condition on bus.
void start_cond(void){
  P5DIR |= 0x0C; // ensure: P52(SDA), P53(SCL) output
  SCL_LOW; SDA_HIGH; SCL_HIGH; SDA_LOW; SCL_LOW;
}

/// Puts the stop condition on bus.
void stop_cond(void){
  SCL_LOW; SDA_LOW; SCL_HIGH; SDA_HIGH; SCL_LOW;
  P5DIR &= ~0x0C;
}

/// Writes a byte on the bus, returns the acknowledge bit.
/** \todo Check too many NOPS. */
int writeOnBus(char byte) {
  int i, ack;
  for(i=0;i<8;i++) {
    if(byte & 0x80) SDA_HIGH; else SDA_LOW;
    SCL_HIGH;
    byte = byte << 1;
    SCL_LOW;
  }
  // check ack
  P5DIR &= 0xFB;                              // P52(SDA) input
  SCL_HIGH;
  if(P5IN & 0x04) ack = 0; else ack = 1;      // test if ack=0, else error
  SCL_LOW;
  P5DIR |= 0x04;                              // P52(SDA) output
  return ack;
}

/// Reads one byte from the bus.
/** \param ack If set, the ackbit after the received byte will be set. */
char readFromBus(UINT8 ack) {
  int i;
  char byte=0;
  P5DIR &= 0xFB;                              // P52(SDA) input
  for(i=0;i<8;i++) {
    byte = byte << 1;                
    SCL_HIGH;
    if(P5IN & 0x04) byte |= 0x01; else byte &= 0xFE;
    SCL_LOW;
  }
  P5DIR |= 0x04;                              // P52(SDA) output
  if(ack) SDA_LOW; else SDA_HIGH;
  SCL_HIGH;
  SCL_LOW;
  return byte;
}
//@}

/// \name Writing/reading several bytes.
//@{

/** Reads size bytes from the eeprom, uses sequential read (faster than ::readEEPROMByte). */
UINT8* IO_read(int e_adr, char* r_adr, int size){
  UINT16 i, current_e_adr;
  System_stopWatchdog();
  do {                                        // wait if writecycle not finished yet
    start_cond();                           
  } while(! writeOnBus(0xA0 | EEPROMADDRESS));                // 1010 control, 000 address, 0=write  --- but only inits address                
  writeOnBus(e_adr >> 8); 
  writeOnBus(e_adr);  
  start_cond();
  writeOnBus(0xA1 | EEPROMADDRESS);                           // 1010 control, 000 address, 1=read     
  for(i=0; i<(size-1); i++){
    current_e_adr = e_adr + i;
    r_adr[i] = readFromBus(1);
  }
  r_adr[size-1] = readFromBus(0);                                           
  stop_cond();
  System_startWatchdog();  
  return r_adr;
}

/** Writes size bytes to the eeprom, uses sequential write (faster than ::writeEEPROMByte). */
bool IO_write(UINT16 e_adr, UINT8* r_adr, UINT16 size){
  UINT16 i = 0;
  P5OUT &= 0xEF;                              // disable write protection
  for(i=0; i<size; i++){
      System_startWatchdog();
    // if we are writing the first byte or are on a 128b page boundary
    // we have to start a new write
    if( (i==0) || ( !((e_adr + i) & EEPROMPAGEMASK) ) ){
      UINT16 adr = e_adr + i;
      do { start_cond(); }                           
      while(!writeOnBus(0xA0 | EEPROMADDRESS)); // 1010 control, 000 addresse, 0=write                 	
      if(!writeOnBus( adr >> 8  )) return False;
      if(!writeOnBus( adr ))       return False; 
    }
    // write byte 
    if(!writeOnBus(r_adr[i])) return False;  
    // if we are writing the last byte totally or of a 128b page generate a stop condition
    if( (i==size-1) || ( ((e_adr + i) & EEPROMPAGEMASK) == EEPROMPAGEMASK ) ){
      stop_cond();	
    }
  }   
  P5OUT |= 0x10;                              // enable write protection  	
  return True;
}

/** Erase several bytes from eeprom (means set them to 0xFF). */
bool IO_erase(UINT16 e_adr, UINT16 size){
  UINT16 i = 0;
  P5OUT &= 0xEF;                              // disable write protection
  for(i=0; i<size; i++){
    // if we are writing the first byte or are on a 128b page boundary
    // we have to start a new write
    if( (i==0) || ( !((e_adr + i) & EEPROMPAGEMASK) ) ){
      UINT16 adr = e_adr + i;
      do { start_cond(); }                           
      while(!writeOnBus(0xA0 | EEPROMADDRESS)); // 1010 control, 000 addresse, 0=write                 	
      if(!writeOnBus( adr >> 8  )) return False;
      if(!writeOnBus( adr ))       return False; 
    }
    // erase byte 
    if(!writeOnBus(0xFF)) return False;  
    // if we are writing the last byte totally or of a 128b page generate a stop condition
    if( (i==size-1) || ( ((e_adr + i) & EEPROMPAGEMASK) == EEPROMPAGEMASK ) ){
      stop_cond();	
    }
  }   
  P5OUT |= 0x10;                              // enable write protection  	
  return True;
}

//@}

/// \name Wrappers and additional functions
//@{

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

//@}

//@}

////////////////////////////////////////////////////////////////////////////////
///\name Terminal Commands: EEPROM
///\ingroup Commands
//@{
 
/// dea <br> Erases complete eeprom.
COMMAND(dea, 0){
    System_stopWatchdog();
    IO_erase(0x0000, 0xFFFF);
    String_write(term_reply, "OK");
    System_startWatchdog();
}

/// rer xxxx xxxx <br> Reads all bytes between the adresses from the EEPROM. Value range: 0000-1FFF, Ex:  rer 0000 07CF
COMMAND(rer, SERIALONLY){   	           
	  System_stopWatchdog();		             
    UINT8 higha, lowa, eb;
    UINT16 fromad, toad, curad;
    higha = String_fromHexToByte( &str[4]);
    lowa = String_fromHexToByte( &str[6]);
    fromad = (higha << 8) + lowa;
    higha = String_fromHexToByte( &str[9]);
    lowa = String_fromHexToByte( &str[11]);
    toad = (higha << 8) + lowa;
    for(curad=fromad; (curad != toad+1) /*&& (curad <= 0x1FFF)*/ ; curad++){     
      if( ((curad - fromad) % 16) == 0){
        Comm_print("\r\n%x:", curad);
      }
      if( ((curad - fromad) % 4) == 0) Comm_print("   ");
      eb = eeprom_readChar(curad);
      Comm_print(" %b", eb);
    }
    Comm_print("\r\n");
    System_startWatchdog();
}

/// web xxxx xx <br> writes byte at a certain address. Value range: 0000-1FFF, 00-FF Ex: web 0103 FA
COMMAND(web, 0){
    UINT16 adr;	             
    UINT8 eb;
    adr = ((String_fromHexToByte( &str[4]))<<8) + (String_fromHexToByte( &str[6]));
    eb = String_fromHexToByte( &str[9]);
    IO_write(adr, &eb, 1);
}

/// rfl xxxx xxxx <br> Reads flash contents like rer does for EEPROM.
COMMAND(rfl, SERIALONLY){   	                // read flash ( and other local memory)
    UINT8 higha, lowa, eb;
    UINT8 *fromad, *toad, *pointer;
	  System_stopWatchdog();		             
    higha = String_fromHexToByte( &str[4]);
    lowa = String_fromHexToByte( &str[6]);
    fromad = (UINT8*) ((higha << 8) + lowa);
    higha = String_fromHexToByte( &str[9]);
    lowa = String_fromHexToByte( &str[11]);
    toad = (UINT8*) ((higha << 8) + lowa);
    for(pointer=fromad; (pointer != toad+1); pointer++){     
      if( ((pointer - fromad) % 16) == 0){
        Comm_print("\r\n%x:", pointer);
      }
      if( ((pointer - fromad) % 4) == 0) Comm_print("   ");
      eb = *pointer;
      Comm_print(" %b", eb);
    }
    Comm_print("\r\n");
    System_startWatchdog();
}

//@}
