#include 	<sys/time.h>
#include 	<sys/timeb.h>
#include    <sys/types.h>
#include    <sys/stat.h>
#include 	<sys/types.h>
#include 	<sys/ioctl.h>
#include 	<sys/socket.h>
#include 	<sys/ipc.h>
#include 	<sys/shm.h>
#include 	<sys/shm.h>
#include 	<sys/mman.h>
#include 	<linux/wireless.h>
#include 	<arpa/inet.h>
#include 	<netinet/in.h>

#include 	<unistd.h>
#include 	<stdarg.h>
#include    <stdio.h>      /*標準輸入輸出定義*/
#include    <stdlib.h>     /*標準函數庫定義*/
#include    <unistd.h>     /*Unix 標準函數定義*/
#include    <fcntl.h>      /*檔控制定義*/
#include    <termios.h>    /*PPSIX 終端控制定義*/
#include    <errno.h>      /*錯誤號定義*/
#include 	<errno.h>
#include 	<string.h>
#include	<time.h>
#include	<ctype.h>
#include 	<ifaddrs.h>
#include 	<math.h>
#include	"../../define.h"
#include	"PrimaryComm.h"
#include 	<stdbool.h>
#include    "Config.h"

#define ARRAY_SIZE(A)		(sizeof(A) / sizeof(A[0]))
#define PASS				1
#define FAIL				-1
#define YES					1
#define NO					0

#define COMM_FAIL_COUNT     10

typedef unsigned char 		byte;

struct SysConfigAndInfo			*ShmSysConfigAndInfo;
struct StatusCodeData 			*ShmStatusCodeData;
struct PrimaryMcuData			*ShmPrimaryMcuData;
ChargerInfoData                 *ShmChargerInfo;

void trim(char *s);
int mystrcmp(char *p1,char *p2);
void substr(char *dest, const char* src, unsigned int start, unsigned int cnt);
void split(char **arr, char *str, const char *del);

int Uart1Fd;
char *priPortName = "/dev/ttyS1";
Ver ver;
Gpio_in gpio_in;
Rtc rtc;

struct timeval _flash_time;
byte _OutputDrv = 0;

byte _acStatus = 0;
byte _acChkCount = 0;
int _CommFailCount = 0;

void PRINTF_FUNC(char *string, ...);

int StoreLogMsg(const char *fmt, ...);
#define DEBUG_INFO(format, args...) StoreLogMsg("[%s:%d][%s][Info] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
#define DEBUG_WARN(format, args...) StoreLogMsg("[%s:%d][%s][Warn] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
#define DEBUG_ERROR(format, args...) StoreLogMsg("[%s:%d][%s][Error] "format, __FILE__, __LINE__, __FUNCTION__, ##args)

int StoreLogMsg(const char *fmt, ...)
{
	char Buf[4096+256];
	char buffer[4096];
	va_list args;
	struct timeb  SeqEndTime;
	struct tm *tm;

	va_start(args, fmt);
	int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
	va_end(args);

	memset(Buf,0,sizeof(Buf));
	ftime(&SeqEndTime);
	SeqEndTime.time = time(NULL);
	tm=localtime(&SeqEndTime.time);

	if (ShmSysConfigAndInfo->SysConfig.SwitchDebugFlag == YES)
	{
		sprintf(Buf,"%02d:%02d:%02d:%03d - %s",
			tm->tm_hour,tm->tm_min,tm->tm_sec,SeqEndTime.millitm, buffer);
		printf("%s \n", Buf);
	}
	else
	{
		sprintf(Buf,"echo \"%04d-%02d-%02d %02d:%02d:%02d:%03d - %s\" >> /Storage/SystemLog/[%04d.%02d]SystemLog",
			tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,SeqEndTime.millitm,
			buffer,
			tm->tm_year+1900,tm->tm_mon+1);
		system(Buf);
	}

	return rc;
}

int DiffTimeb(struct timeb ST, struct timeb ET)
{
	//return milli-second
	unsigned int StartTime,StopTime;

	StartTime=(unsigned int)ST.time;
	StopTime=(unsigned int)ET.time;
	return (StopTime-StartTime)*1000+ET.millitm-ST.millitm;
}

void PRINTF_FUNC(char *string, ...)
{
	va_list args;
	char buffer[4096];
	va_start(args, string);
	vsnprintf(buffer, sizeof(buffer), string, args);
	va_end(args);

	DEBUG_INFO("%s \n", buffer);
}
//=================================
// Common routine
//=================================
char* getTimeString(void)
{
	char *result=malloc(21);
	time_t timep;
	struct tm *p;
	time(&timep);
	p=gmtime(&timep);

	sprintf(result, "[%04d-%02d-%02d %02d:%02d:%02d]", (1900+p->tm_year), (1+p->tm_mon), p->tm_mday, p->tm_hour, p->tm_hour, p->tm_sec);

	return result;
}

void trim(char *s)
{
    int i=0, j, k, l=0;

    while((s[i]==' ')||(s[i]=='\t')||(s[i]=='\n'))
        i++;

    j = strlen(s)-1;
    while((s[j]==' ')||(s[j]=='\t')||(s[j]=='\n'))
        j--;

    if(i==0 && j==strlen(s)-1) { }
    else if(i==0) s[j+1] = '\0';
    else {
        for(k=i; k<=j; k++) s[l++] = s[k];
        s[l] = '\0';
    }
}

int mystrcmp(char *p1,char *p2)
{
    while(*p1==*p2)
    {
        if(*p1=='\0' || *p2=='\0')
            break;
        p1++;
        p2++;
    }
    if(*p1=='\0' && *p2=='\0')
        return(PASS);
    else
        return(FAIL);
}

void substr(char *dest, const char* src, unsigned int start, unsigned int cnt)
{
	strncpy(dest, src + start, cnt);
	dest[cnt] = 0;
}

void split(char **arr, char *str, const char *del)
{
	char *s = strtok(str, del);

	while(s != NULL)
	{
		*arr++ = s;
		s = strtok(NULL, del);
	}
}

//==========================================
// Init all share memory
//==========================================
int InitShareMemory()
{
	int result = PASS;
	int MeterSMId;

	//creat ShmSysConfigAndInfo
	if ((MeterSMId = shmget(ShmSysConfigAndInfoKey, sizeof(struct SysConfigAndInfo),  0777)) < 0)
    {
		#ifdef SystemLogMessage
		DEBUG_ERROR("shmget ShmSysConfigAndInfo NG\n");
		#endif
		result = FAIL;
	}
    else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0)) == (void *) -1)
    {
    	#ifdef SystemLogMessage
    	DEBUG_ERROR("shmat ShmSysConfigAndInfo NG\n");
		#endif
    	result = FAIL;
   	}

   	//creat ShmStatusCodeData
 	if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData),  0777)) < 0)
    {
		#ifdef SystemLogMessage
   		DEBUG_ERROR("shmget ShmStatusCodeData NG\n");
		#endif
   		result = FAIL;
	}
    else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
    {
    	#ifdef SystemLogMessage
    	DEBUG_ERROR("shmat ShmStatusCodeData NG\n");
		#endif
    	result = FAIL;
   	}

	//creat ShmStatusCodeData
	if ((MeterSMId = shmget(ShmPrimaryMcuKey, sizeof(struct PrimaryMcuData), 0777)) < 0)
	{
		#ifdef SystemLogMessage
		DEBUG_ERROR("shmget ShmPrimaryMcuData NG\n");
		#endif
		result = FAIL;
	}
	else if ((ShmPrimaryMcuData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
	{
		#ifdef SystemLogMessage
		DEBUG_ERROR("shmat ShmPrimaryMcuData NG\n");
		#endif
		result = FAIL;
	}

    if((MeterSMId = shmget(SM_ChargerInfoKey, sizeof(ChargerInfoData), 0777)) < 0)
    {
        #ifdef SystemLogMessage
        DEBUG_ERROR("shmat ChargerInfoData NG \n");
        #endif
        result = FAIL;
    }
    else if((ShmChargerInfo = shmat(MeterSMId, NULL, 0)) == (void *) -1)
    {
        #ifdef SystemLogMessage
        DEBUG_ERROR("shmat ChargerInfoData NG \n");
        #endif
        result = FAIL;
    }

    return result;
}

//================================================
// Function
//================================================
void GetFwAndHwVersion()
{
	if(Query_FW_Ver(Uart1Fd, Addr.IoExtend, &ver) == PASS)
	{
		PRINTF_FUNC("s1 = %s \n", ver.Version_FW);
		strcpy((char *)ShmPrimaryMcuData->version, ver.Version_FW);
		strcpy((char *) ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev, ver.Version_FW);
	}
	else
	{
	    _CommFailCount++;
	}

	if (Query_HW_Ver(Uart1Fd, Addr.IoExtend, &ver) == PASS)
	{
		PRINTF_FUNC("s2 = %s \n", ver.Version_HW);
	}
}

void GetInputGpioStatus()
{
	//PRINTF_FUNC("GetInputGpioStatus \n");
	if (Query_Gpio_Input(Uart1Fd, Addr.IoExtend, &gpio_in) == PASS)
	{
		if (_acStatus != gpio_in.AC_Connector)
		{
			if (_acChkCount >= 3)
			{
				_acStatus = gpio_in.AC_Connector;

				// DO360 AC_Connector Status is the inverse of DS's
				if(ShmChargerInfo->Control.PrimaryCtrl.bits.AcContactorReverse)
				{
				    ShmSysConfigAndInfo->SysInfo.AcContactorStatus = gpio_in.AC_Connector ? 0 : 1;
				    ShmPrimaryMcuData->InputDet.bits.AcContactorDetec = gpio_in.AC_Connector ? 0 : 1;
				}
				else
				{
                    ShmSysConfigAndInfo->SysInfo.AcContactorStatus = gpio_in.AC_Connector ? 1 : 0;
                    ShmPrimaryMcuData->InputDet.bits.AcContactorDetec = gpio_in.AC_Connector ? 1 : 0;
				}
				PRINTF_FUNC("Ac Contactor Status %s", ShmPrimaryMcuData->InputDet.bits.AcContactorDetec > 0 ? "On" : "Off");
			}
			else
				_acChkCount++;
		}
		else
			_acChkCount = 0;

		ShmPrimaryMcuData->InputDet.bits.AcMainBreakerDetec = gpio_in.AC_MainBreaker;
		ShmPrimaryMcuData->InputDet.bits.SpdDetec = gpio_in.SPD;

		// DO360 Door Status is the inverse of DS's
		if(ShmChargerInfo->Control.PrimaryCtrl.bits.DoorSensorReverse)
		{
		    ShmPrimaryMcuData->InputDet.bits.DoorOpen = gpio_in.Door_Open ? 0 : 1;
		}
		else
		{
		    ShmPrimaryMcuData->InputDet.bits.DoorOpen = gpio_in.Door_Open ? 1 : 0;
		}

		// Bypass door open
		//ShmPrimaryMcuData->InputDet.bits.DoorOpen = 0;

		ShmPrimaryMcuData->InputDet.bits.Button1 = gpio_in.Button[0];
		ShmPrimaryMcuData->InputDet.bits.Button2 = gpio_in.Button[1];
		ShmPrimaryMcuData->InputDet.bits.EmergencyButton = gpio_in.Emergency_Btn;

		//PRINTF_FUNC("left = %d \n", ShmPrimaryMcuData->InputDet.bits.Button1);
		//PRINTF_FUNC("right = %d \n", ShmPrimaryMcuData->InputDet.bits.Button2);
		//PRINTF_FUNC("ShmSysConfigAndInfo->SysInfo.AcContactorStatus = %d \n", ShmSysConfigAndInfo->SysInfo.AcContactorStatus);
		//if (ShmPrimaryMcuData->InputDet.bits.AcMainBreakerDetec == YES)
		//	DEBUG_ERROR("AC Mainbreaker occur. \n");
	}
}

void SetOutputGpio(byte flash)
{
	Gpio_out gpio;

	if(_OutputDrv != flash)
	{
        gpio.Button_LED[0] = (flash & 0x01) > 0 ? 1 : 0;
        gpio.Button_LED[1] = (flash & 0x02) > 0 ? 1 : 0;
        gpio.System_LED[0] = (flash & 0x04) > 0 ? 1 : 0;
        gpio.System_LED[1] = (flash & 0x08) > 0 ? 1 : 0;
        gpio.System_LED[2] = (flash & 0x10) > 0 ? 1 : 0;
        gpio.System_LED[3] = (flash & 0x20) > 0 ? 1 : 0;
        gpio.AC_Connector  = (flash & 0x40) > 0 ? 1 : 0;
        gpio.AC_Breaker    = (flash & 0x80) > 0 ? 1 : 0;

        if (Config_Gpio_Output(Uart1Fd, Addr.IoExtend, &gpio) == PASS)
        {
            _OutputDrv = flash;
        }
	}
	else
	{
	    // do nothing when no change
	}
}

void SetRtcData()
{
	struct timeb csuTime;
	struct tm *tmCSU;

	ftime(&csuTime);
	tmCSU = localtime(&csuTime.time);
//	PRINTF_FUNC("Time : %04d-%02d-%02d %02d:%02d:%02d \n", tmCSU->tm_year + 1900,
//			tmCSU->tm_mon + 1, tmCSU->tm_mday, tmCSU->tm_hour, tmCSU->tm_min,
//			tmCSU->tm_sec);

	rtc.RtcData[0] = '0' + (tmCSU->tm_year + 1900) / 1000 % 10;
	rtc.RtcData[1] = '0' + (tmCSU->tm_year + 1900) / 100 % 10;
	rtc.RtcData[2] = '0' + (tmCSU->tm_year + 1900) / 10 % 10;
	rtc.RtcData[3] = '0' + (tmCSU->tm_year + 1900) / 1 % 10;

	rtc.RtcData[4] = '0' + (tmCSU->tm_mon + 1) / 10 % 10;
	rtc.RtcData[5] = '0' + (tmCSU->tm_mon + 1) / 1 % 10;

	rtc.RtcData[6] = '0' + (tmCSU->tm_mday) / 10 % 10;
	rtc.RtcData[7] = '0' + (tmCSU->tm_mday) / 1 % 10;

	rtc.RtcData[8] = '0' + (tmCSU->tm_hour) / 10 % 10;
	rtc.RtcData[9] = '0' + (tmCSU->tm_hour) / 1 % 10;

	rtc.RtcData[10] = '0' + (tmCSU->tm_min) / 10 % 10;
	rtc.RtcData[11] = '0' + (tmCSU->tm_min) / 1 % 10;

	rtc.RtcData[12] = '0' + (tmCSU->tm_sec) / 10 % 10;
	rtc.RtcData[13] = '0' + (tmCSU->tm_sec) / 1 % 10;

	if (Config_Rtc_Data(Uart1Fd, Addr.IoExtend, &rtc) == PASS)
	{
		//PRINTF_FUNC("SetRtc sucessfully. \n");
	}
	else
	{
		//PRINTF_FUNC("SetRtc fail. \n");
	}
}

//================================================
// Main process
//================================================
int InitComPort()
{
	int fd;
	struct termios tios;

	fd = open(priPortName, O_RDWR);
	if(fd<=0)
	{
		#ifdef SystemLogMessage
		DEBUG_ERROR("open 407 Communication port NG \n");
		#endif
		return -1;
	}
	ioctl (fd, TCGETS, &tios);
	tios.c_cflag = B115200| CS8 | CLOCAL | CREAD;
	tios.c_lflag = 0;
	tios.c_iflag = 0;
	tios.c_oflag = 0;
	tios.c_cc[VMIN]=0;
	tios.c_cc[VTIME]=(unsigned char)1;
	tios.c_lflag=0;
	tcflush(fd, TCIFLUSH);
	ioctl (fd, TCSETS, &tios);

	return fd;
}

unsigned long GetTimeoutValue(struct timeval _sour_time)
{
	struct timeval _end_time;
	gettimeofday(&_end_time, NULL);

	return 1000000 * (_end_time.tv_sec - _sour_time.tv_sec) + _end_time.tv_usec - _sour_time.tv_usec;
}

int main(void)
{
	if(InitShareMemory() == FAIL)
	{
		#ifdef SystemLogMessage
		DEBUG_ERROR("InitShareMemory NG\n");
		#endif
		if(ShmStatusCodeData!=NULL)
		{
			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory = 1;
		}
		sleep(5);
		return 0;
	}
	Uart1Fd = InitComPort();
	PRINTF_FUNC("407 Port id = %d \n", Uart1Fd);

	if(Uart1Fd < 0)
	{
		#ifdef SystemLogMessage
		DEBUG_ERROR("InitComPort (Uart1 : AM3352 - STM32) NG");
		#endif

		if (ShmStatusCodeData != NULL)
		{
			ShmStatusCodeData->AlarmCode.AlarmEvents.bits.CsuInitFailed = 1;
		}
		sleep(5);
		return 0;
	}

	SetRtcData();
	gettimeofday(&_flash_time, NULL);

	// update ac contact status
	//_acStatus = ShmSysConfigAndInfo->SysInfo.AcContactorStatus;
	_acStatus = ShmSysConfigAndInfo->SysInfo.AcContactorStatus > 0 ? 0 : 1;

	// set wrong value, it will update at the first time
	_OutputDrv = ~ShmPrimaryMcuData->OutputDrv.OutputDrvValue[0];

	for(;;)
	{
	    if(!ShmSysConfigAndInfo->SysInfo.FirmwareUpdate)
	    {
            // 程序開始之前~ 必須先確定 FW 版本與硬體版本,確認後!!~ 該模組才算是真正的 Initial Comp.
            // 模組更新 FW 後,需重新做
            if(ShmPrimaryMcuData->SelfTest_Comp != PASS)
            {
                memset(ShmPrimaryMcuData->version, 0x00, 16);

                GetFwAndHwVersion();
                sleep(1);

                if(strlen((char *)ShmPrimaryMcuData->version) != 0)
                {
                    ShmPrimaryMcuData->SelfTest_Comp = YES;
                }

                if(_CommFailCount >= COMM_FAIL_COUNT)
                {
                    PRINTF_FUNC("Primary MCU Communication Fail: %d", _CommFailCount);
                    _CommFailCount = 0;
                }
            }
            else
            {
                GetInputGpioStatus();
                //PRINTF_FUNC("Input Status: %02X %02X", ShmPrimaryMcuData->InputDet.InputDetValue[1], ShmPrimaryMcuData->InputDet.InputDetValue[0]);

                SetOutputGpio(ShmPrimaryMcuData->OutputDrv.OutputDrvValue[0]);
            }
	    }
		usleep(100000);
	}

	return FAIL;
}