#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>

#include "NetSDKDLL.h"
#include "common_head.h"
#include "msg_def.h"
#include "configlib.h"

 
#define  CONFIG_FILE   "demoTestConfig.cfg"


#define V_HEADFLAG    "1234567890"
int g_LogonOk = 0 ;
long gHandle_realplay = NULL;
LONG m_nLastCmdId=NULL;

int g_newVidRecord = 0;
int g_newAudRecord = 0;

STREAM_AV_PARAM * g_AVParam=NULL;
char g_ip[20] = "" , 
     g_user[20] = "",
     g_pass[20] = "" ;
int g_onMediaRecv = 0; 
int g_port = 0;

static char remotefilename[256];

static unsigned long getmstime()
{
    struct timespec ts;

    clock_gettime(CLOCK_MONOTONIC, &ts);

    return (ts.tv_sec * 1000 + ts.tv_nsec / 1000000);
    
}
/*
struct stateEvent
{
	EVENT_CONNECTING,   //0
	EVENT_CONNECTOK,
	EVENT_CONNECTFAILED,
	EVENT_SOCKETERROR,
	EVENT_LOGINOK,
	EVENT_LOGINFAILED,   //5
	EVENT_STARTAUDIOOK,
	EVENT_STARTAUDIOFAILED,
	EVENT_STOPAUDIOOK,
	EVENT_STOPAUDIOFAILED,
	EVENT_SENDPTZOK,    //10
	EVENT_SENDPTZFAILED,
	EVENT_SENDAUXOK,
	EVENT_SENDAUXFAILED,
	EVENT_UPLOADOK,
	EVENT_UPLOADFAILED,  //15
	EVENT_DOWNLOADOK,
	EVENT_DOWNLOADFAILED,
	EVENT_REMOVEOK,
	EVENT_REMOVEFAILED,
	EVENT_SENDPTZERROR,   //20
	EVENT_PTZPRESETINFO,  
	EVNET_PTZNOPRESETINFO,
	EVENT_PTZALARM,
	EVENT_RECVVIDEOPARAM,
	EVENT_RECVAUDIOPARAM,  //25
	EVENT_CONNECTRTSPERROR,
	EVENT_CONNECTRTSPOK,
	EVENT_RTSPTHREADEXIT,
	EVENT_URLERROR,
	EVENT_RECVVIDEOAUDIOPARAM,  //30
	EVENT_LOGIN_USERERROR,
	EVENT_LOGOUT_FINISH,			//登录线程已停止
	EVENT_LOGIN_RECONNECT,			//进行重新登录   33
	EVENT_LOGIN_HEARTBEAT_LOST,		//心跳丢失
	EVENT_STARTAUDIO_ISBUSY,		//  35
	EVENT_STARTAUDIO_PARAMERROR,
	EVENT_STARTAUDIO_AUDIODDISABLED,
	EVENT_CONNECT_RTSPSERVER_ERROR,
	EVENT_CREATE_RTSPCLIENT_ERROR,
	EVENT_GET_RTSP_CMDOPTION_ERROR,     //40
	EVENT_RTSP_AUTHERROR,
	EVNET_RECORD_FILEBEGIN,
	EVENT_RECORD_FILEEND,
	EVENT_RECORD_TASKEND,
	EVENT_RECORD_DISKFREESPACE_TOOLOW,  //45
	EVNET_RECORD_FILEBEGIN_ERROR,
	EVNET_RECORD_WRITE_FILE_ERROR,
	EVENT_RECORD_INITAVIHEAD_ERROR,
	EVENT_RECORD_MEDIA_PARAM_ERROR,	   //49
};
*/

typedef struct
{
  int wSecond;			 /* Seconds.	 [0-60] (1 leap second) */
  int wMinute;			 /* Minutes.	 [0-59] */
  int wHour;			 /* Hours.	 [0-23] */
  int wDay;			    /* Day.		 [1-31] */
  int wMonth;			 /* Month.	 [0-11] */
  int wYear;			 /* Year	 - 1900.  */
  int wDayOfWeek;		 /* Day of week.	 [0-6] */
  int tm_yday;			 /* Days in year.[0-365]	 */
  int tm_isdst;			 /* DST.		 [-1/0/1]*/
#ifdef	 __USE_BSD
  long int tm_gmtoff;		 /* Seconds east of UTC.  */
  __const char *tm_zone;	 /* Timezone abbreviation.  */
#else
  long int __tm_gmtoff;		 /* Seconds east of UTC.  */
  __const char *__tm_zone;	 /* Timezone abbreviation.  */
#endif
}SYSTEMTIME;

void GetLocalTime1(SYSTEMTIME *st)
{
    if(st)
    {
        struct tm *pst = NULL;
        time_t t = time(NULL);
        pst = localtime(&t);
        memcpy(st,pst,sizeof(SYSTEMTIME));
        st->wYear += 1900;
    }
}

LONG  OnStateEvent(LONG lUser,LONG nStateCode,char *pResponse,void *pUser)
{
    //IP_NET_DVR_PTZControl(lUser,UP_LEFT,5,5);

    int i=0 ; 
    printf("get one state:%ld\n",nStateCode);
    switch(nStateCode)
	{		
		case	EVNET_RECORD_FILEBEGIN:
		case	EVENT_RECORD_FILEEND:
		case	EVENT_RECORD_TASKEND:
		case	EVENT_RECORD_DISKFREESPACE_TOOLOW:
		case	EVNET_RECORD_FILEBEGIN_ERROR:
		case	EVNET_RECORD_WRITE_FILE_ERROR:
		case	EVENT_RECORD_INITAVIHEAD_ERROR:
		case	EVENT_RECORD_MEDIA_PARAM_ERROR:
		{

		}
		break;
	    case EVENT_RECVVIDEOAUDIOPARAM:
		{
            printf("$$$$$$$$$$$$$$$$$EVENT_RECVVIDEOAUDIOPARAM$$$$$$$$$ puser:%s\n",(char *)pUser);
            int playport = 554 ;
            int size=sizeof(VIDEO_PARAM);
            STREAM_AV_PARAM * pParam=(STREAM_AV_PARAM*)pResponse;
            g_AVParam = pParam ;
        }
		break;
        case EVENT_SOCKETERROR:
		{
            printf("::::::::::::EVENT_SOCKETERROR!!!!!!!!!!\n");
		}
		break;
		case EVENT_CONNECTING:
		{
            printf("::::::::::::EVENT_CONNECTING!!!!!!!!!!\n");
		}
		break;
		case EVENT_CONNECTOK:
		{
            printf("::::::::::::EVENT_CONNECTOK!!!!!!!!!!\n");
		}
		break;
		case EVENT_CONNECTFAILED:
		{
            printf("::::::::::::EVENT_CONNECTFAILED!!!!!!!!!!\n");
		}
		break;
		case EVENT_LOGINOK:
		{
			for(i=0 ; i<5 ; i++)
			{
				printf("::::::::::::Login OK!!!!!!!!!!\n");
			}
			g_LogonOk =1 ;
		}
		break;
		case EVENT_PTZALARM:
		{
            
            ALARM_ITEM* pa = (ALARM_ITEM*)pResponse;
            printf("EVENT_PTZALARM, code:%d\n", pa->code);
            if(pa->code == ALARM_CODE_JPEG_CAPTURED)
            {
                printf("snap pic done, we download it at, time:%lu .\n", getmstime());
                char tmp[256];
                snprintf(tmp, 256, "/tmp/%s", remotefilename);
                IP_NET_DVR_GetFileByName(m_nLastCmdId, 1, tmp, (char*)"./");
            }
		}
		break;
		case EVENT_PTZPRESETINFO:
		{

		}
		break;
		case EVENT_SENDPTZOK:
		{			

		}
		break;
		case EVENT_DOWNLOADOK:
		{
            //endtime = getmstime();
            printf("EVENT_DOWNLOADOK");// end time:%lu\n", endtime);
            //printf("download ok, use time(%lu)ms\n", endtime - begintime);
			
			if(0)
            {
                int ret = 0;
                char xml[256] = "<REQUEST_PARAM\n"
                                "Stream=\"0\"\n"
                                "Quality=\"100\"\n"
                                "PictureId=\"testpic\"\n"
                                "/>\n";
                //begintime = getmstime();
                //printf("IP_NET_DVR_SystemControl(CMD_SNAP_JPEG_PICTURE) begin time:%lu\n", begintime);
                ret = IP_NET_DVR_SystemControl(m_nLastCmdId, (long)CMD_SNAP_JPEG_PICTURE, 0, xml);
            	if(ret<0)
            	{
            		printf("snappic error!\n");
            	}
                else
                {
                    printf("IP_NET_DVR_SystemControl return ok\n");
                }
            }
		}
		break;
		case EVENT_UPLOADOK:
		{

		}
		break;
		case EVENT_UPLOADFAILED:
		{

		}
		break;
		case EVENT_DOWNLOADFAILED:
		{
            //endtime = getmstime();
            //printf("download fail, use time(%lu)ms\n", endtime - begintime);
            if(0)
            {
                int ret = 0;
                char xml[256] = "<REQUEST_PARAM\n"
                                "Stream=\"0\"\n"
                                "Quality=\"100\"\n"
                                "PictureId=\"testpic\"\n"
                                "/>\n";
                //begintime = getmstime();
                //printf("IP_NET_DVR_SystemControl(CMD_SNAP_JPEG_PICTURE) begin time:%lu\n", begintime);
                ret = IP_NET_DVR_SystemControl(m_nLastCmdId, (long)CMD_SNAP_JPEG_PICTURE, 0, xml);
            	if(ret<0)
            	{
            		printf("snappic error!\n");
            	}
                else
                {
                    printf("IP_NET_DVR_SystemControl return ok\n");
                }
            }
		}
		break;
		case EVENT_STARTAUDIOFAILED:
		{

		}
		break;
		case EVENT_STARTAUDIOOK:
		{

		}
		break;
		default:
		{

		}
		break;
	}

    return 0;
}

struct VIDEOINFO
{
    char beginFlag[10];
    int dataType;
    long bufSize;
    int		bIsKey;
	double	timestamp;
	//void    *pUserData;
};

struct AUDIOINFO
{
    char beginFlag[10];
    int dataType;
    long bufSize;
	double	timestamp;
	//void    *pUserData;
};

LONG  OnMediaRecv(LONG lRealHandle,DWORD dwDataType,BYTE *pBuffer,DWORD dwBufSize,LPFRAME_EXTDATA  pExtData)
{

    size_t wsize = 0;

    if(!g_onMediaRecv)
    {
        return 0;
    }
    
    if(dwDataType == 0)
    {
 
        struct VIDEOINFO *videoInfo = (struct VIDEOINFO*)malloc( sizeof(struct VIDEOINFO) );
        if(videoInfo ==NULL)
        {
            printf("malloc error!\n");
            return 0;
        }
        memset(videoInfo,0,sizeof(struct VIDEOINFO) );
        sprintf(videoInfo->beginFlag,"%s",V_HEADFLAG);
        videoInfo->bIsKey = (int) pExtData->bIsKey ;
        videoInfo->bufSize = (long) dwBufSize;
        videoInfo->dataType = (int) dwDataType ;
        
        static FILE * pf_video=NULL;
	    if(pf_video==NULL || g_newVidRecord==1 )
	    {

            if(pf_video)
            {
                fclose(pf_video);
            }
            
            if(g_newVidRecord==1)
            {
                g_newVidRecord=0;
            }
            
            char savefile[256];
            SYSTEMTIME tm;
        	GetLocalTime1(&tm);	
            snprintf(savefile,256,"%02d%02d.h264", tm.wMinute,tm.wSecond);

		    pf_video=fopen(savefile,"wb+");
            if(pf_video == NULL)
            {
                printf("open file error!\n");
                return 0;
            }
            /*
            if(g_AVParam)
            {
                fseek(pf_video,0,SEEK_SET);
                wsize = fwrite(g_AVParam,1,sizeof(STREAM_AV_PARAM),pf_video );
                if(wsize <1)
                {
                    printf("write AVParam error!\n");
                }
            }
            else
            {
                printf("get AVParam error!\n");
                return 0;
            }
            */
	    }
        
        //wsize = fwrite(videoInfo,1,sizeof(struct VIDEOINFO),pf_video); 
        free(videoInfo);
        wsize = fwrite(pBuffer,1,dwBufSize,pf_video);
        printf("OnMediaRecv video,size:%d\n",wsize); 

    }
    else if(dwDataType == 1)
    {
        struct AUDIOINFO *audioInfo = (struct AUDIOINFO*)malloc( sizeof(struct AUDIOINFO) );
        if(audioInfo ==NULL)
        {
            printf("malloc error!\n");
            return 0;
        }
        memset(audioInfo,0,sizeof(struct AUDIOINFO) );
        sprintf(audioInfo->beginFlag,"%s",V_HEADFLAG);

        audioInfo->bufSize = (long) dwBufSize;
        audioInfo->dataType = (int) dwDataType ;
 
		static FILE * pf_audio=NULL;
        
		if(pf_audio==NULL || g_newAudRecord==1 )
		{
            if(pf_audio)
            {
                fclose(pf_audio);
            }
            
            if(g_newAudRecord==1)
            {
                g_newAudRecord=0;
            }
            
            char savefile[256];
            SYSTEMTIME tm;
        	GetLocalTime1(&tm);	
            snprintf(savefile,256,"%02d%02d.g711", tm.wMinute,tm.wSecond);
            
			pf_audio=fopen(savefile,"wb+");

            if(pf_audio == NULL)
            {
                printf("open file error!\n");
                return 0;
            }
            /*
            if(g_AVParam)
            {
                fseek(pf_audio,0,SEEK_SET);
                wsize = fwrite(g_AVParam,1,sizeof(STREAM_AV_PARAM),pf_audio );
                if(wsize <1)
                {
                    printf("write AVParam error!\n");
                }
            }
            else
            {
                printf("get AVParam error!\n");
            }
            */            
		}


        //wsize = fwrite(audioInfo,1,sizeof(struct AUDIOINFO),pf_audio);
       
		wsize = fwrite(pBuffer,1,dwBufSize,pf_audio);
        printf("OnMediaRecv audio,size:%d\n",wsize);
        
        int ret_inAudio=0;
        //ret_inAudio=IP_TPS_InputAudioData(554,pBuffer,dwBufSize,(DWORD)pExtData->timestamp);
        if(ret_inAudio)
        {
            printf("########################IP_TPS_InputAudioData ERROR :%d\n",ret_inAudio);
        }

        free(audioInfo);
    }
    else if(dwDataType == 2)
    {
        printf("OnMediaRecv param\n");
    }
    
    return 0;
}

LONG CALLBACK OnAUXResponse(LONG lUser,LONG nType,char *pResponse,void *pUser)
{
    
    int ErrorCode=nType & 0xff000000;
	int ActionCode=nType & 0xffffff;

    printf("\nOnAUXResponse. acitionCode:%d \n",ActionCode);
    printf("%s\n",pResponse);
    
	switch(ActionCode)
	{
    	case CMD_SYSTEM_MANAGE_BASE + 34:
    	{
    		int error=1;
    		
    	}
    	break;
    	case CMD_GET_SERIALNUMBER:
    	{

    	}
    	break;
    	case CMD_GET_LOGFILE_LIST:
    	{//日志返回信息

    	}
    	break;
    	case CMD_GET_RECORD_FILE_LIST:
    	{

    	}
    	break;
    	case CMD_GET_SYSTEMCONTROLSTRING:
    	{//获取能力集

    	}
    	break;
        
    	case CMD_GET_MEDIA_VIDEO_CONFIG:
    	{

    	}
    	break;
        
    	case CMD_SNAP_JPEG_PICTURE:
    	{
            char* fname = (char*)malloc(strlen(pResponse)+1);
            if(!fname)
            {
                printf("malloc fail\n");
                break;
            }

            if(1 == sscanf(pResponse, "%*[^\"]\"%[^\"]", fname))
            {
                printf("CMD_SNAP_JPEG_PICTURE, filename:%s, download it\n", fname);
                //IP_NET_DVR_GetFileByName(m_nLastCmdId, 1, fname, (char*)"./");                
                strncpy(remotefilename, fname, 256);
            }
            free(fname);
    	}
    	break;
	}
    
    
    return 0;
}

int cfg_GetLogonInfo(char*ip , char*user, char* pass, int *port)
{
    char buf[20];
    int ret ;
    ret = ConfigGetKey( (void*)CONFIG_FILE, (void*)"Logon", (void*)"logon_ip", buf);
    sprintf(ip,"%s",buf);

    ret = ConfigGetKey( (void*)CONFIG_FILE, (void*)"Logon", (void*)"logon_user", buf);
    sprintf(user,"%s",buf);    

    ret = ConfigGetKey( (void*)CONFIG_FILE, (void*)"Logon", (void*)"logon_pass", buf);
    sprintf(pass,"%s",buf);

    ret = ConfigGetKey( (void*)CONFIG_FILE, (void*)"Logon", (void*)"logon_port", buf);
    //sprintf(port,"%s",buf);   
    *port = (int)atol(buf);

    printf("=========================================\n");
    printf("==========[%s]\n",CONFIG_FILE);
    printf("logon_ip:%s\n",ip);
    printf("logon_user:%s\n",user);
    printf("logon_pass:%s\n",pass);
    printf("logon_port:%d\n",*port);

    usleep(1000*1000);
    printf("==========press Ctrl+c to abort, Enter to continue ... \n");
    //printf("press Ctrl+c to abort\n");
    while( !getchar() )
    {
        usleep(1000*100);
    }

    return 0;
}


int ptzControl(long lUserID)
{
    char cmdstr[100];

    char xmldata[1200];
    long nPspeed=5,nTspeed=5;

    printf("============================================\n");
    printf("enter  ptz control, input 'ptz esc' to quit ,'help' for detail \n");
    printf("============================================\n");
    while( fgets(cmdstr,sizeof(cmdstr),stdin) )
    {
        
        if( strlen(cmdstr) <2 )
        {
            continue;
        }
        
        if( !strncmp(cmdstr,"ptz esc",strlen("ptz esc") ) )
        {
            break;
        }
        else if( !strncmp(cmdstr,"esc",strlen("esc") ) )
        {
            break;
        }
        else if( !strncmp(cmdstr,"help",strlen("help") ) )
        {
            printf("============================================\n");
            printf("valid command :[up] [down] [left] [right] [stop] [esc]....\n");
            printf("See documents for more details\n");
            printf("============================================\n");
            continue;
        }

        if(strlen(cmdstr) >1)
        {
           cmdstr[strlen(cmdstr)-1]='\0';
        }

        printf("get ptzcmd ----%s--\n",cmdstr);
        
        sprintf(xmldata,"<xml>\n<cmd>%s</cmd><panspeed>%ld</panspeed><tiltspeed>%ld</tiltspeed></xml>",cmdstr,nPspeed,nTspeed);

        IP_NET_DVR_PTZControlEx(lUserID,(char *)xmldata);

        Sleep(10);

    }

    printf(" quit  ptz control! \n");

}

int showCmdCtlHelp()
{
    printf("============================================\n");
    printf("valid commands:[begin searchIPC] [stop searchIPC] [ptz begin] \n" );
    printf("[begin realplay] [stop realplay] [show debug] [hide debug] [readsn] \n");
    printf("[get config]...\n");
    printf("See documents for more details\n");
    printf("============================================\n");
    
    return 0;
}

int waitforLogon()
{
    printf("\n##########Logon...");
    while(1)
    {
        if(g_LogonOk)
        {
            break;
        }
        printf(".");
        usleep(1000*1000*1);
        
    }
    
    printf(".\n");
}

int commandProcess()
{

    char inStr[300];
 
    LONG ret=0;
    Sleep(1);
    printf("============================================\n");
    printf("enter command control , input 'ctrl+c' to quit ,'help' for details\n");
    printf("============================================\n");
    while(fgets(inStr, sizeof(inStr), stdin))
    {
        if( strlen(inStr) <2 )
        {
            continue;
        }

        inStr[strlen(inStr)-1]='\0';
        printf("input str: %s%s%s\n","---",inStr,"--");

        if( !strcmp(inStr,"begin searchIPC") )
        {
            ret = IP_NET_DVR_StartSearchIPC();
            if(ret)
            {
                printf("#######call IP_NET_DVR_StartSearchIPC() fail\n");
            }
            
        }/*
        else if( !strcmp(inStr,"logon") )
        {
            //cfg_GetLogonInfo(ip,user,pass,&port);


            //m_nLastCmdId=IP_NET_DVR_Login((char *)ip,port,(char *)user,(char *)pass,NULL);
            if(m_nLastCmdId==0)
            {
        	    printf("call logon error!");
        	    return 0;
            }else
            {
                //printf("call logon OK!");
            }
        }*/
        else if( !strcmp(inStr,"stop searchIPC") )
        {            
            
            IP_NET_DVR_StopSearchIPC();
            long ipc_count = IP_NET_DVR_GetSearchIPCCount();
            printf("SearchIPC get IPC count: %ld\n",ipc_count);
            for(int idx=0;idx<ipc_count;idx++)
			{
				IPC_ENTRY info;
				int ErrorCode=IP_NET_DVR_GetIPCInfo(idx,&info);
				if(ErrorCode>=0)
				{//读成功了

                    printf("type:%s ipAddr:%s macAddr:%s\n",info.deviceType,
                                                            info.lanCfg.IPAddress,
                                                            info.lanCfg.MACAddress);				
				}
            }
            IP_NET_DVR_SearchIPCReleaseInfo();
        }
        else if( !strcmp(inStr,"ptz begin") )
        {
            ptzControl(m_nLastCmdId);
        }
        else if( !strcmp(inStr,"begin realplay") )
        {

            g_onMediaRecv = 1;
            
            USRE_VIDEOINFO userinfo;
            userinfo.bIsTcp=1;
            userinfo.nVideoPort=554;
            userinfo.nVideoChannle=1;
            userinfo.pUserData=(char *)"12";
            gHandle_realplay = IP_NET_DVR_RealPlayEx((char *)g_ip,(char *)g_user,(char *)g_pass,OnMediaRecv,&userinfo,1);
            if(gHandle_realplay!=0)
            {
                printf("realplay retValue:%ld\n",gHandle_realplay);
            }
        }
        else if( !strcmp(inStr,"stop realplay") )
        {
            g_onMediaRecv =0 ;
            g_newVidRecord = 1;
            g_newAudRecord = 1;
            IP_NET_DVR_StopRealPlay(gHandle_realplay);             
        }
        else if( !strcmp(inStr,"show debug") )
        {
            IP_NET_DVR_SetLogToFile(3,(char*)".",0);
        }
        else if( !strcmp(inStr,"hide debug") )
        {
            //IP_NET_DVR_SetLogToFile(0,(char*)".",0);
        }
        else if( !strcmp(inStr,"get config") )
        {
            IP_NET_DVR_GetDVRConfig(m_nLastCmdId, CMD_MEDIA_CONFIG_BASE,0,(void*)"",0,0);
        }
        else if( !strcmp(inStr,"readsn") )
        {
            ret=IP_NET_DVR_SystemControl(m_nLastCmdId,(long)CMD_GET_SERIALNUMBER,0,(char*)"");
        	if(ret<0)
        	{
        		printf("readsn error!\n");
        	}
        }
        else if( !strcmp(inStr,"snappic") )
        {
            char xml[256] = "<REQUEST_PARAM\n"
                            "Stream=\"0\"\n" 
                            "Quality=\"100\"\n" 
                            "PictureId=\"testpic\"\n"
                            "/>\n";
            //begintime = getmstime();
            
            //printf("CMD_SNAP_JPEG_PICTURE begin name, time:%lu\n", getmstime());
            ret = IP_NET_DVR_SystemControl(m_nLastCmdId, (long)CMD_SNAP_JPEG_PICTURE, 0, xml);
        	if(ret<0)
        	{
        		printf("snappic error!\n");
        	}
            else
            {
                printf("IP_NET_DVR_SystemControl return ok\n");
            }
        }
        else if( !strcmp(inStr,"help"))
        {
            showCmdCtlHelp();
        }
        else if(!strcmp(inStr, "start record"))
        {
            ret = IP_NET_DVR_StartRecord(gHandle_realplay, "./", 1*60, 10*60);
            if(ret < 0)
            {
                printf("IP_NET_DVR_StartRecord fail, :%d\n", ret);
            }
        }
        else if(!strcmp(inStr, "stop record"))
        {
             ret = IP_NET_DVR_StopRecord(gHandle_realplay);
            if(ret < 0)
            {
                printf("IP_NET_DVR_StopRecord fail, :%d\n", ret);
            }
        }
        else
        {
            printf("unrecognized command!\n");
        }


        usleep(1000*1000);       
    }

    return 0;
}


int main()
{
    g_AVParam = (STREAM_AV_PARAM *)malloc( sizeof(STREAM_AV_PARAM) );
    if(g_AVParam ==NULL)
    {
        printf("malloc error!\n");
        return 0;
    }
    
    memset( g_AVParam,0,sizeof(STREAM_AV_PARAM) );
    
    IP_NET_DVR_Init();    
    IP_NET_DVR_SetStatusEventCallBack(OnStateEvent,NULL);  
    IP_NET_DVR_SetAUXResponseCallBack(OnAUXResponse,NULL); 

    int video_port = 554;
    cfg_GetLogonInfo(g_ip,g_user,g_pass,&g_port);

    m_nLastCmdId=IP_NET_DVR_Login((char *)g_ip,g_port,(char *)g_user,(char *)g_pass,NULL);
    if(m_nLastCmdId==0)
    {
	    printf("call logon error 0 !\n");
	    return 0;
    }

    
    while(0)
    {
        if(g_LogonOk==1)
        {
            break;
        }
        usleep(1000*1000);
        printf("waiting for logon....\n");
    }

    
    commandProcess();
    return 0;
}


