/************************************/
/*Title:	alarmGen.c                                   	*/
/*Descr:	Alram Generator                             */
/*Author:	Yi Zheng                                      */
/*Create:	2006-6-21                                       */
/************************************/
#include "alarmGen.h"

#define ALARM_AGENT_OID				{1,3,6,1,4,1,1373,2,4,2} 
#define ALARM_AGENT_OIDLEN			10
#define CONF_FILE

void alarm_Gen_timer(void);
/*----------------------------------------------------------------------------*/
static BYTE 		testflag			= 0;
static WORD 	selDeviceID 	= 0;
static BYTE 		selAlarmLevel = 0;
static WORD		selCompCode	=	0;
static BYTE 		selAlarmCode	=	0;
static BYTE 		selInterval 		= 100;
static BYTE		snmp_packet_log	= 0;
static FILE 		*alarmlog_fp;

static char		szWhere[128];
static char		szVersion[16];
static char 		szOmcIP[16]="127.0.0.1";
static DWORD	omc0_ip;
static char 		omc_ver;
static BYTE		sysNo=0;
static BYTE		subSysNo=0;


const	BYTE	wxc2_trap_prelen = 8;
const	BYTE	alarm_version[3]={ 8, 0, 1};
/*DateBase----------------------------------------------------------------*/
static BYTE DbconnFlag = 0;
static MYSQL *omcPub_conn;
/*for MMI------------------------------------------------------------------*/
static char				debug_flag;	
static char				debug_buf[4096];
static char				asc_in[256];
void							alarm_MMIInit(void);
void 						alarm_MMItimer();
void 						alarm_debug_out(char *info);
void 						alarm_debug(const char *fmt,...);
static char				help_info[] = 
					"***************************************\r\n"
                    "* Alarm Generator Command  Help  Menu *\r\n"
                    "***************************************\r\n"
"[0.] help                            Display this page\r\n"     
"[1.] log all                         Output all debug information\r\n"
"[2.] log none                        Turn off all information\r\n"
"[3.] list par                        List Generator parameter\r\n"
"[4.] list omcip                      List the ip address of OMC\r\n"
"     Set Generator command/parameter(s):\r\n"
"[5.] set alarmLevel=xxx              e.g: >set alarmLevel=6\r\n"
"                                       1=Critical, 2=Major,         3=Minor,\r\n"
"                                       4=Warning,  5=Indeterminate, 6=ALL\r\n"
"[6.] set DeviceID=xxx                e.g: >set DeviceID=9999\r\n"
"                                       0   = OMC,  111  = 8KE1,  113 = MTP2,\r\n"
"                                       130 = PCR,  160  = CNF,   200 = PLAT,\r\n"
"                                       320 = MSC,  330  = HLR,   340 = AUC, \r\n"
"                                       350 = SMSC, 360  = PPS,   370 = MNP,\r\n"
"                                       390 = VMS,  311  = AAS,   9999= ALL\r\n"
"[7.] set compCode=xxx                e.g: >set compCode=9999\r\n"
"                                       xxx: 9999=ALL\r\n"
"[8.] set alarmCode=xxx               e.g: >set alarmCode=6\r\n"
"                                       xxx: 255=ALL\r\n"
"[9.] set sysNo=xxx                	  e.g: >set sysNo=0\r\n"
"                                       Degault=0\r\n"
"[10.]set subSysNo=xxx                e.g: >set subSysNo=0\r\n"
"                                       Degault=0\r\n"
"[11.]set Interval=xxx                e.g: >set Interval=5\r\n"
"                                       Interval=xxx*100ms\r\n"
"[12.]set omcver=x                    e.g: >set omcver=9\r\n"
"                                       Default=9\r\n"
"[13.]set omcip=xxx                   e.g: >set omcip=172.18.128.1\r\n"
"                                       xxx= ip address or host name\r\n"
"[14.]./start                         Start generating alarm.    e.g: >./start\r\n"
"[15.]./stop                          Stop generating alarm.     e.g: >./stop\r\n"
"[16.]./clear                         Clear alarm.               e.g: >./clear\r\n"
"[17.]snmp_packet log on              save snmp packet to log file.\r\n"                                   
"[18.]snmp_packet log off             disable save snmp packet to log file.\r\n"
"Press 'x' or 'X' to return \"Help Menu\"\r\n"
"\33[33m-->Press \"Esc\" then \"Enter\"<--\33[37m\r\n";

/*for SNMP-----------------------------------------------------------------*/

int alarm_set_rsp(BYTE oidlen, DWORD *oid, BYTE *pdata, WORD datalen);
void alarm_snmp_trap(BYTE oidlen,DWORD *oid, BYTE *pdata,WORD msg_len,snmp_addr *addr);
int alarm_GenInit(void);

/*for Log-----------------------------------------------------------------*/
void alarmlog_init();
void alarmlog_timer();
void alarmlog_put(const char *fmt, ...);

static char ascii[16] = {0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
						 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46};
int	hex_to_ascii(BYTE *from_hex, BYTE from_len, BYTE *to_asc);
/*private-------------------------------------------------------------------*/
static DWORD assign_rid();
static int build_snmpmsg(BYTE *pbuf, snmp_pdu *psnmp);
static int snmp_send_self(snmp_pdu *msgbuf, snmp_addr *addr);
static int alarm_db_init(void);
static int testtimer();
static int loadConfigure();	
static int saveConfigure();
static void sendHeartbeat();

/*---------------------------------------------------------------------------*/
void alarm_MMIInit(void)
{
	DWORD				ascout_id[20]	={1,3,6,1,4,1,1373,2,1,2,3,1,2,17,4};
	DWORD				ascin_id[20]	={1,3,6,1,4,1,1373,2,1,2,3,1,2,17,3};
//	DWORD				name_id[20]	={1,3,6,1,4,1,1373,1,1,2,3,1,2,17,2};
//	DWORD				status_id[20]	={1,3,6,1,4,1,1373,1,1,2,3,1,2,17,1};
	
	
//	static  BYTE		debug_status=1;

	debug_set_response(15,ascout_id,(BYTE*)debug_buf,1);
	debug_set_response(15,ascin_id,(BYTE*)asc_in,1);
	
//	debug_set_response(15,status_id,&debug_status,1);
//	debug_set_response(15,name_id, szVersion, strlen(szVersion));
}


void alarm_MMItimer()
{
	BYTE			npage, nline;
	char			*cmdstr = asc_in + 1;
	char			*pParam = NULL;
	char 		info[1024];
	int			num;
	
	if(strlen(asc_in) <= 1)
		return;
	debug_buf[0] = '\0';
	npage = asc_in[0] - 1;

	if(npage > 0)
	{
		nline = atoi(asc_in + 1);
		switch(npage)
		{
		case 1:		//
			break;
		}
		asc_in[0]='\0';
		return;
	}

	asc_in[0]='\0';
	if(strstr(cmdstr, "help") != NULL || strstr(cmdstr, "?") != NULL)
	{
		alarm_debug_out(help_info);
		return;
	}
	else if(strstr(cmdstr, "log all") != NULL)
	{
		debug_flag=1;
	}
	else if(strstr(cmdstr, "log none") != NULL)
	{
		debug_flag=0;
	}
	else if(strstr(cmdstr, "list par") != NULL)
	{
		char status[10];
		if(testflag==1)
		{	
			sprintf(status,"Running...");
		}
		else if(testflag==2)	
			sprintf(status,"Clearing...");
		else
			sprintf(status,"Stop.");	
		sprintf(info,"Generator parameter:\r\n\
									\r\tDeviceID=%d\r\n\
									\r\tcompCode=%d\r\n\
									\r\talarmCode=%d\r\n\
									\r\tsysNo=%d\r\n\
									\r\tsubSysNo=%d\r\n\
									\r\talarmLevel=%d\r\n\
									\r\tInterval=%d\r\n\
									\r\tOMC Version=%d\r\n\
									\r\tOMC IP=%s\r\n\
									\r\tStatus=%s\r\n\
									"
									,selDeviceID,selCompCode,selAlarmCode,sysNo,subSysNo,selAlarmLevel,selInterval,omc_ver,szOmcIP,status);
		alarm_debug_out(info);
	}
	else if(strstr(cmdstr, "list omcip") != NULL)
	{
		sprintf(info,"OMC IP=%s",szOmcIP);
		alarm_debug_out(info);
	}	
	else if(strncasecmp(cmdstr, "set omcip", 9) == 0)
	{
		pParam = strchr(cmdstr, '=');
		if(pParam!=NULL)
		{	
			memset(szOmcIP,0,sizeof(szOmcIP));
			sprintf(szOmcIP,"%s",pParam+1);
			DbconnFlag = alarm_db_init();
			if(DbconnFlag)
			{	
				saveConfigure();
			}
		}
	}	
	else if(strncasecmp(cmdstr, "set omcver", 10) == 0)
	{
		pParam = strchr(cmdstr, '=');
		if(pParam == NULL ||strlen(pParam + 1) > 2)
		{
			alarm_debug_out("Invalid command/parameter(s).");
			return;			
		}
		omc_ver = atoi(pParam+1);
	}	
	else if(strncasecmp(cmdstr, "./", 2) == 0)
	{
		pParam = strchr(cmdstr, '/');
		if(strncasecmp(pParam+1, "start",5) == 0)
		{	
			int 		p=0;
			testflag = 1;
			num=0;
			if(selDeviceID<9999)
			{	
				p+=sprintf(szWhere+p,"AND sysTypeNo=%d ",selDeviceID);
				num++;
			}
			if(selCompCode<9999)
			{	
				p+=sprintf(szWhere+p,"AND compCode=%d ",selCompCode);
				num++;
			}
			if(selAlarmCode<255)
			{	
				p+=sprintf(szWhere+p,"AND alarmCode=%d ",selAlarmCode);
				num++;
			}
			if(selAlarmLevel<6&&num<3)	
				p+=sprintf(szWhere+p,"AND alarmLevel=%d ",selAlarmLevel);
			alarm_debug_out("Generating...");	
			alarmlog_put("cmd>./start");
			
		}
		else if(strncasecmp(pParam+1, "clear",5) == 0)		
		{	
			testflag = 2;
			alarm_debug_out("Clear...");
			alarmlog_put("cmd>./Clear");
			
		}		
		else if(strncasecmp(pParam+1, "stop",4) == 0)
		{	
			testflag = 3;
			alarm_debug_out("Stop...");
			alarmlog_put("cmd>./Stop");
			
		} 
		else
		{
			alarm_debug_out("Invalid command/parameter(s).");
			return;
		}
		if(DbconnFlag==0)
		{
//			printf("%s\n",szOmcIP);
			DbconnFlag = alarm_db_init();
		}		
	}
	else if(strncasecmp(cmdstr, "set DeviceID", 12) == 0)
	{
		pParam = strchr(cmdstr, '=');		
		if(pParam == NULL ||strlen(pParam + 1) > 5)
		{
			alarm_debug_out("Invalid command/parameter(s).");
			return;
		}
		num = atoi(pParam+1);
		if(num>9999)
			selDeviceID=9999;				
		else					
			selDeviceID = num;
		sprintf(info,"DeviceID=%d",selDeviceID);
		alarm_debug_out(info);
	}	
	else if(strncasecmp(cmdstr, "set compCode", 12) == 0)
	{	
		pParam = strchr(cmdstr, '=');
		if(pParam == NULL ||strlen(pParam + 1) > 5)
		{
			alarm_debug_out("Invalid command/parameter(s).");
			return;
		}
		num = atoi(pParam+1);		
		if(num>9999)
			selCompCode=9999;				
		else			
			selCompCode = num;
		sprintf(info,"compCode=%d",selCompCode);
		alarm_debug_out(info);
	}
	else if(strncasecmp(cmdstr, "set alarmCode", 13) == 0)
	{	
		pParam = strchr(cmdstr, '=');
		if(pParam == NULL ||strlen(pParam + 1) > 5)
		{
			alarm_debug_out("Invalid command/parameter(s).");
			return;
		}
		num = atoi(pParam+1);		
		if(num>255)
			selAlarmCode=255;				
		else	
			selAlarmCode = num;
		sprintf(info,"alarmCode=%d",selAlarmCode);
		alarm_debug_out(info);
	}
	else if(strncasecmp(cmdstr, "set sysNo", 9) == 0)
	{	
		pParam = strchr(cmdstr, '=');
		if(pParam == NULL ||strlen(pParam + 1) > 3)
		{
			alarm_debug_out("Invalid command/parameter(s).");
			return;
		}
		num= atoi(pParam+1);		
		if(num>256)
			sysNo=0;				
		else			
			sysNo = num;
		sprintf(info,"sysNo=%d",sysNo);
		alarm_debug_out(info);
	}
	else if(strncasecmp(cmdstr, "set subSysNo", 12) == 0)
	{	
		pParam = strchr(cmdstr, '=');
		if(pParam == NULL ||strlen(pParam + 1) > 3)
		{
			alarm_debug_out("Invalid command/parameter(s).");
			return;
		}
		num = atoi(pParam+1);		
		if(num>256)
			subSysNo=0;				
		else	
			subSysNo = num;
		sprintf(info,"subSysNo=%d",subSysNo);
		alarm_debug_out(info);
	}
	else if(strncasecmp(cmdstr, "set alarmLevel", 13) == 0)
	{	
		pParam = strchr(cmdstr, '=');
		if(pParam == NULL ||strlen(pParam + 1) > 5)
		{
			alarm_debug_out("Invalid command/parameter(s).");
			return;
		}
		num = atoi(pParam+1);		
		if(num>6||num==0)
			selAlarmLevel=6;				
		else
			selAlarmLevel = num;		
		sprintf(info,"alarmLevel=%d",selAlarmLevel);
		alarm_debug_out(info);
	}
	else if(strncasecmp(cmdstr, "set Interval", 12) == 0)
	{	
		pParam = strchr(cmdstr, '=');		
		if(pParam == NULL ||strlen(pParam + 1) > 5)
		{
			alarm_debug_out("Invalid command/parameter(s).");
			return;
		}	
		num = atoi(pParam+1);
		if(num>255||num==0)
			selInterval=5;				
		else	
			selInterval = num;
		sprintf(info,"Interval=%d",selInterval);
		alarm_debug_out(info);
	}
	else if(strncasecmp(cmdstr, "snmp_packet log on", 18) == 0)
	{
		snmp_packet_log =1;
	}
	else if(strncasecmp(cmdstr, "snmp_packet log off", 19) == 0)
	{	
		snmp_packet_log =0;
	}
	else if(strncasecmp(cmdstr, "batch", 19) == 0)
	{
			
	}
	else
	{
		alarm_debug_out("Invalid command/parameter(s).");
		return;
	}
	alarm_debug_out("Command OK");
	return;
}

void alarm_debug(const char *fmt,...)
{
	va_list			ap;
	char			info[1024];		
	
	if(debug_flag==0)
		return;
	strcat(debug_buf, "--");	
	va_start(ap, fmt);
	vsnprintf(info, 1024, fmt, ap);
	va_end(ap);

	alarm_debug_out(info);
}

void alarm_debug_out(char *info)
{
	if(strlen(debug_buf) + strlen(info) > 4096)
	{
		return;
	}

	strncat(debug_buf, info, 4094);
	strcat(debug_buf, "\r\n");
	return;
}

int alarm_GenInit(void)
{
//	DWORD		alarm_oid_prefix[20] = ALARM_AGENT_OID;
	
//	inquire_setmsg(ALARM_AGENT_OIDLEN, alarm_oid_prefix, alarm_set_rsp);	
	inquire_trapmsg(alarm_snmp_trap);	
	sprintf(szVersion, "R%dV%d_%02d", alarm_version[0], alarm_version[1], alarm_version[2]); 
	alarm_MMIInit();
	printf("Alarm Generator ...\n");
	
	testflag			=0;
	DbconnFlag 	=0;
	selDeviceID		=9999;
	selAlarmLevel	=6;	
	selCompCode	=9999;
	selAlarmCode	=255;
	selInterval		=10;
	debug_flag		=1;
	omc_ver			=9;
	snmp_packet_log =0;
	sprintf(szOmcIP,"127.0.0.1");
	alarmlog_init();
	loadConfigure();
	
	return 1;
}


int alarm_db_init(void)
{
	char 	info[1024];
		
	while ((omcPub_conn = mysql_init(NULL)) == NULL) 
	{
		sprintf(info,"Fail to init mysql:%s\n", mysql_error(omcPub_conn));
		alarm_debug_out(info);
		sleep(2);
	}
	sprintf(info,"Connect Datebase:%s\n", szOmcIP);
//	printf("Connect Datebase:%s\n", szOmcIP);
	alarm_debug_out(info);
	if(mysql_real_connect(omcPub_conn, szOmcIP, "root", "rootaa", "OMC_PUB", 0, NULL,0) == NULL) 
	{
		sprintf(info,"Fail to init mysql:%s\n", mysql_error(omcPub_conn));
		alarm_debug_out(info);
		return 0;
	}
//	printf("Connect Datebase ok...\n");
	alarm_debug_out("Connect Datebase ok...\n");
	return 1;
}

void alarm_Gen_timer(void)
{	
	static int m_state = 0,mlog_st = 0;
	if(m_state++>selInterval*5)
	{			
		if(testflag)
			testtimer();
		m_state=0;	
	}
	alarm_MMItimer();
	if(mlog_st++>500)
	{	
		mlog_st = 0;
		alarmlog_timer();
	}
}
/*
int alarm_set_rsp(BYTE oidlen, DWORD *oid, BYTE *pdata, WORD datalen)
{	
	DWORD		*alarmOid = oid + ALARM_AGENT_OIDLEN;
	WORD		*pW;
	int 			p=0;
	BYTE		pri=0;
		
	if(alarmOid[0]==2&&alarmOid[1]==1&&alarmOid[2]==0)
	{
		if(pdata[1]!=0)
			selInterval		=	pdata[1];
		pW					= (WORD *)(pdata+2);
		selDeviceID		= htons(pW[0]);	
		selAlarmLevel = pdata[4];	
		pW					= (WORD *)(pdata+5);
		selCompCode	= htons(pW[0]);	
		selAlarmCode	=	pdata[7];

		if(pdata[0]==0xF1)
		{	
			testflag = 1;				//generate
		}
		else if(pdata[0]==0x1F)
		{	
			testflag = 2;				//clear
			return datalen;
		}
		else
		{
			testflag = 3;				//stop			
			return datalen;
		}
		
		pri=0;
		if(selDeviceID!=0xFFFF)
		{	
			p+=sprintf(szWhere+p,"AND sysTypeNo=%d ",selDeviceID);
			pri++;
		}
		if(selCompCode!=0xFFFF)
		{	
			p+=sprintf(szWhere+p,"AND compCode=%d ",selCompCode);
			pri++;
		}
		if(selAlarmCode!=0xFF)
		{	
			p+=sprintf(szWhere+p,"AND alarmCode=%d ",selAlarmCode);
			pri++;
		}
		if(selAlarmLevel!=0xFF&&pri<3)	
			p+=sprintf(szWhere+p,"AND alarmLevel=%d ",selAlarmLevel);
		printf("%s\n",szWhere);
	}
	
	return datalen;
}
*/
static void sendHeartbeat(int sysTypeNo,int compCode,int alarmCode)
{
	DWORD		oid_prefix[20];
	char 		*oneOid;
	int 			len,sub_sysTypeNo;
	static 		int count=0;
	DWORD		 request_id;
	BYTE		*buf;
//	BYTE		acsii_buf[64];
	time_t		cur_time;
	
	char 		sqlstr[1024];
	char 		info[1024];
	MYSQL_ROW		 get_row;	
	MYSQL_RES 		*get_res;
	
	snmp_pdu pdu;
	snmp_addr request_addr;
			
	pdu.pdu_type = PDU_TRAP;
	pdu.error_status = 0;
	pdu.error_index = 0;
	pdu.request_id = 0;
	pdu.var_num = 1;
	buf = pdu.var[0].msg;
	if(compCode>=9999)
		compCode=0;
	if(sysTypeNo>=9999)	
		sprintf(sqlstr,
				"SELECT maxSysNum,maxSubSysNum,snmpHead,snmpPort,snmpCommunity,sysTypeNo "
				"FROM sysConf WHERE snmpHead > '0' AND needHeartBeat > '0'");		
	else	
		sprintf(sqlstr,
				"SELECT maxSysNum,maxSubSysNum,snmpHead,snmpPort,snmpCommunity,sysTypeNo "
				"FROM sysConf WHERE snmpHead > '0' AND needHeartBeat > '0' AND sysTypeNo='%d'", sysTypeNo);
	
			
	if (mysql_query(omcPub_conn, sqlstr) != 0)
		return;	
	if ((get_res = mysql_store_result(omcPub_conn)) == NULL)
		return;								
	while ((get_row = mysql_fetch_row(get_res)) != NULL) 
	{
		buf[0]	=	sysNo;
		buf[1] = 	subSysNo;
		if(get_row[5]!=NULL)
			sub_sysTypeNo = atoi(get_row[5]);
		sprintf(pdu.community, get_row[4]);
		len = 0;
		while ((oneOid = strsep(&(get_row[2]), "."))) 
		{
			oid_prefix[len] = atol(oneOid);	//<--
			len++;
		}
		if (len < 1)
			break;
		memcpy(pdu.var[0].oid, oid_prefix, len*4);
		pdu.var[0].oidlen = len;
		pdu.var[0].vartype = 4;

		cur_time = time(NULL);
		buf[2] = cur_time >> 24;	// time stamp
		buf[3] = cur_time >> 16;
		buf[4] = cur_time >> 8;
		buf[5] = cur_time;
		buf[6] = 0x99;		//16 LED control code  Byte6-13:
		buf[7] = 90;
		buf[8] = 90;
		buf[9] = 0;
		buf[10] = 0;
		buf[11] = 0;
		buf[12] = 0;
		buf[13] = 0;		
		if(omc_ver==8)
		{	
			buf[14] = compCode;
			buf[15] = alarmCode;	
			buf[16] = 0;
		}
		else
		{	
			buf[14] = compCode>>8;
			buf[15] = compCode&255;	
			buf[16] = alarmCode;
		}
		buf[17] = 0;
		buf[18] = 0;//length 1
	
		buf[19] = 0;//component id
		buf[20] = 0;//component id
	
		buf[21] = 0;
		buf[22] = 20;//length 2	
		
		pdu.var[0].msglen = 23;
		
		request_addr.remote_ip		=inet_addr(szOmcIP);
		request_addr.remote_port	=atoi(get_row[3]);
		request_addr.local_port		=GENPORT;
		request_addr.broadcast		=0;
		
		request_id = snmp_send_self(&pdu, &request_addr);
//		hex_to_ascii(buf,pdu.var[0].msglen,acsii_buf);
//		alarmlog_put("%s->%s:(sysTypeNo=%d  compCode=%d  alarmCode=%d)",acsii_buf,szOmcIP,sub_sysTypeNo,compCode,alarmCode);
		if(request_id==0)
			sprintf(info,"\33[31m%d.Send--->sysTypeNo=%d  compCode=%d  alarmCode=%d  Failed\n\33[37m",count,sub_sysTypeNo,compCode,alarmCode);
		else
			sprintf(info,"%d.Send--->sysTypeNo=%d  compCode=%d  alarmCode=%d  Succeed\n",count,sub_sysTypeNo,compCode,alarmCode);
		alarm_debug(info);
		count++;				
		if(sysTypeNo>=9999)	
			usleep(200);	
	}
	mysql_free_result(get_res);
}

static int testtimer()
{
	char 				sqlstr[2048];
	MYSQL_ROW		 get_row;	
	static MYSQL_RES 		*get_res;
	static int 						send_state = 0;	
	if(DbconnFlag==0)
	{
		alarm_debug_out("connect to omc server Error!");
		testflag = 0;
		return 0;
	}	
	if(testflag==1)			//generate
	{
		switch (send_state) 
		{
			case 0:
				sprintf(sqlstr,"SELECT sysTypeNo,compCode,alarmCode FROM sysAlarmConf WHERE 2=2 %s",szWhere);							
				alarm_debug(sqlstr);			 
				alarmlog_put(sqlstr);				
				if (mysql_query(omcPub_conn, sqlstr) != 0)
					return -1;	
				if ((get_res = mysql_store_result(omcPub_conn)) == NULL)
					return -1;				
				send_state = 1;
				return 0;
			case 1:	
				if ((get_row = mysql_fetch_row(get_res)) != NULL) 
				{
					if(get_row[0]!=NULL&&get_row[1]!=NULL&&get_row[2]!=NULL)								
						sendHeartbeat(atoi(get_row[0]),atoi(get_row[1]),atoi(get_row[2]));
					return 0;
				}
				
				if(get_res!=NULL)
					mysql_free_result(get_res);
				alarm_debug_out("Completed.");
				alarmlog_put("Completed.");
				send_state 	= 0;		
				testflag 		= 0;		
				return 0;
			default:
				if(get_res!=NULL)
					mysql_free_result(get_res);				
				send_state = 0;
				testflag = 0;
				return 0;
		}
	}
	else if(testflag==2)			//clear
	{
		if(selCompCode!=0xFFFF)
			sendHeartbeat(selDeviceID,selCompCode,0);
		else	
			sendHeartbeat(selDeviceID,0,0);
		alarm_debug_out("Completed.");
		alarmlog_put("Completed.");
		send_state = 0;	
		testflag = 0;		
		return 0;					
	}
	else if(testflag==3)			//stop
	{
		send_state = 0;
		testflag = 0;
		if(get_res!=NULL)
			mysql_free_result(get_res);
		alarm_debug_out("Stoped.");
		alarmlog_put("Stoped.");
		return 0;
	}
	return 0;
}

void alarm_snmp_trap(BYTE oidlen,DWORD *oid, BYTE *pdata,WORD msg_len,snmp_addr *addr)
{
	DWORD		*alarmOid = oid + wxc2_trap_prelen;
	BYTE		*pBYTE;
	if(alarmOid[0]==4)//OMC
	{
		if(pdata[0] == 0)
		{	
			omc0_ip = addr->remote_ip;
			pBYTE	   = (BYTE *)&omc0_ip;
//			sprintf(szOmcIP,"%d.%d.%d.%d",pBYTE[0],pBYTE[1],pBYTE[2],pBYTE[3]);			
//			if(DbconnFlag==0)
//			{
//				printf("%s\n",szOmcIP);
//				DbconnFlag = alarm_db_init();
//			}
		}
	}	
 
}


void alarmlog_init() 
{
		
	char log_file[64],cmdstr[64];
		
	long l_time;		
	struct tm *t;

	if (access("./log", F_OK) != 0)
	{		
		sprintf(cmdstr, "mkdir -p -m755 ./log");				
		printf("%s\n", cmdstr);				
		system(cmdstr);			
	}
			
	l_time = time(NULL);		
	t = localtime(&l_time);	
	
	sprintf(log_file, "./log/alarmGen_%02d_%02d.log", 
				  t->tm_mon + 1, t->tm_mday);
		
	if (alarmlog_fp != NULL)
		fclose(alarmlog_fp);								
	alarmlog_fp = fopen(log_file, "a");
	alarmlog_put("Alarm Generator(R%dV%d_%02d) start up.%s%s", 
								alarm_version[0], alarm_version[1], alarm_version[2],ctime(&l_time),log_file);
}

void alarmlog_put(const char *fmt, ...) 
{	
	char buf[2048];
		
	va_list ap;
		
	if (alarmlog_fp == NULL)
		return;
		
	va_start(ap, fmt);
		
	vsprintf(buf, fmt, ap);
	fputs(buf, alarmlog_fp);
	fputs("\n", alarmlog_fp);
//	if(fputs(buf, alarmlog_fp)>0){
//		printf("write OK\n");
//	}else{
//		perror("write error\n");
//	}
		
	fflush(alarmlog_fp);
//	if(fflush(alarmlog_fp)==0){
//		printf("flush OK\n");
//	}else{
//		perror("flush error\n");
//	}
		
	va_end(ap);
}

void alarmlog_timer() 
{
	long l_time;		
	struct tm *t;
	static int ch = 0;		
	
			
	l_time = time(NULL);		
	t = localtime(&l_time);
	
	if (t->tm_hour == 0 && ch == 0)			
	{		
		alarmlog_init();
		ch = 1;
	}		
	else if (t->tm_hour > 0)
		ch = 0;
}


int	hex_to_ascii(BYTE *from_hex, BYTE from_len, BYTE *to_asc)
{
	int	i, j;
	
	j = 0;
	
	for (i = 0; i< from_len; i++)
	{
		to_asc[j] = ascii[from_hex[i] >> 4];
		j++;
		to_asc[j] = ascii[from_hex[i] & 0x0F];
		j++;
		to_asc[j] = ' ';
		j++;
	}
	
	to_asc[j] = '\0';
	
	return 1;
}

static DWORD assign_rid()
{
	static DWORD	rid = 1; 

	rid = (rid-1)%0x10000000+2; 
	return rid; 
}

int snmp_send_self(snmp_pdu *msgbuf, snmp_addr *addr)
{
	message_list		msgout; 
	BYTE					acsii_buf[1500];
	
	if(msgbuf->var_num == 0 || msgbuf->var_num >50)
		return 0; 

	switch(msgbuf->pdu_type)
	{
	case PDU_SET:
		msgbuf->error_index = msgbuf->error_status = 0; 
		if(msgbuf->request_id == 0  )
			msgbuf->request_id = assign_rid(); 
		break; 
	case PDU_GET:
		msgbuf->error_index = msgbuf->error_status = 0; 
		if(msgbuf->request_id == 0  )
			msgbuf->request_id = assign_rid(); 
		break; 
	case PDU_TRAP:
		msgbuf->request_id = 1; 
		break; 
	case PDU_RSP:
		break; 
	default:
		return 0; 
	}

	msgout.msgLength = build_snmpmsg(msgout.msgContent , msgbuf); 
	if(msgout.msgLength == 0 || msgout.msgLength > 1500)
	{
		return 0; 
	}
	if(snmp_packet_log)
	{	
		hex_to_ascii(msgout.msgContent,msgout.msgLength,acsii_buf);
		alarmlog_put("SNMP: %s",acsii_buf);
	}
	msgout.msgDstIP = addr->remote_ip ; 
	msgout.msgDstPort  = addr->remote_port ; 
	msgout.msgSrcIP = addr->local_ip ; 
	msgout.msgSrcPort = addr->local_port ; 
	msgout.msgBroadcast = addr->broadcast ; 
	
	if(iptrPutMessage(msgout) == 0)
		return 0; 
	else
		return msgbuf->request_id; 
}

int build_snmpmsg(BYTE *pbuf, snmp_pdu *psnmp)
{
	BYTE		msg[2000]; 
	short		pos = 1900, len; 
	var_list	*pvar; 
	BYTE		var_num; 
	BYTE		idlen; 
	DWORD		*poid, val; 
	short		stack[10]; 
	BYTE		pstack = 0; 
	BOOL		error_status = 0; 

		
	var_num = psnmp->var_num; 
	for(pstack = 0; pstack < 5; pstack++)
		stack[pstack] = pos; 			//push
	
	while(var_num-- >0)
	{
		stack[pstack++] = pos; 		//push
		pvar = &psnmp->var[var_num]; 
		if(psnmp->pdu_type == PDU_GET)
		{
			pvar->vartype = 5; 
			pvar->msglen = 0; 
		}
		else
		{
			switch(pvar->vartype)
			{
			case 5:		//NULL
			case NoSuchObject:
			case NosuchInstance:
			case EndOfMibView:
				pvar->msglen = 0; 
			}
		}
		poid = pvar->oid; 
		//Value
		if(pvar->msglen>SNMP_VAR_MAX)
		{
			if(psnmp->error_status == 0)
			{
				psnmp->error_status = 1; 			//Too big
				psnmp->error_index = var_num; 
			}
//			snmp_debug(SNMPDB_ERR, "Variable length(%d) exceed limit:varindex = %d", pvar->msglen, SNMP_VAR_MAX, var_num); 
			pvar->msglen = 0; 
			error_status = 1; 
		}
		else if((pos - pvar->msglen) < 500)
		{
			if(psnmp->error_status == 0)
			{
				psnmp->error_status = 1; 			//Too big
				psnmp->error_index = var_num; 
			}
			pvar->msglen = 0; 
			error_status = 1; 
		}
		else if(pvar->msglen > 0)
		{
			memcpy(msg + pos - pvar->msglen + 1, pvar->msg, pvar->msglen); 	//V
		}
		pos -= pvar->msglen; 

		insert_length(msg, pos, pvar->msglen); 					//L
		msg[pos--] = pvar->vartype; 								//T
		//Object ID
		stack[pstack++] = pos; 		//push
		
		idlen = pvar->oidlen; 
		if(idlen >= OID_MAXLEN)
		{
//			snmp_debug(SNMPDB_ERR, "OIDs Length(%d) is Invalid.", idlen); 
			return 0; 
		}

		while(idlen-- > 2)										//V
		{
			val = poid[idlen]; 
			if(val < 0x80)			//1byte
				*(msg + (pos--)) = val; 
			else if(val < 0x4000)	//2byte
			{
				*(msg + (pos--)) = val & 0x7F; 
				*(msg + (pos--)) = ((val & 0x3FFF) >> 7) | 0x80; 
			}
			else if(val < 0x200000)	//3byte
			{
				*(msg + (pos--)) = val & 0x7F; 
				*(msg + (pos--)) = ((val & 0x3FFF) >> 7) | 0x80; 
				*(msg + (pos--)) = (val >> 14) | 0x80; 
			}
			else if(val < 0x10000000)	//4byte
			{
				*(msg + (pos--)) = val & 0x7F; 
				*(msg + (pos--)) = ((val & 0x3FFF) >> 7) | 0x80; 
				*(msg + (pos--)) = ((val & 0x1FFFFF) >> 14) | 0x80; 
				*(msg + (pos--)) = (val >> 21) | 0x80; 
			}
			else					//5byte
			{
				*(msg+(pos--)) = val & 0x7F; 
				*(msg+(pos--)) = ((val & 0x3FFF) >> 7) | 0x80; 
				*(msg+(pos--)) = ((val & 0x1FFFFF) >> 14) | 0x80; 
				*(msg+(pos--)) = ((val & 0x0FFFFFFF) >> 21) | 0x80; 
				*(msg+(pos--)) = (val>>28) | 0x80; 
			}
		}
		if(poid[0] > 3 || (poid[0] < 3 && poid[1] >= 40))
		{
//			snmp_debug(SNMPDB_ERR, "Wrong oid, varindex = %d, oid = %ld.%ld...\n", var_num, poid[0], poid[1]); 
			return 0; 
		}
		*(msg + (pos--)) = poid[idlen] + poid[idlen - 1] * 40; 


		len = stack[--pstack] - pos; 	//pop
		insert_length(msg, pos, len); 								//L
		msg[pos--] = 0x06; 
		//Variable
		len = stack[--pstack] - pos; 	//pop
		insert_length(msg, pos, len); 		//L
		msg[pos--] = 0x30; 					//T
	}; 
	
	//Variable Binding
	len = stack[--pstack] - pos; 	//pop
	insert_length(msg, pos, len); 						//L
	msg[pos--] = 0x30; 									//T
	//error index
	msg[pos--] = psnmp->error_index; 					//V
	msg[pos--] = 1; 										//L
	msg[pos--] = 0x02; 									//T
	//error status
	msg[pos--] = psnmp->error_status ; 					//V
	msg[pos--] = 1; 										//L
	msg[pos--] = 0x02; 									//T
	//request-id
	enc_integer(msg, pos, psnmp->request_id); 			//V L
	msg[pos--] = 0x02; 									//T
	//PDU
	len = stack[--pstack] - pos; 	//pop
	insert_length(msg, pos, len); 							//L
	msg[pos--] = psnmp->pdu_type | 0xA0; 					//T
	//community

	if(psnmp->pdu_type == PDU_TRAP)
	{
		memcpy(msg + pos - 5, (BYTE *)COMMUNITY, 6); 			//V
		pos -= 6; 
		msg[pos--] = 6; 
	}
	else
	{
#if SNMP_ANY_COMMUNITY
		psnmp->community[15] = 0; 							//max length = 15
		comm_len = strlen(psnmp->community); 

		memcpy(msg + pos - comm_len + 1, (BYTE *)psnmp->community, comm_len); 			//V
		pos -= comm_len; 
		msg[pos--] = comm_len; 
#else						//use "public" as community
		memcpy(msg + pos - 5, (BYTE *)COMMUNITY, 6); 			//V
		pos -= 6; 
		msg[pos--] = 6; 
#endif
	}
	if(pos<4)   return 0;
	/*added by LHB, Oct. 30 04 */
	if(pstack<2) return 0;
	/*added by LHB, Oct. 30 04 */
											//L
	msg[pos--] = 0x04; 								//T
	//version
	msg[pos--] = SNMP_V2; 								//V
	msg[pos--] = 1; 									//L
	msg[pos--] = 0x02; 								//T
	//head
	len = stack[--pstack] - pos; 	//pop
	if(len<0) return 0;
	insert_length(msg, pos, len); 							//L
	msg[pos--] = 0x30; 									//T
	len = stack[--pstack] - pos; 	//pop
	if(len<0) return 0;	
	memcpy(pbuf, msg + pos + 1, len); 
	return len; 
}

int loadConfigure()
{
   char confile[]={"./conf/alarmGen.conf"};
   char s[80],s1[80];//work[80];
   int len;
//   int  loop,priority,port,len,type,direct=0;
//   char *off;
   FILE *fpConf;
    
   fpConf = fopen(confile,"rb");
   if(fpConf==NULL)
   {
	  printf("%s not found!\n",confile);
   }
   else
   {
      strcpy(s,"");
      strcpy(s1,"");
      if(fgets(s,1024,fpConf) !=(char *)0)
      {
        len = strlen(s);
        if(len >15||len==0) 
        {
        	printf("Error line: %s len=%d\n",s,len);
        }
        else
        {	
        	memcpy(szOmcIP,s,len);
        }

      }
	  fclose(fpConf);
   }
   return 1;
}
 
 int saveConfigure()
{
   char confile[]={"./conf/alarmGen.conf"};
   FILE *fpConf;
    
   fpConf = fopen(confile,"w");
   if(fpConf==NULL)
   {
	  printf("%s not found!\n",confile);
   }
   else
   {
		fputs(szOmcIP, fpConf);
		fclose(fpConf);
   }
   return 1;
}
