/**********************************************************************
 *****  COMMON FILE FOR EVERY GILD-SYSTEM PROJECTS                *****
 *****  (WARNING: do not change main routines except user areas)  *****
 *****                                                            *****
 *****  Name: _core_data.h                                        *****
 *****  Desc: API functions for GILD protocol				      *****
 *****  Ver.: 1.0                                                 *****
 *****  Date: 01/2011		                                      *****
 *****  Auth: Martin Mechacek		                              *****
 *****  Comp: ESTELAR s.r.o.									  *****
 *****                                                            *****
 *****  Copyright ESTELAR s.r.o. (c) 2010, all rights reserved    *****
 **********************************************************************/ 

/**********************************************************************
 *****  IMPLEMENTATION AREA - insert into your code 			   ****
 ********************************************************************** 


/////// end of IMPLEMENTATION AREA ///////////////////////////////////*/


#ifndef __CORE_DATA_H
#define __CORE_DATA_H

/**********************************************************************
 *****  USER AREA - set global definitions here					  *****
 **********************************************************************/ 
// centralni definice pro vse co se tyka pristupu na sbernici a prenosu dat 

// prenosova rychlost na sbernici---------------------------------------





// definice makra pro zamenu horniho a dolniho bytu v pameti
// kvuli odlisnosti Big Endian,Small Endian na procesoru Renesas R8C...
#if defined CORE_EDK || defined CORE_POW || defined CORE_LOG

  #define SWAP(a) 	((a>>8) | (a<<8))
  //#define SWAP(a)	((((a)&0xFF00)>>8) | (((a)&0x00FF)<<8))         
  
  #define _DATALEN  (((gPh->ph_datalen)>>8)&0x00ff)

#else

  #define SWAP(a) 	a
  #define _DATALEN   gPh->ph_datalen

#endif

/////// end of USER AREA //////////////////////////////////////////////


/**********************************************************************
 *****  MAIN GLOBAL DEFINITION - do not change !			      *****
 **********************************************************************/ 

//========================================================================
//>> CORE function headers 

#define		Data_BUSY_SET		BusControl.BusState |= (SCI_BUSY);
#define		Data_BUSY_CLEAR		BusControl.BusState &= ~(SCI_BUSY);
#define		Data_BUSY_CHECK		(BusControl.BusState&SCI_BUSY)

//+-------------------------------------------------------------------+
//| DataInitParse()
//| initialise packet data parsing
//+-------------------------------------------------------------------+
void DataInitParse(void);

//+-------------------------------------------------------------------+
//| DataInitVar()
//| re-initialise packet parsing variables, if not data buffered
//+-------------------------------------------------------------------+
void DataInitVar(void);


//+-------------------------------------------------------------------+
//| DataAddrSet()
//| store the bus address of main unit. Use for all packet creation 
//| je treba aktualizovat pri kazde zmene idAdr v aplikaci
//+-------------------------------------------------------------------+
void DataAddrSet(unsigned int idAdr);
unsigned int DataAddrRead();

//+-------------------------------------------------------------------+
//| DataInitPacket()
//| re-initialise packet parsing variables, if not data buffered
//+-------------------------------------------------------------------+
unsigned int DataInitPacket(void);


//+-------------------------------------------------------------------+
//| SCI_PutPacket()
//| send packet on bus with collision check
//+-------------------------------------------------------------------+
unsigned int SCI_PutPacket( unsigned char *pbStrPtr, unsigned char px );  

unsigned int SCI_ResendReq();
unsigned int SCI_ResendCnt();

//+-------------------------------------------------------------------+
//| SCI_RecvPacket()
//| receive packet from bufer and prepare for parsing
//+-------------------------------------------------------------------+
int SCI_RecvPacket( unsigned char _Data, unsigned char *_DataLen);


//+-------------------------------------------------------------------+
//| SCI_CheckPacketAddr()
//| check target address in received packet 
//+-------------------------------------------------------------------+
int SCI_CheckPacketAddr(unsigned int _which);


//+-------------------------------------------------------------------+
//| SCI_GetPacketPID()
//| return masked PID type of received packet
//+-------------------------------------------------------------------+
#define SCI_PACKETPID	( SWAP(gPh->ph_PID.INT)&PID_MASK)


//+-------------------------------------------------------------------+
//| SCI_GetPacketType()
//| return masked data type of received packet
//+-------------------------------------------------------------------+
#define SCI_PACKETTYPE	( SWAP(gPh->ph_PID.INT)&PAC_TYPE_MASK)




//+-------------------------------------------------------------------+
//| DataAddCrcMessage()
//| vypocet CRC a doplneni na konec buferu
//+-------------------------------------------------------------------+
// data musi byt naplnena v gData.bufferTxD
// parametr _Datalen se zadava v bytech
void DataAddCrcMessage( unsigned int _Datalen );


//+-------------------------------------------------------------------+
//| DataCreateSystemMessage()
//| funkce sestavi paket SYS_STATE_CHANGE, vcetne hlavicky a crc
//| a ulozi do gData.bufferTxD pro nasledne odeslani
//+-------------------------------------------------------------------+
void DataCreateSystemMessage(unsigned int _Sys, unsigned int _ioAdr, unsigned int _Code);


//+-------------------------------------------------------------------+
//| DataCreateMessageHeader()
//| funkce vytvori hlavicku paketu a ulozi gData.bufferTxD pro nasledne odeslani
//+-------------------------------------------------------------------+
void DataCreateMessageHeader(unsigned int _Sys, unsigned int _UnitAddr, unsigned int _Rid, unsigned int _Datalen);

/*
obecny princip vytvoreni paketu ktery chceme odeslat:
naplnit datovy obsah paketu do: gData.bufferTxD+SYS_HEADER_LEN
do promenne msgLen ulozit delku dat
doplnit crc volanim funkce DataAddCrcMessage( msgLen );  
crc bylo prodano k datum -> navysit msgLen += 2;
doplnit hlavicku> DataCreateMessageHeader( typ paketu, cilova adresa, 0, msgLen);
odeslani pomoci funkce> SCI_PutPacket( gData.bufferTxD, SYS_HEADER_LEN + msgLen )

*/


//<< end of CORE function headers 


//+-------------------------------------------------------------------+
//| CONSTANTS
//+-------------------------------------------------------------------+

// maximalni delka celeho jednoho paketu pro prijem i odesilani
//#define MAX_MESSAGE_LEN			32	

#define SYS_HEADER_LEN			8							// delka hlavicky paketu
#define SYS_ACK_LEN				8							// delka ACK paketu
#define SYS_MESSAGE_LEN			SYS_HEADER_LEN+8			// delka systemoveho paketu SYS_STATE
//#define SYS_MESSAGE_LEN		SYS_HEADER_LEN+10			// delka paketu pro systemovy cas
#define CARD_DATA_LEN			14						// delka datove casti paketu SYS_CARD


// bitove flagy pro SciState
#define SCI_PARITY_FLAG			0x10		// pracovni priznak pro kontrolu parity v hlavicce
#define SCI_CRCCOUNT_FLAG		0x20		// priznak pocitani CRC
#define SCI_HEADERREC_FLAG		0x40		// flag pro signalizaci prijeti hlavicky paketu
#define SCI_OVERFLOW_FLAG		0x80		// flag pri zaplneni buferu pri prijeti delsi zpravy nez je nastaveno

//#define SCI_PARITY_ERR			0x10		// zjistena chyba parity
//#define SCI_CRC_ERR				0x20		// zjistena chyba CRC

// pocet opakovani ideslani paketu pri chybe pristupu na sbernici
#if defined CORE_GR_U01 || CORE_DH485
 #define SCI_MAX_RESEND			30			
// melo by byt 5, ale protoze cely mechanismus pristupu na sbernici v GR-U01 a GE-DH1 neni spravne tak se to nestiha...
// pokud = 30 nehlasi chybu ERR_SCI_SEND
// asi s tim souvisi take chyba ERR_SCI_BUFFER pri hromadnem nacteni vsech IO (mobilni aplikace)
#else
 #define SCI_MAX_RESEND			5
#endif

//+-------------------------------------------------------------------+
//| CORE VARIABLES
//+-------------------------------------------------------------------+




//========================================================================
//>> DATA_PACKET_HEADER_STRUCT
// struktura hlavicky paketu
//------------------------------------------------------------------------
typedef struct 
{
	union 
		{  
		 unsigned int INT;
		 struct {                            
              	 unsigned char HI;
              	 unsigned char LO;
		 		} CHAR;
		} ph_PID;
	unsigned int ph_ADDR;
	unsigned int ph_datalen;
	unsigned int ph_RID;
//	unsigned int *ph_data;
	
} PACKET_HEADER;

extern PACKET_HEADER	*gPh;

//========================================================================
//>> DATA_PARSING_CONTROL_STRUCT
// struktura promennych pro dekodovani prijatych dat na pakety
//------------------------------------------------------------------------
typedef struct 
{
	unsigned char   PacCount;	// pocita celkovou delku zpracovavaneho paketu
	unsigned char   SciState;	// udrzuje stav zpracovani paketu
	unsigned int 	Crc;		// vypocet CRC pro aktualne zpracovavany paket
	unsigned int    RID;		// udrzuje posledni RID odesilanych paketu

#if defined CORE_EDK || defined CORE_POW  || defined CORE_LOG
	unsigned char	bufferRxD[RX_BUFF_SIZE+1];		// data jednoho paketu prebrana z prijimaciho buferu (gRx)
	unsigned char	bufferTxD[RX_BUFF_SIZE+1];		// data urcena k odeslani na sbernici
#else												// pro jistotu o jedno vice, kvuli alokaci v pameti na sude mista...
	unsigned char	bufferRxD[MAX_MESSAGE_LEN];		// data jednoho paketu prebrana z prijimaciho buferu (gRx)
	unsigned char	bufferTxD[MAX_MESSAGE_LEN];		// data urcena k odeslani na sbernici
#endif
	
} DATA_PARSING;

extern DATA_PARSING		gData;



/////// end of MAIN AREA //////////////////////////////////////////////

#endif 		// __CORE_DATA_H
