// PatrolDemoDlg.cpp : 实现文件
//

#include "stdafx.h"
#include "PatrolDemo.h"
#include "PatrolDemoDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// 用于应用程序“关于”菜单项的 CAboutDlg 对话框

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// 对话框数据
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持

// 实现
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()


// CPatrolDemoDlg 对话框
CPatrolDemoDlg::CPatrolDemoDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CPatrolDemoDlg::IDD, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	m_bSearchDev = FALSE;
	m_bPatrol = FALSE;
	m_bSound = FALSE;
	m_pPlayDev = NULL;
	m_nPlayIndex = 0;
}

void CPatrolDemoDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_TREE_DEV, m_treeDev);
	DDX_Control(pDX, IDC_LIST_DEV, m_lstDev);
}

BEGIN_MESSAGE_MAP(CPatrolDemoDlg, CDialog)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDC_BUTTON2, &CPatrolDemoDlg::OnBnClickedButton2)
	ON_BN_CLICKED(IDC_BTN_ADD_DEV, &CPatrolDemoDlg::OnBnClickedBtnAddDev)
	ON_WM_CLOSE()
	ON_NOTIFY(NM_DBLCLK, IDC_TREE_DEV, &CPatrolDemoDlg::OnNMDblclkTreeDev)
	ON_BN_CLICKED(IDC_BTN_STOP, &CPatrolDemoDlg::OnBnClickedBtnStop)
	ON_BN_CLICKED(IDC_BTN_PATROL, &CPatrolDemoDlg::OnBnClickedBtnPatrol)
	ON_WM_TIMER()
	ON_BN_CLICKED(IDC_BTN_TEST, &CPatrolDemoDlg::OnBnClickedBtnTest)
	ON_BN_CLICKED(IDC_BTN_OPEN_SERIAL, &CPatrolDemoDlg::OnBnClickedBtnOpenSerial)
	ON_BN_CLICKED(IDC_BTN_CLOSE_SERIAL, &CPatrolDemoDlg::OnBnClickedBtnCloseSerial)
END_MESSAGE_MAP()


LONG CALLBACK CPatrolDemoDlg::OnSerialDataCallBack(LONG lUser, char *pRecvDataBuffer, DWORD dwBufSize, void *pUser)
{
	CPatrolDemoDlg * parent=(CPatrolDemoDlg*)pUser;
	if (lUser == parent->m_pPlayDev->lAuxPtzId)
	{
		ALARM_ITEM *pAlarmItem = (ALARM_ITEM*)pRecvDataBuffer;
	}
	return 0;
}

LONG CALLBACK CPatrolDemoDlg::OnSearchIPCCallBack(LONG nEventCode,LONG index,IPC_ENTRY *pResponse,void *pUser)
{
	CPatrolDemoDlg * parent=(CPatrolDemoDlg*)pUser;		
	if(nEventCode==EVENT_SEARCH_RECV_NEWIPCINFO)//搜索IPC时，找到新的IPC
	{
		IPC_ENTRY *entry = new IPC_ENTRY;
		memset((void*)entry, 0, sizeof(IPC_ENTRY));
		memcpy(entry, pResponse, sizeof(IPC_ENTRY));
		int nIndex = parent->m_lstDev.GetItemCount();		
		int newidx=parent->m_lstDev.InsertItem(nIndex,"");		
		parent->m_lstDev.SetItemText(newidx,0,pResponse->lanCfg.IPAddress);
		parent->m_lstDev.SetItemText(newidx,1,pResponse->deviceType);
		parent->m_lstDev.SetItemText(newidx,2,pResponse->lanCfg.MACAddress);	
		parent->m_lstDev.SetItemText(newidx,3,pResponse->ipc_sn);
		parent->m_lstDev.SetItemData(newidx,(DWORD)entry);		
	}	
	return 0;
}

LONG CALLBACK CPatrolDemoDlg::OnDevStatusCallBack(LONG lUser,LONG nStateCode,char *pResponse,void *pUser)
{
	CPatrolDemoDlg *pPatrolDemoDlg = (CPatrolDemoDlg *)pUser;
	switch (nStateCode)
	{
	case EVENT_LOGINOK://登录成功		
	case EVENT_CONNECTFAILED:
	case EVENT_SOCKETERROR:
	case EVENT_LOGINFAILED://登录失败
		::PostMessage(pPatrolDemoDlg->m_hWnd, WM_USR_DEV_STATUS_WND, lUser, nStateCode);
		break;
	}

	return 0;
}

LONG CALLBACK CPatrolDemoDlg::OnRealDataCallBack(LONG lRealHandle,DWORD dwDataType,BYTE *pBuffer,DWORD dwBufSize,LPFRAME_EXTDATA  pExtData)
{

	CPatrolDemoDlg *pPatrolDemoDlg = (CPatrolDemoDlg *)pExtData->pUserData;
	DevInfo_t *pDevInfo = NULL;
	pDevInfo = pPatrolDemoDlg->m_pPlayDev;

	if(pDevInfo==NULL)
		return 0;

	if (dwDataType == 0)
	{
		// Video
		long lInputErr = IP_TPS_InputVideoData(pDevInfo->lPlayerId, pBuffer, dwBufSize, pExtData->bIsKey, pExtData->timestamp);
		if (lInputErr != 0) TRACE("IP_TPS_InputVideoData failed!!!!!\n");
	}
	else if(dwDataType==1)
	{
		// Audio		
		long lInputErr = IP_TPS_InputAudioData(pDevInfo->lPlayerId, pBuffer, dwBufSize, pExtData->timestamp);
		if (lInputErr != 0) TRACE("IP_TPS_InputAudioData failed  lInputErr = %d!!!!!\n", lInputErr);		
	}
	else if(dwDataType==2)
	{
		STREAM_AV_PARAM *pavParam = (STREAM_AV_PARAM *)pBuffer;		
		if ( pDevInfo->lPlayerId <= 0)
		{
			srand( (unsigned)time( NULL ) );
			int RANGE_MIN = 1;
			int RANGE_MAX = 9999;
			pDevInfo->lPlayerId = (((double) rand() / (double) RAND_MAX) * RANGE_MAX + RANGE_MIN);
		}
		if (pavParam->bHaveVideo)
		{
			int isAudioParam = 0;
			int nBufPoolSize = 40;
			long lRet = IP_TPS_OpenStream(pDevInfo->lPlayerId, (BYTE *)&(pavParam->videoParam), sizeof(VIDEO_PARAM), isAudioParam, nBufPoolSize);
			if (lRet != 0)
			{
				TRACE("Video IP_TPS_OpenStream faild!!!\n"); 
				return 0;
			}
		}
		if (pavParam->bHaveAudio)
		{
			int isAudioParam = 1;
			int nBufPoolSize = 40;
			long lRet = IP_TPS_OpenStream(pDevInfo->lPlayerId, (BYTE *)&(pavParam->audioParam), sizeof(AUDIO_PARAM), isAudioParam, nBufPoolSize);
			if (lRet != 0)
				TRACE("Audio IP_TPS_OpenStream faild!!!\n");
		}
		RECT rcArea;
		rcArea.left=0;
		rcArea.top = 0;
		rcArea.bottom=200;
		rcArea.right = 600;
		//int ret = IP_TPS_PlayByArea(pDevInfo->lPlayerId, pPatrolDemoDlg->GetDlgItem(IDC_STATIC_VIDEO)->m_hWnd, rcArea);
		int ret = IP_TPS_Play(pDevInfo->lPlayerId, pPatrolDemoDlg->GetDlgItem(IDC_STATIC_VIDEO)->m_hWnd);
		if(!ret)
		{
			pDevInfo->bVideo = TRUE;	
			IP_TPS_SetFullFillStatus(pDevInfo->lPlayerId, 1);
		}
		memcpy((void*)&pDevInfo->oAVParam, pavParam, sizeof(STREAM_AV_PARAM));
		//IP_TPS_SetMotionDetectConfigOn(pDevInfo->lPlayerId, 1);
		//IP_TPS_SetMotionDetectConfig(pDevInfo->lPlayerId, 4,4,"1000000000000000");
	}
	return 0;
}

// CPatrolDemoDlg 消息处理程序

BOOL CPatrolDemoDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// 将“关于...”菜单项添加到系统菜单中。

	// IDM_ABOUTBOX 必须在系统命令范围内。
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// 设置此对话框的图标。当应用程序主窗口不是对话框时，框架将自动
	//  执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标

	// TODO: 在此添加额外的初始化代码

	OnInit();

	SetTimer(200, 1000, NULL);

	return TRUE;  // 除非将焦点设置到控件，否则返回 TRUE
}

void CPatrolDemoDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// 如果向对话框添加最小化按钮，则需要下面的代码
//  来绘制该图标。对于使用文档/视图模型的 MFC 应用程序，
//  这将由框架自动完成。

void CPatrolDemoDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 用于绘制的设备上下文

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// 使图标在工作矩形中居中
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// 绘制图标
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

//当用户拖动最小化窗口时系统调用此函数取得光标显示。
//
HCURSOR CPatrolDemoDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}


void CPatrolDemoDlg::OnBnClickedButton2()
{
	int ret = 0;
	if (m_bSearchDev)
	{
		ret = IP_NET_DVR_StopSearchIPC();
		m_bSearchDev = FALSE;
		GetDlgItem(IDC_BUTTON2)->SetWindowText("开始搜索");
	}
	else
	{
		m_lstDev.SetRedraw(FALSE);
		int nCount = m_lstDev.GetItemCount();
		for (int nItem=0; nItem<nCount; nItem++ )
		{
			IPC_ENTRY* entry = (IPC_ENTRY*)m_lstDev.GetItemData(0);		
			delete entry;
			m_lstDev.DeleteItem(0);
		}
		m_lstDev.SetRedraw(TRUE);
		ret = IP_NET_DVR_StartSearchIPC();
		m_bSearchDev = TRUE;
		GetDlgItem(IDC_BUTTON2)->SetWindowText("停止搜索");
	}
}

void CPatrolDemoDlg::OnBnClickedBtnAddDev()
{
	std::list<DevInfo_t>::iterator  iterDev;
	std::list<IPC_ENTRY*>::iterator  iterIPC;
	DevInfo_t  oDevInfo;
	BOOL  bAdd = FALSE;
#if 0
	memset((void*)&oDevInfo, 0, sizeof(DevInfo_t));
	
	strcpy(oDevInfo.szDevId,"192.168.88.227");	
	strcpy(oDevInfo.szLoginName, "admin");
	strcpy(oDevInfo.szLoginPsw, "123456");	
	strcpy(oDevInfo.szIPAddr, "192.168.88.227");
	
	oDevInfo.nPtzPort = 8091;
	
	oDevInfo.nRtpOverRtsp = 1;//1:TCP;0:UDP
	oDevInfo.nVideoPort = 554;
	
	oDevInfo.nDevType = DEV_TYPE_IPC;
	strcpy(oDevInfo.szDevName, oDevInfo.szDevId);
	strcpy(oDevInfo.szResolution, "cif");					
	//登录设备
	m_lstDevInfo.push_back(oDevInfo);	
	bAdd = TRUE;
#endif
#if 1
	
	int nIndex = 0;
	m_lstIPC.clear();
	int nCount = m_lstDev.GetItemCount();
	for (int i=0; i<nCount; i++)
	{
		if (m_lstDev.GetCheck(i))
		{
			IPC_ENTRY *entry = NULL;			
			entry = (IPC_ENTRY*)m_lstDev.GetItemData(i);
			if (entry)
			{
				BOOL bExist = FALSE;
				for (iterDev = m_lstDevInfo.begin(); iterDev != m_lstDevInfo.end(); iterDev++)
				{
					if (strcmp(entry->ipc_sn, (*iterDev).szDevSN) == 0 && strcmp(entry->lanCfg.IPAddress, (*iterDev).szIPAddr)!=0)
					{
						//设备序列号相同，但IP不相同								
						m_lstDevInfo.erase(iterDev);
						break;
					}
					else if (strcmp(entry->lanCfg.IPAddress, (*iterDev).szIPAddr) == 0)				      					   				
					{							
						bExist = TRUE;
						break;
					}
				}
				if(bExist)
					continue;
				
				//
				memset((void*)&oDevInfo, 0, sizeof(DevInfo_t));
				strcpy(oDevInfo.szDevSN, entry->ipc_sn);
				strcpy(oDevInfo.szDevId, entry->lanCfg.IPAddress);	
				strcpy(oDevInfo.szLoginName, entry->userCfg.accounts->userName);
				strcpy(oDevInfo.szLoginPsw, entry->userCfg.accounts->password);
				strcpy(oDevInfo.szStatus, entry->userCfg.accounts->status);
				strcpy(oDevInfo.szIPAddr, entry->lanCfg.IPAddress);
				strcpy(oDevInfo.szMACAddr, entry->lanCfg.MACAddress);
				strcpy(oDevInfo.szDNS1, entry->lanCfg.DNS1);
				strcpy(oDevInfo.szDNS2, entry->lanCfg.DNS2);
				strcpy(oDevInfo.szGateWay, entry->lanCfg.gateWay);
				strcpy(oDevInfo.szNetMask, entry->lanCfg.netMask);		
				oDevInfo.nEnableDHCP = entry->lanCfg.dhcpEnable;
				oDevInfo.nAuth = entry->streamCfg.auth;
				oDevInfo.nPtzPort = entry->streamCfg.ptzPort;
				oDevInfo.nRtpOverRtsp = 1;//1:TCP;0:UDP
				oDevInfo.nVideoPort = entry->streamCfg.videoPort;
				oDevInfo.nWebPort = entry->streamCfg.webPort;

				if (strcmp(entry->deviceType, "DVS4-DM365") == 0)
				{
					oDevInfo.nDevType = DEV_TYPE_DVS;
					//轮巡测试暂不添加DVS设备
				}
				else if (strcmp(entry->deviceType, "DEC-DM365") == 0)
				{
					oDevInfo.nDevType = DEV_TYPE_DECODE;				
					//轮巡测试暂不添加解码器设备
				}
				else
				{
					nIndex++;
					oDevInfo.nDevType = DEV_TYPE_IPC;
					strcpy(oDevInfo.szDevName, oDevInfo.szDevId);
					strcpy(oDevInfo.szResolution, "cif");					
					oDevInfo.nIndex = nIndex;
					//登录设备
					m_lstDevInfo.push_back(oDevInfo);	
					bAdd = TRUE;
				}
			}
		}
	}	
#endif
	if(bAdd)
	{
		RefreshDevTree();
		OnLoginDev();
	}
}

int  CPatrolDemoDlg::OnInit()
{
	int ret = 0;
	
	//初始化设备列表图标
	m_ImageList.Create(IDB_TREEIMAGE, 16, 1, RGB(255, 0, 255));
	m_treeDev.SetItemHeight(20);
	m_treeDev.SetImageList(&m_ImageList, TVSIL_NORMAL);

	//初始化设备查询列表
	CRect     rcList;
	CString   strColHeader;
	m_lstDev.GetWindowRect(&rcList);	
	strColHeader.Format("IP地址,%d; 设备类型,%d; MAC地址,%d;SN,%d", rcList.Width()/4, rcList.Width()/4, rcList.Width()/4, rcList.Width()/4);
	m_lstDev.SetColumnHeader(strColHeader);
	m_lstDev.SetCheckboxeStyle(RC_CHKBOX_NORMAL); // Enable checkboxes	
	m_lstDev.SetGridLines(TRUE);
	m_lstDev.m_bSortItem = TRUE;

	//初始化DLL
	ret = IP_NET_DVR_Init();
	if(ret)
		return ret;

	//设置设备搜索回调函数
	ret = IP_NET_DVR_SetSearchStatusCallBack(CPatrolDemoDlg::OnSearchIPCCallBack,this);

	//设置设备状态回调函数
	ret = IP_NET_DVR_SetStatusEventCallBack(CPatrolDemoDlg::OnDevStatusCallBack, this);	

	return ret;
}

int CPatrolDemoDlg::RefreshDevTree()
{
	m_treeDev.DeleteAllItems();
		
	std::list<DevInfo_t>::iterator iterDev;
	HTREEITEM  HRootDev;
	HTREEITEM  HItemDev;
	HTREEITEM  HItemDev2;
	HTREEITEM  HChildDev;
	char       szDevID[MAX_IP_NAME_LEN];
	memset(szDevID, 0, MAX_IP_NAME_LEN);	

	HRootDev = m_treeDev.InsertItem("设备列表", 0, 0, TVI_ROOT, TVI_LAST);
	if(m_lstDevInfo.size() == 0)
	{		
		return 0;
	}


	for (iterDev = m_lstDevInfo.begin(); iterDev != m_lstDevInfo.end(); iterDev++)
	{
			CString  strMsg;
			
			if((*iterDev).nDevType == DEV_TYPE_IPC)
			{
				strMsg.Format("%s", (*iterDev).szDevName);
				if ((*iterDev).nOnline == 1 && (*iterDev).bVideo == TRUE)//当前设备在线播放
				{
					HChildDev = m_treeDev.InsertItem(strMsg, 7, 7, HRootDev, TVI_LAST);
				}
				else if ((*iterDev).nOnline == 1 && (*iterDev).bVideo == FALSE )//当前设备在线没播放
				{
					HChildDev = m_treeDev.InsertItem(strMsg, 3, 3, HRootDev, TVI_LAST);						
				}				
				else//当前设备不在线
				{
					HChildDev = m_treeDev.InsertItem(strMsg, 2, 2, HRootDev, TVI_LAST);
				}					
				m_treeDev.SetItemData(HChildDev, (DWORD)&(*iterDev));				
			}			
	}
		

	HTREEITEM  hItem = m_treeDev.GetFirstVisibleItem();
	int nCount = m_treeDev.GetCount();
	for(int i = 0; i< nCount; i++)
	{
		m_treeDev.Expand(hItem, TVE_EXPAND);
		hItem = m_treeDev.GetNextVisibleItem(hItem);							
	}

	hItem = m_treeDev.GetRootItem();
	m_treeDev.SelectSetFirstVisible(hItem);	

	return 0;
}

int CPatrolDemoDlg::RefreshDevTreeImage()
{	
	std::list<DevInfo_t>::iterator iterDev;
	HTREEITEM  HRootDev = m_treeDev.GetRootItem();	
	m_treeDev.Expand(HRootDev, TVE_EXPAND);
	HTREEITEM  HItem = m_treeDev.GetChildItem(HRootDev);
	if(HItem == NULL)
		return 0;
	HTREEITEM  HChildDev = NULL;	
	do 
	{
		while(m_treeDev.ItemHasChildren(HItem))
		{
			HChildDev = m_treeDev.GetChildItem(HItem);
			HItem = HChildDev;
		}
		HChildDev = HItem;		

		DevInfo_t  *pDevInfo = NULL;
		pDevInfo = (DevInfo_t*)m_treeDev.GetItemData(HChildDev);	//获取设备列表中的子设备	
		if(pDevInfo)
		{
			for (iterDev = m_lstDevInfo.begin(); iterDev != m_lstDevInfo.end(); iterDev++)
			{
				if (strcmp((*iterDev).szDevName, pDevInfo->szDevName) == 0)
				{
					//找到设备对应的状态															
					if ((*iterDev).nOnline == 1 && (*iterDev).bVideo == TRUE)//当前设备在线播放
					{
						m_treeDev.SetItemImage(HChildDev, 7, 7);					
					}
					else if ((*iterDev).nOnline == 1 && (*iterDev).bVideo == FALSE)//当前设备在线没播放
					{
						m_treeDev.SetItemImage(HChildDev, 3, 3);						
					}					
					else//当前设备不在线
					{
						m_treeDev.SetItemImage(HChildDev, 2, 2);						
					}					
					break;
				}				
			}
		}			

		if (m_treeDev.GetNextItem(HChildDev, TVGN_NEXT) != NULL)
		{
			HItem = m_treeDev.GetNextItem(HChildDev, TVGN_NEXT);
		}
		else
		{
			HItem = m_treeDev.GetParentItem(HChildDev);
			HTREEITEM HNextItem = m_treeDev.GetNextItem(HItem, TVGN_NEXT);
			if (HNextItem==NULL)
			{
				HNextItem = m_treeDev.GetParentItem(HItem);
				HItem = m_treeDev.GetNextItem(HNextItem, TVGN_NEXT);
			}
			else
				HItem = HNextItem;
		}		

	} while (HItem);

	return 0;
}

int  CPatrolDemoDlg::OnLoginDev()
{
	std::list<DevInfo_t>::iterator iterDev;
	for (iterDev = m_lstDevInfo.begin(); iterDev != m_lstDevInfo.end(); iterDev++)
	{
		LONG lAuxPtzId = IP_NET_DVR_Login((*iterDev).szIPAddr, (*iterDev).nPtzPort, (*iterDev).szLoginName, (*iterDev).szLoginPsw, NULL);
		if(lAuxPtzId==0)
			TRACE("CPatrolDemoDlg::OnLoginDev(): DevIp=%s login failed", (*iterDev).szIPAddr);
		else
			(*iterDev).lAuxPtzId = lAuxPtzId;
	}

	return 0;
}

int CPatrolDemoDlg::OnAddWatch(DevInfo_t *pDevInfo)
{
	if(pDevInfo==NULL)
		return -1;

	if (m_pPlayDev)
	{
		OnStopWatch();
		Sleep(200);
	}

	USRE_VIDEOINFO user;
	memset(&user, 0, sizeof(USRE_VIDEOINFO));
	user.bIsTcp = pDevInfo->nRtpOverRtsp; 	
	user.nVideoChannle = 1;
	user.nVideoPort = pDevInfo->nVideoPort;
	user.pUserData = this;
	char szUrl[512];
	memset(szUrl, 0, 512);
	//sprintf(szUrl,"tps://%s", pDevInfo->szIPAddr);
	sprintf(szUrl,"%s", pDevInfo->szIPAddr);
	LONG lRealHandle = IP_NET_DVR_RealPlayEx(pDevInfo->lAuxPtzId,szUrl, pDevInfo->szLoginName, pDevInfo->szLoginPsw, CPatrolDemoDlg::OnRealDataCallBack, &user, NULL);
	if(lRealHandle==0)
		return 0;	
	pDevInfo->lRealHandle = lRealHandle;
	m_pPlayDev = pDevInfo;
	m_nPlayIndex = pDevInfo->nIndex;

	IP_NET_DVR_SetAutoReconnect(lRealHandle, FALSE);

	return 0;
}

int CPatrolDemoDlg::OnStopWatch()
{
	if(m_pPlayDev == NULL)
		return -1;
	int ret = 0;
	ret = IP_NET_DVR_StopRealPlay(m_pPlayDev->lRealHandle);
	ret = IP_TPS_Stop(m_pPlayDev->lPlayerId);
	m_pPlayDev->bVideo = FALSE;
	RefreshDevTreeImage();
	GetDlgItem(IDC_STATIC_VIDEO)->Invalidate();
	m_pPlayDev = NULL;
	m_nPlayIndex = 0;

	return ret;
}

int CPatrolDemoDlg::OnExit()
{
	int ret = 0;

	std::list<DevInfo_t>::iterator iterDev;
	for (iterDev = m_lstDevInfo.begin(); iterDev != m_lstDevInfo.end(); iterDev++)
	{
		IP_NET_DVR_Logout((*iterDev).lAuxPtzId);
	}

	ret = IP_NET_DVR_Cleanup();

	return ret;
}

void CPatrolDemoDlg::OnClose()
{	
	OnExit();

	int nCount = m_lstDev.GetItemCount();
	for (int nItem=0; nItem<nCount; nItem++ )
	{
		IPC_ENTRY* entry = (IPC_ENTRY*)m_lstDev.GetItemData(0);		
		delete entry;
		m_lstDev.DeleteItem(0);
	}

	CDialog::OnClose();
}

BOOL CPatrolDemoDlg::PreTranslateMessage(MSG* pMsg)
{	
	if (pMsg->message == WM_USR_DEV_STATUS_WND)//设备状态消息
	{
		LONG lAuxPtzId = (LONG)pMsg->wParam;
		std::list<DevInfo_t>::iterator  iterDev;
		for (iterDev = m_lstDevInfo.begin(); iterDev != m_lstDevInfo.end(); iterDev++)
		{
			if ((*iterDev).lAuxPtzId == lAuxPtzId)
			{
				switch (pMsg->lParam)
				{
				case EVENT_LOGINOK:
					(*iterDev).nOnline = 1;
					IP_NET_DVR_SetAutoReconnect((*iterDev).lAuxPtzId, TRUE);
					break;
				case EVENT_CONNECTFAILED:
				case EVENT_SOCKETERROR:
				case EVENT_LOGINFAILED://登录失败
					(*iterDev).nOnline = 0;
					break;
				}

				RefreshDevTreeImage();
				break;
			}
		}
		
	}
	if (pMsg->message == WM_LBUTTONUP)
	{
		if (m_pPlayDev)
		{
			IP_TPS_InputMouseEvent(m_pPlayDev->lPlayerId, pMsg->message, pMsg->wParam, pMsg->lParam);
		}
		
	}
	return CDialog::PreTranslateMessage(pMsg);
}

void CPatrolDemoDlg::OnNMDblclkTreeDev(NMHDR *pNMHDR, LRESULT *pResult)
{
	CPoint   pt;   
	GetCursorPos(&pt);   
	m_treeDev.ScreenToClient(&pt);
	HTREEITEM   hTreeItemSelected   =   m_treeDev.HitTest(pt);
	m_treeDev.Select(hTreeItemSelected, TVGN_DROPHILITE );
	HTREEITEM   hRootItem = m_treeDev.GetRootItem();

	//双击单个设备进行播放
	if ((hTreeItemSelected != NULL) && (!m_treeDev.ItemHasChildren(hTreeItemSelected))) 
	{
		//set device info
		DevInfo_t*  pDevInfo = NULL;
		pDevInfo = (DevInfo_t*)m_treeDev.GetItemData(hTreeItemSelected);
		if(pDevInfo == NULL)
			return;	
		if (pDevInfo->nOnline==0)
		{
			AfxMessageBox("设备不在线，无法播放！");
			return;
		}				
		
		OnAddWatch(pDevInfo);				
	}	

	*pResult = 0;
}

void CPatrolDemoDlg::OnBnClickedBtnStop()
{	
	if (m_bPatrol)
	{
		m_bPatrol =FALSE;
		KillTimer(100);
		GetDlgItem(IDC_BTN_PATROL)->SetWindowText("启动轮巡");
	}
	OnStopWatch();
}

void CPatrolDemoDlg::OnBnClickedBtnPatrol()
{
	if (m_bPatrol)
	{
		m_bPatrol = FALSE;
		KillTimer(100);
		GetDlgItem(IDC_BTN_PATROL)->SetWindowText("启动轮巡");
	}
	else
	{
		m_bPatrol = TRUE;
		SetTimer(100, 10000, NULL);
		GetDlgItem(IDC_BTN_PATROL)->SetWindowText("停止轮巡");
	}
	
}

void CPatrolDemoDlg::OnTimer(UINT_PTR nIDEvent)
{
	if (nIDEvent == 100)
	{
		m_nPlayIndex++;
		BOOL bFind = FALSE;
		std::list<DevInfo_t>::iterator iterDev;
		for (iterDev = m_lstDevInfo.begin(); iterDev != m_lstDevInfo.end(); iterDev++)
		{
			if ((*iterDev).nIndex == m_nPlayIndex)
			{
				if((*iterDev).nOnline)
					OnAddWatch(&(*iterDev));
				bFind  = TRUE;
				break;
			}
		}
		if(!bFind)
		{
			iterDev = m_lstDevInfo.begin();
			OnAddWatch(&(*iterDev));
		}
	}

	if (nIDEvent == 200)
	{
		RefreshDevTreeImage();
	}

	CDialog::OnTimer(nIDEvent);
}

void CPatrolDemoDlg::OnBnClickedBtnTest()
{	
// 	char szConfig[128];
// 	memset(szConfig, 0, 128);
// 	int ret = IP_TPS_GetMotionDetectConfigString(m_pPlayDev->lPlayerId, szConfig);
	//IP_TPS_SetMotionDetectConfig(m_pPlayDev->lPlayerId, 2,2,"1111");
	if (m_pPlayDev)
	{
		if (!m_bSound)
		{
			IP_TPS_PlaySound(m_pPlayDev->lPlayerId);
			m_bSound = TRUE;
			GetDlgItem(IDC_BTN_TEST)->SetWindowText("关闭声音");

		}
		else
		{
			IP_TPS_StopSound();
			m_bSound = FALSE;
			GetDlgItem(IDC_BTN_TEST)->SetWindowText("打开声音");
		}		
	}
	

	int i=0;
}

void CPatrolDemoDlg::OnBnClickedBtnOpenSerial()
{	
	if(m_pPlayDev == NULL)
		return;
	LONG lRet = IP_NET_DVR_SerialStart(m_pPlayDev->lAuxPtzId, CPatrolDemoDlg::OnSerialDataCallBack, this);

	return;
}

void CPatrolDemoDlg::OnBnClickedBtnCloseSerial()
{	
	if(m_pPlayDev == NULL)
		return;

	LONG lRet = IP_NET_DVR_SerialStop(m_pPlayDev->lAuxPtzId);
}
