#include "environment.h"
#include "flash.h"
//#include "common.h"

unsigned short 	BoardID = 0;
unsigned int packetID = 0xFFFFFFFF;

#pragma DATA_SECTION(ProgramBuffer, ".sdram");
#pragma DATA_ALIGN(ProgramBuffer, 1024);
unsigned char ProgramBuffer[DOWNLOAD_MAX_SIZE];
#pragma DATA_SECTION(ProgramBinBuffer, ".sdram");
#pragma DATA_ALIGN(ProgramBinBuffer, 1024);
unsigned char ProgramBinBuffer[CODE_MAX_SIZE];

#pragma DATA_ALIGN(HCBProgramHeader, 8);
#pragma DATA_ALIGN(HCBDBHeader, 8);
#pragma DATA_ALIGN(HCBMachineSpecificHeader, 8);
THCBProgramHeader HCBProgramHeader;
THCBDBHeader HCBDBHeader;
THCBMachineSpecificHeader HCBMachineSpecificHeader;
THCBCompatibility HCBCompatibility;
//THCBStatusList HCBStatusList;
TPcUiFlag PCUIFlag;
TProgramVersion ProgramVersion;
TBlackoutInfo BlackoutInfo;

TPortStatus PortStatus;
int SafetCircuitMode;

int ServoMotorBaseSpeed[MAX_SERVO_MOTOR_COUNT];


TErrorCode ReadFromFlash(TFFID idFile, unsigned char *addr, int size, int *length)
{
	TFFHandle hFile;
	TErrorCode rtn = ERROR_CODE_NONE;

	hFile = FlashOpen(idFile, FFS_OPEN_READ);
	if (hFile < 0) rtn = ERROR_CODE_FLASH_OPEN;
	else
	{
		*length = FlashSize(hFile);
		if (*length > size)	rtn = ERROR_CODE_OVERFLOW;
		else if (!FlashRead(hFile, addr, *length)) rtn = ERROR_CODE_FLASH_WRITE;
	}
	if (rtn)
	{
		ErrorUnit_Put(BoardID, ERROR_TYPE_WARNING, rtn, __LINE__, idFile, size);
	}
	return rtn;
}

TErrorCode WriteToFlash(TFFID idFile, unsigned char *addr, int size, int time)
{
	TFFHandle hFile;
	TErrorCode rtn = ERROR_CODE_NONE;

	hFile = FlashOpen(idFile, FFS_OPEN_WRITE);
	if (hFile < 0) rtn = ERROR_CODE_FLASH_OPEN;
	else if (!FlashWrite(hFile, addr, size, time)) rtn = ERROR_CODE_FLASH_WRITE;
	//if (rtn)
	//{
		//ErrorUnit_Put(BoardID, ERROR_TYPE_WARNING, rtn, __LINE__, idFile, size);
	//}
	return rtn;
}


void Environment_Init(void)
{
	ProgramVersion.MajorVersion = PROGRAM_MAJOR_VERSION;
	ProgramVersion.MinorVersion = PROGRAM_MINOR_VERSION;
	ProgramVersion.Date = PROGRAM_RELEASE_DATE;
	ProgramVersion.Type = PROGRAM_TARGET_SYSTEM;

	BlackoutInfo.MasterLastComTime = EXPECTED_COM_START_TIME;
	BlackoutInfo.BlackoutOccured = 0;
}

void WriteHCBMSHeader(THCBMachineSpecificHeader *hcbMachineSpecificHeader)
{
	WriteToFlash(PID_HCB_MS_HEADER, (unsigned char *)hcbMachineSpecificHeader, sizeof(THCBMachineSpecificHeader), 0);
}

