/*************************************************
File name:	pmcli.c
Author: 	
Version:	9:00:00 
Date:  		2007-8-4
Description:由于修改PPS用户参数要修改到PPS的系统参数，该文件实现了向系统参数命令表保存命令记录
			再由paramComm模块处理该命令
			
			
			
												
History:               
No. 		
Author:		  
Date:		 
Version:	   
Description:
*************************************************/
#include "smcli.h"

void pmcli(char *inputBuf, int loop);
//int pmcliProcInput(char *inputBuf, int loop, int keyNo, int instance);
//int doCmdReadParam(int loop, int keyNo, int instance);
//int doCmdModifyParam(int loop, int keyNo);
//int fillParamOptValue(int loop, char *onePart, int keyNo, int instance);
//int paramSendCommand(int loop, int keyNo, int commType, int commId);
int pmcliProcInput(char *inputBuf, int loop);
int doCmdReadParam(int loop);
int doResultReadParam(int loop);
int valueToOpt(const char *value,const char *optArr,char *outDes);
int doCmdModifyParam(int loop);
int fillParamOptValue(int loop, char *onePart);
int paramSendCommand(int loop, int commType, int commId);
int paramScanCommand(int loop, int commId);
int chkComm(int commId, char *remark);
void deleteParamComm();

extern int CloseTcpConn(int sock);
extern void CheckDbConnection();

extern MYSQL *dbConn;

int COMM_ID;
char REMARK[256];
int keyNo, instance;

extern unsigned char CmdTypeNo;
extern char OutputBuf[OutputBufSize];
extern int OutputLen;
extern CmdBuf defCmdBuf[CmdBufSize];
extern char CmdList[MaxCmdTypeNum][16];

/* by simon at 23/9/26 */
extern _PORT_STATUS port_status[MAX_CLIENTS];
extern CmdBuf *cmdBuf;

/*************************************************
Function:        // pmcli
Description:     // 分析命令行，判断是否需要修改系统参数
Calls:           // pmcliProcInput
Called By:       // smcli.c:ReceiveTCP
Table Accessed:  // OMC_PUB.sysOperLog
Table Updated:   // OMC_PUB.sysOperLog
Input:           // inputBuf:命令缓冲区; loop:the index of port_status; 
Output:          // 
Return:          // 
Others:          // 
*************************************************/
void pmcli(char *inputBuf, int loop)
{
	//int keyNo = 0, instance = 0;
	//int keyNo = 0, instance = 0;
	int sock;

	long l_time;
	struct tm *t;
	char tmpSql[1024];
	
	CheckDbConnection();

	sock = port_status[loop].connfd;

	if (0 == pmcliProcInput(inputBuf, loop)) {
		switch (CmdTypeNo) {
		case CMD_READ:
			doCmdReadParam(loop);
			break;
		case CMD_MODIFY:
			doCmdModifyParam(loop);
			break;
		default:
			break;
		}
	}

	l_time = time(NULL);
	t = localtime(&l_time);
	sprintf(tmpSql, "INSERT INTO %s	"
			"(operTypeNo,operNo,remark,userName,datetime)"
			"VALUES"
			"(\'0\',\'0\',\'Command:%s,Result:%s\',\'smcli:%s\',\'%04d-%02d-%02d %02d:%02d:%02d\')",
			sysOperLogTable, port_status[loop].tmpInputBuf, OutputBuf,
			port_status[loop].username, t->tm_year + 1900,
			t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec);
	mysql_getnores(dbConn, tmpSql);
	usleep(delayTime);
	sprintf(OutputBuf, "%s", "CLI>");
	OutputLen = strlen(OutputBuf);
	send(sock, OutputBuf, OutputLen, 0);
	port_status[loop].time = time(NULL);
	return;
}

/*************************************************
Function:        // pmcliProcInput
Description:     // 分析命令，判断是否要改系统参数
Calls:           // send; CloseTcpConn; fillParamOptValue; 
Called By:       // pmcli
Table Accessed:  // parameterComm
Table Updated:   // 
Input:           // input:命令缓冲区; loop:the index of port_status;
Output:          // 
Return:          // 0:successful: 1:failed;
Others:          // 
*************************************************/
int pmcliProcInput(char *inputBuf, int loop)
{
	char *paramPart = NULL;
	char *onePart = NULL;
	char *tmpStr = NULL;
	int i = 0;
	int j = 0;
	int k = 0;
	int sock;

	char tmpSql[256];
	MYSQL_RES *tmpResult = NULL;
	MYSQL_ROW tmpRow = NULL;
	
	CheckDbConnection();

	sock = port_status[loop].connfd;

	for (i = 0; i < CmdBufSize; i++)
		defCmdBuf[i].isConnected = port_status[loop].isConnected[i];
	i = 0;

	if (strstr(inputBuf, "exit") || strstr(inputBuf, "quit")) {
		sprintf(OutputBuf, "%s", "Good bye\n\r");
		OutputLen = strlen(OutputBuf);
		send(sock, OutputBuf, OutputLen, 0);
		CloseTcpConn(sock);
		sprintf(OutputBuf, "%s", "Login out");
		return (1);
	}

	while ((paramPart = strsep(&(inputBuf), "-"))) {
		//printf("paramPart=%s\n", paramPart);
		if (strlen(paramPart) < 2) {
			sprintf(OutputBuf, "%s:%s\n\r", ERR_0001, onePart);
			OutputLen = strlen(OutputBuf);
			send(sock, OutputBuf, OutputLen, 0);
			return (1);
		}

		switch (i) {
		case 0:				//command and object
			//first part is command name
			if ((onePart = strsep(&(paramPart), " "))) {
				//printf("onePart=%s\n",onePart);
				//printf("lastPart=%s\n",paramPart);
				//try to find
				for (j = 0; j < MaxCmdTypeNum; j++) {
					if (strcmp(CmdList[j], onePart) == 0) {
						CmdTypeNo = j + 1;
						break;
					}
				}
				//cannot find
				if (j == MaxCmdTypeNum) {
					sprintf(OutputBuf, "%s:%s\n\r", ERR_0001, onePart);
					OutputLen = strlen(OutputBuf);
					send(sock, OutputBuf, OutputLen, 0);
					return (1);
				}
				
				//if (CmdTypeNo != CMD_MODIFY) {
				if (CmdTypeNo != CMD_MODIFY && CmdTypeNo != CMD_READ) {
					sprintf(OutputBuf, "%s:%s\n\r", ERR_0001, onePart);
					OutputLen = strlen(OutputBuf);
					send(sock, OutputBuf, OutputLen, 0);
					return (1);
				}
			} else {
				sprintf(OutputBuf, "%s\n\r", ERR_0002);
				OutputLen = strlen(OutputBuf);
				send(sock, OutputBuf, OutputLen, 0);
				return (1);
			}
			//second part is command object
			if (paramPart != NULL) {
				k = strlen(paramPart);
				while (' ' == *(paramPart + k - 1)) {
					k = k - 1;
					if (k == 0)
						break;
				}
				*(paramPart + k) = '\0';
			}
			if (paramPart != NULL) {
				onePart = paramPart;
				for (j = 0; j < CmdBufSize; j++) {
					if (strcmp(onePart, defCmdBuf[j].paramStr) == 0) {
						if (defCmdBuf[j].isConnected == 0) {
							sprintf(OutputBuf, "%s\n\r", ERR_0254);
							OutputLen = strlen(OutputBuf);
							send(sock, OutputBuf, OutputLen, 0);
							return (1);
						}
						cmdBuf = &defCmdBuf[j];
						if (cmdBuf->cmdFlag[CmdTypeNo - 1] >
							port_status[loop].privilege) {
							sprintf(OutputBuf, "%s:%s %s\n\r",
									ERR_0005, CmdList[CmdTypeNo - 1],
									onePart);
							OutputLen = strlen(OutputBuf);
							send(sock, OutputBuf, OutputLen, 0);
							return (1);
						}
						break;
					}
				}
				if (j == CmdBufSize) {
					sprintf(OutputBuf, "%s:%s\n\r", ERR_0003, onePart);
					OutputLen = strlen(OutputBuf);
					send(sock, OutputBuf, OutputLen, 0);
					return (1);
				}
			} else {
				sprintf(OutputBuf, "%s\n\r", ERR_0002);
				OutputLen = strlen(OutputBuf);
				send(sock, OutputBuf, OutputLen, 0);
				return (1);
			}
			break;
		default:
			//case 1:               //parameters name and value
			//parameter name
			if ((onePart = strsep(&(paramPart), " "))) {
				//printf("onePart=%s\n", onePart);
				//printf("lastPart=%s\n", paramPart);
				if (!(tmpStr = strrchr(onePart, '.'))) {
					sprintf(OutputBuf, "%s\n\r", ERR_0002);
					OutputLen = strlen(OutputBuf);
					send(sock, OutputBuf, OutputLen, 0);
					return (1);
				}

				instance = atoi(tmpStr+1);
				tmpStr[0] = 0;

				sprintf(tmpSql,
						"SELECT keyNo,writePrivilege FROM OMC_PUB.%s WHERE fieldName='%s'",
						cmdBuf->paramTable, onePart);
				//printf("tmpSql=%s\n", tmpSql);
				tmpResult = (MYSQL_RES *) mysql_getres(dbConn, tmpSql);

				//cannot find
				if (tmpResult == NULL || mysql_num_rows(tmpResult) == 0) {
					mysql_free_result(tmpResult);
					sprintf(OutputBuf, "%s:%s\n\r", ERR_0010, onePart);
					OutputLen = strlen(OutputBuf);
					send(sock, OutputBuf, OutputLen, 0);
					return (1);
				} else {
					tmpRow = mysql_fetch_row(tmpResult);
					if (atoi(tmpRow[1]) > port_status[loop].privilege) {
						mysql_free_result(tmpResult);
						sprintf(OutputBuf, "%s:%s\n\r", ERR_0012, onePart);
						OutputLen = strlen(OutputBuf);
						send(sock, OutputBuf, OutputLen, 0);
						return (1);
					}
					keyNo = atoi(tmpRow[0]);
					mysql_free_result(tmpResult);
				}

			} else {
				sprintf(OutputBuf, "%s\n\r", ERR_0002);
				OutputLen = strlen(OutputBuf);
				send(sock, OutputBuf, OutputLen, 0);
				return (1);
			}
			if (CmdTypeNo == CMD_MODIFY) {
				//parameter value
				if (paramPart != NULL) {
					k = strlen(paramPart);
					while (' ' == *(paramPart + k - 1)) {
						k = k - 1;
						if (k == 0)
							break;
					}
					*(paramPart + k) = '\0';
				} else {
					sprintf(OutputBuf, "%s\n\r", ERR_0003);
					OutputLen = strlen(OutputBuf);
					send(sock, OutputBuf, OutputLen, 0);
					return (1);
				}

				if (paramPart != NULL) {
					onePart = paramPart;
					if (0 != fillParamOptValue(loop, onePart))
						return (1);
				} else {
					sprintf(OutputBuf, "%s\n\r", ERR_0003);
					OutputLen = strlen(OutputBuf);
					send(sock, OutputBuf, OutputLen, 0);
					return (1);
				}
			}
			break;
			//default:
			//  break;
		}						//end of switch
		i++;
	}							//end of while

	return (0);
}

/*************************************************
Function:        // doCmdReadParam
Description:     // 
Calls:           // 
Called By:       // 
Table Accessed:  // 
Table Updated:   // 
Input:           // 
Output:          // 
Return:          // 
Others:          // 未实现
*************************************************/
int doCmdReadParam(int loop)
{
	int commType = 0;
	int commId = 0;
	int result;
	
	
	result = paramSendCommand(loop, commType, commId);
	if (0 != result)
		return (0);
	result = paramScanCommand(loop, commId);
	
	return (0);
}

/*************************************************
Function:        // doResultReadParam
Description:     // show the result after read the parameter
Calls:           // 
Called By:       // paramScanCommand
Table Accessed:  // OMC_PUB.parameterComm
Table Updated:   // 
Input:           // 
Output:          // 
Return:          // 
Others:          // 
*************************************************/
int doResultReadParam(int loop)
{
	char selSql[512];
	MYSQL_RES *selResult = NULL;
	MYSQL_ROW selRow = NULL;
	int sock;
	char levelstr[256];
	char objIdStr[64];
	char tmpstr[64];
	char initValue[256],paramTable[32],paramName[64];
	char limitValue[256];
	char outputValue[128];
	char unitDefArr[6][32];
	char selectType[2048];
	int instanceNo;
	int commType;
	int i;
	char *c;
	char tmpStr[2048];
	//char *part = NULL;
	char *tmpPart = NULL;
	char *onePart = NULL;
	int bgnByte, bgnBit, endByte, endBit, byteLen;
	
	CheckDbConnection();

	sock = port_status[loop].connfd;
	
	sprintf(selSql, "SELECT objId,instanceNo,commType FROM %s WHERE commId = '%d'",
			paramCommandTable, COMM_ID);
	selResult = (MYSQL_RES *) mysql_getres(dbConn, selSql);
	if (selResult == NULL || mysql_num_rows(selResult) == 0) {
		//mysql_free_result(selResult);
		return 0;
	}

	selRow = mysql_fetch_row(selResult);
	//make the parameter level
	sprintf(objIdStr,"%s",selRow[0]);
	instanceNo = atoi(selRow[1]);
	commType = atoi(selRow[2]);
	mysql_free_result(selResult);
	//only fix read operation
	if(commType != 0)
		return 0;
	c=strtok(objIdStr,".");
	sprintf(levelstr," level_1=%s ",c);
	i=2;
	while((c=strtok(NULL,".")))
	{
		sprintf(tmpstr,"and level_%d=%s ",i++,c);
		strcat(levelstr,tmpstr);
	}
	while(i<=10)
	{
		sprintf(tmpstr,"and level_%d=0 ",i++);
		strcat(levelstr,tmpstr);
	}
	
	
	
	//------------get the define of parameter-------------------
	sprintf(selSql, "SELECT * FROM OMC_PUB.%s WHERE keyNo='%d'",
			cmdBuf->paramTable, keyNo);
	selResult = (MYSQL_RES *) mysql_getres(dbConn, selSql);
	if (selResult == NULL || mysql_num_rows(selResult) == 0) {
		mysql_free_result(selResult);
		sprintf(OutputBuf, "%s\n\r", ERR_0010);
		OutputLen = strlen(OutputBuf);
		send(sock, OutputBuf, OutputLen, 0);
		return (1);
	}
	
	//paramTable
	selRow = mysql_fetch_row(selResult);
	strcpy(paramName,selRow[1]);
	if (2 == atoi(selRow[2]))
		sprintf(paramTable, "param_99");
	else
		sprintf(paramTable, "param_%d", cmdBuf->sysNo);
	
	//selectType
	sprintf(tmpStr, "%s", selRow[4]);
	i = 0;
	tmpPart = &(tmpStr[0]);
	for (i = 0; i < 6; i++) 
	{
		onePart = strsep(&(tmpPart), "-");
		strcpy(unitDefArr[i], onePart);
	}
	sprintf(selectType, "%s", tmpPart);
	mysql_free_result(selResult);
	
	tmpPart = &(unitDefArr[0][0]);
	onePart = strsep(&(tmpPart), ".");
	bgnByte = atoi(onePart);
	bgnBit = atoi(tmpPart);
	tmpPart = &(unitDefArr[1][0]);
	onePart = strsep(&(tmpPart), ".");
	endByte = atoi(onePart);
	endBit = atoi(tmpPart);
	byteLen = endByte - bgnByte + 1;
	//printf("bgnByte=%d,bgnBit=%d,endByte=%d,endBit=%d,byteLen=%d\n",bgnByte,bgnBit,endByte,endBit,byteLen);
	
	//printf("selectType=%s\n",selectType);
		
	//-----------get the readValue in parameter table---------------
	//ISSUE-2
	sprintf(selSql,
			"SELECT initValue FROM OBJ_%d.%s WHERE %s AND instanceNo=%d ",
			cmdBuf->sysTypeNo, paramTable, levelstr, instanceNo);
	selResult = (MYSQL_RES *) mysql_getres(dbConn, selSql);
	if (selResult == NULL || mysql_num_rows(selResult) == 0) 
	{
		mysql_free_result(selResult);
		sprintf(OutputBuf, "%s\n\r", ERR_0010);
		OutputLen = strlen(OutputBuf);
		send(sock, OutputBuf, OutputLen, 0);
		return (1);
	}

	selRow = mysql_fetch_row(selResult);
	sprintf(initValue, "%s", selRow[0]);
	//printf("initValue=+%s+\n",initValue);
	mysql_free_result(selResult);
	
	memset(outputValue,0,128);
	
	//only support entire byte
	if(endByte == bgnByte)
	{
		sprintf(limitValue,"%s",initValue+bgnByte*2);
		limitValue[bgnByte*2+2]='\0';
	}
	else
	{
		sprintf(limitValue,"%s",initValue+bgnByte*2);
		limitValue[(endByte-bgnByte+1)*2]='\0';
	}
	//printf("limitValue=%s\n",limitValue);
	//-----------------show the value-----------------------
	if(strcasecmp(unitDefArr[3], "toDec") == 0)
	{
		//select
		if(strcasecmp(unitDefArr[2], "select") == 0)
		{
			valueToOpt(limitValue,selectType,outputValue);
		}
		//input
		else
		{
			long decValue=0;
			sscanf(limitValue,"%x",(unsigned int*)&decValue);
			sprintf(outputValue,"%ld",decValue);
		}
	}
	else if(strcasecmp(unitDefArr[3], "keepDec") == 0)
	{
		sprintf(outputValue,"%s",limitValue);
	}
	else if(strcasecmp(unitDefArr[3], "keepHex") == 0)
	{
		sprintf(outputValue,"%s",limitValue);
	}
	else if(strcasecmp(unitDefArr[3], "toAscii") == 0)
	{
		int hb,lb,tb,zeroN=0;
		for(i=bgnByte;i<=endByte;i++)
		{
			hb=initValue[i*2]-'0';
			lb=initValue[i*2+1]-'0';
			tb=hb*16+lb;
			if(tb == 0)
				zeroN++;
			sprintf(tmpstr,"%c",tb);
			strcat(outputValue,tmpstr);
		}
		if(zeroN == (endByte-bgnByte+1))
			sprintf(outputValue,"(null)");
	}
	else
	{
		sprintf(outputValue,"%s",limitValue);
	}
	
	sprintf(OutputBuf, "%s -%s %s\n", cmdBuf->paramStr,paramName,outputValue);
	OutputLen = strlen(OutputBuf);
	send(sock, OutputBuf, OutputLen, 0);
	
	return 0;
}

/*************************************************
Function:        // valueToOpt
Description:     // transform the value to label in select
Calls:           // 
Called By:       // 
Table Accessed:  // 
Table Updated:   // 
Input:           // 
Output:          // 
Return:          // 1: failed; 0: successful
Others:          // 
*************************************************/
int valueToOpt(const char *value,const char *optArr,char *outDes)
{
	int iValue;
	char *c=NULL,*p=NULL,*q=NULL;
	char tmpOptArr[2048];
	char sOpt[64][64];
	int iOpt[64];
	int optLen;
	int i;
	
	for(i=0;i<64;i++)
	{
		sprintf(sOpt[i],"(undefined)");
		iOpt[i]=-1;
	}
	
	sprintf(outDes,"(undefined)");
	sprintf(tmpOptArr,"%s",optArr);
	iValue=atoi(value);
	if(optArr == NULL || strlen(optArr) == 0)	
		return 1;
	optLen=0;
	c=strstr(tmpOptArr,";");
	if(c == NULL)
	{
		p=strtok(tmpOptArr,".");
		iOpt[optLen]=atoi(p);
		p=strtok(NULL,".");
		if(p == NULL)
			return 1;
		sprintf(sOpt[optLen],"%s",p);	
		optLen++;
	}
	else
	{
		q=strtok(tmpOptArr,";");
		iOpt[optLen]=atoi(q);
		p=strstr(q,".");	
		if(p == NULL)
			return 1;
		sprintf(sOpt[optLen],"%s",p+1);	
		optLen++;
		while((q=strtok(NULL,";")))
		{
			if(optLen >= 64)
				return 1;
			iOpt[optLen]=atoi(q);
			p=strstr(q,".");	
			if(p == NULL)
				return 1;
			sprintf(sOpt[optLen],"%s",p+1);	
			optLen++;
		}
	}
	
	for(i=0;i<optLen;i++)
	{
		if(iOpt[i] == iValue)
		{
			sprintf(outDes,"%s",sOpt[i]);
			//printf("iOpt=%d,sOpt=%s\n",iOpt[i],sOpt[i]);
			return 0;
		}
	}
	
	return 1;
}

/*************************************************
Function:        // doCmdModifyParam
Description:     // 执行命令修改
Calls:           // paramSendCommand;
Called By:       // pmcli
Table Accessed:  // 
Table Updated:   // 
Input:           // loop:the index of port_status;
Output:          // 
Return:          // 
Others:          // 
*************************************************/
int doCmdModifyParam(int loop)
{
	int commType = 3;
	int commId = 0;
	int result;
	result = paramSendCommand(loop, commType, commId);
	if (0 != result)
		return (0);
	paramScanCommand(loop, commId);
	return (0);
}

/*************************************************
Function:        // fillParamOptValue
Description:     // 填写命令的参数值
Calls:           // mysql_getres; mysql_num_rows;
Called By:       // pmcliProcInput
Table Accessed:  // param_XX; parameterComm; 
Table Updated:   // 
Input:           // loop:the index of port_status; value:填入的值
Output:          // 
Return:          // 0:successful; 1:failed;
Others:          // 
*************************************************/
int fillParamOptValue(int loop, char *value)
{
	int i, j;
	char selSql[256];
	MYSQL_RES *selResult = NULL;
	MYSQL_ROW selRow = NULL;

	char paramTable[32];
	char unitDefArr[6][32];
	char selectType[2048];
	int bgnByte, bgnBit, endByte, endBit, byteLen;

	char tmpSql[512];
	MYSQL_RES *tmpResult = NULL;
	MYSQL_ROW tmpRow = NULL;
	char initValue[256];

	unsigned char bitValue;
	int existFlag = 0;
	char tmpStr[2048];
	char *part = NULL;
	char *tmpPart = NULL;
	char *onePart = NULL;
	//char tmpDecValue[256];
	char tmpHexValue[256];
	int sock;
	int jj;

	CheckDbConnection();
	
	sock = port_status[loop].connfd;

	sprintf(selSql, "SELECT * FROM OMC_PUB.%s WHERE keyNo='%d'",
			cmdBuf->paramTable, keyNo);
	selResult = (MYSQL_RES *) mysql_getres(dbConn, selSql);
	if (selResult == NULL || mysql_num_rows(selResult) == 0) {
		mysql_free_result(selResult);
		sprintf(OutputBuf, "%s\n\r", ERR_0010);
		OutputLen = strlen(OutputBuf);
		send(sock, OutputBuf, OutputLen, 0);
		return (1);
	}

	selRow = mysql_fetch_row(selResult);
	if (2 == atoi(selRow[2]))
		sprintf(paramTable, "param_99");
	else
		sprintf(paramTable, "param_%d", cmdBuf->sysNo);
	//ISSUE-2
	sprintf(tmpSql,
			"SELECT initValue FROM OBJ_%d.%s WHERE level_1='%s' AND level_2='%s' AND level_3='%s' AND level_4='%s' AND level_5='%s' AND level_6='%s' AND level_7='%s' AND level_8='%s' AND level_9='%s' AND level_10='%s' AND instanceNo=%d ",
			cmdBuf->sysTypeNo, paramTable, selRow[5], selRow[6], selRow[7],
			selRow[8], selRow[9], selRow[10], selRow[11], selRow[12],
			selRow[13], selRow[14], instance);
	//printf("tmpSql=%s\n",tmpSql);
	tmpResult = (MYSQL_RES *) mysql_getres(dbConn, tmpSql);
	if (tmpResult == NULL || mysql_num_rows(tmpResult) == 0) {
		mysql_free_result(tmpResult);
		sprintf(OutputBuf, "%s\n\r", ERR_0010);
		OutputLen = strlen(OutputBuf);
		send(sock, OutputBuf, OutputLen, 0);
		return (1);
	}

	tmpRow = mysql_fetch_row(tmpResult);
	sprintf(initValue, "%s", tmpRow[0]);
	mysql_free_result(tmpResult);

	sprintf(tmpStr, "%s", selRow[4]);
	i = 0;
	tmpPart = &(tmpStr[0]);
	for (i = 0; i < 6; i++) {
		onePart = strsep(&(tmpPart), "-");
		strcpy(unitDefArr[i], onePart);
		//printf("unitDefArr[%d]=%s\n",i,unitDefArr[i]);
	}

	sprintf(selectType, "%s", tmpPart);

/*
	bgnOffset	= unitDefArr[0];
	endOffset	= unitDefArr[1];
	operType	= unitDefArr[2];
	valueType	= unitDefArr[3];
	fillWay		= unitDefArr[4];
	fillChar	= unitDefArr[5];

*/
	tmpPart = &(unitDefArr[0][0]);
	onePart = strsep(&(tmpPart), ".");
	//printf("onePart=%s\n",onePart);
	bgnByte = atoi(onePart);
	bgnBit = atoi(tmpPart);
	tmpPart = &(unitDefArr[1][0]);
	onePart = strsep(&(tmpPart), ".");
	//printf("onePart=%s\n",onePart);
	endByte = atoi(onePart);
	endBit = atoi(tmpPart);
	byteLen = endByte - bgnByte + 1;
	if (!strcmp(unitDefArr[2], "select")) {
		part = &(selectType[0]);
		while ((tmpPart = strsep(&(part), ";"))) {
			if ((onePart = strsep(&(tmpPart), "."))) {
				if (!strcmp(tmpPart, value)) {
					strcpy(value, onePart);
					existFlag = 1;
				}
			}
		}
		if (existFlag != 1) {
			sprintf(OutputBuf, "%s:%s\n\r", ERR_0203, value);
			OutputLen = strlen(OutputBuf);
			send(sock, OutputBuf, OutputLen, 0);
			return (1);
		}
	}
	//printf("unitDefArr[3]=%s\n",unitDefArr[3]);
	//printf("bgnByte=%d,bgnBit=%d,endByte=%d,endBit=%d\n",bgnByte,bgnBit,endByte,endBit);
	//printf("before initValue=%s\n",initValue);
	//printf("value=%s\n",value);


	if (!strcmp(unitDefArr[3], "toDec")) {
		if (bgnBit > 0 || endBit < 7) {
			//tmpDecValue=atoi(value);
			sprintf(tmpHexValue, "%X", atoi(value));
			for (j = 0; j < endBit - bgnBit + 1; j++) {
				getBitValue(tmpHexValue, 0, j, &bitValue);
				setBitValue(initValue, bgnByte, bgnBit + j, bitValue);
			}
		} else {
			//tmpDecValue=atoi(value);
			sprintf(tmpHexValue, "%X", atoi(value));
			//printf("tmpHexValue=%s\n",tmpHexValue);
			//printf("byteLen=%d\n",byteLen);
			jj = byteLen * 2 - strlen(tmpHexValue);
			for (j = 0; j < jj; j++) {
				if (!strcmp(unitDefArr[4], "high")) {
					strcpy(tmpStr, unitDefArr[5]);
					strcat(tmpStr, tmpHexValue);
					strcpy(tmpHexValue, tmpStr);
					//printf("%d=%s\n",j,tmpHexValue);
				} else
					strcat(tmpHexValue, unitDefArr[5]);
			}

			//printf("tmpHexValue=%s\n",tmpHexValue);
			memcpy(initValue + bgnByte * 2, tmpHexValue, byteLen * 2);
			//printf("after initValue=%s\n",initValue);
		}
		//break;

	} else if (!strcmp(unitDefArr[3], "keepDec")) {
		//  case "keepDec":
		jj = byteLen * 2 - strlen(value);
		for (j = 0; j < jj; j++) {
			if (!strcmp(unitDefArr[4], "high")) {
				strcpy(tmpStr, unitDefArr[5]);
				strcat(tmpStr, value);
				strcpy(value, tmpStr);
			} else
				strcat(value, unitDefArr[5]);
		}
		memcpy(initValue + bgnByte * 2, value, byteLen * 2);
		//      break;
	} else if (!strcmp(unitDefArr[3], "keepHex")) {
		//  case "keepHex":
		if (bgnBit > 0 || endBit < 7) {
			for (j = 0; j < endBit - bgnBit + 1; j++) {
				getBitValue(value, 0, j, &bitValue);
				setBitValue(initValue, bgnByte, bgnBit + j, bitValue);
			}
		} else {
			jj = byteLen * 2 - strlen(value);
			for (j = 0; j < jj; j++) {
				if (!strcmp(unitDefArr[4], "high")) {
					strcpy(tmpStr, unitDefArr[5]);
					strcat(tmpStr, value);
					strcpy(value, tmpStr);
				} else
					strcat(value, unitDefArr[5]);
			}
			memcpy(initValue + bgnByte * 2, value, byteLen * 2);
		}
		//      break;
	} else if (!strcmp(unitDefArr[3], "toAscii")) {
		//  case "toAscii":
		tmpHexValue[0] = 0;
		for (i = 0; i < strlen(value); i++) {
			sprintf(tmpStr, "%02X", value[i]);
			strcat(tmpHexValue, tmpStr);
		}
		jj = byteLen * 2 - strlen(tmpHexValue);
		for (i = 0; i < jj; i++) {
			if (!strcmp(unitDefArr[4], "high")) {
				strcpy(tmpStr, unitDefArr[5]);
				strcat(tmpStr, tmpHexValue);
				strcpy(tmpHexValue, tmpStr);
			} else
				strcat(tmpHexValue, unitDefArr[5]);
		}
		memcpy(initValue + bgnByte * 2, tmpHexValue, byteLen * 2);
	}
	//      break;
	//  default: 
	//      break;
	//} 
	//ISSUE-2
	sprintf(tmpSql,
			"UPDATE OBJ_%d.%s SET `initValue`='%s',`readValue`='%s' WHERE level_1='%s' AND level_2='%s' AND level_3='%s' AND level_4='%s' AND level_5='%s' AND level_6='%s' AND level_7='%s' AND level_8='%s' AND level_9='%s' AND level_10='%s' AND instanceNo=%d ",
			cmdBuf->sysTypeNo, paramTable, initValue, initValue, selRow[5],
			selRow[6], selRow[7], selRow[8], selRow[9], selRow[10],
			selRow[11], selRow[12], selRow[13], selRow[14], instance);
	mysql_getnores(dbConn, tmpSql);

	mysql_free_result(selResult);
	return (0);
}

/*************************************************
Function:        // paramSendCommand
Description:     // 往系统参数命令表里插入命令
Calls:           // mysql_getres; mysql_num_rows; 
Called By:       // doCmdModifyParam
Table Accessed:  // parameterComm
Table Updated:   // parameterComm
Input:           // loop:the index of port_status; commType:命令类型; commId:命令索引;
Output:          // 
Return:          // 0:successful; 1:failed;
Others:          // 
*************************************************/
int paramSendCommand(int loop, int commType, int commId)
{
	int i;
	char chkSql[512];
	MYSQL_RES *chkResult = NULL;
	//MYSQL_ROW chkRow = NULL;

	int existNum;
	int paramType;

	char selSql[512];
	MYSQL_RES *selResult = NULL;
	MYSQL_ROW selRow = NULL;

	char objIdStr[256];

	char sendSql[512];
	int sock;

	CheckDbConnection();
	
	sock = port_status[loop].connfd;

	//step 1: delete overtime and imcompetent command(have not done) , check the exist command num
	//check the exist command num
	sprintf(chkSql, "SELECT commId FROM %s", paramCommandTable);
	
	chkResult = (MYSQL_RES *) mysql_getres(dbConn, chkSql);
	if (chkResult == NULL) {
		mysql_free_result(chkResult);
		sprintf(OutputBuf, "%s:Mysql have been stopped\n\r", ERR_0205);
		OutputLen = strlen(OutputBuf);
		send(sock, OutputBuf, OutputLen, 0);
		return (1);
	}

	existNum = mysql_num_rows(chkResult);
	mysql_free_result(chkResult);

	if (existNum > 15) {
		sprintf(OutputBuf,
				"%s:The system is busy,please wait a moment.\n\r",
				ERR_0205);
		OutputLen = strlen(OutputBuf);
		send(sock, OutputBuf, OutputLen, 0);
		return (1);
	}
	//step 2: check the command(...........)
	if (commType == 0) {		//0=Get,2=response,3=Set
		sprintf(chkSql,
				"SELECT commId FROM %s WHERE sysTypeNo='%d' AND sysNo='%d' AND commType ='0' AND remark not like '0000:%%' ",
				paramCommandTable, cmdBuf->sysTypeNo, cmdBuf->sysNo);
	} else {
		sprintf(chkSql,
				"SELECT commId FROM %s WHERE sysTypeNo='%d' AND commType ='0' AND remark not like '0000:%%' ",
				paramCommandTable, cmdBuf->sysTypeNo);
	}
	
	chkResult = (MYSQL_RES *) mysql_getres(dbConn, chkSql);
	if (chkResult == NULL) {
		mysql_free_result(chkResult);
		sprintf(OutputBuf, "%s:Mysql have been stopped\n\r", ERR_0205);
		OutputLen = strlen(OutputBuf);
		send(sock, OutputBuf, OutputLen, 0);
		return (1);
	}

	existNum = mysql_num_rows(chkResult);

	if (existNum > 0) {
		mysql_free_result(chkResult);
		sprintf(OutputBuf,
				"%s:The system is busy,please wait a moment.\n\r",
				ERR_0205);
		OutputLen = strlen(OutputBuf);
		send(sock, OutputBuf, OutputLen, 0);
		return (1);
	}

	mysql_free_result(chkResult);

	sprintf(selSql, "SELECT * FROM OMC_PUB.%s WHERE keyNo='%d'",
			cmdBuf->paramTable, keyNo);
	
	selResult = (MYSQL_RES *) mysql_getres(dbConn, selSql);
	if (selResult == NULL || mysql_num_rows(selResult) == 0) {
		mysql_free_result(selResult);
		sprintf(OutputBuf, "%s\n\r", ERR_0010);
		OutputLen = strlen(OutputBuf);
		send(sock, OutputBuf, OutputLen, 0);
		return (1);
	}
	selRow = mysql_fetch_row(selResult);

	objIdStr[0] = 0;
	for (i = 0; i < 10; i++) {
		if (atoi(selRow[5 + i]) != 0) {
			strcat(objIdStr, selRow[5 + i]);
			strcat(objIdStr, ".");
		} else
			break;
	}

	i = strlen(objIdStr);
	objIdStr[i - 1] = 0;

	//step 3:insert commands into command table
	sprintf(sendSql, "INSERT INTO %s "
			"(commType,sysTypeNo,sysNo,subSysNo,paramType,objId,InstanceNo,commState,sendTime)"
			"VALUES"
			"('%d','%d','%d','%d','%d','%s','%d','1',CURRENT_TIMESTAMP)",
			paramCommandTable,
			commType,
			cmdBuf->sysTypeNo,
			cmdBuf->sysNo, cmdBuf->subSysNo, atoi(selRow[2]), objIdStr, instance);		
	mysql_getnores(dbConn, sendSql);
	
	paramType=atoi(selRow[2]);
	mysql_free_result(selResult);
	
	//check to send command to another plat
	if(commType == 3 && cmdBuf->sysTypeNo/100 == 3)
	{
		int ano_sysNo=!cmdBuf->sysNo;
		sprintf(selSql,"select * from OMC_PUB.sysInfo where sysTypeNo=%d and sysNo=%d and baseStat=1 ",cmdBuf->sysTypeNo,ano_sysNo);
		selResult = (MYSQL_RES *) mysql_getres(dbConn, selSql);
		if(mysql_num_rows(selResult) == 1)
		{
			sprintf(sendSql, "INSERT INTO %s "
					"(commType,sysTypeNo,sysNo,subSysNo,paramType,objId,InstanceNo,commState,sendTime)"
					"VALUES"
					"('%d','%d','%d','%d','%d','%s','%d','1',CURRENT_TIMESTAMP)",
					paramCommandTable,
					commType,
					cmdBuf->sysTypeNo,
					ano_sysNo, cmdBuf->subSysNo, paramType, objIdStr, instance);		
			mysql_getnores(dbConn, sendSql);
		}
		mysql_free_result(selResult);
	}

	

	//step 4:Return commIdStr
	sprintf(selSql,
			"SELECT commId FROM %s WHERE sysTypeNo='%d' AND sysNo='%d' AND subSysNo='%d'",
			paramCommandTable, cmdBuf->sysTypeNo, cmdBuf->sysNo,
			cmdBuf->subSysNo);
	selResult = (MYSQL_RES *) mysql_getres(dbConn, selSql);

	if (selResult == NULL || mysql_num_rows(selResult) == 0) {
		mysql_free_result(selResult);
		sprintf(OutputBuf, "%s:Mysql have been stopped\n\r", ERR_0205);
		OutputLen = strlen(OutputBuf);
		send(sock, OutputBuf, OutputLen, 0);
		return (1);
	}
	selRow = mysql_fetch_row(selResult);
	COMM_ID = atoi(selRow[0]);
	mysql_free_result(selResult);

	return (0);
}

/*************************************************
Function:        // paramScanCommand
Description:     // 扫描系统参数命令表,获得命令的执行结果
Calls:           // deleteParamComm; chkComm; send; 
Called By:       // doCmdModifyParam
Table Accessed:  // parameterComm
Table Updated:   // 
Input:           // loop:the index of port_status; commId:命令索引
Output:          // 
Return:          // 
Others:          // 
*************************************************/
int paramScanCommand(int loop, int commId)
{
	int i = 0, maxNum = 10000;
	int chRes;
	char remark[256];
	int sock;

	sock = port_status[loop].connfd;


	while (1) {
		if (i > maxNum) {
			deleteParamComm();
			sprintf(OutputBuf, "%s\n\r", ERR_0255);
			OutputLen = strlen(OutputBuf);
			send(sock, OutputBuf, OutputLen, 0);
			return 1;
		}
		chRes = chkComm(commId, remark);
		if (chRes == nProcFail) {
			deleteParamComm();
			//sprintf(OutputBuf, "%s:%s\n\r", ERR_0205, REMARK);
			sprintf(OutputBuf, "%s\n\r", ERR_0205);
			OutputLen = strlen(OutputBuf);
			send(sock, OutputBuf, OutputLen, 0);
			return 1;
		}
		if (chRes == nOutProc) {
			//if the cmd is read,then show the result
			if(doResultReadParam(loop) == 1)
				return 1;
			deleteParamComm();
			sprintf(OutputBuf, "%s\n\r", ERR_0000);
			OutputLen = strlen(OutputBuf);
			send(sock, OutputBuf, OutputLen, 0);
			return 0;
		}

		usleep(1000);
		i++;
	}
	return 0;
}

/*************************************************
Function:        // chkComm
Description:     // 检查命令执行的状态
Calls:           // mysql_getres
Called By:       // paramScanCommand
Table Accessed:  // parameterComm
Table Updated:   // 
Input:           // commId:命令索引; remark:命令的描述;
Output:          // 
Return:          // commState
Others:          // 
*************************************************/
int chkComm(int commId, char *remark)
{
	char selSql[256];
	MYSQL_RES *selResult = NULL;
	MYSQL_ROW selRow = NULL;

	int result;
	
	CheckDbConnection();

	sprintf(selSql, "SELECT commState,remark FROM %s WHERE commId = '%d'",
			paramCommandTable, COMM_ID);
	selResult = (MYSQL_RES *) mysql_getres(dbConn, selSql);
	if (selResult == NULL || mysql_num_rows(selResult) == 0) {
		mysql_free_result(selResult);
		return 0;
	}

	selRow = mysql_fetch_row(selResult);

	//if (strlen(selRow[1]) > 0)
	//  sprintf(REMARK, "%s", selRow[1]);
	result = atoi(selRow[0]);
	mysql_free_result(selResult);
	return (result);
}

/*************************************************
Function:        // deleteParamComm
Description:     // 删除已经执行的命令或者错误的命令
Calls:           // mysql_getnores
Called By:       // paramScanCommand
Table Accessed:  // parameterComm
Table Updated:   // parameterComm
Input:           // 
Output:          // 
Return:          // 
Others:          // 
*************************************************/
void deleteParamComm()
{
	char tmpSql[1024];

	if (COMM_ID >= 50000) {
		//先删除表
		//sprintf(tmpSql, "DROP TABLE %s", paramCommandTable);
		sprintf(tmpSql, "TRUNCATE TABLE %s", paramCommandTable);
		CheckDbConnection();
		mysql_getnores(dbConn, tmpSql);
		/*
		//再建一个结构相同的新表
		sprintf(tmpSql, "CREATE TABLE parameterComm ("
				"commId int(6) NOT NULL auto_increment,"
				"commType tinyint(1) NOT NULL default '0',"
				"sysTypeNo smallint(3) NOT NULL default '0',"
				"sysNo smallint(3) NOT NULL default '0',"
				"subSysNo smallint(3) NOT NULL default '0',"
				"instanceNo varchar(32) unsigned NOT NULL default '0',"
				"paramType tinyint(1) NOT NULL default '0',"
				"objId varchar(30) NOT NULL default '',"
				"commState tinyint(1) NOT NULL default '0',"
				"totalNum int(6) NOT NULL default '0',"
				"finishNum int(6) NOT NULL default '0',"
				"sendTime datetime NOT NULL default '0000-00-00 00:00:00',"
				"bgnTime datetime default '0000-00-00 00:00:00',"
				"endTime datetime default '0000-00-00 00:00:00',"
				"remark varchar(200) binary default NULL,"
				"PRIMARY KEY ( commId ),"
				"KEY commType ( commType ),"
				"KEY sysTypeNo ( sysTypeNo ),"
				"KEY sysNo ( sysNo ),"
				"KEY subSysNo ( subSysNo ),"
				"KEY paramType ( paramType ),"
				"KEY objId ( objId )," "KEY commState ( commState )" ")");
		//  printf("tmpSql=%s\n",tmpSql);
		mysql_getnores(dbConn, tmpSql);
		*/
	} else {
		sprintf(tmpSql, "DELETE FROM %s WHERE commId='%d'",
				paramCommandTable, COMM_ID);
		CheckDbConnection();
		mysql_getnores(dbConn, tmpSql);
	}

}
