/*-------------------------------------------------------------------------
   AR1688 Serial function copy right information

   Copyright (c) 2007-2015. Lin, Rongrong <woody@palmmicro.com>

   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of Palmmicro nor the names of its contributors may be
	  used to endorse or promote products derived from this software without
	  specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   DISCLAIMED. IN NO EVENT SHALL COPYRIGHT OWNER BE LIABLE FOR ANY
   DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-------------------------------------------------------------------------*/

#include "version.h"
#include "type.h"
#include "ar168.h"
#include "core.h"
#include "apps.h"

#include "bank1.h"

#ifdef OEM_YEDZ
#include "sip.h"
#endif

#ifdef SYS_UART
volatile UCHAR Serial_iRecvHead, Serial_iRecvTail;
volatile UCHAR Serial_pRecv[SERIAL_BUF_SIZE_RX];

#ifdef SERIAL_UI

//#define SERIAL_STRING_SIZE	64		// max string length to handle
#define SERIAL_STRING_SIZE	48		// max string length to handle

UCHAR Serial_iSendHead, Serial_iSendTail;
UCHAR Serial_pSend[SERIAL_BUF_SIZE_TX];

PCHAR _pUnHandledData;
UCHAR _iUnHandledLen;

#ifdef OEM_YEDZ
extern UCHAR CPU_PTT_FLAG;
extern UCHAR CPU_COR_FLAG;
extern UCHAR CPU_DTMF_KEY;

extern UCHAR  CPU_PTT_sensitity ;
extern USHORT CPU_PTT_HANGTIME  ;
extern USHORT CPUT_PTT_INHIBITTIME ;
extern UCHAR  CPU_COR_TYPE      ;
extern UCHAR  CPU_COR_SENSITITY ;  
extern USHORT CPU_COR_HANGTIME ;
extern USHORT CPU_COR_INHIBITTIME;
extern UCHAR  CPU_COR_PRIORITY   ;
extern UCHAR  CPU_AUDIO_RCV_GAIN ;
extern UCHAR  CPU_AUDIO_TRAN_GAIN ;
extern UCHAR  CPU_DTMF_ENABLE   ;
 
extern BOOLEAN  _bMute;
#endif

void SerialInit()
{
	Serial_iSendHead = 0;
	Serial_iSendTail = SERIAL_BUF_SIZE_TX - 1;
	Serial_iRecvHead = 0;
	Serial_iRecvTail = SERIAL_BUF_SIZE_RX - 1;

	_pUnHandledData = NULL;
	_iUnHandledLen = 0;

	UART_Init(78, FALSE);	// 19200 bps, 8 bit data, 1 bit stop, no parity
}

#define SERIAL_COMMAND_LEN	4

const UCHAR _pStat[] = "STAT";
const UCHAR _pText[] = "TEXT";

#ifdef OEM_YEDZ
void SerialUI_Event(UCHAR iType,UCHAR iParam)
#else
void SerialUI_Event(UCHAR iType)
#endif
{
	UCHAR pBuf[SERIAL_COMMAND_LEN + 4];

	strcpy(pBuf, _pStat);
	itoa(iType, (PCHAR)(pBuf + SERIAL_COMMAND_LEN), 10);
	SerialSendString(pBuf);
#ifdef OEM_YEDZ
	if(iType==45)
	{
		strcpy(pBuf, "Dtmf");
		pBuf[4]=iParam;
		pBuf[5]=0; 
		SerialSendString(pBuf);
	}
#endif
//	UdpDebugString(pBuf);
}

#ifdef OEM_YEDZ
void _SendPara()
{
	char pBuf[20];
	char pSendBuf[228];
	
	
	
	
	
	strcpy(pSendBuf,"PTT_sensitity=");
	itoa(CPU_PTT_sensitity, (PCHAR)(pBuf), 10);
	strcat(pSendBuf,pBuf);
	
	strcat(pSendBuf,",PTT_HANGTIME=");
	itoa(CPU_PTT_HANGTIME, (PCHAR)(pBuf), 10);
	strcat(pSendBuf,pBuf);
	
	strcat(pSendBuf,",PTT_INHIBITTIME=");
	itoa(CPUT_PTT_INHIBITTIME, (PCHAR)(pBuf), 10);
	strcat(pSendBuf,pBuf);
	
	strcat(pSendBuf,",COR_TYPE=");
	itoa(CPU_COR_TYPE, (PCHAR)(pBuf), 10);
	strcat(pSendBuf,pBuf);
	
	strcat(pSendBuf,",COR_SENSITITY=");
	itoa(CPU_COR_SENSITITY, (PCHAR)(pBuf), 10);
	strcat(pSendBuf,pBuf);
	
	strcat(pSendBuf,",COR_HANGTIME=");
	itoa(CPU_COR_HANGTIME, (PCHAR)(pBuf), 10);
	strcat(pSendBuf,pBuf);
	
	strcat(pSendBuf,",COR_INHIBITTIME=");
	itoa(CPU_COR_INHIBITTIME, (PCHAR)(pBuf), 10);
	strcat(pSendBuf,pBuf);
	
	strcat(pSendBuf,",COR_PRIORITY=");
	itoa(CPU_COR_PRIORITY, (PCHAR)(pBuf), 10);
	strcat(pSendBuf,pBuf);
	
	strcat(pSendBuf,",AUDIO_RCV_GAIN=");
	itoa(CPU_AUDIO_RCV_GAIN, (PCHAR)(pBuf), 10);
	strcat(pSendBuf,pBuf);
	
	strcat(pSendBuf,",AUDIO_TRAN_GAIN=");
	itoa(CPU_AUDIO_TRAN_GAIN, (PCHAR)(pBuf), 10);
	strcat(pSendBuf,pBuf);
	

	
	 
	strcat(pSendBuf,",DTMF_ENABLE=");
	itoa(CPU_DTMF_ENABLE, (PCHAR)(pBuf), 10);
	strcat(pSendBuf,pBuf);  	
	strcat(pSendBuf,",\r\n");
	
	
	
	
TaskSerialSendString(pSendBuf); //ye add
 
	
	

	
	
}
void strToIp(char* mstrIp, unsigned char Ip[])
{
	char tmp[10];
	char strIp[20];
	char* point;
	int index=0;
	int first=0;
	int i=0;
	strcpy(strIp,mstrIp);
	while (i<=3)
	{
		point=strchr((const char*)(strIp+first),'.');
		if(point!=NULL)
			index=point-strIp;
		else
			index=-1;
		if(index!=-1)
		{
			*point=0;
			strcpy(tmp,strIp+first);
			tmp[index-first]=0;
			first=index+1;
			Ip[i]=atoi(tmp,10);
			i++;
		}else
		{
			strcpy(tmp,strIp+first);
			tmp[strlen(strIp)-first]=0;
			Ip[i]=atoi(tmp,10);
			i++;
			return;
		}
	}
}
void _SendSipPara()
{
	char pBuf[20];
	char pSendBuf[230];
	
	
	
	
	
	strcpy(pSendBuf,"IPTYPE=");
	itoa(Sys_iIpType, (PCHAR)(pBuf), 10);
	strcat(pSendBuf,pBuf);
	
	strcat(pSendBuf,",IPADDR=");
	itoa(Sys_pIpAddress[0], (PCHAR)(pBuf), 10);
	strcat(pSendBuf,pBuf);
	strcat(pSendBuf,"."); 
	
	itoa(Sys_pIpAddress[1], (PCHAR)(pBuf), 10);
	strcat(pSendBuf,pBuf);
	strcat(pSendBuf,"."); 
	
	itoa(Sys_pIpAddress[2], (PCHAR)(pBuf), 10);
	strcat(pSendBuf,pBuf);
	strcat(pSendBuf,"."); 
	
	itoa(Sys_pIpAddress[3], (PCHAR)(pBuf), 10);
	strcat(pSendBuf,pBuf);
	  
	strcat(pSendBuf,",MASK=");
	itoa(Sys_pSubnetMask[0], (PCHAR)(pBuf), 10);
	strcat(pSendBuf,pBuf);
	strcat(pSendBuf,"."); 
	
	itoa(Sys_pSubnetMask[1], (PCHAR)(pBuf), 10);
	strcat(pSendBuf,pBuf);
	strcat(pSendBuf,"."); 
	
	itoa(Sys_pSubnetMask[2], (PCHAR)(pBuf), 10);
	strcat(pSendBuf,pBuf);
	strcat(pSendBuf,"."); 
	
	itoa(Sys_pSubnetMask[3], (PCHAR)(pBuf), 10);
	strcat(pSendBuf,pBuf);
	 
	

	
	strcat(pSendBuf,",DOMAIN=");
	 
	strcat(pSendBuf,Sys_pSipDomain);
	strcat(pSendBuf,",\r\n");
	 
 TaskSerialSendString(pSendBuf); //ye add
}
void _SendSipPara1()
{
	char pBuf[20];
	char pSendBuf[250];
	strcpy(pSendBuf,"PROXY=");


	 
	
	
	
	
	
	itoa(Sys_pRouterIp[0], (PCHAR)(pBuf), 10);
	strcat(pSendBuf,pBuf);
	strcat(pSendBuf,"."); 
	
	itoa(Sys_pRouterIp[1], (PCHAR)(pBuf), 10);
	strcat(pSendBuf,pBuf);
	strcat(pSendBuf,"."); 
	
	itoa(Sys_pRouterIp[2], (PCHAR)(pBuf), 10);
	strcat(pSendBuf,pBuf);
	strcat(pSendBuf,"."); 
	
	itoa(Sys_pRouterIp[3], (PCHAR)(pBuf), 10);
	strcat(pSendBuf,pBuf);
	
	
	
	
	
	
	strcat(pSendBuf,",USER=");
	 
	strcat(pSendBuf,Sys_pUserNumber);
	
	strcat(pSendBuf,",PASS=");
	 
	strcat(pSendBuf,Sys_pAuthPin);
	


	strcat(pSendBuf,",\r\n");
	
	
	
	
TaskSerialSendString(pSendBuf); //ye add
 
	
	

	
	
}
#endif

void SerialUI_DisplayMsg(PCHAR pMsg)
{
	if (!memcmp(pMsg, _pText, SERIAL_COMMAND_LEN))
	{
#ifdef SYS_DEBUG
		UdpDebugString("Send Serial TEXT");
#endif		
		SerialSendString(pMsg);
	}
#ifdef SYS_DEBUG
	else
	{
		UdpDebugString("Unknown Serial TEXT");
		UdpDebugString(pMsg);
	}
#endif
}

void _SerialProcessString(PCHAR pStr)
{
#ifdef OEM_YEDZ
//	UCHAR pBuf[10 + 4];//ye add
unsigned char ip[MAX_DNS_LEN+1];
	// Simply call UdpDebugString();
//	UdpDebugString(pStr);
	if (!memcmp_str(pStr, "LOOP"))
	{
		UdpDebugString(pStr);
		return;
	}
	if(!memcmp_str(pStr, "CLEAR STATE"))
	{
		Sys_iMissedCalls=0;
		return;
	}
#endif

	if (!memcmp_str(pStr, "KEY "))
	{
#if defined SYS_DEBUG || defined OEM_YEDZ
		UdpDebugString("Serial KEY");
#endif		
		UI_HandleKeys(pStr[SERIAL_COMMAND_LEN]);
		return;
	}
#ifdef OEM_YEDZ
	if (!memcmp_str(pStr, "PTTCOR="))
	{
		 
			CPU_PTT_FLAG=pStr[7];
			CPU_COR_FLAG=pStr[8];
			TaskSntpSendQuery();
			return;
	}
	if (!memcmp_str(pStr, "GETPARA"))
	{
		 
			_SendPara();
			return;
			
		
	}if (!memcmp_str(pStr, "MUTE"))
	{
		 
			_bMute=FALSE;//Æô¶¯¾²Òô
			OnMute();
			return;
			
		
	}if (!memcmp_str(pStr, "OPENMIC"))
	{
		 
			_bMute=TRUE;//Æô¶¯¾²Òô
			OnMute();
			return;
			
		
	}
	if (!memcmp_str(pStr, "GETSIP"))
	{
		 
			
			_SendSipPara();
			return;
		
	}
	if (!memcmp_str(pStr, "GET_SIP1"))
	{
		 
			
			_SendSipPara1();
			return;
		
	}
	if (!memcmp_str(pStr, "DTMF="))
	{
		 
			CPU_DTMF_KEY=pStr[5];
			TaskSntpSendDTMF();
			//SipOutgoingKey((UCHAR)pStr[5]);
			//TaskSntpSendQuery();
			return;
	}
	if (!memcmp_str(pStr, "OUTVOL="))
	{
		 
			
			Sys_iHandsetVol=pStr[7];
			CodecSetVol(Sys_iHandsetVol);
			return;
		
	}
	if (!memcmp_str(pStr, "INVOL="))
	{
		 
			 
			CodecSetInputVol(pStr[6]); 
			return;
		
	}
	if (!memcmp_str(pStr, "SETIPAD="))
	{
		 
			//unsigned char ip[4];
 	 		strToIp(pStr+8,ip); 
			 
			SetData(ip,OPT_IP_ADDRESS,4);
			FlashReboot();
			return;
 
	}
	if (!memcmp_str(pStr, "SETIPTYPE="))
	{
		 	//unsigned char ip[4];
			ip[0]=pStr[10]-0x30; 
			SetData(ip,OPT_IP_TYPE,1);
			FlashReboot();
 			return;
	}
	if (!memcmp_str(pStr, "SETDOMAIN="))
	{
 	 		
 	 		memset(ip,0,MAX_DNS_LEN);
 	 		strcpy(ip,pStr+10);
			SetData(ip,OPT_SIP_PROXY,MAX_DNS_LEN); 
			SetData(ip,OPT_SIP_DOMAIN,MAX_DNS_LEN);
			FlashReboot();
 			return;
	}
	if (!memcmp_str(pStr, "SETPROXY="))
	{
 	 		
 	 		strToIp(pStr+9,ip); 
 	 		 
			SetData(ip,OPT_ROUTER_IP,4);
			 
			FlashReboot();
 			return;
	}
	 if (!memcmp_str(pStr, "SETMASK="))
	{
 	 	
 	 		//unsigned char ip[4];
 	 		strToIp(pStr+8,ip);
			SetData(ip,OPT_SUBNET_MASK,4);
			FlashReboot();
 			return;
	} 
	if (!memcmp_str(pStr, "SETUSER="))
	{
 	 		//unsigned char ip[MAX_USER_NUMBER_LEN+1];
 	 		memset(ip,0,MAX_USER_NUMBER_LEN);
 	 		strcpy(ip,pStr+8);
			SetData(ip,OPT_AUTH_ID,MAX_USER_NUMBER_LEN);
			SetData(ip,OPT_USER_NUMBER,MAX_USER_NUMBER_LEN);
			FlashReboot();
 			return;
	} 
	if (!memcmp_str(pStr, "SETPIN="))
	{
 	 		//unsigned char ip[MAX_AUTH_PIN_LEN+1];
 	 		memset(ip,0,MAX_AUTH_PIN_LEN);
 	 		strcpy(ip,pStr+7);
			SetData(ip,OPT_AUTH_PIN,MAX_AUTH_PIN_LEN);
			FlashReboot();
 			return;
	}
#endif

	if (!memcmp_str(pStr, _pText))
	{
#if defined SYS_DEBUG || defined OEM_YEDZ
		UdpDebugString("Receive Serial TEXT");
#endif		
		TaskHandleEvent(UI_EVENT_TEXT, (USHORT)pStr);
		return;
	}

#ifndef OEM_YEDZ
	if (!memcmp_str(pStr, "LOOP"))
	{	// debug LOOP
		UdpDebugString(pStr);
		return;
	}
#endif

#ifdef SYS_DEBUG
	// debug other unknown string
	UdpDebugString(pStr);
#endif
}

BOOLEAN _SerialHandleString(PCHAR pBuf, UCHAR iLen)
{
	UCHAR iTotal;
	PCHAR p;

	if (_iUnHandledLen)
	{	// Has old unhandled data, we do not support remalloc, so need to malloc a larger buffer again
		iTotal = _iUnHandledLen + iLen;
		if (iTotal >= SERIAL_STRING_SIZE)
		{	// must be something wrong
			free(_pUnHandledData);
			_iUnHandledLen = 0;
			return FALSE;
		}
		p = malloc(iTotal);
		if (p)	// fail silently when malloc failed
		{
			memcpy(p, _pUnHandledData, _iUnHandledLen);
			memcpy((PCHAR)(p + _iUnHandledLen), pBuf, iLen);
			free(_pUnHandledData);
			_iUnHandledLen = 0;

			_SerialProcessString(p);
			free(p);
		}
		else
		{
			return FALSE;
		}
	}
	else
	{
		if (iLen > 1)
		{
			_SerialProcessString(pBuf);
		}
	}
	return TRUE;
}

BOOLEAN _SerialSaveUnHandledData(PCHAR pBuf, UCHAR iLen)
{
	UCHAR iTotal;
	PCHAR p;

	if (_iUnHandledLen)
	{	// Has old unhandled data, we do not support remalloc, so need to malloc a larger buffer again
		iTotal = _iUnHandledLen + iLen;
		if (iTotal >= SERIAL_STRING_SIZE)
		{	// must be something wrong
			free(_pUnHandledData);
			_iUnHandledLen = 0;
			return FALSE;
		}
		p = malloc(iTotal);
		if (p)	// fail silently when malloc failed
		{
			memcpy(p, _pUnHandledData, _iUnHandledLen);
			memcpy((PCHAR)(p + _iUnHandledLen), pBuf, iLen);
			free(_pUnHandledData);
			_pUnHandledData = p;
			_iUnHandledLen = iTotal;
		}
		else
		{
			return FALSE;
		}
	}
	else
	{
		_pUnHandledData = malloc(iLen);
		if (_pUnHandledData)	// fail silently when malloc failed
		{
			memcpy(_pUnHandledData, pBuf, iLen);
			_iUnHandledLen = iLen;
		}
		else
		{
			return FALSE;
		}
	}
//	UdpDebugVal(_iUnHandledLen, 10);
	return TRUE;
}

// Handle UART received data here, as an loop back example, we simply use UDP debug output
void _SerialHandleData(PCHAR pBuf, UCHAR iLen)	
{
	UCHAR i, iStrLen, iZeroNum;
	PCHAR pCur;

	iZeroNum = 0;

	// get "real" data by minus 1
	for (i = 0; i < iLen; i ++)
	{
//		pBuf[i] --;
		if (!pBuf[i])
		{
			iZeroNum ++;
		}
	}

	pCur = pBuf;
	for (i = 0; i < iZeroNum; i ++)
	{
		iStrLen = strlen(pCur) + 1;
		if (!_SerialHandleString(pCur, iStrLen))
		{
			UdpDebugString("UART data unhanded");
		}
		pCur += iStrLen;
		iLen -= iStrLen;
	}
	if (iLen)
	{
		if (!_SerialSaveUnHandledData(pCur, iLen))
		{
			UdpDebugString("UART data lost");
#ifdef SYS_DEBUG
			for (i = 0; i < iLen; i ++)
			{
				UdpDebugVal(pCur[i], 16);
			}
#endif
		}
	}
}

void _SerialSendData()
{
	UCHAR iTail;

//	DI;

	iTail = Serial_iSendTail + 1;
	if (iTail == SERIAL_BUF_SIZE_TX)
	{
		iTail = 0;
	}

	while (iTail != Serial_iSendHead)
	{
		if (UART_SendByte(Serial_pSend[iTail]))
		{
			Serial_iSendTail = iTail;
			iTail ++;
			if (iTail == SERIAL_BUF_SIZE_TX)
			{
				iTail = 0;
			}
		}
		else
		{
			break;
		}
	}

//	EI;
}

void SerialRun()
{
	UCHAR iLen;
	UCHAR pBuf[SERIAL_BUF_SIZE_RX];
	UCHAR iTail;

	_SerialSendData();

	iLen = 0;

	DI;

	iTail = Serial_iRecvTail + 1;
	if (iTail == SERIAL_BUF_SIZE_RX)
	{
		iTail = 0;
	}

	while (iTail != Serial_iRecvHead)
	{
		pBuf[iLen] = Serial_pRecv[iTail];
		iLen ++;
		Serial_iRecvTail = iTail;
		iTail ++;
		if (iTail == SERIAL_BUF_SIZE_RX)
		{
			iTail = 0;
		}
	}

	EI;

	if (iLen)
	{
		_SerialHandleData(pBuf, iLen);
	}

	_SerialSendData();
}

void SerialSend(PCHAR pBuf, UCHAR iLen)
{
	UCHAR i;

	_SerialSendData();
	for (i = 0; i < iLen; i ++)
	{
		if (Serial_iSendTail != Serial_iSendHead)
		{
			Serial_pSend[Serial_iSendHead] = pBuf[i];
			Serial_iSendHead ++;
			if (Serial_iSendHead == SERIAL_BUF_SIZE_TX)
			{
				Serial_iSendHead = 0;
			}
		}
	}
	_SerialSendData();
}

const UCHAR _pZero[4] = {0, 0, 0, 0};
void SerialSendString(PCHAR pStr)
{
//	UCHAR pZero[4];

//	memset(pZero, 0, 4);
	SerialSend(pStr, strlen(pStr) + 1);
	SerialSend(_pZero, 4);
}

#elif defined SERIAL_LOOP

// UART serial template

// ToDo: Add user globals here

//	Initialize serial communication (has to be called before/after[...])
void SerialInit()
{
	// ToDo: Insert user specific initiaization here
	Serial_iRecvHead = 0;
	Serial_iRecvTail = SERIAL_BUF_SIZE_RX - 1;

	UART_Init(78, FALSE);	// 19200 bps, 8 bit data, 1 bit stop, no parity
}

// Serial handler (main-loop)
void SerialRun()
{
	UCHAR i, iLen, iTail;
	UCHAR pBuf[SERIAL_BUF_SIZE_RX];

	iLen = 0;

	// read received data
	DI;

	iTail = Serial_iRecvTail + 1;
	if (iTail == SERIAL_BUF_SIZE_RX)
	{
		iTail = 0;
	}

	while (iTail != Serial_iRecvHead)
	{
		pBuf[iLen] = Serial_pRecv[iTail];
		iLen ++;
		Serial_iRecvTail = iTail;
		iTail ++;
		if (iTail == SERIAL_BUF_SIZE_RX)
		{
			iTail = 0;
		}
	}

	EI;

	// loop back
	for (i = 0; i < iLen; i ++)
	{
		if (!UART_SendByte(pBuf[i]))			// Check for transmit error
		{
			UdpDebugString("UART Send Error");		// Report error on Udp
		}
	}
}
#endif
#endif	// SYS_UART

