#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <sys/ioctl.h>

#include "main.h"
#include "Api.h"
#include "SDRRecord.h"
#include "SELRecord.h"
#include "SEL.h"
#include "MsgHndlr.h"

pthread_mutex_t Flash_Mutex;

int PlatformInit(void)
{
	uint8_t PrimaryIPMBBusNum, SecondaryIPMBBusNum;
	printf("Init Platform...\r\n");

	//hardware init
	//槽位号识别
	GPIO_InitTypeDef GPIO_InitStruct;
	GPIO_InitStruct.Pin = GA0_PIN | GA1_PIN | GA2_PIN | GA3_PIN | GA4_PIN | RACKID2_PIN;
	GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
	GPIO_InitStruct.Pull = GPIO_NOPULL;
	GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
	stm32_gpio_init(GPIOH, &GPIO_InitStruct);

	GPIO_InitStruct.Pin = GAP_PIN | RACKID1_PIN | RACKID3_PIN | RACKID4_PIN | RACKID5_PIN;
	stm32_gpio_init(GPIOI, &GPIO_InitStruct);

	//LED灯 D2
	GPIO_InitStruct.Pin = GPIO1_PIN;
	GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
	GPIO_InitStruct.Pull = GPIO_NOPULL;
	GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
	stm32_gpio_write(IDENTIFY_PORT, IDENTIFY_PIN, GPIO_PIN_RESET);
	stm32_gpio_init(GPIO1_PORT, &GPIO_InitStruct);

	g_BMCInfo.SelfTestByte 	=	0;
	g_BMCInfo.SlotID		=	PDK_GetSlotID();
	g_BMCInfo.ChassisID		=	PDK_GetChassisID();

	
	
	//LAN地址
	LanInfo_T *pSetLanInfo = &g_BMCInfo.LanInfo[0];
	strcpy(pSetLanInfo->EthName, "eth0");
	pSetLanInfo->IPAddrSrc 	= 	0x01;	//static
	pSetLanInfo->IPAddr[0] = 192;
	pSetLanInfo->IPAddr[1] = 168;
	pSetLanInfo->IPAddr[2] = 1;		//网段
	pSetLanInfo->IPAddr[3] = 120+g_BMCInfo.SlotID; 
	pSetLanInfo->BroadCast[0] = 192;
	pSetLanInfo->BroadCast[1] = 168; 
	pSetLanInfo->BroadCast[2] = 1; //网段
	pSetLanInfo->BroadCast[3] = 255;	
	pSetLanInfo->NetMask[0] = 255; 
	pSetLanInfo->NetMask[1] = 255; 
	pSetLanInfo->NetMask[2] = 255;
	pSetLanInfo->NetMask[3] = 0;
	pSetLanInfo->DefaultGW[0] 	= 	pSetLanInfo->IPAddr[0];
	pSetLanInfo->DefaultGW[1] 	= 	pSetLanInfo->IPAddr[1];
	pSetLanInfo->DefaultGW[2] 	= 	pSetLanInfo->IPAddr[2];
	pSetLanInfo->DefaultGW[3] 	= 	1;
	pSetLanInfo->MACAddr[0]	=	0; //no default mac
	pSetLanInfo->MACAddr[1]	=	0;
	pSetLanInfo->MACAddr[2]	=	0;
	pSetLanInfo->MACAddr[3]	=	0;
	pSetLanInfo->MACAddr[4]	=	0;
	pSetLanInfo->MACAddr[5]	=	0;

	//机箱及刀片信息
	g_BMCInfo.ChassisIdentify		=	FALSE;
	g_BMCInfo.ChassisIdentifyForce  = 	FALSE;
	g_BMCInfo.ChassisIdentifyTimeout = 0;
	g_BMCInfo.PowerGoodFlag =  	1;
	g_BMCInfo.BladeManageEn = 0;
	g_BMCInfo.BladeHealthSta = 1;
	memset(g_BMCInfo.BladeName, 0, 31);
	sprintf(g_BMCInfo.BladeName, "板卡%d", g_BMCInfo.SlotID);

	switch(g_BMCInfo.SlotID)
	{
		case 0x1:
			g_BMCInfo.IndexInChassis = 0;
			break;
		case 0x2:
			g_BMCInfo.IndexInChassis = 1;
			break;
		case 0x3:
			g_BMCInfo.IndexInChassis = 2;
			break;
		case 0x4:
			g_BMCInfo.IndexInChassis = 3;
			break;
		case 0x5:
			g_BMCInfo.IndexInChassis = 4;
			break;
		case 0x6:
			g_BMCInfo.IndexInChassis = 5;
			break;
		case 0x7:
			g_BMCInfo.IndexInChassis = 6;
			break;
		case 0x8:
			g_BMCInfo.IndexInChassis = 7;
			break;
		case 0x9:
			g_BMCInfo.IndexInChassis = 8;
			break;
		case 0xA:
			g_BMCInfo.IndexInChassis = 9;
			break;

		default:
			printf("\n\n\nWarning: Invalid SlotID %#x\n\n\n", g_BMCInfo.SlotID);
			g_BMCInfo.IndexInChassis = 0xff;
			break;
	}

	if(g_BMCInfo.SlotID == 1)
	{
		g_BMCInfo.isChMC 		= 1;
		//IPMB地址
		g_BMCInfo.PrimaryIPMBAddr = 0x20;
		g_BMCInfo.SecondaryIPMBAddr = 0x20;
		if(g_BMCInfo.IndexInChassis < BLADE_NUMBERS)
		{
			gChassisIPMBAddr[g_BMCInfo.IndexInChassis] = 0x20;
		}
	}
	else
	{
		g_BMCInfo.isChMC 		= 0;
		//IPMB地址
		g_BMCInfo.PrimaryIPMBAddr = (0x40+(g_BMCInfo.SlotID&0x1F))<<1;
		g_BMCInfo.SecondaryIPMBAddr = (0x40+(g_BMCInfo.SlotID&0x1F))<<1;
	}

	//init DevGUID
	g_BMCInfo.DeviceGUID[0]	=	0x01;
	g_BMCInfo.DeviceGUID[1]	=	0x01;
	g_BMCInfo.DeviceGUID[2]	=	0x01;
	g_BMCInfo.DeviceGUID[3]	=	0x01;
	g_BMCInfo.DeviceGUID[4]	=	0x01;
	g_BMCInfo.DeviceGUID[5]	=	0x01;
	g_BMCInfo.DeviceGUID[6]	=	0x01;
	g_BMCInfo.DeviceGUID[7]	=	0x01;
	g_BMCInfo.DeviceGUID[8]	=	0x01;
	g_BMCInfo.DeviceGUID[9]	=	0x01;
	g_BMCInfo.DeviceGUID[10]	=	0x01;
	g_BMCInfo.DeviceGUID[11]	=	0x01;
	g_BMCInfo.DeviceGUID[12]	=	0x01;
	g_BMCInfo.DeviceGUID[13]	=	0x01;
	g_BMCInfo.DeviceGUID[14]	=	0x01;
	g_BMCInfo.DeviceGUID[15]	=	0x01;
	
	g_BMCInfo.FwMajorVer		=	FW_VERSION_MAJOR;
	g_BMCInfo.FwMinorVer		=	FW_VERSION_MINOR;
	g_BMCInfo.SendMsgSeqNum				=	0;
	
	// g_BMCInfo.OemFlags.BladeWorkMode			=	BLADE_IPMC;
	// g_BMCInfo.OemFlags.chassisManageFnEnable	=	0;
	// g_BMCInfo.OemFlags.thisBladeIndex			=	0;
	// g_BMCInfo.OemFlags.bladeStatus				=	1;	//0: not present, 1: normal, 2: error, others: reserved.
	
	g_BMCInfo.HealthLevel		=	SENSOR_STATUS_NORMAL;
	g_BMCInfo.SensorSharedMem.SensorTick=	0;	
	g_BMCInfo.SenConfig.PowerOnTick		=	0;
	g_BMCInfo.SenConfig.SysResetTick	=	0;
	g_BMCInfo.CurTimerTick				=	0;
	g_BMCInfo.CurTimerSecond			=	0;
	g_BMCInfo.BootValidMinutes			=	0;
	g_BMCInfo.m_Lan_SetInProgress 		=	0;

	return 0;
}

int InitTimerTaskTbl(void)
{
	printf("InitTimerTaskTbl...\n");
	g_BMCInfo.TimerTaskTblSize = 2;
    memcpy(g_BMCInfo.TimerTaskTbl, m_TimerTaskTbl, sizeof(TimerTaskTbl_T)*g_BMCInfo.TimerTaskTblSize);
}

int Init_SessionTbl(void)
{
	printf("Init_SessionTbl...\n");
	g_BMCInfo.SessionHandle 					=	0;
	g_BMCInfo.UDSSessionHandle 					=	0;

	g_BMCInfo.IpmiConfig.MaxSession				= 	10;
	g_BMCInfo.IpmiConfig.SessionTimeOut			= 	10;	//10s
	g_BMCInfo.IpmiConfig.SendMsgTimeout			=	10;	//10s
	
	/*Allocating Memory to hold session Table informations */
    g_BMCInfo.SessionTblInfo.SessionTbl = (SessionInfo_T *) malloc(sizeof(SessionInfo_T)*( g_BMCInfo.IpmiConfig.MaxSession + 1));
    if(g_BMCInfo.SessionTblInfo.SessionTbl == NULL)
    {
        printf("Error in allocating memory for SessionTbl \n");
        return 1;
    }
    g_BMCInfo.SessionTblInfo.Count = 0;
    /*Initialize the Session Table memory */
    memset(g_BMCInfo.SessionTblInfo.SessionTbl,0,sizeof(SessionInfo_T)*(g_BMCInfo.IpmiConfig.MaxSession + 1));

    /*Allocating Memory to hold UDS session Table informations */
    g_BMCInfo.UDSSessionTblInfo.UDSSessionTbl = (UDSSessionTbl_T *) malloc(sizeof(UDSSessionTbl_T)*(g_BMCInfo.IpmiConfig.MaxSession + 1));
    if(g_BMCInfo.UDSSessionTblInfo.UDSSessionTbl == NULL)
    {
        printf("Error in allocating memory for SessionTbl \n");
        return 1;
    }
    g_BMCInfo.UDSSessionTblInfo.SessionCount = 0;
    /*Initialize the UDS Session Table memory */
    memset(g_BMCInfo.UDSSessionTblInfo.UDSSessionTbl,0,sizeof(UDSSessionTbl_T)*(g_BMCInfo.IpmiConfig.MaxSession + 1));
}

const char FirstPowerOnStr[] = "First power on the bmc";
int Init_IPMI_FRU_SDR_SEL(void)
{
	int i;
	uint32_t	sdrSize =
		sizeof(SDRRepository_T) + sizeof(HdrMgmtCtrlrDevLocator_T) + sizeof(HdrFullSensorRec_T)*SENSOR_NUMBERS;
	uint32_t	selSize = sizeof(SELRepository_T) + sizeof(SELRec_T)*MAX_SEL_RECORD ;	
	uint8_t*	pSDR = NULL;
	uint8_t*	pSEL = NULL;
	
	
	g_BMCInfo.pSDR = malloc(sdrSize);
	if((g_BMCInfo.pSDR == NULL) && (sdrSize != 0))
	{
		printf("g_BMCInfo.pSDR Malloc failed!\r\n");
	}
	g_BMCInfo.pSEL = malloc(selSize);
	if((g_BMCInfo.pSEL == NULL) && (selSize != 0))
	{
		printf("g_BMCInfo.pSEL Malloc failed!\r\n");
	}
	
	GetIPMIFromFlash();
	if(strncmp(g_BMCInfo.IpmiConfig.FirstPowerOnStr, FirstPowerOnStr, sizeof(FirstPowerOnStr)) != 0)
//	if(1)
	{
		//first power on
		printf("\n\n*** BMC first power on! ***\n\n");
		/************************** Init IPMI ******************************/
		memcpy(g_BMCInfo.IpmiConfig.FirstPowerOnStr, FirstPowerOnStr, sizeof(FirstPowerOnStr));
		
		g_BMCInfo.IpmiConfig.SerialIfcSupport		=	SERIAL_IFC_SUPPORT;
		g_BMCInfo.IpmiConfig.SerialTerminalSupport	=	SERIAL_TERMINAL_SUPPORT;
		g_BMCInfo.IpmiConfig.LANIfcSupport			=	LAN_IFC_SUPPORT;
		g_BMCInfo.IpmiConfig.SYSIfcSupport			=	SYS_IFC_SUPPORT;
		g_BMCInfo.IpmiConfig.GrpExtnSupport 		= 	GROUP_EXTERN_SUPPORT;
		g_BMCInfo.IpmiConfig.UDSIfcSupport			=	UDS_IFC_SUPPORT;
		g_BMCInfo.IpmiConfig.ChassisTimerInterval	=	CHASSIS_TIMER_INTERVAL;	
		g_BMCInfo.IpmiConfig.PowerCycleInterval		=	PWR_CYCLE_INTERVAL;
		g_BMCInfo.IpmiConfig.FanControlInterval		=	FAN_CONTROL_INTERVAL;		
		g_BMCInfo.IpmiConfig.RearmSetSensorThreshold	=	REARM_SET_SENSOR_THRESHOLD;
		g_BMCInfo.IpmiConfig.SELTimeUTCOffset		=	8*60;
		
		//IPMB
		g_BMCInfo.IpmiConfig.PrimaryIPMBSupport		=	PRIMARY_IPMB_SUPPORT;
		g_BMCInfo.IpmiConfig.SecondaryIPMBSupport	=	SECONDARY_IPMB_SUPPORT;
		g_BMCInfo.IpmiConfig.PrimaryIPMBBus 		= 	PRIMARY_IPMB_BUS;
		g_BMCInfo.IpmiConfig.SecondaryIPMBBus 		= 	SECONDARY_IPMB_BUS;
		
		//Init FRU
		memcpy(&g_BMCInfo.FRU, &Default_FRUData, sizeof(OemFRUData_T));
		
		/************************ Init SDR *************************************/

		pSDR = g_BMCInfo.pSDR;
		//init SDR repository header
		((SDRRepository_T*)pSDR)->Signature[0]	=	0x00;
		((SDRRepository_T*)pSDR)->Signature[1]	=	0x11;
		((SDRRepository_T*)pSDR)->Signature[2]	=	0x22;
		((SDRRepository_T*)pSDR)->Signature[3]	=	0x33;
		
		((SDRRepository_T*)pSDR)->NumRecords		=	SENSOR_NUMBERS + 1;
		((SDRRepository_T*)pSDR)->Size			=	sdrSize;
		((SDRRepository_T*)pSDR)->AddTimeStamp	=	0;
		((SDRRepository_T*)pSDR)->EraseTimeStamp	=	0;
		//init MgmtCtrlrDevLocator SDR
		pSDR	+= sizeof(SDRRepository_T);
		((HdrMgmtCtrlrDevLocator_T*)pSDR)->Valid	=	1;
		((HdrMgmtCtrlrDevLocator_T*)pSDR)->Len	=	sizeof(HdrMgmtCtrlrDevLocator_T); 
		memcpy(&(((HdrMgmtCtrlrDevLocator_T*)pSDR)->MgmtCtrlrDevLocator), &bmc_sdr, sizeof(MgmtCtrlrDevLocator_T));
		//init FullSensorRec SDR
		pSDR	+= sizeof(HdrMgmtCtrlrDevLocator_T);
		for(i=0;i<SENSOR_NUMBERS;i++)
		{
			((HdrFullSensorRec_T*)pSDR)->Valid	=	1;
			((HdrFullSensorRec_T*)pSDR)->Len	=	sizeof(HdrFullSensorRec_T); 
			memcpy(&(((HdrFullSensorRec_T*)pSDR)->FullSensorRec), &full_sdr_tbl[i], sizeof(FullSensorRec_T));
			pSDR	+= sizeof(HdrFullSensorRec_T);
		}

		
		
		
		/******************************* Init SEL *************************************/	    
		pSEL = g_BMCInfo.pSEL;
		((SELRepository_T*)pSEL)->Signature[0] 	= 0x00;
		((SELRepository_T*)pSEL)->Signature[1] 	= 0x11;
		((SELRepository_T*)pSEL)->Signature[2] 	= 0x22;
		((SELRepository_T*)pSEL)->Signature[3] 	= 0x33;
		((SELRepository_T*)pSEL)->NumRecords	= 0;
		((SELRepository_T*)pSEL)->Padding		= 0;
		((SELRepository_T*)pSEL)->AddTimeStamp	= 0;
		((SELRepository_T*)pSEL)->EraseTimeStamp = 0;
		((SELRepository_T*)pSEL)->FirstRecID	= 0;
		((SELRepository_T*)pSEL)->LastRecID		= 0;
		((SELRepository_T*)pSEL)->SELIndex		= 0;
		((SELRepository_T*)pSEL)->SELRecord		= (SELRec_T*)(pSEL + sizeof(SELRepository_T));
		
		g_BMCInfo.IpmiConfig.SELConfig.SelReservationID = 0;;
	    g_BMCInfo.IpmiConfig.SELConfig.LastEvtTS		=	0;
	    g_BMCInfo.IpmiConfig.SELConfig.PartialAddRecordID	=	0;
	    g_BMCInfo.IpmiConfig.SELConfig.PartialAddRecOffset	=	0;
	    g_BMCInfo.IpmiConfig.SELConfig.PartialAdd		=	0;
	    g_BMCInfo.IpmiConfig.SELConfig.SenMonSELFlag	=	0;
	    g_BMCInfo.IpmiConfig.SELConfig.MaxSELRecord	=	MAX_SEL_RECORD;
	//    g_BMCInfo.SELConfig.RsrvIDCancelled	=	FALSE;
	    g_BMCInfo.IpmiConfig.SELConfig.SELOverFlow		=	FALSE;
	    g_BMCInfo.IpmiConfig.SELConfig.selalmostfull	=	0;
		
		memset(g_BMCInfo.UserInfoTbl, 0x0, sizeof(UserInfo_T)*MAX_USER_NUM);
		g_BMCInfo.UserInfoTbl[2].UserId = 3;
		strcpy(g_BMCInfo.UserInfoTbl[2].UserName, "admin");
		strcpy(g_BMCInfo.UserInfoTbl[2].UserPassword, "admin");
		g_BMCInfo.UserInfoTbl[2].UserStatus = TRUE;

		g_BMCInfo.CurrentNoUser = 1;
		g_BMCInfo.pUserInfo = NULL;

		/************** Sensor History ****************/
		memset(gSensorHistoryInfo, 0, sizeof(SensorHistoryInfo_T)*SENSOR_NUMBERS);
		FlushSensorHistoryToFlash();

		FlushUserInfoTbl();
		UpdateFlash();
	}
	else
	{
		//Init FRU
		GetFRUFromFlash();
		
		//Init SDR
		GetSDRFromFlash();
		
		//Init SEL
		GetSELFromFlash();
		((SELRepository_T*)g_BMCInfo.pSEL)->SELRecord		= (SELRec_T*)(g_BMCInfo.pSEL + sizeof(SELRepository_T));

		

		g_BMCInfo.IpmiConfig.SELConfig.SelReservationID = 0;;
	    g_BMCInfo.IpmiConfig.SELConfig.LastEvtTS		=	0;
	    g_BMCInfo.IpmiConfig.SELConfig.PartialAddRecordID	=	0;
	    g_BMCInfo.IpmiConfig.SELConfig.PartialAddRecOffset	=	0;
	    g_BMCInfo.IpmiConfig.SELConfig.PartialAdd		=	0;
	    g_BMCInfo.IpmiConfig.SELConfig.SenMonSELFlag	=	0;
	    g_BMCInfo.IpmiConfig.SELConfig.MaxSELRecord	=	MAX_SEL_RECORD;
	//    g_BMCInfo.SELConfig.RsrvIDCancelled	=	FALSE;
	    g_BMCInfo.IpmiConfig.SELConfig.SELOverFlow		=	FALSE;
	    g_BMCInfo.IpmiConfig.SELConfig.selalmostfull	=	0;

	    //Init SensorHistory
		GetSensorHistoryFromFlash();

	    UpdateUserInfoTble();
		g_BMCInfo.CurrentNoUser = 0;
		for(i=0;i<MAX_USER_NUM;i++)
		{
			if((g_BMCInfo.UserInfoTbl[i].UserId != 0) && (g_BMCInfo.UserInfoTbl[i].UserStatus == TRUE))
				g_BMCInfo.CurrentNoUser++;
		}
		g_BMCInfo.pUserInfo = NULL;
	}

	g_BMCInfo.IpmiConfig.SDRConfig.UpdatingSDR	=	FALSE;
	g_BMCInfo.IpmiConfig.SDRConfig.UpdatingChannel	=	0;
	g_BMCInfo.IpmiConfig.SDRConfig.TrackPOffset	=	0;
	g_BMCInfo.IpmiConfig.SDRConfig.TrackRecID		=	0;
	g_BMCInfo.IpmiConfig.SDRConfig.IPMB_Seqnum		=	0;
	g_BMCInfo.IpmiConfig.SDRConfig.PartAddbytes	=	0;
	g_BMCInfo.IpmiConfig.SDRConfig.LatestRecordID	=	0;
	g_BMCInfo.IpmiConfig.SDRConfig.NumMarkedRecords	=	0;
	g_BMCInfo.IpmiConfig.SDRConfig.RepositoryInfo.Version	=	0x51;
	g_BMCInfo.IpmiConfig.SDRConfig.RepositoryInfo.FreeSpace	=	0xffff;
	g_BMCInfo.IpmiConfig.SDRConfig.RepositoryInfo.AddTimeStamp	=	0;
	g_BMCInfo.IpmiConfig.SDRConfig.RepositoryInfo.EraseTimeStamp	=	0;
	g_BMCInfo.IpmiConfig.SDRConfig.RepositoryInfo.OpSupport	=	0x23;
	g_BMCInfo.IpmiConfig.SDRConfig.RepositoryAllocInfo.NumAllocUnits	=	MAX_SENSOR_NUMBERS+1;
	g_BMCInfo.IpmiConfig.SDRConfig.RepositoryAllocInfo.AllocUnitSize	=	SDR_ALLOC_UNIT_SIZE;
	g_BMCInfo.IpmiConfig.SDRConfig.RepositoryAllocInfo.NumFreeAllocUnits	=	MAX_SENSOR_NUMBERS - SENSOR_NUMBERS;
	g_BMCInfo.IpmiConfig.SDRConfig.RepositoryAllocInfo.LargestFreeBlock	=	SDR_MAX_RECORD_SIZE;
	g_BMCInfo.IpmiConfig.SDRConfig.RepositoryAllocInfo.MaxRecSize	=	SDR_MAX_RECORD_SIZE;	//Maximum record size in allocation units
	g_BMCInfo.IpmiConfig.SDRConfig.SDRRAM			=	(SDRRepository_T*)g_BMCInfo.pSDR;
	g_BMCInfo.IpmiConfig.SDRConfig.RepositoryInfo.RecCt	=	((SDRRepository_T*)g_BMCInfo.IpmiConfig.SDRConfig.SDRRAM)->NumRecords;
	g_BMCInfo.IpmiConfig.SDRConfig.SDRError	=	0;
	g_BMCInfo.IpmiConfig.SDRConfig.ReservationID	=	0;


	
	return 0;
}


int SetSysTime(uint32_t *timeSecond)
{
	time_t tt;
	tt = *timeSecond;
	stime(&tt);	//TODO:注意时区
	return 0;
}

long int GetSysTime(void)
{
	time_t tt;
	time(&tt);
	//TODO: 注意时区
	//tt += 8*60*60;	UTC+8
	return tt;
}

int PostEventMessage (uint8_t *EventMsg,uint8_t size)
{
	uint8_t             SelReq [sizeof(SELEventRecord_T)];
	uint8_t             SelRes [sizeof(AddSELRes_T)];
	SELEventRecord_T*   SelRecord = ( SELEventRecord_T*) SelReq;

	SelRecord->hdr.Type = 0x02;
	SelRecord->hdr.TimeStamp = GetSysTime ();
	memcpy (SelRecord->GenID, EventMsg, size);
	
	LockedAddSELEntry(SelReq, sizeof (SELEventRecord_T), SelRes);

	return 0;
}

uint8_t PDK_GetSlotID(void)
{
	uint8_t SlotID = 0;
	// uint8_t check = 0;

	if(stm32_gpio_read(GA0_PORT, GA0_PIN) == GPIO_PIN_RESET)
		SlotID |= 0x01;
	if(stm32_gpio_read(GA1_PORT, GA1_PIN) == GPIO_PIN_RESET)
		SlotID |= 0x02;
	if(stm32_gpio_read(GA2_PORT, GA2_PIN) == GPIO_PIN_RESET)
		SlotID |= 0x04;
	if(stm32_gpio_read(GA3_PORT, GA3_PIN) == GPIO_PIN_RESET)
		SlotID |= 0x08;
	if(stm32_gpio_read(GA4_PORT, GA4_PIN) == GPIO_PIN_RESET)
		SlotID |= 0x10;

	// if(stm32_gpio_read(GAP_PORT, GAP_PIN) == GPIO_PIN_RESET)
	// 	SlotID |= 0x20;

	// int i;
	// for(i=0;i<6;i++)
	// 	check ^= (SlotID>>i)&0x01;

	// if(check == 0)
	// 	printf("Slot ID check error! GAP = %#x, GA[4:0] = %#x.\n", (SlotID>>5), (SlotID&0x1f));

	// return SlotID&0x1f;

	return SlotID;

}

uint8_t PDK_GetChassisID(void)
{
	uint8_t ChassisID = 0;
	// if(stm32_gpio_read(RACKID0_PORT, RACKID0_PIN) == GPIO_PIN_SET)
	// 	ChassisID |= 0x01;
	// if(stm32_gpio_read(RACKID1_PORT, RACKID1_PIN) == GPIO_PIN_SET)
	// 	ChassisID |= 0x02;
	// if(stm32_gpio_read(RACKID2_PORT, RACKID2_PIN) == GPIO_PIN_SET)
	// 	ChassisID |= 0x04;
	// if(stm32_gpio_read(RACKID3_PORT, RACKID3_PIN) == GPIO_PIN_SET)
	// 	ChassisID |= 0x08;
	// if(stm32_gpio_read(RACKID4_PORT, RACKID4_PIN) == GPIO_PIN_SET)
	// 	ChassisID |= 0x10;
	// if(stm32_gpio_read(RACKID5_PORT, RACKID5_PIN) == GPIO_PIN_SET)
	// 	ChassisID |= 0x20;

	return ChassisID;
}

int PDK_PowerOffChassis(void)
{
	//printf("Api power off chassis\n");
	g_BMCInfo.PowerGoodFlag = 0;
	printf("Not support power control!\n");
	return 0;
}

int PDK_PowerOnChassis(void)
{
	//printf("power on chassis\n");
	g_BMCInfo.PowerGoodFlag = 1;
	printf("Not support power control!\n");
}

int PDK_SoftOffChassis(void)
{
	//printf("soft off chassis\n");
	g_BMCInfo.PowerGoodFlag = 0;
	printf("Not support power control!\n");
}

int PDK_GetPowerStatus(void)
{
	//TODO:
	return 1;
}

int PDK_PowerCycleChassis(void)
{
	//printf("power cycle chassis\n");
	printf("Not support power control!\n");
	return 0;
}

int PDK_ResetChassis(void)
{
	//printf("power reset chassis\n");
	printf("Not support power control!\n");
	return 0;
}

int PDK_DiagInterruptChassis(void)
{
	printf("power diag chassis\n");
}

int PDK_FanControl(void)
{
	;
}

//设置IP地址
/*
 * 函数名称 ： int setip(char *ip)
 * 函数功能 ： 设置系统IP地址
 * 参    数 ： 
 *char *ip ：设置的IP地址，以点分十进制的字符串方式表示，如“192.168.0.5” 
 * 返 回 值 ： 0 : 成功 ；  -1 :  失败 
 */
int setip(char *ip)
{
    struct ifreq temp;
    struct sockaddr_in *addr;
    int fd = 0;
    int ret = -1;
    strcpy(temp.ifr_name, "eth0");
    if((fd=socket(AF_INET, SOCK_STREAM, 0))<0)
    {
      return -1;
    }
    addr = (struct sockaddr_in *)&(temp.ifr_addr);
    addr->sin_family = AF_INET;
    addr->sin_addr.s_addr = inet_addr(ip);
    ret = ioctl(fd, SIOCSIFADDR, &temp);
    close(fd);
    if(ret < 0)
       return -1;
    return 0;
}

//获取IP地址
/*
 * 函数名称 ： char * getip(char *ip_buf)
 * 函数功能 ： 获取系統IP地址
 * 参    数 ： 
 *char *ip_buf ：用来存放IP地址的内存空间
 * 返 回 值 ： ip_buf ： 存放IP地址的内存地址
 */
char* getip(char *ip_buf)
{
    struct ifreq temp;
    struct sockaddr_in *myaddr;
    int fd = 0;
    int ret = -1;
    strcpy(temp.ifr_name, "eth0");
    if((fd=socket(AF_INET, SOCK_STREAM, 0))<0)
    {
        return NULL;
    }
    ret = ioctl(fd, SIOCGIFADDR, &temp);
    close(fd);
    if(ret < 0)
        return NULL;
    myaddr = (struct sockaddr_in *)&(temp.ifr_addr);
    strcpy(ip_buf, (char*)inet_ntoa(myaddr->sin_addr));
    return ip_buf;
}

char* getnetmask(char *netmask_buf)
{
    struct ifreq temp;
    struct sockaddr_in *myaddr;
    int fd = 0;
    int ret = -1;
    strcpy(temp.ifr_name, "eth0");
    if((fd=socket(AF_INET, SOCK_STREAM, 0))<0)
    {
        return NULL;
    }
    ret = ioctl(fd, SIOCGIFNETMASK, &temp);
    close(fd);
    if(ret < 0)
        return NULL;
    myaddr = (struct sockaddr_in *)&(temp.ifr_addr);
    strcpy(netmask_buf, (char*)inet_ntoa(myaddr->sin_addr));

    return netmask_buf;
}

char* getbroadcast(char *broadcast_buf)
{
    struct ifreq temp;
    struct sockaddr_in *myaddr;
    int fd = 0;
    int ret = -1;
    strcpy(temp.ifr_name, "eth0");
    if((fd=socket(AF_INET, SOCK_STREAM, 0))<0)
    {
        return NULL;
    }
    ret = ioctl(fd, SIOCGIFBRDADDR, &temp);
    close(fd);
    if(ret < 0)
        return NULL;
    myaddr = (struct sockaddr_in *)&(temp.ifr_addr);
    strcpy(broadcast_buf, (char*)inet_ntoa(myaddr->sin_addr));

    return broadcast_buf;
}


char* getmac(char *mac_buf)
{
    struct ifreq temp;
    struct sockaddr_in *myaddr;
    int fd = 0;
    int ret = -1;
    strcpy(temp.ifr_name, "eth0");
    if((fd=socket(AF_INET, SOCK_STREAM, 0))<0)
    {
        return NULL;
    }
    if(ioctl(fd,SIOCGIFHWADDR,&temp)<0)
    {
        printf("Get mac address ioctl fail!\n");
    }
    else
    {
        sprintf(mac_buf, "%02x:%02x:%02x:%02x:%02x:%02x\n",
                (unsigned char)temp.ifr_hwaddr.sa_data[0],
                (unsigned char)temp.ifr_hwaddr.sa_data[1],
                (unsigned char)temp.ifr_hwaddr.sa_data[2],
                (unsigned char)temp.ifr_hwaddr.sa_data[3],
                (unsigned char)temp.ifr_hwaddr.sa_data[4],
                (unsigned char)temp.ifr_hwaddr.sa_data[5]);
    }
    close(fd);
    return mac_buf;
}

int getSensorHistory(uint8_t sensorNum, uint8_t *phistoryBuf)
{
	int i =0;
	for(i=0;i<SENSOR_NUMBERS;i++)
	{
		if(gSensorHistoryInfo[i].SensorNum == sensorNum)
		{
			memcpy(phistoryBuf, gSensorHistoryInfo[i].History, HISTORY_DATA_SIZE);
			return 0;
		}
	}
	
	if(i >= SENSOR_NUMBERS)
	{
		printf("Warning: Can't find sensorNum!\n");
		return -1;
	}
}


pthread_mutex_t api_bridge_mutex;	
int API_BridgeInternal(MsgPkt_T* pReqPkt, MsgPkt_T* pResPkt, uint8_t DestAddr, int Channel)
{
    
    IPMIMsgHdr_T*  pReqMsgHdr;
    IPMIMsgHdr_T*  pResMsgHdr;
    uint8_t SeqNum = g_BMCInfo.SendMsgSeqNum;
	int 			RetVal;
	int 			fd_BridgeQue;
	uint8_t 		PBTbl;
	
	pthread_mutex_lock(&api_bridge_mutex);
	//create BRIDGE_QUEUE
    if(-1 != access(BRIDGE_QUEUE, F_OK))
    {
        remove(BRIDGE_QUEUE);
    }
    if(0 != mkfifo (BRIDGE_QUEUE, 0777))
    {
        printf("%s: Create %s fifo failed! \n", __FUNCTION__, BRIDGE_QUEUE);
        pthread_mutex_unlock(&api_bridge_mutex);
        return -1;
    }
    fd_BridgeQue = open (BRIDGE_QUEUE, O_RDWR);
    if(-1 == fd_BridgeQue)
    {
        printf("%s: Open %s fifo failed! \n", __FUNCTION__, BRIDGE_QUEUE);
        pthread_mutex_unlock(&api_bridge_mutex);
        return -1;
    }
	
    if(NULL != pReqPkt)
    {
		memcpy(&(pReqPkt->Data[sizeof(IPMIMsgHdr_T)]), pReqPkt->Data, pReqPkt->Size);
		pReqPkt->Size += sizeof(IPMIMsgHdr_T);
		pReqMsgHdr = (IPMIMsgHdr_T*)pReqPkt->Data;
    }
    else
    {
        printf("Warning: Message Packet to be bridged is NULL\r\n");
		remove(BRIDGE_QUEUE);
		pthread_mutex_unlock(&api_bridge_mutex);
        return -1;
    }    
    if(NULL != pResPkt)
    {
      pResMsgHdr = (IPMIMsgHdr_T*)pResPkt->Data;
    }
    else
    {
        printf("Warning: Message Packet to be bridged is NULL\r\n");
		remove(BRIDGE_QUEUE);
		pthread_mutex_unlock(&api_bridge_mutex);
        return -1;
    }   
    /* Format IPMI message header */
    pReqMsgHdr->ResAddr  = DestAddr;
	pReqMsgHdr->NetFnLUN = pReqPkt->NetFnLUN;
    pReqMsgHdr->ChkSum   = ~(pReqMsgHdr->ResAddr + pReqMsgHdr->NetFnLUN) + 1;
	
    if(Channel == PRIMARY_IPMB_CHANNEL)
    {
        pReqMsgHdr->ReqAddr = g_BMCInfo.PrimaryIPMBAddr;	//PRIMARY_IPMB_ADDR;
    }
    else if(Channel == SECONDARY_IPMB_CHANNEL) 
    {
        pReqMsgHdr->ReqAddr = g_BMCInfo.SecondaryIPMBAddr;	//PRIMARY_IPMB_ADDR;
    }
    else
    {
        printf ("Warning: Invalid IPMB Channel: %d\r\n", Channel);
		remove(BRIDGE_QUEUE);
		pthread_mutex_unlock(&api_bridge_mutex);
        return -1;
    }
	
	pResPkt->NetFnLUN 	=	pReqPkt->NetFnLUN + 0x40;
	pResPkt->Cmd 		=	pReqPkt->Cmd;
	
	pReqMsgHdr->Cmd		=	pReqPkt->Cmd;
	
	pResMsgHdr->ResAddr  = pReqMsgHdr->ReqAddr;
	pResMsgHdr->ChkSum   = ~(pResMsgHdr->ResAddr + pResMsgHdr->NetFnLUN) + 1;
	pResMsgHdr->ReqAddr	= pReqMsgHdr->ResAddr;
	pResMsgHdr->RqSeqLUN = pReqMsgHdr->RqSeqLUN;
	pResMsgHdr->Cmd 	= pReqMsgHdr->Cmd;
	
	PBTbl = (Channel == SECONDARY_IPMB_CHANNEL) ? SECONDARY_PB_TBL : PRIMARY_PB_TBL ;
	/* Store in the table for response tracking */
	while(TRUE)
	{
		if (FALSE == m_PendingBridgedResTbl[PBTbl][SeqNum].Used)
		{			
			m_PendingBridgedResTbl[PBTbl][SeqNum].TimeOut = DEFAULT_TIMEOUT;
	  
			m_PendingBridgedResTbl[PBTbl][SeqNum].ChannelNum = pReqPkt->Channel; 
			m_PendingBridgedResTbl[PBTbl][SeqNum].OriginSrc  = ORIGIN_INT_REQ;
			g_BMCInfo.SendMsgSeqNum = SeqNum;
			printf("g_BMCInfo.SendMsgSeqNum %d\n", g_BMCInfo.SendMsgSeqNum);

			/* Format Sequence Number */
			pReqMsgHdr->RqSeqLUN = ((g_BMCInfo.SendMsgSeqNum) << 2) & 0xFC;
			pResMsgHdr->RqSeqLUN = pReqMsgHdr->RqSeqLUN + 0x40;
			
			memcpy (&m_PendingBridgedResTbl[PBTbl][SeqNum].ReqMsgHdr, pReqMsgHdr, sizeof (IPMIMsgHdr_T));
			memcpy (&m_PendingBridgedResTbl[PBTbl][SeqNum].ResMsgHdr, pResMsgHdr,  sizeof (IPMIMsgHdr_T));
			m_PendingBridgedResTbl[PBTbl][SeqNum].DestQ = fd_BridgeQue;
			
			/* Store Session ID for final response to the origin for KCS*/
			//m_PendingBridgedResTbl[SeqNum].SrcSessionID = pReqPkt->SessionID;
			
			m_PendingBridgedResTbl[PBTbl][SeqNum].Used = TRUE;
			//printf( "---> oemApi.c:  Bridged message added index = %d.\n", SeqNum );
			
			break;
		}
		else
		{
			SeqNum = (SeqNum + 1) & 0x3F;
			if(SeqNum == g_BMCInfo.SendMsgSeqNum)
			{
				printf ("Warning: Pending Bridge Response Table is full \n");
				remove(BRIDGE_QUEUE);
				pthread_mutex_unlock(&api_bridge_mutex);
				return -1;
			}
		}
	}
    
    /* Format message packet */
    pReqPkt->Channel = Channel;
    pReqPkt->Param   = PARAM_BRIDGE;
    
    /* Recalculate the checksum */
    pReqPkt->Data [pReqPkt->Size] =  CalculateCheckSum2 (pReqPkt->Data, pReqPkt->Size);
	pReqPkt->Size++;
    
	if(Channel == PRIMARY_IPMB_CHANNEL) 
	{
		pReqPkt->SrcQ = gFd_PrimaryIpmbIfcQ; 
	}
	else if(Channel == SECONDARY_IPMB_CHANNEL)
	{
		pReqPkt->SrcQ = gFd_SecondaryIpmbIfcQ; 
	}
	else
	{
		printf("Warning: Invalid Channel %d\n", Channel);
		remove(BRIDGE_QUEUE);
		pthread_mutex_unlock(&api_bridge_mutex);
		return -1;
	}
  
    /* Post Message to the bridge queue */
    if(0 != PostMsg(pReqPkt->SrcQ, pReqPkt) )
    {
        printf ("Warning: oemApi.c : Error posting message to Queue %p \n", pReqPkt->SrcQ);
		remove(BRIDGE_QUEUE);
		pthread_mutex_unlock(&api_bridge_mutex);
        return -1;
    }
	
	m_PendingBridgedResTbl[PBTbl][SeqNum].ResDataOk = 1;
	
    RetVal = GetMsg (fd_BridgeQue, pResPkt, 5000);  //3s

    int i;
    printf("Bridge recv: ");
    for(i=0;i<pResPkt->Size;i++)
    {
    	printf("%#x ", pResPkt->Data[i]);
    }
    printf("\n");

	remove(BRIDGE_QUEUE);
	pthread_mutex_unlock(&api_bridge_mutex);
	if(RetVal != 0)
	{
		return -1;
	}
	
	memcpy(pResPkt->Data, &(pResPkt->Data[sizeof(IPMIMsgHdr_T)]), pResPkt->Size - sizeof(IPMIMsgHdr_T)-1);
	pResPkt->Size = pResPkt->Size - sizeof(IPMIMsgHdr_T)-1;	//remove header & checksum2

    return 0;
}


/***************** Flash 保存非易失数据 *******************/

int FlushSDRToFlash()
{
	uint32_t 	writeLen = 0;
	uint32_t 	offset = 0;
	uint32_t	sdrSize =
		sizeof(SDRRepository_T) + sizeof(HdrMgmtCtrlrDevLocator_T) + sizeof(HdrFullSensorRec_T)*SENSOR_NUMBERS;
		
	pthread_mutex_lock(&Flash_Mutex);
	while(sdrSize > 0)
	{
		if(sdrSize > 4*1024)
			writeLen = 4*1024;
		else
			writeLen = sdrSize;

		sf_sector_erase(5, SDR_FLASH_ADDR+offset);
		sf_write(5, SDR_FLASH_ADDR+offset, g_BMCInfo.pSDR+offset, writeLen);
		offset += writeLen;
		sdrSize -= writeLen;
	}
	pthread_mutex_unlock(&Flash_Mutex);
	return 0;
}

int GetSDRFromFlash()
{
	uint32_t	sdrSize =
		sizeof(SDRRepository_T) + sizeof(HdrMgmtCtrlrDevLocator_T) + sizeof(HdrFullSensorRec_T)*SENSOR_NUMBERS;
		
	pthread_mutex_lock(&Flash_Mutex);
	sf_read(5, SDR_FLASH_ADDR, g_BMCInfo.pSDR, sdrSize);
	pthread_mutex_unlock(&Flash_Mutex);
	return 0;
}

int FlushSELToFlash()
{
	uint32_t 	writeLen = 0;
	uint32_t 	offset = 0;
	uint32_t	selSize = sizeof(SELRepository_T) + sizeof(SELRec_T)*MAX_SEL_RECORD ;	

	pthread_mutex_lock(&Flash_Mutex);
	while(selSize > 0)
	{
		if(selSize > 4*1024)
			writeLen = 4*1024;
		else
			writeLen = selSize;

		sf_sector_erase(5, SEL_FLASH_ADDR+offset);
		sf_write(5, SEL_FLASH_ADDR+offset, g_BMCInfo.pSEL+offset, writeLen);
		offset += writeLen;
		selSize -= writeLen;
	}
	pthread_mutex_unlock(&Flash_Mutex);
	return 0;
}

int GetSELFromFlash()
{
	uint32_t	selSize = sizeof(SELRepository_T) + sizeof(SELRec_T)*MAX_SEL_RECORD ;	
	pthread_mutex_lock(&Flash_Mutex);
	sf_read(5, SEL_FLASH_ADDR, g_BMCInfo.pSEL, selSize);
	pthread_mutex_unlock(&Flash_Mutex);
	return 0;
}

int FlushIPMIToFlash()
{
	uint32_t 	writeLen = 0;
	uint32_t 	offset = 0;
	uint32_t	ipmiSize = sizeof(IPMIConfig_T);
	pthread_mutex_lock(&Flash_Mutex);
	while(ipmiSize > 0)
	{
		if(ipmiSize > 4*1024)
			writeLen = 4*1024;
		else
			writeLen = ipmiSize;

		sf_sector_erase(5, IPMI_CFG_FLASH_ADDR+offset);
		sf_write(5, IPMI_CFG_FLASH_ADDR+offset, ((uint8_t*)&g_BMCInfo.IpmiConfig)+offset, writeLen);
		offset += writeLen;
		ipmiSize -= writeLen;
	}
	pthread_mutex_unlock(&Flash_Mutex);
	return 0;
}

int GetIPMIFromFlash()
{
	uint32_t	ipmiSize = sizeof(IPMIConfig_T);
	pthread_mutex_lock(&Flash_Mutex);
	sf_read(5, IPMI_CFG_FLASH_ADDR, (uint8_t*)&g_BMCInfo.IpmiConfig, ipmiSize);
	pthread_mutex_unlock(&Flash_Mutex);
	return 0;
}

int FlushFRUToFlash()
{
	uint32_t	fruSize = sizeof(OemFRUData_T);
	pthread_mutex_lock(&Flash_Mutex);
	sf_sector_erase(5, FRU_FLASH_ADDR);
	sf_write(5, FRU_FLASH_ADDR, (uint8_t*)&g_BMCInfo.FRU, fruSize);
	pthread_mutex_unlock(&Flash_Mutex);
	return 0;
}

int GetFRUFromFlash()
{
	uint32_t	fruSize = sizeof(OemFRUData_T);
	pthread_mutex_lock(&Flash_Mutex);
	sf_read(5, FRU_FLASH_ADDR, (uint8_t*)&g_BMCInfo.FRU, fruSize);
	pthread_mutex_unlock(&Flash_Mutex);
	return 0;
}

int FlushSensorHistoryToFlash()
{
	uint32_t	writeLen = 0;
	uint32_t 	offset = 0;
	uint32_t	sensorSize = SENSOR_NUMBERS*sizeof(SensorHistoryInfo_T);

	pthread_mutex_lock(&Flash_Mutex);
	while(sensorSize > 0)
	{
		if(sensorSize > 4*1024)
			writeLen = 4*1024;
		else
			writeLen = sensorSize;

		sf_sector_erase(5, SENSOR_HISTORY_FLASH_ADDR+offset);
		sf_write(5, SENSOR_HISTORY_FLASH_ADDR+offset, ((uint8_t*)gSensorHistoryInfo)+offset, writeLen);
		offset += writeLen;
		sensorSize -= writeLen;
	}
	pthread_mutex_unlock(&Flash_Mutex);
	return 0;
}

int GetSensorHistoryFromFlash()
{
	uint32_t	sensorSize = SENSOR_NUMBERS*sizeof(SensorHistoryInfo_T);

	pthread_mutex_lock(&Flash_Mutex);
	sf_read(5, SENSOR_HISTORY_FLASH_ADDR, (uint8_t*)gSensorHistoryInfo, sensorSize);
	pthread_mutex_unlock(&Flash_Mutex);
	return 0;
}


int FlushUserInfoTbl(void)
{
	pthread_mutex_lock(&Flash_Mutex);
	sf_sector_erase(5, USERTBL_FLASH_ADDR);
	sf_write(5, USERTBL_FLASH_ADDR, (uint8_t*)g_BMCInfo.UserInfoTbl, sizeof(UserInfo_T)*MAX_USER_NUM);
	pthread_mutex_unlock(&Flash_Mutex);
	return 0;
}

int UpdateUserInfoTble(void)
{
	pthread_mutex_lock(&Flash_Mutex);
	sf_read(5, USERTBL_FLASH_ADDR, (uint8_t*)g_BMCInfo.UserInfoTbl, sizeof(UserInfo_T)*MAX_USER_NUM);
	pthread_mutex_unlock(&Flash_Mutex);
	return 0;
}


int UpdateFlash(void)
{
	FlushSDRToFlash();
	FlushSELToFlash();
	FlushIPMIToFlash();
	FlushFRUToFlash();
	return 0;
}