/*
* bmc_app application main code.
*/



#include <stdio.h>
#include <stdint.h>
#include <sys/prctl.h>
#include <semaphore.h>
#include <pthread.h>
#include <stdlib.h>
//#include <fcntl.h>
#include "linux/fcntl.h"
#include <signal.h>
#include <sys/time.h>

#include "com_BmcType.h"
#include "com_IPMIDefs.h"
#include "com_Message.h"

#include "BmcType.h"
#include "main.h"
#include "Session.h"

#include "LANIfc.h"
#include "UDSIfc.h"
#include "IPMBIfc.h"
#include "MsgHndlrTask.h"
#include "ChassisTimerTask.h"
#include "TimerTask.h"
#include "CM_LIB.h"
#include "stm32f429xx.h"
#include "com_gpio.h"
#include "hal_interface_api.h"
#include "com_BMCCfg.h"
#include "PendActionTask.h"
#include "Api.h"
#include "driver.h"
#include "sensor_tbl.h"
#include "com_IPMI_SDRRecord.h"
#include "AuthLicense.h"


/* gloabl varible */
BMCInfo_t 	g_BMCInfo;
pthread_t 	gThreadIDs[256];
uint8_t		gThreadIndex = 0;
uint8_t 	gChassisIPMBAddr[BLADE_NUMBERS] = {0x82, 0x84, 0x86, 0x88, 0x8A, 0x8C,
											   0x8E, 0x90, 0x92, 0x94}; 
SensorHistoryInfo_T 	gSensorHistoryInfo[SENSOR_NUMBERS];

FanInfo_T	gFanInfo[FAN_NUMBERS] = {
								// /* Index | name | mode | level | speed  */
								// 	{0, {"Fan1"}, 0, 0, 0 },
								// 	{1, {"Fan2"}, 0, 0, 0 },
								// 	{2, {"Fan3"}, 0, 0, 0 },
								// 	{3, {"Fan4"}, 0, 0, 0 },
								};
BladeStatus_T gBladeStatus[BLADE_NUMBERS] = {
								/*  healthStatus | name | slotID | pwrStatus */
									{ 0, "---", 0, 0},
									{ 0, "---", 0, 0},
									{ 0, "---", 0, 0},
									{ 0, "---", 0, 0},
									{ 0, "---", 0, 0},
									{ 0, "---", 0, 0},
									{ 0, "---", 0, 0},
									{ 0, "---", 0, 0},
									{ 0, "---", 0, 0},
									{ 0, "---", 0, 0},
								};
//void *test_thread(void *var);
//uint8_t test_flag = 0;



static int tmp_fd;
void main(void)
{
// 	if(0 != cm_Auth_Encrp_Init(1, 1, TRUE))
// 	{
// 		printf("Initialize AT88SC0104C failed!\n");
// 		sleep(1);
// 		return;
// 	}
// 	printf("cm_Auth_Encrp_Init ok\n");

// #if 0
// 	if(0 != cm_Auth_Encrp_Personal(1, 1))
// 	{
// 		printf("Personal AT88SC0104C failed!\n");
// 		sleep(1);
// 		return ;
// 	}
// #endif

// 	if(0 != test_cryptomem())
// 	{
// 		while(1)
// 		{
// 			printf("Illegal Board!\n");
// 			sleep(3);
// 		}
// 	}

	//检查软件授权
	// if(CheckLicense() != 0)
	// {
	// 	system("killall -9 damon.sh");
	// 	exit(0);
	// }

	PlatformInit();
	Init_IPMI_FRU_SDR_SEL();
	Init_SessionTbl();
	InitTimerTaskTbl();

	pthread_mutex_init(&api_bridge_mutex, NULL);
	pthread_mutex_init(&Flash_Mutex, NULL);

	//初始化系统时间
	system("date -s 2020.05.12-00:00:00");

	//Initialize IP
	char cmdStr[100];
	LanInfo_T *pSetLanInfo = &g_BMCInfo.LanInfo[0];
	// //down
	// sprintf(cmdStr, "ifconfig %s down", pSetLanInfo->EthName);
	// printf("%s\n", cmdStr);
	// system(cmdStr);
	// //set mac
	// sprintf(cmdStr, "ifconfig %s hw ether %02x:%02x:%02x:%02x:%02x:%02x", 
	// 	pSetLanInfo->EthName, pSetLanInfo->MACAddr[0], pSetLanInfo->MACAddr[1],
	// 	pSetLanInfo->MACAddr[2], pSetLanInfo->MACAddr[3], 
	// 	pSetLanInfo->MACAddr[4], pSetLanInfo->MACAddr[5]);
	// printf("%s\n", cmdStr);
	// system(cmdStr);
	//ip, broadcast, netmask
	sprintf(cmdStr, "ifconfig %s %d.%d.%d.%d broadcast %d.%d.%d.%d netmask %d.%d.%d.%d up",
		pSetLanInfo->EthName, pSetLanInfo->IPAddr[0], pSetLanInfo->IPAddr[1],
		pSetLanInfo->IPAddr[2], pSetLanInfo->IPAddr[3], pSetLanInfo->BroadCast[0],
		pSetLanInfo->BroadCast[1], pSetLanInfo->BroadCast[2], pSetLanInfo->BroadCast[3],
		pSetLanInfo->NetMask[0], pSetLanInfo->NetMask[1], pSetLanInfo->NetMask[2],
		pSetLanInfo->NetMask[3]);
	printf("%s\n", cmdStr);
	system(cmdStr);

	printf("\tChassisID %#02x, SlotID %#02x\r\n", g_BMCInfo.ChassisID, g_BMCInfo.SlotID);
	if(g_BMCInfo.IpmiConfig.PrimaryIPMBSupport)
	{
		printf("\tPrimaryIPMBBus: %d, channel %d, Addr %#02x\n", g_BMCInfo.IpmiConfig.PrimaryIPMBBus, 
			PRIMARY_IPMB_CHANNEL, g_BMCInfo.PrimaryIPMBAddr);
	}
	if(g_BMCInfo.IpmiConfig.SecondaryIPMBSupport)
	{
		printf("\tSecondaryIPMBBus %d, Channel %d, Addr %#02x\n", g_BMCInfo.IpmiConfig.SecondaryIPMBBus,
			SECONDARY_IPMB_CHANNEL, g_BMCInfo.SecondaryIPMBAddr);
	}

	/* Create TimerTask */
	// gThreadIndex = 0;
	// if(0 != pthread_create(&gThreadIDs[gThreadIndex],NULL,TimerTask,NULL))
 //    {
 //        printf("%s: Create TimerTask thread failed!\n", __FUNCTION__);
 //    }
	signal(SIGALRM, TimerTask);

    struct itimerval new_value;
    new_value.it_value.tv_sec = 0;
    new_value.it_value.tv_usec = 1;
    new_value.it_interval.tv_sec = 1;
    new_value.it_interval.tv_usec = 0;
    setitimer(ITIMER_REAL, &new_value, NULL);


	/* Create MsgHndlr Task */
	gThreadIndex++;
	if(0 != pthread_create(&gThreadIDs[gThreadIndex],NULL,MsgHndlrTask,NULL))
    {
        printf("%s: Create MsgHndlrTask thread failed!\n", __FUNCTION__);
    }

    /* Create ChassisTimerTask */
	gThreadIndex++;
	if(0 != pthread_create(&gThreadIDs[gThreadIndex],NULL,ChassisTimerTask,NULL))
    {
        printf("%s: Create ChassisTimerTask thread failed!\n", __FUNCTION__);
    }

   /* Create SensorMonitorTask */
	gThreadIndex++;
	if(0 != pthread_create(&gThreadIDs[gThreadIndex],NULL,SensorMonitorTask,NULL))
   {
       printf("%s: Create SensorMonitorTask thread failed!\n", __FUNCTION__);
   }

	/* Create UDS interface */
	gThreadIndex++;
	if(0 != pthread_create(&gThreadIDs[gThreadIndex],NULL,UDSIfcTask,NULL))
    {
        printf("%s: Create UDSIfcTask thread failed!\n", __FUNCTION__);
    }

	/* Create LAN interface */
	gThreadIndex++;
	if(0 != pthread_create(&gThreadIDs[gThreadIndex],NULL,LANIfcTask,NULL))
    {
        printf("%s: Create LANIfcTask thread failed!\n", __FUNCTION__);
    }

	/* Create IPMB interface */
	uint8_t primaryIpmbSelect = 0;	//primary
	gThreadIndex++;
	if(0 != pthread_create(&gThreadIDs[gThreadIndex],NULL,IPMBIfcTask,&primaryIpmbSelect))
  {
      printf("%s: Create LANIfcTask thread failed!\n", __FUNCTION__);
  }

  uint8_t secondaryIpmbSelect = 1;	//secondary
  gThreadIndex++;
  if(0 != pthread_create(&gThreadIDs[gThreadIndex],NULL,IPMBIfcTask,&secondaryIpmbSelect))
  {
      printf("%s: Create LANIfcTask thread failed!\n", __FUNCTION__);
  }

    /* Create PendActionTask */
	gThreadIndex++;
	if(0 != pthread_create(&gThreadIDs[gThreadIndex],NULL,PendActionTask,NULL))
    {
        printf("%s: Create PendActionTask thread failed!\n", __FUNCTION__);
    }

	/* Create Update FPGA thread */

	/* Create UDS interface */

	/* Create UDS interface */

	/* Create UDS interface */

    // pthread_mutex_init(&mutex,NULL);
    // tmp_fd = open("/dev/i2c2", O_RDWR);;
    // uint8_t buf[7] = {0x20, 0xb8, 0x8, 0x20, 0x4, 0x1, 0xdb };
    // gThreadIndex++;
    // pthread_create(&gThreadIDs[gThreadIndex],NULL,test_thread,NULL);

    /* 看门狗，10s无喂狗就复位 */
    // int fd_iwdg = open("/dev/iwdg", O_RDWR);
    // ioctl(fd_iwdg, START_IWATCHDOG, NULL);       //打开看狗      

	while(1)	//在这里实现各线程的健康状态检测，发现出错的线程就重启它。
	{
		// //喂看门狗
	 //    if(ioctl(fd_iwdg, FEED_WATCHDOG, NULL) != 0)
	 //    {
	 //            printf("---> Feed watchdog failed\n");
	 //    }

		sleep(10);
	}
}

// void *test_thread(void *var)
// {
// 	uint8_t len, i;
// 	uint8_t recvBuf[100];
// 	printf("---> test_thread start...\n");
// 	stm32_i2c_set_addr(tmp_fd, 0x44);
// 	uint8_t buf[7] = {0x20, 0xb8, 0x8, 0x20, 0x4, 0x1, 0xdb };
// 	while(1)
// 	{
// 		pthread_mutex_lock(&mutex);
// 		pthread_mutex_unlock(&mutex);
// 		len = 0;
//     	len = stm32_i2c_slave_recv(tmp_fd, recvBuf);
//     	if(len > 0)
//     	{
// 	    	printf("Recv: ");
// 	    	for(i=0;i<len; i++)
// 	    		printf("%#x ", recvBuf[i]);
// 	    	printf("\n");

// 	    	test_flag = 1;
// 	    	//sleep(1);
// 	  //   	if(0 != stm32_i2c_master_write(tmp_fd, buf[0], &buf[1], 6))
// 			// {
// 			// 	printf("---> Send ipmb error!\n");
// 			// }
// 			// else
// 			// 	printf("---> send ipmb ok\n");
// 		}
// 	}


// }