/*
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 EEPROMADDRESS (0x00) // use 8k EEPROM, future versions will have only one 64k eeprom at this address
#define EEPROMPAGEMASK (0x7F)  // 64k EEPROM, 128b page writes possible
#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

COMMAND(dea, 0) {
    System_stopWatchdog();
    IO_erase(0x0000, 0xFFFF);
    String_write(term_reply, "OK");
    System_startWatchdog();
}

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 = *IO_read(curad, (UINT8*)&eb, 1);
      Comm_print(" %b", eb);
    }
    Comm_print("\r\n");
    System_startWatchdog();
}

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

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

void start_cond() {
  P5DIR |= 0x0C; // ensure: P52(SDA), P53(SCL) output
  SCL_LOW; SDA_HIGH; SCL_HIGH; SDA_LOW; SCL_LOW;
}

void stop_cond() {
  SCL_LOW; SDA_LOW; SCL_HIGH; SDA_HIGH; SCL_LOW;
  P5DIR &= ~0x0C;
}

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

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

UINT8* IO_read(UINT16 e_adr, UINT8* r_adr, UINT16 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;
}

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

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