/*	Copyright  (c)	Günter Woigk 2013 - 2015
					mailto:kio@little-bat.de

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

	Permission to use, copy, modify, distribute, and sell this software and
	its documentation for any purpose is hereby granted without fee, provided
	that the above copyright notice appear in all copies and that both that
	copyright notice and this permission notice appear in supporting
	documentation, and that the name of the copyright holder not be used
	in advertising or publicity pertaining to distribution of the software
	without specific, written prior permission.  The copyright holder makes no
	representations about the suitability of this software for any purpose.
	It is provided "as is" without express or implied warranty.

	THE COPYRIGHT HOLDER DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
	INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
	EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY SPECIAL, INDIRECT OR
	CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
	DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
	TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
	PERFORMANCE OF THIS SOFTWARE.
*/


#include "Device.h"
#include "Cpu.h"
#include "unix/FD.h"
#include "unix/os_utilities.h"
#include <math.h>


inline double random(double r)	{ return ldexp(random() * r, -31); }


Device::Device(QObject* parent, uint16 my_bit, cstr eeprom_filepath)
:	QObject(parent),
	cpu((Cpu*)parent),
	i2c_dc(0b11),
	i2c_address(0),
	i2c_bits(0),
	i2c_byte(0),
	i2c_state(i2c_idle),
	i2c_buffer_index(0),
	i2c_busyuntil(0),
	select_mask(1<<my_bit),
	select_ff(0),
	irpt_ei_ff(0),
	irpt_pending(0),
	eeprom_size(0),
	eeprom(NULL)
{
	if(eeprom_filepath) load_eeprom(eeprom_filepath);
}


Device::~Device()
{
	delete[] eeprom;
}


//void Device::log(cstr fmt, ...)
//{
//	va_list va;
//	va_start(va,fmt);
//		cpu->log(fmt,va);
//	va_end(va);
//}



void Device::set_irpt(bool f)
{
	irpt_pending = f ? select_mask : 0;
	cpu->k1bus_set_irpt(select_mask, irpt_pending & irpt_ei_ff);
}

void Device::wr_select(uint16 pmask)
{
	select_ff = pmask & select_mask;
}


void Device::wr_irpt(uint16 pmask)
{
	irpt_ei_ff = pmask & select_mask;
	cpu->k1bus_set_irpt(select_mask, irpt_pending & irpt_ei_ff);
}

uint16 Device::rd_irpt()
{
	return irpt_pending & irpt_ei_ff;
}

void Device::load_eeprom(cstr eepromfile)
{
	FD fd(eepromfile,'r');
	uint32 filesize = min(32 kB, (int32)fd.file_size());
	eeprom_size = filesize>8 kB ? 32 kB : filesize>2 kB ? 8 kB : 2 kB;
	eeprom_mask = eeprom_size-1;
	eeprom = new uint8[eeprom_size];
	memset(eeprom,0xff,eeprom_size);
	fd.read_bytes(eeprom,filesize);
	//fd.close_file(0);
}



/*	read data from i2c bus
 *	both, reading and writing, are performed by a read operation of the cpu.
 *	input:	data bus byte
 *	output:
 */
uint16 Device::rd_i2c(uint32 mc2)
{
	uint16 dbus = (floating_k1_bus & ~1) | ((mc2>>17)&1);

	if(!eeprom) return dbus;

	i2c_dc = ((i2c_dc<<2)&0xC) + ((mc2>>16)&3);			// %dc  d=data c=clk

//	if(tr) { log"[",dc&2?"D":"-",dc&1?"C":"-","]"; }

// ---- start condition ----
	if(i2c_dc == 0b1101)
	{
		if(i2c_state!=i2c_busy || now()>i2c_busyuntil)
		{
			i2c_state = i2c_a0;
			i2c_bits  = -1;
			i2c_byte  = 0;
			i2c_buffer_index = 0;
		}
	}

// ---- idle ----
	else if(i2c_state==i2c_idle)
	{
		return dbus;
	}

// ---- clock 1->0 ----				aktive Flanke
	else if((i2c_dc & 0b0101) == 0b0100)
	{
		if(i2c_dc == 0b0110) log("[i2c:0110]");			// both toggled: also stop condition
		else if(i2c_dc == 0b1100) log("[i2c:1100]");	// both toggled: also start condition

		if(i2c_bits==8)		// ack
		{
			i2c_bits=0;
			if(i2c_state==i2c_rd)
			{
				if(i2c_dc & 0b1000)	i2c_state=i2c_idle;			// ack cpu->eeprom = 1 => NAK
				else i2c_byte=eeprom[i2c_address++&0x1FFF];		// ack cpu->eeprom = 0 => ACK
			}
			else if(i2c_state==i2c_a0)
			{
				if(i2c_byte==0xA0) { dbus=floating_k1_bus; i2c_state = i2c_a1; }
				else if(i2c_byte==0xA1) { dbus=floating_k1_bus; i2c_state = i2c_rd; i2c_byte=eeprom[i2c_address++&0x1FFF]; }
				else i2c_state = i2c_idle;
			}
			else if(i2c_state==i2c_a1) { dbus=floating_k1_bus; i2c_state = i2c_a2; i2c_address = ((i2c_address<<8)&0xFF00) + (i2c_byte&0xFF); }
			else if(i2c_state==i2c_a2) { dbus=floating_k1_bus; i2c_state = i2c_wr; i2c_address = ((i2c_address<<8)&0xFF00) + (i2c_byte&0xFF); }
			else if(i2c_state==i2c_wr) { dbus=floating_k1_bus; i2c_address++; i2c_buffer[i2c_buffer_index++] = i2c_byte; }
		}
		else			// data xfer:
		{
			i2c_bits++;
			if(i2c_state==i2c_rd) dbus &= (i2c_byte>>7)&1;			// data eeprom->cpu
			i2c_byte += i2c_byte + ((i2c_dc>>3)&1);					// data cpu->eeprom
			if(i2c_bits==8 && i2c_state==i2c_a0)
			{
				if((i2c_byte&0xFE) == 0xA0)
					{}
				//	log "+"
				else
				//	log "-"
					i2c_state = i2c_idle;
			}
		}
	}

// ---- stop condition ----
	else if(i2c_dc == 0b0111)
	{
		if(i2c_state==i2c_wr)		// program data
		{
			i2c_address &= 0x1FFF; if(i2c_address==0) i2c_address=0x2000;
			uint n = i2c_address&0x3F; n = n?n:64;
			if(i2c_buffer_index>n) memmove(i2c_buffer,i2c_buffer+i2c_buffer_index-n,n); else n = i2c_buffer_index;	// TODO: ...
			uint a0 = i2c_address-n;		// start of block
			memcpy(eeprom+a0,i2c_buffer,n);
			i2c_busyuntil = (uint)(now() + 0.5e-3 + 5e-3 * n/64 * (1-random(0.5)));
			i2c_state=i2c_busy;
		}
		else
			i2c_state=i2c_idle;

	}

	// 0000 0101 1010 1111		both stable
	// 0010 1001				data toggles while clock low
	// 0001 1011				clock rises while data stable
	// 1001 0011				clock rises while data toggles	((bummer))

// ---- transfer ack ----
	else if(i2c_bits==8)
	{
		if(i2c_state!=i2c_rd) dbus = floating_k1_bus;	// a0 a1 a2 wr => pull bus low for ack
														// rd: latch ack bit on clock edge
	}

// ---- transfer data bit ----
	else if(i2c_state==i2c_rd)
	{
		dbus &= (i2c_byte>>7)&1;	// rd: put bit on bus
	}

	return dbus;
}




























