// r12ceprom example c code for the Raspberry pi
//
// ri2ceprom_rpi_24LC128_0x51.c - use Raspberry Pi to flash 24LC128 on cypress board.
//
// Address 0xA2 ( 0x78 /2 )
//
// It reads and display some of the eeprom, 
// use Cntrl-c to breako out or continue to write 
//
// usage: 
//	gcc ri2ceprom_rpi_24LC128_0x51_.c 
//
//
//	./a.out 			- reads eeprom then writes LOGIC VIDPID
//	./a.out filename 	- reads eeprom then writes iic file into eeprom
//  e.g.
//  ./a.out build/lights.iic
//
//	Use Cntrl-C to break out after read
//

/*

What I need is a program to use the Raspbery Pi to fill the 24LC128 on 
* cypress fx2 (cyc768013) board from ebay.
* 
* This writes the binanry lights.iic file 
* into the 24LC128 BLKSIZE bytes at a time
* BLKSIZE is 32
* 
* using the raspberry pi i2c bus and 3 volts. 
* 
* convert *.ihx ti *.iic files using ihx2iic.py
* iic files are packed in the bootload format.

comment out i2c in black list in /etc/modprobe.d and reboot 

then run:
sudo modprobe i2c-dev
sudo chmod o+rw /dev/ic*

tools:- 
i2cdump 1 0x51 c 0 0
i2cdetect
*
*/
/* pack the ihx output from sdcc into the format for the 24LC128 us
 * 
 * python ihx2iic.py lights.ihx lights.iic
 * 
 * use hexdup to display iic.
 * hexdump convert.iic -C
 * xxd convert.iic
 * xxd -i convert.iic
 */

/*
 * we want to pump the binary into the i2c prom.
 * 1) Assume file is binary and in right format
 * writes "lights.iic" into 24LC128 @ 0x50
 * 
 * 2)
 * read in BLKSIZE bytes and write and flush
 * 
 * Connect Raspberry Pi I2C interface to cypress board 
 * 
 * Raspberry Pi connector:-
 *    3V3 *  * 5V0
 *    SDA *  * 5V0
 *    SCL *  * GND
 *  GPCLK *  * TXD
 *    GND *  * +PWM  
 * 
 * */


/*
*******************************************************************************
SEC 1.0 - includes
*******************************************************************************
*/

#include <stdio.h>
#include <stdlib.h>
#include <linux/i2c-dev.h>
#include <fcntl.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

//We need to write BLKSIZE bytes at a time to the eeprom.

/*
 * 
 * 
 *     image = [
        0xC2,                           # boot from EEPROM
        lsb (vid),
        msb (vid),
        lsb (pid),
        msb (pid),
        lsb (devid),
        msb (devid),
        cb                               # configuration byte
        ]


 data
 * 
 *   
 # writes 0 to CPUCS reg (brings FX2 out of reset)
    image.extend (  [
        0x80,
        0x01,
        0xe6,
        0x00,
        0x00
        ] )


 * */


/*
*******************************************************************************
SEC 2.0 - variables
*******************************************************************************
*/
	int read_ip;
	int fd;
	int fd2;
	int count;
								// File descrition
	//char *fileName = "/dev/i2c-0";
	// I needed to change the device
	char *fileName = "/dev/i2c-1";


#define BLKSIZE 64

/*
*******************************************************************************
SEC 3.0 - ProtoTypes
*******************************************************************************
*/
int iis_start( int address );
int iis_close(  );
int disp_buff( char * buff );
 
/*
*******************************************************************************
SEC 4.0 - functions
*******************************************************************************
*/

int iis_start( int address ){
  	  if ((fd = open(fileName, O_RDWR)) < 0) {					// Open port for reading and writing
		printf("Failed to open i2c port\n");
                printf(" run: \n");
                printf(" sudo modprobe i2c-dev  \n");
                printf(" sudo chmod o+rw /dev/i2c* \n");
		exit(1);
	  }
	  if (ioctl(fd, I2C_SLAVE, address) < 0) {					// Set the port options and set the address of the device we wish to speak to
		printf("Unable to get bus access to talk to slave\n");
		exit(1);
	  }
}

int iis_close(  ){
  close(fd );
}




int write_file_to_i2c( char *fileName ){ //"build/lights.iic"
	int fd_ip;
	int finished;
	int8_t buffer[100];
	//char buffer[100];
	int bytesRead;
	int bytesWritten;

	int count;
	int readCount;
	
	int  address = 0x51;
	
	//Want 16 bit
	int i2c_data_addr = 0;
	
	//char *fileName = "build/lights.iic";

  	if ( (fd_ip = open( fileName, O_RDWR ) ) < 0) {					// Open port for reading and writing
		printf("Failed to open: %s\n", fileName );
		exit(1);
	}
	  	  
	//fseek( fd_ip,0,0); 
	  	  
	finished = ( 1 == 0 );

	printf( "**** write_file_to_i2c: %s ****\n",fileName );
	  
	while( ! finished ){
	    printf( "\n**** addr: %04x ****\n",i2c_data_addr );

		for( count = 0; count < BLKSIZE; count++){
			buffer[count]=0;
		}
		
		readCount = read(fd_ip, &buffer[2], BLKSIZE );
	  	printf( "readCount: %d %d",readCount,sizeof(buffer[0]));
		
		for( count = 0; count < BLKSIZE; count++){
			if ( ( count & 15 ) == 0 ){
				printf( "\n");
			} 
			if ( buffer[count+2]< 0){
			  printf( "%02X ",0x100+buffer[count+2] );
			} else {
			  printf( "%02X ",buffer[count+2] );
		    }  
		}

		// write BLKSIZE bytes to eprom
		
		buffer[0] = ( int8_t) ( ( i2c_data_addr >> 8 ) & 0xff );
		buffer[1] = ( int8_t) ( i2c_data_addr & 0xff );
		
		
	    iis_start( address  );
	    // if last write is still updating eeprom then write returns -1 
	    bytesWritten= write(fd,&buffer[0], 2+BLKSIZE );	    
	    iis_close( address   );
		printf("\nbytesWritten %d \n ",bytesWritten);
		i2c_data_addr +=BLKSIZE;
		usleep( 10000 );
	 		  	
	  	if ( !( readCount > 0 ) ) {
			finished = ( 1==1 );
			close( fd_ip );	
		}  
     }
	 printf( "\n" );		  
 
}


int read_i2c( void ){
	int fd_ip;
	int finished;
	int8_t buffer[100];
	//char buffer[100];
	int bytesRead;
	int bytesWritten;
	int count;
	int readCount;
	
	int  address = 0x51;
	
	//Want 16 bit
	int i2c_data_addr = 0;
	  	  
	finished = ( 1 == 0 );	  
	while( ! finished ){
	    printf( "\n**** addr: %04x ****\n",i2c_data_addr );

		for( count = 0; count < BLKSIZE; count++){
			buffer[count]=0;
		}
		// write BLKSIZE bytes to eprom
		buffer[0] = ( int8_t) ( ( i2c_data_addr >> 8 ) & 0xff );
		buffer[1] = ( int8_t) ( i2c_data_addr & 0xff );
		
	    iis_start( address  );
	    bytesWritten=0;
	    bytesWritten=write(fd,&buffer[0], 2 );
	    read(fd, &buffer[2], BLKSIZE );   
	    iis_close( address   );

		for( count = 0; count < BLKSIZE; count++){
			if ( ( count & 15 ) == 0 ){
				printf( "\n");
			} 
			if ( buffer[count+2]< 0){
			  printf( "%02X ",0x100+buffer[count+2] );
			} else {
			  printf( "%02X ",buffer[count+2] );
		    }  
		}
				
		i2c_data_addr +=BLKSIZE;
		if ( i2c_data_addr > 128 ){
			finished = ( 1 == 1 );
	    }
		usleep( 100000 );
		printf( "\n" );		  
     } 
}


/*
 * 
 * 
pi@raspberrypi:~ $ lsusb
Bus 001 Device 006: ID 05e3:1205 Genesys Logic, Inc. Afilias Optical Mouse H3003 / Trust Optical USB MultiColour Mouse MI-2330
Bus 001 Device 005: ID 04f2:0841 Chicony Electronics Co., Ltd HP Multimedia Keyboard
Bus 001 Device 004: ID 05e3:0660 Genesys Logic, Inc. USB 2.0 Hub
Bus 001 Device 007: ID 0925:3881 Lakeview Research Saleae Logic
Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp. SMSC9512/9514 Fast Ethernet Adapter
Bus 001 Device 002: ID 0424:9514 Standard Microsystems Corp. SMC9514 Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

 * 
 * 
 */ 

int set_eeprom( void ){
	int fd_ip;
	int finished;
	
	int bytesRead;
	int count;
	int readCount;
	
	int  address = 0x51;
	printf("**** 0925:3881 Lakeview Research Saleae Logic ****\n");
	
	/*
pi@raspberrypi:~/Desktop/cyp/fx2lib-master/examples/i2c $ hexdump -C build/i2c.iic
* 0925:3881 Lakeview Research Saleae Logic
00000000  c2 25 09 81 38 00 00 04  03 ff 00 00 02 00 06 02  |.%..8...........|
0
	 */

	int8_t buffer[100]={ 
		0,0,		//ADDRESS
		0xc0,		// if C0 - boot from USB, if C2 boot from 24LC128 eprom
		0x25,0x09,  //VID
		0x81,0x38,  //PID
		0,0,			//
		4			// config
	};		
		
	iis_start( address  );
	write(fd,&buffer[0], 2+8 );
	iis_close( address   );
 
    usleep( 100000 );
	printf( "\n" );		  
}



/*
*******************************************************************************
SEC 10.0 - main
*******************************************************************************
*/

int main(int argc, char **argv)
{
	char buff[100];
    int  buffIndex;		
    int  readCnt;
    int  writeCount;
	
    char ipChar;
	int  count;
	
	;
	
	printf("**** r12c_eprom test program ****\n");
	printf("**** r12c_eprom test program ****\n");


	printf("**** Read eeprom at 0x51 ****\n");
	read_i2c(  );
	printf("\n**** Cntl-C to break out or any key to continue, eeprom at 0x51 ****\n");
	getchar(); 
	
	//printf("**** 0925:3881 Lakeview Research Saleae Logic ****\n");
	//set_eeprom(  );	// set 24LC128 for USB boot

	printf("**** Write eeprom at 0x51 ****\n");

    for( readCnt = 0 ; readCnt < argc ; readCnt++ ){
		printf("argv[ %d ] = %s \n", readCnt, argv[ readCnt ] );
	}	

    // If no file set USB boot for LOGIC
    if ( argc > 1 ){
	  write_file_to_i2c( argv[ 1 ] );		
	} else { 	
	  set_eeprom(  );	// set 24LC128 for USB boot
    }

	printf("**** Read eeprom at 0x51 ****\n");
	read_i2c(  ); 
    
    for( readCnt = 0 ; readCnt < argc ; readCnt++ ){
		printf("argv[ %d ] = %s \n", readCnt, argv[ readCnt ] );
	}	
    exit( 1 );
    
}
