/*
 * blogmem.h
 *
 *  Created on: 18.5.2009
 *      Author: BazikaP
 */

#ifndef _BLOGMEM_H_
#define _BLOGMEM_H_

#include <ctktypes.h>
#include <datadef.h>
#include <nvmem.h>
#include <ucrc16.h>
#include <stmachine.h>


// Maximalni delka dat v backlogu
#define BACKLOG_MAX_SIZE		(sizeof(datavalue_t))


#ifdef MSVC
#pragma pack(push,1)
#endif

//
// Zahlavi dat ulozenych v EEPROM
// Po resetu se kontroluje toto zahlavi ulozene
// na adrese DATA_CONFIG_HEADER_ADDR. Pokud neni platne, pak
// se provede inicializace EEPROM
//

typedef struct
{
	uint16_t	Magic;			//!< Magicke cislo
	uint16_t	Version;		//!< Verze backlog knihovny

#ifdef MSVC
} BACKLOG_HEADER;
#else
} __attribute__((packed)) BACKLOG_HEADER;
#endif


//
// Polozka backlogu
//

typedef struct
{
	nvptr_t		Address;					//!< Adresa dat
	nvptr_t		Size;						//!< Delka dat (1..8)
	uint8_t		Data[BACKLOG_MAX_SIZE];		//!< Data

#ifdef MSVC
} BACKLOG_ITEM;
#else
} __attribute__((packed)) BACKLOG_ITEM;
#endif

//
// Struktura backlogu
//

typedef struct
{
	crc16_t			CRC;			//!< Crc backlogu
	uint8_t			Valid;			//!< Priznak platnosti
	BACKLOG_ITEM	Item;			//!< Polozka backlogu

#ifdef MSVC
} BACKLOG;
#else
} __attribute__((packed)) BACKLOG;
#endif

#ifdef MSVC
#pragma pack(pop)
#endif


//
// Kontext automatu pro pristup k datum v EEPROM
//

typedef struct _BACKLOG_CTX
{
	NVMEMDESC	Parent;				//!< Objekt rodice

	NVMEMDESC	*MainMem;			//!< Ovladana pamet
	nvptr_t		MainMemAddr;		//!< Adresa pocatku ovladane oblasti

	NVMEMDESC	*BacklogMem;		//!< Pamet pro ulozeni backlogu
	nvptr_t		BacklogAddr;		//!< Adresa pro ulozeni backlogu

	STMACHINE	Stm;				//!< Automat ukladani a nacitani
	uint8_t		Status;				//!< Status probihajici operace
	uint8_t		Command;			//!< Prikaz k vykonani

	BACKLOG		Backlog;			//!< Buffer pro ulozeni obsahu backlogu
	BACKLOG_HEADER	Header;			//!< Buffer pro hlavicku dat

	uint8_t		AttemptCount;		//!< Pocet neupsesnych pokusu
} BACKLOG_CTX;


//------------------------------------------------
// eepStorageInit()
//---
// Inicializace automatu pro pristup k parametrum v EEPROM
//---
// copyDefault	 0  = normalni inicializace
//				 1  = nakopirovani default parametru
//

bool_t BacklogInitialize(
			BACKLOG_CTX * const _ctx,
			NVMEMDESC * const _mainMem,
			const nvptr_t _mainMemAddr,
			const nvptr_t _mainMemSize,
			NVMEMDESC * const _backlogMem,
			const nvptr_t _backlogMemAddr);

void BacklogFinalize(BACKLOG_CTX * const _ctx);

#endif /* _BLOGMEM_H_ */
