// NetViewXCtl.cpp : Implementation of the CNetViewXCtrl ActiveX Control class.

#include "stdafx.h"
#include "NetViewX.h"
#include "NetViewXCtl.h"
#include "NetViewXPpg.h"
#include "FullDisplayWnd.h"
#include "ServerControl.h"
#include "DirectoryDialog.h"
#include "FileDialogST.h"
#include "DiskObject.h"

#include <mmsystem.h>
#include <sys/stat.h>
#include <shlwapi.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

#define LAN_NET_MSG_SIZE		(352 * 288 / 8) + 320 + 16	//消息数据最大长度

#define LANGUAGE_TYPE_ENGLISH	0
#define LANGUAGE_TYPE_CHINA		1

#define TIMERID_SWITCH		10
#define TIMERID_RELINK		20
#define TIMERID_DISKCHECK	21
#define TIMERID_JPEGRELINK  22
#define TIMERID_SYS			23
#define FILE_PACKTIME		1000 * 60 * 20

#define NET_MODE_UDP	1
#define NET_MODE_MULTI	2
#define NET_MODE_TCP	3

#define MAX_VIDEOMASK_AREA	4

IMPLEMENT_DYNCREATE(CNetViewXCtrl, COleControl)

#define DISK_CHANGE_DRV_SIZE	0X12C00000    //bytes 硬盘空间小于300M时，切换当前分区到下一个可用分区。
#define RECORD_PACK_MAXMINS     90            //最长打包时间90分钟
#define RECORD_PACK_MINMINS     10            //最短打包时间10分钟
//extern HCURSOR	g_hCursor;

#define STOP_RELINKTIMER()	if(m_timerRelink) {KillTimer(m_timerRelink); m_timerRelink = 0;}

static UINT TalkRelinkThread(void *prag);

void WINAPI TalkEncCallBack(char *pbuff,int size,void *context)
{
	CNetViewXCtrl *parent = (CNetViewXCtrl*)context;
	if (!parent)
		return;
	if (size < 0 && parent->m_bTalkRelinkThread == FALSE)
	{//自动重连
		UINT ID;
		parent->m_bTalkRelinkThread = TRUE;
		parent->m_hTalkRelinkThread = (HANDLE)_beginthreadex(0,1024*10,
			(unsigned (__stdcall *) (void *))&TalkRelinkThread,
			context,0,&ID);
		if (parent->m_hTalkRelinkThread == NULL)
		{
			TRACE("启动对讲重连失败\n");
		}
	}
}

static UINT TalkRelinkThread(void *prag)
{
	CNetViewXCtrl *parent = (CNetViewXCtrl*)prag;
	if (!parent)
		return 0;

	int ret;
	while (parent->m_bTalkRelinkThread)
	{
		ret = parent->RelinkTalk();
		if (ret < 0)
			continue;
		else
			break;
	}
	
	parent->m_bTalkRelinkThread = FALSE;
	CloseHandle(parent->m_hTalkRelinkThread);
	parent->m_hTalkRelinkThread = NULL;
	return 0;
}


void WINAPI s_jpegdatacallback(LONG hHandle,int m_ch,char *pBuffer,int size,void *userdata)
{
	FILE *fpFile = NULL;
	CNetViewXCtrl *parent = (CNetViewXCtrl*)userdata;
	if(size > 0)
	{
		if(parent->m_jpegfilename[0] != '\0')
		{
			TRACE("Point:%x size:%d.\n",pBuffer,size);
			fpFile = fopen(parent->m_jpegfilename,"wb");
			if(fpFile)
			{
				fwrite(pBuffer,size,1,fpFile);
				fclose(fpFile);
			}
			::SendMessage(parent->m_hWnd, WM_USERMSG_JPEGEVENT, NULL, NULL);
		}
		else
		{
//			parent->FireJPEGData((BSTR FAR*)pBuffer,size);
			::SendMessage(parent->m_hWnd, WM_USERMSG_JPEGDATA, (WPARAM)pBuffer, size);
		}
	}
	else
	{
		parent->m_jpegerror = TRUE;
	}
}

void WINAPI s_ShowCallBack(BYTE *m_y,BYTE *m_u,BYTE *m_v,int stridey,int strideuv,int width,int height,void *context)
{
	CNetViewXCtrl *parent = (CNetViewXCtrl*)context;
	if(parent)
	{
		if(parent->m_bdisplay != 2)
		{
			parent->m_bdisplay = 2;
			PostMessage(parent->m_hWnd,WM_PAINT,NULL,NULL);
		}
		parent->m_bdisplay = 2;

#if defined(PROTYPE_XISHI) || defined(PROTYPE_LOGO)
		if(parent->m_displayhandle)
			VSNET_ClientShowImageShow(parent->m_displayhandle,m_y,m_u,m_v,stridey,strideuv);
#endif
	}
}

static LPITEMIDLIST ConvertPathToLpItemIdList(const char *pszPath)
{
	LPITEMIDLIST  pidl;
	LPSHELLFOLDER pDesktopFolder;
	OLECHAR       olePath[MAX_PATH];
	ULONG         chEaten;
	ULONG         dwAttributes;
	HRESULT       hr;

	if (SUCCEEDED(SHGetDesktopFolder(&pDesktopFolder)))
	{
		MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, pszPath, -1, olePath, MAX_PATH);
		hr = pDesktopFolder->ParseDisplayName(NULL, NULL, olePath, &chEaten, &pidl, &dwAttributes);
		pDesktopFolder->Release();
	}
	return pidl;
}
/////////////////////////////////////////////////////////////////////////////
// Message map

BEGIN_MESSAGE_MAP(CNetViewXCtrl, COleControl)
	ON_MESSAGE(NET_MSG_ID, OnClientMessage)
	ON_MESSAGE(WM_SERIAL, OnSerial)
	ON_MESSAGE(WM_USERMSG_JPEGEVENT, OnJPEGEventMsg)
	ON_MESSAGE(WM_USERMSG_JPEGDATA, OnJPEGDataMsg)
	ON_MESSAGE(WM_USEABLEWIFI, OnWMUseableWifi)
	ON_MESSAGE(WM_INVALIDATE, OnWMInvalidate)
	//{{AFX_MSG_MAP(CNetViewXCtrl)
	ON_WM_CLOSE()
	ON_WM_DESTROY()
	ON_WM_PAINT()
	ON_WM_MOVE()
	ON_WM_SIZING()
	ON_WM_TIMER()
	ON_WM_MOUSEMOVE()
	ON_WM_LBUTTONDOWN()
	ON_WM_LBUTTONDBLCLK()
	ON_WM_LBUTTONUP()
	ON_WM_CREATE()
	ON_WM_RBUTTONDOWN()
	ON_WM_RBUTTONUP()
	//}}AFX_MSG_MAP
	ON_OLEVERB(AFX_IDS_VERB_EDIT, OnEdit)
	ON_OLEVERB(AFX_IDS_VERB_PROPERTIES, OnProperties)
END_MESSAGE_MAP()

#ifdef L_IMPL_OBJECTSAFETY 

BEGIN_INTERFACE_MAP(CNetViewXCtrl, COleControl) 
	INTERFACE_PART(CNetViewXCtrl, IID_IObjectSafety, ObjectSafety) 
END_INTERFACE_MAP() 

#endif // L_IMPL_OBJECTSAFETY
/////////////////////////////////////////////////////////////////////////////
// Dispatch map

BEGIN_DISPATCH_MAP(CNetViewXCtrl, COleControl)
	//{{AFX_DISPATCH_MAP(CNetViewXCtrl)
	DISP_PROPERTY_NOTIFY(CNetViewXCtrl, "url", m_url, OnUrlChanged, VT_BSTR)
	DISP_PROPERTY_NOTIFY(CNetViewXCtrl, "channel", m_channel, OnChannelChanged, VT_I2)
	DISP_PROPERTY_NOTIFY(CNetViewXCtrl, "username", m_username, OnUsernameChanged, VT_BSTR)
	DISP_PROPERTY_NOTIFY(CNetViewXCtrl, "password", m_password, OnPasswordChanged, VT_BSTR)
	DISP_PROPERTY_NOTIFY(CNetViewXCtrl, "servername", m_servername, OnServernameChanged, VT_BSTR)
	DISP_PROPERTY_NOTIFY(CNetViewXCtrl, "ViewQCIF", m_viewQCIF, OnViewQCIFChanged, VT_BOOL)
	DISP_PROPERTY_NOTIFY(CNetViewXCtrl, "trantype", m_trantype, OnTrantypeChanged, VT_I2)
	DISP_PROPERTY_NOTIFY(CNetViewXCtrl, "buffernum", m_buffernum, OnBuffernumChanged, VT_I2)
	DISP_PROPERTY_NOTIFY(CNetViewXCtrl, "wServerPort", m_wServerPort, OnWServerPortChanged, VT_I4)
	DISP_PROPERTY_NOTIFY(CNetViewXCtrl, "bUseOverlay", m_bUseOverlay, OnBUseOverlayChanged, VT_BOOL)
	DISP_PROPERTY_NOTIFY(CNetViewXCtrl, "delaytime", m_delaytime, OnDelaytimeChanged, VT_I2)
	DISP_PROPERTY_NOTIFY(CNetViewXCtrl, "streamtype", m_streamtype, OnStreamtypeChanged, VT_I2)
	DISP_FUNCTION(CNetViewXCtrl, "FullScreen", FullScreen, VT_EMPTY, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "StartView", StartView, VT_BOOL, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "StopView", StopView, VT_BOOL, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "StartRecord", StartRecord, VT_I2, VTS_BSTR)
	DISP_FUNCTION(CNetViewXCtrl, "StopRecord", StopRecord, VT_EMPTY, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "CaptureBmp", CaptureBmp, VT_BOOL, VTS_BSTR)
	DISP_FUNCTION(CNetViewXCtrl, "StartTalk", StartTalk, VT_I4, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "StopTalk", StopTalk, VT_I4, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "SoundOn", SoundOn, VT_EMPTY, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "SoundOff", SoundOff, VT_EMPTY, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "ImageWidth", ImageWidth, VT_I2, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "ImageHeight", ImageHeight, VT_I2, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "PostProMethon", PostProMethon, VT_EMPTY, VTS_I4)
	DISP_FUNCTION(CNetViewXCtrl, "PTZCtrl", PTZCtrl, VT_I2, VTS_I2 VTS_I4)
	DISP_FUNCTION(CNetViewXCtrl, "ViParamAdjust", ViParamAdjust, VT_I4, VTS_I2 VTS_I2 VTS_I2 VTS_I2)
	DISP_FUNCTION(CNetViewXCtrl, "MotionTest", MotionTest, VT_EMPTY, VTS_BOOL)
	DISP_FUNCTION(CNetViewXCtrl, "MotionEdit", MotionEdit, VT_EMPTY, VTS_BOOL)
	DISP_FUNCTION(CNetViewXCtrl, "SetMotionArea", SetMotionArea, VT_EMPTY, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "SetMotionVal", SetMotionVal, VT_EMPTY, VTS_I2)
	DISP_FUNCTION(CNetViewXCtrl, "MotionAreaSetAll", MotionAreaSetAll, VT_EMPTY, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "MotionAreaClear", MotionAreaClear, VT_EMPTY, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "GetSaveFileName", GetSaveFileName, VT_BSTR, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "SetLanguage", SetLanguage, VT_EMPTY, VTS_I2)
	DISP_FUNCTION(CNetViewXCtrl, "StartConnect", StartConnect, VT_I4, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "StartDisplay", StartDisplay, VT_I4, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "StopDisplay", StopDisplay, VT_EMPTY, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "GetCurStatus", GetCurStatus, VT_I2, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "ClearAlarm", ClearAlarm, VT_EMPTY, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "SetPTZAddr", SetPTZAddr, VT_EMPTY, VTS_I2)
	DISP_FUNCTION(CNetViewXCtrl, "PTZExDevCtrl", PTZExDevCtrl, VT_EMPTY, VTS_I2 VTS_I2)
	DISP_FUNCTION(CNetViewXCtrl, "CtrolAlarmOut", CtrolAlarmOut, VT_EMPTY, VTS_I2 VTS_I2)
	DISP_FUNCTION(CNetViewXCtrl, "ChannelSwitch", ChannelSwitch, VT_EMPTY, VTS_I2 VTS_I2)
	DISP_FUNCTION(CNetViewXCtrl, "ChannelSel", ChannelSel, VT_EMPTY, VTS_I2)
	DISP_FUNCTION(CNetViewXCtrl, "SetSwitchChannel", SetSwitchChannel, VT_EMPTY, VTS_I2 VTS_I2)
	DISP_FUNCTION(CNetViewXCtrl, "SearchFile", SearchFile, VT_EMPTY, VTS_I4 VTS_I4 VTS_I4 VTS_I4 VTS_I4 VTS_I4 VTS_I4)
	DISP_FUNCTION(CNetViewXCtrl, "VideoMaskEnable", VideoMaskEnable, VT_EMPTY, VTS_I2)
	DISP_FUNCTION(CNetViewXCtrl, "VideoMaskEdit", VideoMaskEdit, VT_EMPTY, VTS_I2)
	DISP_FUNCTION(CNetViewXCtrl, "SetTalkChannel", SetTalkChannel, VT_EMPTY, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "SwitchGangChannel", SwitchGangChannel, VT_EMPTY, VTS_I2)
	DISP_FUNCTION(CNetViewXCtrl, "Transparent", Transparent, VT_BOOL, VTS_I4 VTS_I2)
	DISP_FUNCTION(CNetViewXCtrl, "SetGangBandrate", SetGangBandrate, VT_EMPTY, VTS_I4)
	DISP_FUNCTION(CNetViewXCtrl, "StartSerial", StartSerial, VT_EMPTY, VTS_I2 VTS_I4 VTS_I2 VTS_I2 VTS_I2 VTS_I2)
	DISP_FUNCTION(CNetViewXCtrl, "StopSerial", StopSerial, VT_EMPTY, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "StartServerRecord", StartServerRecord, VT_I2, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "StopServerRecord", StopServerRecord, VT_I2, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "TransparentSend", TransparentSend, VT_BOOL, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "CaptureJpeg", CaptureJpeg, VT_BOOL, VTS_BSTR)
	DISP_FUNCTION(CNetViewXCtrl, "CaptureJpegStart", CaptureJpegStart, VT_BOOL, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "CaptureJpegStop", CaptureJpegStop, VT_BOOL, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "SetWaitTime", SetWaitTime, VT_BOOL, VTS_I2 VTS_I2)
	DISP_FUNCTION(CNetViewXCtrl, "SyncTime", SyncTime, VT_BOOL, VTS_I4 VTS_I4 VTS_I4 VTS_I4 VTS_I4 VTS_I4)
	DISP_FUNCTION(CNetViewXCtrl, "TransparentSendEx", TransparentSendEx, VT_BOOL, VTS_I2)
	DISP_FUNCTION(CNetViewXCtrl, "ReadRecordFile", ReadRecordFile, VT_I2, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "StartClientRecord", StartClientRecord, VT_BSTR, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "StopClientRecord", StopClientRecord, VT_I2, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "SetRecordType", SetRecordType, VT_EMPTY, VTS_I2)
	DISP_FUNCTION(CNetViewXCtrl, "SendBankInfo", SendBankInfo, VT_BOOL, VTS_BSTR VTS_BSTR VTS_I2 VTS_I2)
	DISP_FUNCTION(CNetViewXCtrl, "SetRecordPackTime", SetRecordPackTime, VT_EMPTY, VTS_I2)
	DISP_FUNCTION(CNetViewXCtrl, "SetAudioVolume", SetAudioVolume, VT_BOOL, VTS_I4)
	DISP_FUNCTION(CNetViewXCtrl, "SetCurMaskArea", SetCurMaskArea, VT_BOOL, VTS_I2)
    DISP_FUNCTION(CNetViewXCtrl, "FlipVideo", FlipVideo, VT_BOOL, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "CleanMaskArea", CleanMaskArea, VT_BOOL, VTS_I2)
    DISP_FUNCTION(CNetViewXCtrl, "ServerCapturePic", ServerCapturePic, VT_BOOL, VTS_NONE)
    DISP_FUNCTION(CNetViewXCtrl, "TranCtrl", TranCtrl, VT_BOOL, VTS_I4)
	DISP_FUNCTION(CNetViewXCtrl, "GetChannelOsd", GetChannelOsd, VT_I2, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "SetChannelOsd", SetChannelOsd, VT_I2, VTS_I2 VTS_I2 VTS_I2 VTS_I2 VTS_I2 VTS_I2 VTS_BSTR VTS_I2 VTS_I2 VTS_BSTR VTS_I2 VTS_I2)
	DISP_FUNCTION(CNetViewXCtrl, "GetChannelEncParam", GetChannelEncParam, VT_I2, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "SetChannelEncParam", SetChannelEncParam, VT_I2, VTS_I2 VTS_I2 VTS_I2 VTS_I2 VTS_I2 VTS_I2 VTS_I2 VTS_I2)
	DISP_FUNCTION(CNetViewXCtrl, "GetViParam", GetViParam, VT_I2, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "SetViParam", SetViParam, VT_I2, VTS_I2 VTS_I2 VTS_I2 VTS_I2)
	DISP_FUNCTION(CNetViewXCtrl, "SaveParam", SaveParam, VT_I2, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "RestartDevice", RestartDevice, VT_I2, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "GetUseableWifi", GetUseableWifi, VT_BSTR, VTS_NONE)
    DISP_FUNCTION(CNetViewXCtrl, "ChooseVideoInput", ChooseVideoInput, VT_BOOL, VTS_I2)
	DISP_FUNCTION(CNetViewXCtrl, "PtzLock", PtzLock, VT_BOOL, VTS_BOOL VTS_I4 VTS_I4)
	DISP_FUNCTION(CNetViewXCtrl, "SetDeviceName", SetDeviceName, VT_BOOL, VTS_BSTR)
	DISP_FUNCTION(CNetViewXCtrl, "PTZCtrlPriority", PTZCtrlPriority, VT_I2, VTS_I2 VTS_I4 VTS_I2)
	DISP_FUNCTION(CNetViewXCtrl, "PISNow", PISNow, VT_BOOL, VTS_BOOL)
	DISP_FUNCTION(CNetViewXCtrl, "PISNexttime", PISNexttime, VT_BOOL, VTS_BOOL)
	DISP_FUNCTION(CNetViewXCtrl, "FullScreenEx", FullScreenEx, VT_EMPTY, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "StartDDNSConnect", StartDDNSConnect, VT_I4, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "StartDDNSView", StartDDNSView, VT_BOOL, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "IsFullScreen", IsFullScreen, VT_BOOL, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "SendSerialString", SendSerialString, VT_EMPTY, VTS_BSTR)
	DISP_FUNCTION(CNetViewXCtrl, "MailTest", MailTest, VT_EMPTY, VTS_I2)
	DISP_FUNCTION(CNetViewXCtrl, "GetConnectIPNumber", GetConnectIPNumber, VT_I4, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "FlipVideoH", FlipVideoH, VT_BOOL, VTS_NONE)
	DISP_FUNCTION(CNetViewXCtrl, "SharpeVideo", SharpeVideo, VT_I4, VTS_I4)
	//}}AFX_DISPATCH_MAP
END_DISPATCH_MAP()


/////////////////////////////////////////////////////////////////////////////
// Event map

BEGIN_EVENT_MAP(CNetViewXCtrl, COleControl)
	//{{AFX_EVENT_MAP(CNetViewXCtrl)
	EVENT_CUSTOM("UserChange", FireUserChange, VTS_I4)
	EVENT_CUSTOM("TalkStatus", FireTalkStatus, VTS_I4)
	EVENT_CUSTOM("StringMsg", FireStringMsg, VTS_NONE)
	EVENT_CUSTOM("Alarm", FireAlarm, VTS_I4  VTS_I4)
	EVENT_CUSTOM("ClickSel", FireClickSel, VTS_BSTR  VTS_I4)
	EVENT_CUSTOM("SearchRet", FireSearchRet, VTS_BSTR  VTS_BSTR  VTS_BSTR  VTS_I4  VTS_BSTR)
	EVENT_CUSTOM("ExOutPutStatus", FireExOutPutStatus, VTS_I4)
	EVENT_CUSTOM("TempNotify", FireTempNotify, VTS_BSTR)
	EVENT_CUSTOM("HumNotify", FireHumNotify, VTS_BSTR)
	EVENT_CUSTOM("ServerRecordStatus", FireServerRecordStatus, VTS_I4)
	EVENT_CUSTOM("JPEGEvent", FireJPEGEvent, VTS_I4)
	EVENT_CUSTOM("LinkStatus", FireLinkStatus, VTS_I4)
	EVENT_CUSTOM("RecordFileNotify", FireRecordFileNotify, VTS_I2  VTS_BSTR  VTS_BSTR  VTS_I4)
	EVENT_CUSTOM("ClientRecordStatus", FireClientRecordStatus, VTS_I4)
	EVENT_CUSTOM("JPEGData",FireJPEGData, VTS_PBSTR  VTS_I4)
	EVENT_CUSTOM("LButtonDblClk", FireLButtonDblClk, VTS_BSTR  VTS_I4)
	EVENT_CUSTOM("VideoMaskParam", FireVideoMaskParam, VTS_I4  VTS_I2)
    EVENT_CUSTOM("DiskStatus",FireDiskStatus,VTS_I4 VTS_I4)
    EVENT_CUSTOM("SwitchScreenName",FireSwitchScreenName,VTS_BSTR VTS_BSTR VTS_BSTR VTS_BSTR VTS_BSTR VTS_BSTR VTS_BSTR VTS_BSTR VTS_BSTR)
	EVENT_CUSTOM("ChannelOsd", FireChannelOsd, VTS_I2  VTS_I2  VTS_I2  VTS_I2  VTS_I2  VTS_I2  VTS_BSTR  VTS_I2  VTS_I2  VTS_BSTR  VTS_I2  VTS_I2)
	EVENT_CUSTOM("ChannelEncParam", FireChannelEncParam, VTS_I2  VTS_I2  VTS_I2  VTS_I2  VTS_I2  VTS_I2  VTS_I2  VTS_I2)
	EVENT_CUSTOM("ViParam", FireViParam, VTS_I2  VTS_I2  VTS_I2  VTS_I2)
	EVENT_CUSTOM("UseableWifi", FireUseableWifi, VTS_BSTR)
	EVENT_CUSTOM("SerialReceiveString", FireSerialReceiveString, VTS_BSTR)
	EVENT_CUSTOM("RButtonDown", FireRButtonDown, VTS_BSTR  VTS_I4)
	EVENT_CUSTOM("RButtonUp", FireRButtonUp, VTS_BSTR  VTS_I4)
	EVENT_CUSTOM("AudioState", FireAudioState, VTS_BOOL)
	EVENT_CUSTOM("ConnectIPAddr", FireConnectIPAddr, VTS_BSTR)
	//}}AFX_EVENT_MAP
END_EVENT_MAP()


/////////////////////////////////////////////////////////////////////////////
// Property pages

// TODO: Add more property pages as needed.  Remember to increase the count!
BEGIN_PROPPAGEIDS(CNetViewXCtrl, 1)
	PROPPAGEID(CNetViewXPropPage::guid)
END_PROPPAGEIDS(CNetViewXCtrl)


/////////////////////////////////////////////////////////////////////////////
// Initialize class factory and guid

IMPLEMENT_OLECREATE_EX(CNetViewXCtrl, "NETVIEWX.NetViewXCtrl.1",
	0xc615f36, 0xc1c, 0x497b, 0xb9, 0xe4, 0x83, 0x3b, 0xd, 0x7a, 0xa8, 0xca)


/////////////////////////////////////////////////////////////////////////////
// Type library ID and version

IMPLEMENT_OLETYPELIB(CNetViewXCtrl, _tlid, _wVerMajor, _wVerMinor)


/////////////////////////////////////////////////////////////////////////////
// Interface IDs

const IID BASED_CODE IID_DNetViewX =
		{ 0x3f751514, 0x9ae0, 0x4339, { 0xa6, 0x91, 0x2f, 0xcc, 0, 0x66, 0x52, 0xa6 } };
const IID BASED_CODE IID_DNetViewXEvents =
		{ 0x28201816, 0xe414, 0x4880, { 0x96, 0x67, 0xa5, 0xd3, 0xd, 0x9, 0xa2, 0xba } };


/////////////////////////////////////////////////////////////////////////////
// Control type information

static const DWORD BASED_CODE _dwNetViewXOleMisc =
	OLEMISC_ACTIVATEWHENVISIBLE |
	OLEMISC_SETCLIENTSITEFIRST |
	OLEMISC_INSIDEOUT |
	OLEMISC_CANTLINKINSIDE |
	OLEMISC_RECOMPOSEONRESIZE;

IMPLEMENT_OLECTLTYPE(CNetViewXCtrl, IDS_NETVIEWX, _dwNetViewXOleMisc)


/////////////////////////////////////////////////////////////////////////////
// CNetViewXCtrl::CNetViewXCtrlFactory::UpdateRegistry -
// Adds or removes system registry entries for CNetViewXCtrl
BOOL CNetViewXCtrl::CNetViewXCtrlFactory::UpdateRegistry(BOOL bRegister)
{
	// TODO: Verify that your control follows apartment-model threading rules.
	// Refer to MFC TechNote 64 for more information.
	// If your control does not conform to the apartment-model rules, then
	// you must modify the code below, changing the 6th parameter from
	// afxRegInsertable | afxRegApartmentThreading to afxRegInsertable.

	if (bRegister)
		return AfxOleRegisterControlClass(
			AfxGetInstanceHandle(),
			m_clsid,
			m_lpszProgID,
			IDS_NETVIEWX,
			IDB_NETVIEWX,
			afxRegInsertable | afxRegApartmentThreading,
			_dwNetViewXOleMisc,
			_tlid,
			_wVerMajor,
			_wVerMinor);
	else
		return AfxOleUnregisterClass(m_clsid, m_lpszProgID);
}
/////////////////////////////////////////////////////////////////////////////
// CNetViewXCtrl::CNetViewXCtrl - Constructor

#include "DiskOverlay.cpp"

CNetViewXCtrl::CNetViewXCtrl()
{
	InitializeIIDs(&IID_DNetViewX, &IID_DNetViewXEvents);

	// TODO: Initialize your control's instance data here.
	m_bAudioOnInfact = FALSE;
	m_hChHandle = 0;
	//m_keycolor  = RGB(10,10,10);
	m_Optcolor  = RGB(255,255,255);
	memset(m_OptString,'\0',sizeof(m_OptString));
	m_bthreadstartview = FALSE;
	m_OptRect.left   = 0;
	m_OptRect.right  = 200;
	m_OptRect.top    = 0;
	m_OptRect.bottom = 30;

	m_bMotionEdit = FALSE;
	m_bLinkOk     = FALSE;
	m_bMotionTest = FALSE;
	m_PISTag = -1;

	m_ImageWidth  = 704;
	m_ImageHeight = 576;
	m_HCount = m_ImageWidth / 32;
	m_VCount = m_ImageHeight / 32;
	//sprintf(m_OptString,"%s","connecting...");
	memset(&m_ChMotion,0,sizeof(CHANNMOTION));
	memset(&m_DvrChMotion, 0, sizeof(VSNETDVRMOTIONALARM));
	m_curmouse_x = m_curmouse_y = 0;

	m_languagetype = LANGUAGE_TYPE_CHINA;

#if defined(USER_TIMER_ALARM)
	m_timerSec = m_timerInter = 0;
#endif//USER_TIMER_ALARM
	//m_bIsMoutePTZCtrl = FALSE;

	memset(&m_pChSwitch,0,sizeof(CHANNWL_SWITCH));

	m_postflag = 3;
	m_bIsnewTalk = TRUE;
	//m_postflag = 0;
	m_timerRelink = 0;
	m_nRelinkNum  = TRUE;

	m_bUseOverlay = FALSE;//TRUE;

	memset(&m_diskadmin,0,sizeof(DISK_ADMIN));

	LoadTatalDisk();
	m_diskadmin.chudev = 0;

	memset(&m_diskover,0,sizeof(DISK_OVERLAY));
	m_diskover.hThread = NULL;
	m_diskover.timerid = 0;
	m_diskover.bIsRecord = FALSE;
	m_diskover.recordtime = 0;


	m_hChHandle = 0;
	m_viewQCIF  = FALSE;
	m_channel	= 0;
	m_trantype  = NET_MODE_TCP;

	m_password    = "123";
	m_username    = "admin";
	m_servername  = "video server";

	m_url = "192.168.1.81";

	m_curchannel = 0;
	m_buffernum  = 50;
	m_wServerPort = 3000;

	m_streamtype = 0;

	m_audioon  = FALSE;

	m_talkhandle = -1;

	m_bVideoMaskEdit = m_bVideoMaskBtnDown = FALSE;
	VSNET_ClientStartup(0,NULL);
	VSNET_ClientWaitTime(30, 4);

	m_ptzpretype  = -1;
	m_vmask_x	  = m_vmask_y = m_vmask_w = m_vmask_h = 0;
	memset(m_vmask,0,4*sizeof(VSNETVIDEOMASKAREA));
	m_curmaskarea = 0;

	m_delaytime = 10;
	m_control = NULL;
	//m_setgangband = FALSE;

	m_bOnServerRecv = 0;
	m_transbuff[0] = '\0';
	m_translen = 0;

	m_jpegHandle = -1;
	m_jpegfilename[0] = '\0';
	m_jpegerror = FALSE;
	memset(&m_filedata,0,sizeof(VSNETPLAY_FILE_DATA));

	m_recordtype = 0; 
	m_displayhandle = NULL;
	m_displayheight = m_displaywidth = 0;

	m_bdisplay = 0;
	m_flash = NULL;
    m_recordpacktime = FILE_PACKTIME;
	m_playstart		= FALSE;

	m_bSetVolume	= FALSE;
	m_volume		= 0xFFFF;

	m_bMotionBtnDown= FALSE;
    m_bFlipVideo    = FALSE;
    m_bFlipVideoH    = FALSE;
	
	m_szSaveFileName= _T("");

	m_hMessageParam = -1;
	m_pFullScreenWnd = NULL;
    m_dlgMail = NULL;

	m_bTalkRelinkThread = FALSE;
	m_hTalkRelinkThread = NULL;
}


/////////////////////////////////////////////////////////////////////////////
// CNetViewXCtrl::~CNetViewXCtrl - Destructor

CNetViewXCtrl::~CNetViewXCtrl()
{
	// TODO: Cleanup your control's instance data here.
	if(m_hMessageParam != -1)
	{
		VSNET_ClientMessageClose(m_hMessageParam);
		m_hMessageParam = -1;
	}
	if (m_pFullScreenWnd)
	{
		delete m_pFullScreenWnd;
		m_pFullScreenWnd = NULL;
	}

    if (m_dlgMail != NULL)
    {
        delete m_dlgMail;
        m_dlgMail = NULL;
    }
}


/////////////////////////////////////////////////////////////////////////////
// CNetViewXCtrl::OnDraw - Drawing function

void CNetViewXCtrl::OnDraw(
			CDC* pdc, const CRect& rcBounds, const CRect& rcInvalid)
{
	//if((m_hChHandle == NULL) || (VSNET_ClientRefrenshWnd(m_hChHandle) == FALSE))
	{
		//CBrush tempBrush(m_hChHandle == NULL ? UNLINK_COLOR : FACE_COLOR);
		CBrush tempBrush(FACE_COLOR);
		pdc->FillRect(rcBounds, &tempBrush);
		/*if(m_OptString[0] != '\0')
		{
			COLORREF textcolor;
			textcolor = RGB(255,255,255);
			pdc->SetTextColor(textcolor);
			pdc->DrawText("未连接",&m_OptRect,DT_LEFT);
		}*/
	}
}


/////////////////////////////////////////////////////////////////////////////
// CNetViewXCtrl::DoPropExchange - Persistence support

void CNetViewXCtrl::DoPropExchange(CPropExchange* pPX)
{
	ExchangeVersion(pPX, MAKELONG(_wVerMinor, _wVerMajor));
	COleControl::DoPropExchange(pPX);

	// TODO: Call PX_ functions for each persistent custom property.

}


/////////////////////////////////////////////////////////////////////////////
// CNetViewXCtrl::GetControlFlags -
// Flags to customize MFC's implementation of ActiveX controls.
//
// For information on using these flags, please see MFC technical note
// #nnn, "Optimizing an ActiveX Control".
DWORD CNetViewXCtrl::GetControlFlags()
{
	DWORD dwFlags = COleControl::GetControlFlags();

	// The control's output is not being clipped.
	// The control guarantees that it will not paint outside its
	// client rectangle.
	dwFlags &= ~clipPaintDC;
	return dwFlags;
}


/////////////////////////////////////////////////////////////////////////////
// CNetViewXCtrl::OnResetState - Reset control to default state

void CNetViewXCtrl::OnResetState()
{
	COleControl::OnResetState();  // Resets defaults found in DoPropExchange

	// TODO: Reset any other control state here.
}


/////////////////////////////////////////////////////////////////////////////
// CNetViewXCtrl message handlers

void CNetViewXCtrl::OnUrlChanged() 
{
	// TODO: Add notification handler code

	SetModifiedFlag();
}

void CNetViewXCtrl::OnChannelChanged() 
{
	// TODO: Add notification handler code

	SetModifiedFlag();
}

void CNetViewXCtrl::OnUsernameChanged() 
{
	// TODO: Add notification handler code

	SetModifiedFlag();
}

void CNetViewXCtrl::OnPasswordChanged() 
{
	// TODO: Add notification handler code

	SetModifiedFlag();
}

void CNetViewXCtrl::OnServernameChanged() 
{
	// TODO: Add notification handler code

	SetModifiedFlag();
}

void CNetViewXCtrl::OnViewQCIFChanged() 
{
	// TODO: Add notification handler code

	SetModifiedFlag();
}

void CNetViewXCtrl::OnTrantypeChanged() 
{
	// TODO: Add notification handler code

	SetModifiedFlag();
}

void CNetViewXCtrl::FullScreen() 
{
	if(m_hChHandle)
	{
		if (m_pFullScreenWnd == NULL)
		{
			m_pFullScreenWnd = new CFullDisplayWnd(this);
			m_pFullScreenWnd->Create(IDD_DIALOG_FULL,this);
			this->SetFocus();
		}
		m_pFullScreenWnd->m_bKeepProportion = FALSE;
		m_pFullScreenWnd->ShowWindow(SW_SHOW);
		/*
#if defined(PROTYPE_XISHI) || defined(PROTYPE_LOGO)
		if(m_displayhandle)
		{
			VSNET_ClientShowSetWnd(m_displayhandle,m_hWnd);
			VSNET_ClientRefreshImageShow(m_displayhandle);
		}
#else
		VSNET_ClientSetWnd(m_hChHandle,m_hWnd);
		VSNET_ClientRefrenshWnd(m_hChHandle);
#endif*/
	}
}

void CNetViewXCtrl::FullScreenEx() 
{
	// TODO: Add your dispatch handler code here
	if(m_hChHandle)
	{
		if (m_pFullScreenWnd == NULL)
		{
			m_pFullScreenWnd = new CFullDisplayWnd(this);
			m_pFullScreenWnd->Create(IDD_DIALOG_FULL,this);
			
			this->SetFocus();
		}
		m_pFullScreenWnd->m_bKeepProportion = TRUE;
		m_pFullScreenWnd->ShowWindow(SW_SHOW);
/*#if defined(PROTYPE_XISHI) || defined(PROTYPE_LOGO)
		if(m_displayhandle)
		{
			VSNET_ClientShowSetWnd(m_displayhandle,m_hWnd);
			VSNET_ClientRefreshImageShow(m_displayhandle);
		}
#else
		VSNET_ClientSetWnd(m_hChHandle,m_hWnd);
		VSNET_ClientRefrenshWnd(m_hChHandle);
#endif*/
	}
}

void CNetViewXCtrl::UnFullScreen()
{
	if (m_hChHandle)
	{
		if (m_pFullScreenWnd)
		{
			m_pFullScreenWnd->ShowWindow(SW_HIDE);
		}
#if defined(PROTYPE_XISHI) || defined(PROTYPE_LOGO)
		if(m_displayhandle)
		{
			VSNET_ClientShowSetWnd(m_displayhandle,m_hWnd);
			VSNET_ClientRefreshImageShow(m_displayhandle);
		}
#else
		VSNET_ClientSetWnd(m_hChHandle,m_hWnd);
		VSNET_ClientRefrenshWnd(m_hChHandle);
#endif
	}
}

BOOL CNetViewXCtrl::StartView() 
{
	m_nRelinkNum  = TRUE;
	m_playstart	  = TRUE;
	m_bSetVolume  = FALSE;

	
	if ( !InterStartView() )
	{
		m_playstart = FALSE;
		return FALSE;
	}
	else
	{
		//修改m_sername的默认值
// 		WHOLEPARAM		m_wholeparam;
// 		int iRet = VSNET_ClientMessageOpt(m_hMessageParam, MESSAGE_CMD_GETGLOBALPARAM,0,&m_wholeparam,NULL,NULL);
// 		if(iRet)
// 		{
// 			m_servername.Format("%s", m_wholeparam.m_servername);
// 		}
// 		else
// 		{
// 		}
		return TRUE;
	}
}

BOOL CNetViewXCtrl::StopView() 
{
//	GetConnectIPNumber();
	m_diskover.bIsRecord = FALSE;
	m_nRelinkNum = FALSE;
	m_bSetVolume = FALSE;
	InterStopView();
	m_bdisplay = 0;
	Invalidate();
	return TRUE;
}

short CNetViewXCtrl::StartRecord(LPCTSTR filename)
{

#ifndef CONTROL_TYPE_DXHJ
	if(filename == NULL || strlen(filename) < 1)
#else
	if(1)
#endif	
	{
		if(m_hChHandle)
		{
			m_diskover.bIsRecord = TRUE;
			return InterRecord(TRUE,TRUE,filename);
		}
	}
	else if(m_hChHandle)
	{
		CString strpath = filename;
		CString strpathc = strpath.Left(strpath.ReverseFind('\\'));
		CDiskObject cdo;
		cdo.CreateDirectory(strpathc);
		
		if(m_recordtype == 0)
		{
			
			if(VSNET_ClientStartASFFileCap(m_hChHandle,(char*)filename,FALSE)) 
				return 0;
			else                                     
				return -1;
		}
		else
		{
			if(VSNET_ClientStartMp4Capture(m_hChHandle,(char*)filename)) 
				return 0;
			else                                     
				return -1;
		}
	}
	return -1;
}

void CNetViewXCtrl::StopRecord()
{
	m_diskover.bIsRecord = FALSE;
	InterRecord(FALSE);
}

BOOL CNetViewXCtrl::CaptureBmp(LPCTSTR filename) 
{
	if(m_hChHandle)
	{
		if(filename == NULL || strlen(filename) < 1)
		{
			char m_filename[MAX_PATH];
#if defined USER_CUSTOMFILENAME
			CFileDialog dlg(FALSE, 
			".bmp",
			NULL, 
			OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
			"BMP Files(*.bmp)|*.bmp||", this);
			if( dlg.DoModal() == IDCANCEL )
				return FALSE;
			strcpy(m_filename,dlg.GetFileName());
#else
			FILE *fpFile = NULL;
			SYSTEMTIME dwSysTimer={0};
			GetLocalTime(&dwSysTimer);
			CreateDirectory("C:\\TEMP",NULL);
			CString sDir = "C:\\TEMP";
#ifdef USER_CUSTOMCAPBMPDIR
			CFileDialogST	dlg;
			int				nRetValue;
			CString         lpstr;
			lpstr = "";
			nRetValue = dlg.SelectFolder(lpstr, NULL,
				BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS, this);
			if (nRetValue == IDOK)
			{
				sDir.Format("%s", dlg.GetSelectedFolder());
			}
			else
			{
				return FALSE;
			}
#endif

#ifdef USER_YWPICNAME_URL
			sprintf(m_filename,"%s\\%s_%d_%02d_%02d_%02d.bmp", sDir.GetBuffer(0),
				m_url,m_channel + 1,
				dwSysTimer.wHour,
				dwSysTimer.wMinute,
				dwSysTimer.wSecond);
#else
			sprintf(m_filename,"%s\\%s_%d_%02d_%02d_%02d.bmp", sDir.GetBuffer(0),
				m_servername,m_channel + 1,
				dwSysTimer.wHour,
				dwSysTimer.wMinute,
				dwSysTimer.wSecond);
#endif
			fpFile = fopen(m_filename,"r");
			if(fpFile != NULL)
			{
				int i = 1;
				fclose(fpFile);
				for(;;)
				{
#ifdef USER_YWPICNAME_URL
					sprintf(m_filename,"C:\\TEMP\\%s_%d_%02d_%02d_%02d_%02d.bmp",
						m_url,m_channel + 1,
						dwSysTimer.wHour,
						dwSysTimer.wMinute,
						dwSysTimer.wSecond,
						i);
#else
					sprintf(m_filename,"C:\\TEMP\\%s_%d_%02d_%02d_%02d_%02d.bmp",
						m_servername,m_channel + 1,
						dwSysTimer.wHour,
						dwSysTimer.wMinute,
						dwSysTimer.wSecond,
						i);
#endif
					fpFile = fopen(m_filename,"r");
					if(fpFile == NULL) break;
					fclose(fpFile);
					fpFile = NULL;
					i ++;
				}
			}
#endif
			return VSNET_ClientCapturePicture(m_hChHandle,(char*)m_filename);
		}
		else
		{
			CString strpath = filename;
			CString strpathc = strpath.Left(strpath.ReverseFind('\\'));
			CDiskObject cdo;
			cdo.CreateDirectory(strpathc);
			
			return VSNET_ClientCapturePicture(m_hChHandle,(char*)filename);
		}
	}
	return FALSE;
}

long CNetViewXCtrl::StartTalk() 
{
	if (m_hTalkRelinkThread)
	{
		m_bTalkRelinkThread = FALSE;
		return -1;
	}

	StopTalk();
	char url[40],sername[24];
	char username[20],password[20];
	sprintf(url,"%s",m_url);
	sprintf(sername,"%s",m_servername);
	sprintf(username,"%s",m_username);
	sprintf(password,"%s",m_password);
	if(m_hChHandle == 0) return -1;
	m_talkhandle = VSNET_ClientTalkBothwayStart(url, m_channel, username, password, (WORD)m_wServerPort, TalkEncCallBack, sername, m_hWnd,8000,this);//启用新的双向对讲函数
	if (m_talkhandle > 0)
	{
		m_bIsnewTalk = TRUE;
	}
	else
	{
        m_talkhandle = VSNET_ClientTalkExchangeStart(url,username,password,(WORD)m_wServerPort,TalkEncCallBack,sername,8000,this);//启用老的双向对讲函数
	    m_bIsnewTalk = FALSE;
	}
	TRACE("打开双向对讲%s!", m_talkhandle < 0 ? "失败":"成功");
	if (m_talkhandle < 0)
	{
		FireTalkStatus(0);
	}
	else
	{
		if (m_bIsnewTalk)
		{
			FireTalkStatus(2);
		}
		else
		{
			FireTalkStatus(1);
		}
	}
    return (m_talkhandle < 0 ? -1 : 0);
#if 0
	if(m_talkhandle < 0)
	{
		m_Optcolor = RGB(255,0,0);
		if(m_languagetype == LANGUAGE_TYPE_CHINA)
			sprintf(m_OptString,"错误:请求对讲失败%d!",m_talkhandle);
		else
			sprintf(m_OptString,"error:quest talk failed:%d!",m_talkhandle);
		Invalidate();
		Sleep(300);
		m_OptString[0] = '\0';
		Invalidate();
		return -1;
	}
	return 0;
#endif
}

long CNetViewXCtrl::StopTalk() 
{
	if(m_talkhandle >= 0 && ! m_bIsnewTalk)
		VSNET_ClientTalkExchangeStop(m_talkhandle);
	else if (m_talkhandle >= 0 && m_bIsnewTalk)
	{
        VSNET_ClientTalkBothwayStop(m_talkhandle);
	}
	
	m_talkhandle = -1;
	return 0;
}

void CNetViewXCtrl::OnClose() 
{
	StopTalk();
	StopView();
	StopSerial();
	VSNET_ClientCleanup();
	CWnd::OnClose();
}

void CNetViewXCtrl::OnDestroy() 
{

#if defined(USER_TIMER_ALARM)
	if(m_timerSec)
	{
		KillTimer(m_timerSec);
		m_timerSec = 0;
	}
	if(m_timerInter)
	{
		KillTimer(m_timerInter);
		m_timerInter = 0;
	}
#endif//USER_TIMER_ALARM
	KillTimer(TIMERID_JPEGRELINK);
	STOP_RELINKTIMER();
	
	CaptureJpegStop();
	StopTalk();
	StopView();
	StopSerial();\
	if(m_displayhandle)
	{
		VSNET_ClientStopImageShow(m_displayhandle);
		m_displayhandle = NULL;
	}
	VSNET_ClientCleanup();

	if(m_flash)
	{
		m_flash->DestroyWindow();
		delete m_flash;
		m_flash  = NULL;
	}

	if (m_hTalkRelinkThread)
	{
		m_bTalkRelinkThread = FALSE;
		TerminateThread(m_hTalkRelinkThread, -1);
		CloseHandle(m_hTalkRelinkThread);
		m_hTalkRelinkThread = NULL;
	}

	COleControl::OnDestroy();	
}

void CNetViewXCtrl::OnPaint()
{
	CPaintDC dc(this); // device context for painting

	if(!m_bLinkOk)
	{
		CRect Rect;
		CBrush tempBrush(FACE_COLOR);
		GetClientRect(&Rect);
		dc.FillRect(Rect, &tempBrush);
	}

#if defined(PROTYPE_LOGO)
	if(m_bdisplay == 2) 
	{
		if(m_flash) 
		{
			m_flash->ShowWindow(SW_HIDE);
			m_flash->Stop();
		}
		VSNET_ClientRefreshImageShow(m_displayhandle);
	}
	else if(m_bdisplay == 1)
	{
		if(m_flash) 
		{
			m_flash->ShowWindow(SW_HIDE);
			m_flash->Stop();
		}

		CDC *pDc = &dc;
		CRect Rect;
		CBrush tempBrush(FACE_COLOR);
		GetClientRect(&Rect);
		dc.FillRect(Rect, &tempBrush);
		pDc->SetTextColor(m_Optcolor);
		pDc->SetBkColor(RGB(10,10,10));
		pDc->DrawText("对方网络故障，请稍后再试",&m_OptRect,DT_LEFT);
	}
	else if(m_flash)
	{
		CRect Rect;
		GetClientRect(&Rect);
		m_flash->MoveWindow(Rect);
		m_flash->ShowWindow(SW_SHOW);
		m_flash->Play();
	}
	else
	{
		CRect Rect;
		CBrush tempBrush(FACE_COLOR);
		GetClientRect(&Rect);
		dc.FillRect(Rect, &tempBrush);
	}
#elif defined(PROTYPE_XISHI) 
	if(m_displayhandle)
	{
		VSNET_ClientRefreshImageShow(m_displayhandle);
	}
	else
	{
		CRect Rect;
		CBrush tempBrush(FACE_COLOR);
		GetClientRect(&Rect);
		dc.FillRect(Rect, &tempBrush);
	}

#else
	//if((m_hChHandle == NULL) || (VSNET_ClientRefrenshWnd(m_hChHandle) == FALSE))
	{
		if (m_bdisplay == 1 || m_hChHandle == 0)
		{	
			CRect Rect;
			CBrush tempBrush(FACE_COLOR);
			GetClientRect(&Rect);
			dc.FillRect(Rect, &tempBrush);
		}
		else
		{
			VSNET_ClientRefrenshWnd(m_hChHandle);
		}
	}

#endif
#if !defined(PROTYPE_XISHI) && !defined(PROTYPE_LOGO)
	if(m_OptString[0] != '\0')
	{
        UINT  nDrawFormat;
		CDC   *pDc = &dc;
        RECT  *pDrawRect = NULL;         
        CRect Rect;

		pDc->SetTextColor(m_Optcolor);
		pDc->SetBkColor(RGB(10,10,10));

#ifdef CONTROL_TYPE_DXHJ
        if( strcmp(m_OptString,"网络断开") == 0 )
        {
            GetClientRect(&Rect);
            pDrawRect   = &Rect;
            nDrawFormat = DT_CENTER|DT_VCENTER|DT_SINGLELINE;
        }
        else
#endif
        {
			pDrawRect   = &m_OptRect;
            nDrawFormat = DT_LEFT;
        }

        pDc->DrawText(m_OptString,pDrawRect,nDrawFormat);
	}
#endif
	if(m_bVideoMaskEdit && m_bLinkOk)
	{
		RECT rect;
		CBrush BrushRed(RGB(255,0,0));
		CBrush BrushBlue(RGB(0,255,0));
		CDC *pDc = &dc;

		if(m_vmask_w > 0)
		{
			rect.left   = m_vmask_x;
			rect.right  = rect.left + m_vmask_w;
		}
		else
		{
			rect.left   = m_vmask_x + m_vmask_w;
			rect.right  = rect.left - m_vmask_w;
		}
		if(m_vmask_h > 0)
		{
			rect.top    = m_vmask_y;
			rect.bottom = rect.top + m_vmask_h;
		}
		else
		{
			rect.top    = m_vmask_y + m_vmask_h;
			rect.bottom = rect.top - m_vmask_h;
		}
		pDc->FrameRect(&rect,&BrushRed);

		for(int i=0;i<4;i++)
		{
			if(i != m_curmaskarea)
			{
				rect.left	= m_vmask[i].m_x;
				rect.right	= m_vmask[i].m_x + m_vmask[i].m_width;
				rect.top	= m_vmask[i].m_y;
				rect.bottom = m_vmask[i].m_y + m_vmask[i].m_height;
				pDc->FrameRect(&rect,&BrushBlue);
			}
		}
	}
	else if(m_bMotionEdit && m_bLinkOk)
	{
		int h,v;
		CBrush RectBrush(RGB(255,255,255));
		CBrush BrushRead(RGB(255,0,0));
		CDC *pDc = &dc;
		RECT rectwin;
		RECT rect;
		rect.left = m_curmouse_x/m_wblock;
		rect.left = rect.left * m_wblock;
		rect.right= rect.left + m_wblock;
		rect.top  = m_curmouse_y/m_hblock;
		rect.top  = rect.top * m_hblock;
		rect.bottom = rect.top + m_hblock;
		GetClientRect(&rectwin);
		rect.bottom = (rect.bottom > rectwin.bottom) ? rectwin.bottom : rect.bottom;
		rect.top = rect.bottom - m_hblock;
		
		pDc->FrameRect(&rect,&RectBrush);
		for(h=0;h<m_VCount;h++)
		{
			for(v=0;v<m_HCount;v++)
			{
				if(m_ChMotion.m_detect[h][v])
				{
					rect.left = m_wblock * v;
					rect.right = rect.left + m_wblock;
					rect.top  = m_hblock * h;
					rect.bottom = rect.top + m_hblock;
					pDc->FrameRect(&rect,&BrushRead);
				}
			}
		}

		if(m_bMotionBtnDown)
		{
			CBrush BrushYellow(RGB(255,255,0));
			CRect  rc(m_mLtPoint,m_mRbPoint);
			rc.NormalizeRect();
			pDc->FrameRect((LPRECT)&rc,&BrushYellow);
		}
	}
}

void CNetViewXCtrl::SoundOn()
{
	m_audioon = TRUE;
	if(m_hChHandle) 
	{
		m_bAudioOnInfact = VSNET_ClientPlayAudio(m_hChHandle);
	}
	if(m_bLinkOk)
		FireAudioState(m_bAudioOnInfact);
}

void CNetViewXCtrl::SoundOff() 
{
	m_audioon = FALSE;
	if(m_hChHandle)
	{
		VSNET_ClientStopAudio(m_hChHandle);
		m_bAudioOnInfact = FALSE;
	}
	if(m_bLinkOk)
		FireAudioState(m_bAudioOnInfact);
}

short CNetViewXCtrl::ImageWidth() 
{
	// TODO: Add your dispatch handler code here
	BOOL bret = FALSE;
	DWORD width = 352,height = 288;
	if(m_hChHandle)
		bret = VSNET_ClientGetVideoSize(m_hChHandle,&width,&height);
	if (bret)
		return (short)width;
	else
		return 0;
}

short CNetViewXCtrl::ImageHeight() 
{
	// TODO: Add your dispatch handler code here
	BOOL bret = FALSE;
	DWORD width = 352,height = 288;
	if(m_hChHandle)
		bret = VSNET_ClientGetVideoSize(m_hChHandle,&width,&height);
	if (bret)
		return (short)height;
	else
		return 0;
}

void CNetViewXCtrl::PostProMethon(long postmethon)
{
	m_postflag = (int)postmethon;
	if(m_hChHandle)
	{
		VSNET_ClientVideoQuality(m_hChHandle,(int)m_postflag);
	}
}

void CNetViewXCtrl::OnMove(int x, int y) 
{
	COleControl::OnMove(x, y);
#if defined(PROTYPE_XISHI) || defined(PROTYPE_LOGO)
	if(m_displayhandle)
	{
		VSNET_ClientRefreshImageShow(m_displayhandle);
	}
#else
	VSNET_ClientRefrenshWnd(m_hChHandle);
#endif
}

void CNetViewXCtrl::OnSizing(UINT fwSide, LPRECT pRect) 
{
	COleControl::OnSizing(fwSide, pRect);
	
#if defined(PROTYPE_XISHI) || defined(PROTYPE_LOGO)
	if(m_displayhandle)
	{
		VSNET_ClientRefreshImageShow(m_displayhandle);
	}
#else
	VSNET_ClientRefrenshWnd(m_hChHandle);
#endif	
}

short CNetViewXCtrl::PTZCtrl(short type, long param) 
{
	// TODO: Add your dispatch handler code here
	if(m_hChHandle)
	{
		if(type == PTZ_AUTO)
		{
			VSNET_ClientPTZCtrl(m_hChHandle, param ? PTZ_AUTO : PTZ_AUTOSTOP, param ? param : 0);
			return 0;
		}
		if(type == PTZ_STOP && m_ptzpretype != -1)
		{
			switch(m_ptzpretype)
			{
			case PTZ_LEFT:		type = PTZ_LEFTSTOP;	break;
			case PTZ_RIGHT:		type = PTZ_RIGHTSTOP;	break;
			case PTZ_UP:		type = PTZ_UPSTOP;		break;
			case PTZ_DOWN:		type = PTZ_DOWNSTOP;	break;
			case PTZ_IRISADD:	type = PTZ_IRISADDSTOP;	break;
			case PTZ_IRISDEC:	type = PTZ_IRISDECSTOP;	break;
			case PTZ_FOCUSADD:	type = PTZ_FOCUSADDSTOP;break;
			case PTZ_FOCUSDEC:	type = PTZ_FOCUSDECSTOP;break;
			case PTZ_ZOOMADD:	type = PTZ_ZOOMADDSTOP;	break;
			case PTZ_ZOOMDEC:	type = PTZ_ZOOMDECSTOP;	break;
			}
			VSNET_ClientPTZCtrl(m_hChHandle,type,param);
			m_ptzpretype = -1;
		}
		else
		{
			VSNET_ClientPTZCtrl(m_hChHandle,type,param);
			m_ptzpretype = type;
		}
	}
	return 0;
}
short CNetViewXCtrl::PTZCtrlPriority(short type, long param, short npriority) 
{
	if(m_hChHandle)
	{
		if(type == PTZ_AUTO)
		{
			VSNET_ClientPTZCtrl(m_hChHandle,param ? PTZ_AUTO : PTZ_AUTOSTOP,0, npriority);
			return 0;
		}
		if(type == PTZ_STOP && m_ptzpretype != -1)
		{
			switch(m_ptzpretype)
			{
			case PTZ_LEFT:		type = PTZ_LEFTSTOP;	break;
			case PTZ_RIGHT:		type = PTZ_RIGHTSTOP;	break;
			case PTZ_UP:		type = PTZ_UPSTOP;		break;
			case PTZ_DOWN:		type = PTZ_DOWNSTOP;	break;
			case PTZ_IRISADD:	type = PTZ_IRISADDSTOP;	break;
			case PTZ_IRISDEC:	type = PTZ_IRISDECSTOP;	break;
			case PTZ_FOCUSADD:	type = PTZ_FOCUSADDSTOP;break;
			case PTZ_FOCUSDEC:	type = PTZ_FOCUSDECSTOP;break;
			case PTZ_ZOOMADD:	type = PTZ_ZOOMADDSTOP;	break;
			case PTZ_ZOOMDEC:	type = PTZ_ZOOMDECSTOP;	break;
			}
			VSNET_ClientPTZCtrl(m_hChHandle,type,param, npriority);
			m_ptzpretype = -1;
		}
		else
		{
			VSNET_ClientPTZCtrl(m_hChHandle,type,param, npriority);
			m_ptzpretype = type;
		}
	}
	
	return 0;
}

long CNetViewXCtrl::ViParamAdjust(short Brightness, short Contrast, short Staturation, short Hue) 
{
	if(m_hChHandle)
		VSNET_ClientViAdjust(m_hChHandle,
		(unsigned char)Brightness,
		(unsigned char)Contrast,
		(unsigned char)Staturation,
		(unsigned char)Hue);
	return 0;
}

BSTR CNetViewXCtrl::GetSaveFileName() 
{
#ifdef CONTROL_TYPE_DXHJ
	return m_szSaveFileName.AllocSysString();
#else
	CString strResult;
	CFileDialog dlgFile(
		FALSE,
		_T(".asf"),
		"",
		OFN_OVERWRITEPROMPT,
		"asf Files(*.asf)|*.asf||",
		NULL);
	char lpszTitle[]={"save asf file"};
	dlgFile.m_ofn.lpstrTitle = lpszTitle;
	if(dlgFile.DoModal() != IDOK) return NULL;
	strResult = dlgFile.GetPathName();
	return strResult.AllocSysString();
#endif
}

LRESULT CNetViewXCtrl::OnWMInvalidate(WPARAM wParam,LPARAM lParam)
{
	Invalidate();
	return 1;
}

void CNetViewXCtrl::PublicInterStartView()
{
	InterStartView();
}

static DWORD s_thread_startview(CNetViewXCtrl* pCtrl)
{
	pCtrl->m_bthreadstartview = TRUE;
	pCtrl->PublicInterStartView();
	pCtrl->m_bthreadstartview = FALSE;
	return 0;
}

void CNetViewXCtrl::ThreadInterStartView()
{
	DWORD ID;
	if(!m_bthreadstartview)
	{
		HANDLE ii = CreateThread(0,1024*10,
			(LPTHREAD_START_ROUTINE)s_thread_startview,
			this, 0,&ID);
	}
}

void CNetViewXCtrl::OnTimer(UINT nIDEvent) 
{
	// TODO: Add your message handler code here and/or call default
	if(nIDEvent == TIMERID_SYS)
	{
		if(!m_bLinkOk)
		{
			Invalidate();
		}
	}
	else if(nIDEvent == TIMERID_SWITCH)//m_pChSwitch.timerid)
	{
		int i;
		int bFind = FALSE;
		if(m_hChHandle == 0)
		{
			COleControl::OnTimer(nIDEvent);
			return;
		}
		m_pChSwitch.curch ++;
		m_pChSwitch.curch = m_pChSwitch.curch >= 16 ? 0 : m_pChSwitch.curch;
		for(i=0;i<16;i++)
		{
			if(m_pChSwitch.chinclude[m_pChSwitch.curch])
			{
				bFind = TRUE;
				break;
			}
			m_pChSwitch.curch ++;
			m_pChSwitch.curch = m_pChSwitch.curch >= 16 ? 0 : m_pChSwitch.curch;
		}
		if(bFind)
		{
			VSNET_ClientSwitchChannel(m_hChHandle,m_pChSwitch.curch);
		}
	}
#if defined(USER_TIMER_ALARM)
	else if(nIDEvent == m_timerSec)
	{
		Beep(2500,10);
		m_timerCount ++;
		if(m_timerCount >= 5)
		{
			m_timerCount = 0;
			KillTimer(m_timerSec);
			m_timerSec = 0;
			if(m_timerInter)
			{
				KillTimer(m_timerInter);
				m_timerInter = 0;
			}
			m_timerInter = SetTimer(1,1000 * 30,0);
		}
	}
	else if(nIDEvent == m_timerInter)
	{
		KillTimer(m_timerInter);
		m_timerInter = 0;
		if(m_timerSec)
		{
			KillTimer(m_timerSec);
			m_timerSec = 0;
		}
		m_timerSec = SetTimer(2,1000,0);
	}
#endif//USER_TIMER_ALARM
	else if(nIDEvent == TIMERID_RELINK)
	{
		STOP_RELINKTIMER();
		InterStopView();
		Sleep(100);
		ThreadInterStartView();
		//InterStartView();
	}
	else if(nIDEvent == TIMERID_DISKCHECK)
	{
		UINT curtime;
		int curdev = GetCanUseDisk();
		if(curdev == -1)
		{
			DWORD ID;
			if(m_diskover.hThread)
			{
				if(WaitForSingleObject(m_diskover.hThread,0) != WAIT_OBJECT_0)
				{
					COleControl::OnTimer(nIDEvent);
					return;
				}
				CloseHandle(m_diskover.hThread);
				m_diskover.hThread = NULL;
			}
			m_diskover.hThread = CreateThread(0,1024*10,
				(LPTHREAD_START_ROUTINE)s_thread_overlaydisk,
				&m_diskadmin,
				CREATE_SUSPENDED,&ID);
			SetThreadPriority(m_diskover.hThread,THREAD_PRIORITY_LOWEST);
			ResumeThread(m_diskover.hThread);

			COleControl::OnTimer(nIDEvent);
			return;
		}
		else if(curdev != m_diskadmin.chudev)
		{
			m_diskadmin.chudev = curdev;
			InterRecord(TRUE);

			COleControl::OnTimer(nIDEvent);
			return;
		}
		curtime = timeGetTime();
		if((curtime - m_diskover.recordtime) >= m_recordpacktime)
		{
			InterRecord(TRUE);
		}
	}
	else if(nIDEvent == TIMERID_JPEGRELINK)
	{
		if(m_jpegerror == TRUE)
		{
			CaptureJpegStart();
		}
	}
	COleControl::OnTimer(nIDEvent);
}

void CNetViewXCtrl::OnMouseMove(UINT nFlags, CPoint point) 
{
	// TODO: Add your message handler code here and/or call default
	if(m_bMotionEdit && m_bLinkOk)
	{
		if(nFlags == MK_LBUTTON)
		{
			RECT rect;
			GetClientRect(&rect);

			m_mRbPoint.x = point.x < 0 ? 0 : point.x;
			m_mRbPoint.x = point.x > rect.right ? rect.right: m_mRbPoint.x;
			m_mRbPoint.y = point.y < 0 ? 0 : point.y;
			m_mRbPoint.y = point.y > rect.bottom ? rect.bottom: m_mRbPoint.y;
		}
	

		static int no = 0;
		int nonow = (point.y/m_hblock)*m_HCount + (point.x /m_wblock);
		if(no != nonow)
		{
			no = nonow;
			m_curmouse_x = point.x;
			m_curmouse_y = point.y;
		}

		Invalidate();
	}
	else if(m_bVideoMaskEdit && m_bLinkOk)
	{
		if( m_bVideoMaskBtnDown && nFlags == MK_LBUTTON )
		{
			RECT rect;
			GetClientRect(&rect);
			point.x = point.x < 0 ? 0 : point.x;
			point.x = point.x > rect.right ? rect.right : point.x;
			point.y = point.y < 0 ? 0 : point.y;
			point.y = point.y > rect.bottom ? rect.bottom : point.y;

			if(abs(point.x - m_vmask_x) > m_maskmax_w)
			{
				m_vmask_w = point.x > m_vmask_x ? m_maskmax_w : -m_maskmax_w;
			}
			else
			{
				m_vmask_w  = point.x - m_vmask_x;
			}
			if(abs(point.y - m_vmask_y) > m_maskmax_h)
			{
				m_vmask_h = point.y > m_vmask_y ? m_maskmax_h : -m_maskmax_h;
			}
			else
			{
				m_vmask_h = point.y - m_vmask_y;
			}
			if(m_vmask_w > 0)
			{
				m_vmask[m_curmaskarea].m_x     = m_vmask_x;
				m_vmask[m_curmaskarea].m_width = m_vmask_w;
			}
			else
			{
				m_vmask[m_curmaskarea].m_x		= m_vmask_x + m_vmask_w;
				m_vmask[m_curmaskarea].m_width  = -m_vmask_w;
			}
			if(m_vmask_h > 0)
			{
				m_vmask[m_curmaskarea].m_y      = m_vmask_y;
				m_vmask[m_curmaskarea].m_height = m_vmask_h;
			}
			else
			{
				m_vmask[m_curmaskarea].m_y      = m_vmask_y + m_vmask_h;
				m_vmask[m_curmaskarea].m_height = - m_vmask_h;
			}
		}
		Invalidate();
	}
	COleControl::OnMouseMove(nFlags, point);
}

void CNetViewXCtrl::OnLButtonDown(UINT nFlags, CPoint point)
{
	if(m_bMotionEdit && m_bLinkOk)
	{
		m_mRbPoint = m_mLtPoint = point;
		m_bMotionBtnDown = TRUE;
		Invalidate();
	}
	else if(m_bVideoMaskEdit && m_bLinkOk)
	{
		m_bVideoMaskBtnDown = TRUE;
		m_vmask_x = point.x;
		m_vmask_y = point.y;
		m_vmask_w = 0;
		m_vmask_h = 0;
	}
	if(nFlags == MK_LBUTTON)
		FireClickSel(m_url,(unsigned long)m_channel);
	COleControl::OnLButtonDown(nFlags, point);
}

void CNetViewXCtrl::OnLButtonDblClk(UINT nFlags, CPoint point)
{
	if(nFlags == MK_LBUTTON)
		FireLButtonDblClk(m_url,(unsigned long)m_channel);
	COleControl::OnLButtonDblClk(nFlags, point);
}
void CNetViewXCtrl::MotionTest(BOOL bTest) 
{
	if(m_hChHandle && m_bLinkOk)
	{
		char sername[24],url[40],username[20],password[20];
		sprintf(sername,"%s",m_servername);
		sprintf(url,"%s",m_url);
		sprintf(username,"%s",m_username);
		sprintf(password,"%s",m_password);
		VSNET_ClientMotionTest(sername,url,(char)m_channel,username,password,bTest,(WORD)m_wServerPort);

		m_bMotionTest = bTest;
	}
}

void CNetViewXCtrl::MotionEdit(BOOL bStart) 
{
	// TODO: Add your dispatch handler code here
	BOOL bret;
	m_bMotionEdit = bStart;
	if(m_bMotionEdit && m_hChHandle && m_bLinkOk)
	{
		char sername[24],url[40],username[20],password[20];
		sprintf(sername,"%s",m_servername);
		sprintf(url,"%s",m_url);
		sprintf(username,"%s",m_username);
		sprintf(password,"%s",m_password);
		bret = VSNET_ClientGetMotionPara(sername,url,(char)m_channel,username,password,&m_ChMotion,(WORD)m_wServerPort);
		if (!bret)
		{
			VSNET_ClientMessageOpt(m_hMessageParam, MESSAGE_CMD_GETDVRMOTIONALARM, m_channel, &m_DvrChMotion, NULL, NULL);
			m_ChMotion.m_alarmsenstive = m_DvrChMotion.m_alarmsenstive;
			memcpy(m_ChMotion.m_detect,m_DvrChMotion.m_detect,18*22);
		}
		Invalidate();
	}
	else
	{
		Invalidate();
	}
}

void CNetViewXCtrl::SetMotionArea() 
{
	if(m_hChHandle && m_bMotionEdit && m_bLinkOk)
	{
		char sername[24],url[40],username[20],password[20];
		sprintf(sername,"%s",m_servername);
		sprintf(url,"%s",m_url);
		sprintf(username,"%s",m_username);
		sprintf(password,"%s",m_password);
		VSNET_ClientSetMotionPara(sername,url,(char)m_channel,username,password,&m_ChMotion,(WORD)m_wServerPort);

		m_DvrChMotion.m_alarmsenstive = m_ChMotion.m_alarmsenstive;
		memcpy(m_DvrChMotion.m_detect,m_ChMotion.m_detect,18*22);
		VSNET_ClientMessageOpt(m_hMessageParam, MESSAGE_CMD_SETDVRMOTIONALARM, m_channel, &m_DvrChMotion, NULL, NULL);
	}
}

void CNetViewXCtrl::SetMotionVal(short nVal) 
{
	if(m_hChHandle && m_bMotionEdit && m_bLinkOk)
	{
		char sername[24],url[40],username[20],password[20];
		sprintf(sername,"%s",m_servername);
		sprintf(url,"%s",m_url);
		sprintf(username,"%s",m_username);
		sprintf(password,"%s",m_password);
		m_ChMotion.m_alarmsenstive = (BYTE)nVal;
		VSNET_ClientSetMotionPara(sername,url,(char)m_channel,username,password,&m_ChMotion,(WORD)m_wServerPort);

		m_DvrChMotion.m_alarmsenstive = m_ChMotion.m_alarmsenstive;
		memcpy(m_DvrChMotion.m_detect,m_ChMotion.m_detect,18*22);
		VSNET_ClientMessageOpt(m_hMessageParam, MESSAGE_CMD_SETDVRMOTIONALARM, m_channel, &m_DvrChMotion, NULL, NULL);
	}
}

void CNetViewXCtrl::MotionAreaSetAll()
{
	if(m_bMotionEdit && m_bLinkOk)
	{
		char sername[24],url[40],username[20],password[20];
		sprintf(sername,"%s",m_servername);
		sprintf(url,"%s",m_url);
		sprintf(username,"%s",m_username);
		sprintf(password,"%s",m_password);
		memset(m_ChMotion.m_detect,1,18*22);
		VSNET_ClientSetMotionPara(sername,url,(char)m_channel,username,password,&m_ChMotion,(WORD)m_wServerPort);

		m_DvrChMotion.m_alarmsenstive = m_ChMotion.m_alarmsenstive;
		memcpy(m_DvrChMotion.m_detect,m_ChMotion.m_detect,18*22);
		VSNET_ClientMessageOpt(m_hMessageParam, MESSAGE_CMD_SETDVRMOTIONALARM, m_channel, &m_DvrChMotion, NULL, NULL);

		Invalidate();
	}
}

void CNetViewXCtrl::MotionAreaClear() 
{
	if(m_bMotionEdit && m_bLinkOk)
	{
		char sername[24],url[40],username[20],password[20];
		sprintf(sername,"%s",m_servername);
		sprintf(url,"%s",m_url);
		sprintf(username,"%s",m_username);
		sprintf(password,"%s",m_password);
		memset(m_ChMotion.m_detect,0,18*22);
		VSNET_ClientSetMotionPara(sername,url,(char)m_channel,username,password,&m_ChMotion,(WORD)m_wServerPort);

		m_DvrChMotion.m_alarmsenstive = m_ChMotion.m_alarmsenstive;
		memcpy(m_DvrChMotion.m_detect,m_ChMotion.m_detect,18*22);
		VSNET_ClientMessageOpt(m_hMessageParam, MESSAGE_CMD_SETDVRMOTIONALARM, m_channel, &m_DvrChMotion, NULL, NULL);
		Invalidate();
	}
}


void CNetViewXCtrl::SetLanguage(short languagetype)
{
	// TODO: Add your dispatch handler code here
	m_languagetype = languagetype;
}

long CNetViewXCtrl::StartConnect()
{
	if(m_hChHandle) return 0;

	CHANNEL_CLIENTINFO pLinkInfo;
	char sername[24],username[20],password[20],url[40];
	sprintf(sername,"%s",m_servername);
	sprintf(url,"%s",m_url);
	sprintf(username,"%s",m_username);
	sprintf(password,"%s",m_password);

	pLinkInfo.m_sername    = sername;
	pLinkInfo.m_username   = username;
	pLinkInfo.m_password   = password;
	pLinkInfo.m_tranType   = (WORD)m_trantype;
	pLinkInfo.m_playstart  = FALSE;				//默认不启动预览
	pLinkInfo.m_ch		   = (BYTE)m_channel;

	if (m_pFullScreenWnd && m_pFullScreenWnd->IsWindowVisible())
	{
		pLinkInfo.m_hVideohWnd = m_pFullScreenWnd->m_hWnd;
		pLinkInfo.m_hChMsgWnd  = m_pFullScreenWnd->m_hWnd;
	}
	else
	{
		pLinkInfo.m_hVideohWnd = m_hWnd;
		pLinkInfo.m_hChMsgWnd  = m_hWnd;
	}
	pLinkInfo.m_nChmsgid   = NET_MSG_ID;
	pLinkInfo.m_buffnum	   = m_buffernum;
	pLinkInfo.m_useoverlay = FALSE;	//m_bUseOverlay;
	pLinkInfo.nColorKey    = FACE_COLOR;
	pLinkInfo.m_messagecallback = NULL;
	pLinkInfo.context = NULL;
	m_curchannel = m_channel;
	m_hChHandle = VSNET_ClientStart(url,&pLinkInfo,(WORD)m_wServerPort, m_streamtype);
	if(m_hChHandle == -1)
	{
		sprintf(m_OptString,"connect server error...");
	}
	else
	{
		sprintf(m_OptString,"connecting...");
		VSNET_ClientSetDelayTime(m_hChHandle,m_delaytime);
	}

	m_playstart  = FALSE;
	m_bSetVolume = FALSE;
	Invalidate();
	return 0;
}

long CNetViewXCtrl::StartDisplay() 
{
	// TODO: Add your dispatch handler code here
	if(m_hChHandle) 
	{
		if(VSNET_ClientStartView(m_hChHandle))
		{
			m_playstart = TRUE;
			return 0;
		}
		else  return -1;
	}
	return -1;
}

void CNetViewXCtrl::StopDisplay() 
{
	// TODO: Add your dispatch handler code here
	if(m_hChHandle)
	{
		VSNET_ClientStopView(m_hChHandle);
		m_playstart = FALSE;
	}
}

short CNetViewXCtrl::GetCurStatus() 
{
	// TODO: Add your dispatch handler code here
	if(m_hChHandle)
	{
		//NETCLIENT_CH_STATUS pStatus;
		//memset(&pStatus,0,sizeof(NETCLIENT_CH_STATUS));
		//NetClient_GetCurStatus(m_hChHandle,&pStatus);
		//return pStatus.bIsLinked;
		return (short)VSNET_ClientGetState(m_hChHandle);
	}
	return -1;
}

void CNetViewXCtrl::ClearAlarm() 
{
	// TODO: Add your dispatch handler code here
#if defined(USER_TIMER_ALARM)
	if(m_timerSec)
	{
		KillTimer(m_timerSec);
		m_timerSec = 0;
	}
	if(m_timerInter)
	{
		KillTimer(m_timerInter);
		m_timerInter = 0;
	}
	m_timerCount = 0;
#endif//USER_TIMER_ALARM
	if(m_hChHandle)
	{
		char sername[24],url[40],username[20],password[20];
		sprintf(sername,"%s",m_servername);
		sprintf(url,"%s",m_url);
		sprintf(username,"%s",m_username);
		sprintf(password,"%s",m_password);
		VSNET_ClientClearAlarmOut(sername,url,username,password,(WORD)m_wServerPort);
	}
}

LRESULT CNetViewXCtrl::OnClientMessage(WPARAM wParam,LPARAM lParam)
{
	if(wParam == LAUMSG_LINKMSG)
	{
		if(lParam == 0) //连接成功
		{
            m_hMessageParam = VSNET_ClientMessageOpen((char*)(LPCTSTR)m_servername,
                                                      (char*)(LPCTSTR)m_url,
                                                      (char*)(LPCTSTR)m_username,
                                                      (char*)(LPCTSTR)m_password,
	        	                                      (WORD)m_wServerPort);

            WHOLEPARAM wholeparam;
            int iRet = VSNET_ClientMessageOpt(m_hMessageParam, MESSAGE_CMD_GETGLOBALPARAM,0,&wholeparam,NULL,NULL);
            if(iRet)
            {
                m_servername.Format("%s", wholeparam.m_servername);
            }

			char sername[24],url[40],username[20],password[20];
			BYTE outputstate[8] = {0,0,0,0,0,0,0,0};
			sprintf(sername,"%s",m_servername);
			sprintf(url,"%s",m_url);
			sprintf(username,"%s",m_username);
			sprintf(password,"%s",m_password);
		

			DWORD width,height;
			RECT rect;
			m_OptString[0] = '\0';
			Invalidate();
			m_bLinkOk = TRUE;
			m_HCount = m_ImageWidth / 32;
			m_VCount = m_ImageHeight / 32 + ((m_ImageHeight%32) ? 1 : 0);
			GetClientRect(&rect);
			m_wblock = (rect.right  - rect.left)/(m_ImageWidth/32);
			m_hblock = (rect.bottom - rect.top)/(m_VCount);

			VSNET_ClientMediaData(m_hChHandle,TRUE);
			if(VSNET_ClientGetVideoSize(m_hChHandle,&width,&height))
			{
				if(width <= 352)
				{
					VSNET_ClientVideoQuality(m_hChHandle,m_postflag);
				}
				if(m_displayhandle == NULL || m_displaywidth  != width || m_displayheight != height)
				{
					if(m_displayhandle) VSNET_ClientStopImageShow(m_displayhandle);
					m_displayhandle = NULL;
					m_displaywidth = width;
					m_displayheight = height;
					m_displayhandle = VSNET_ClientStartImageShow(m_hWnd,m_displaywidth,m_displayheight);
					if(m_displayhandle <= 0) m_displayhandle = NULL;
				}
				if(m_displayhandle)
				{
					VSNET_ClientShowcallback(m_hChHandle,s_ShowCallBack,this);
				}
			}
			if(m_diskover.bIsRecord)
				InterRecord(TRUE);

			if(m_bMotionEdit)
				MotionEdit(TRUE);
#if !defined(PROTYPE_XISHI)
			VSNET_ClientGetOutputStatus(sername,url,username,password,outputstate,(WORD)m_wServerPort);
			lParam  = 0;
			lParam |= outputstate[0] ? 1: 0;
			lParam |= outputstate[1] ? 2: 0;
			lParam |= outputstate[2] ? 4: 0;
			lParam |= outputstate[3] ? 8: 0;
			FireExOutPutStatus(lParam);

			if(VSNET_GetClientRecordStatus(sername,url,(char)m_channel,username,password,(WORD)m_wServerPort))
			{
				FireClientRecordStatus(1);
			}
			else
			{
				FireClientRecordStatus(0);
			}
#endif
			if (m_bSetVolume)
			{
				VSNET_ClientAudioVolume(m_hChHandle,m_volume);
			}

            if (m_bFlipVideo)
                VSNET_ClientFlipVideo(m_hChHandle);
            if (m_bFlipVideoH)
                VSNET_ClientFlipVideoH(m_hChHandle);
			
			FireLinkStatus(0);
			TRACE("output status : %d\n",lParam);

			if( m_bVideoMaskEdit )
				GetVideoMaskParam();

#ifdef CONTROL_TYPE_DXHJ_H264
            GetRecordPackTime();
#if 0
            GetSwitchScreenName();
#endif
#else
#ifdef CONTROL_TYPE_DXHJ
            GetDiskState();
            GetRecordPackTime();
#endif      
#endif

			if(m_audioon)
			{
				if(!m_bAudioOnInfact)
				{
					m_bAudioOnInfact = VSNET_ClientPlayAudio(m_hChHandle);
				}
			}
			else
			{
				VSNET_ClientStopAudio(m_hChHandle);
				m_bAudioOnInfact = FALSE;
			}
			if(m_bLinkOk)
				FireAudioState(m_bAudioOnInfact);
		}
		else
		{
			//断开连接
			InterRecord(FALSE);
			STOP_RELINKTIMER();
			if(m_nRelinkNum)
			{
				m_timerRelink = SetTimer(TIMERID_RELINK,5000,0);
				//return;
			}
		    FireLinkStatus(lParam);
			TranCodeToString(wParam,lParam,m_OptString);

			if (m_bAudioOnInfact)
				m_bAudioOnInfact = FALSE;

			m_bdisplay = 1;
			Invalidate();
		}
	}
	else if(wParam == LAUMSG_OUTPUTSTATUS)
	{
		FireExOutPutStatus(lParam);
	}
	else if(wParam == LAUMSG_SERVERRECORD)
	{
		m_bOnServerRecv = lParam;
		FireServerRecordStatus(m_bOnServerRecv);
	}
	else if (wParam == LAUMSG_VIDEOMOTION
			|| wParam == LAUMSG_VIDEOLOST
			|| wParam == LAUMSG_ALARM
			|| wParam == LAUMSG_HIDEALARM)
			FireAlarm(wParam == LAUMSG_VIDEOMOTION?0:
					  wParam == LAUMSG_VIDEOLOST?1:
					  wParam == LAUMSG_ALARM?2:3,
					  lParam);
	return 0;
}

void CNetViewXCtrl::TranCodeToString(int wParam,int code,char *lpstr)
{
	lpstr[0] = '\0';
	switch(code)
	{
	case 2:
#ifndef CONTROL_TYPE_DXHJ		
		sprintf(m_OptString,"connecting server failed.");
#else	
		sprintf(m_OptString,"网络断开");
#endif
		break;
	case 3:
		sprintf(m_OptString,"server disconnect.");
		break;
	case 4:
		sprintf(m_OptString,"bind port error.");	
		break;
	case 5:
		sprintf(m_OptString,"malloc buffer failed.");
		break;
	case 6:
		break;
	case -102:
		sprintf(m_OptString,"invalid username or password.");
		break;
	case -103:
		sprintf(m_OptString,"channel user overflow.");
		break;
	case -106:
		sprintf(m_OptString,"invalid channel.");
		break;
	case -112:
		sprintf(m_OptString,"not find server index.");
		break;
	}
}

void CNetViewXCtrl::OnBuffernumChanged() 
{
	// TODO: Add notification handler code

	SetModifiedFlag();
}

void CNetViewXCtrl::SetPTZAddr(short addr) 
{
	if(m_hChHandle)
	{
		VSNET_ClientSetPTZAddr(m_hChHandle,(BYTE)addr);
	}
}

void CNetViewXCtrl::PTZExDevCtrl(short devno, short isOn) 
{
	if(m_hChHandle)
	{
		VSNET_ClientPTZDev(m_hChHandle,(char)devno,(BOOL)isOn);
	}
}

void CNetViewXCtrl::CtrolAlarmOut(short alarmno, short bIsopen) 
{
	if(m_hChHandle)
	{
		VSNET_ClientOutPut(m_hChHandle,(char)alarmno,bIsopen ? 1 : 0);
	}
}

void CNetViewXCtrl::OnWServerPortChanged() 
{
	// TODO: Add notification handler code

	SetModifiedFlag();
}

void CNetViewXCtrl::ChannelSwitch(short bStart, short interval) 
{
	if(m_pChSwitch.timerid)
	{
		KillTimer(m_pChSwitch.timerid);
		m_pChSwitch.timerid = 0;
	}
	if(bStart)
	{
		interval = interval < 1 ? 1 : interval;
		m_pChSwitch.timerid = SetTimer(TIMERID_SWITCH,interval*1000,0);
	}
}

void CNetViewXCtrl::ChannelSel(short channel) 
{
	if(m_pChSwitch.timerid)
	{
		KillTimer(m_pChSwitch.timerid);
		m_pChSwitch.timerid = 0;
	}
	if(m_hChHandle)
	{
		VSNET_ClientSwitchChannel(m_hChHandle,(char)channel);
		m_pChSwitch.curch   = channel;
	}
}

void CNetViewXCtrl::SetSwitchChannel(short channel, short bInswitch) 
{
	if(channel >= 0 && channel < 16)
		m_pChSwitch.chinclude[channel] = (unsigned char)bInswitch;
}

void CNetViewXCtrl::OnBUseOverlayChanged() 
{
	// TODO: Add notification handler code

	SetModifiedFlag();
}

void CNetViewXCtrl::LoadTatalDisk()
{
	int i;
	int m_tataldisks;
	UINT devtype;
	DWORD drivemask;
	char lpdevstr[20];
	drivemask = GetLogicalDrives();

	m_tataldisks = 0;
	for (i = 0 ; i < 'Z' - 'A' ; i++)
	{
		if((drivemask & (1 << i)) != 0)
		{
			sprintf(lpdevstr,"%c://",i+'A');
			devtype = GetDriveType(lpdevstr);
			if(devtype == DRIVE_FIXED)
				m_tataldisks ++;
		}
	}
	if(m_tataldisks > 1)
	{
		m_diskadmin.totaldevs = 0;
		for (i = 0 ; i < 'Z' - 'A' ; i++)
		{
			if((drivemask & (1 << i)) != 0)
			{
				if(('A' + i) != 'C')
				{
					sprintf(lpdevstr,"%c://",i+'A');
					devtype = GetDriveType(lpdevstr);
					if(devtype == DRIVE_FIXED)
					{
						m_diskadmin.devlist[m_diskadmin.totaldevs] = ('A' + i);
						m_diskadmin.totaldevs ++;
					}
				}
			}
		}
	}
	else
	{
		m_diskadmin.totaldevs = 0;
		for (i = 0 ; i < 'Z' - 'A' ; i++)
		{
			if((drivemask & (1 << i)) != 0)
			{
				sprintf(lpdevstr,"%c://",i+'A');
				devtype = GetDriveType(lpdevstr);
				if(devtype == DRIVE_FIXED)
				{
					m_diskadmin.devlist[m_diskadmin.totaldevs] = ('A' + i);
					m_diskadmin.totaldevs ++;
				}
			}
		}
	}
}

int CNetViewXCtrl::GetCanUseDisk()
{
	char   lpDiskStr[] = {0,':','\\',0};
	ULARGE_INTEGER useA={0},totalA={0},freeA={0};
	int i;

	lpDiskStr[0] = m_diskadmin.devlist[m_diskadmin.chudev];
	GetDiskFreeSpaceEx(lpDiskStr,&useA,&totalA,&freeA);
	if(    (freeA.HighPart > 0) 
		|| (freeA.LowPart > DISK_CHANGE_DRV_SIZE))
	{
		return m_diskadmin.chudev;
	}
	for(i = (m_diskadmin.chudev + 1); i < m_diskadmin.totaldevs ; i++)
	{
		lpDiskStr[0] = m_diskadmin.devlist[i];
		GetDiskFreeSpaceEx(lpDiskStr,&useA,&totalA,&freeA);	
	
		if(freeA.HighPart || freeA.LowPart > DISK_CHANGE_DRV_SIZE) return i;
	}
	for(i = 0 ; i <= m_diskadmin.totaldevs; i++)
	{
		lpDiskStr[0] = m_diskadmin.devlist[i];
		GetDiskFreeSpaceEx(lpDiskStr,&useA,&totalA,&freeA);
		if(freeA.HighPart || freeA.LowPart > DISK_CHANGE_DRV_SIZE) return i;
	}
	return -1;
}

int CNetViewXCtrl::InterRecord(BOOL bIsStart,BOOL bUserControl,LPCTSTR filename)
{
	if(bIsStart)
	{
		FLATFISH_RECINDEX RecIndex;
		FILE *fpIndex = NULL;
		SYSTEMTIME dwTime = {0};
		char lpDir[MAX_PATH],szFileName[MAX_PATH],lpfile[MAX_PATH];
		
		if(m_hChHandle == 0) return -1;
		
		InterRecord(FALSE);
        GetLocalTime(&dwTime);
#if defined USER_CUSTOMFILENAME
        if(bUserControl)
        {
#ifdef CONTROL_TYPE_DXHJ
			if( filename != NULL && strlen(filename) > 0 )
			{
				char		*pExtension;
				
				strcpy(lpfile,filename);
				PathRemoveFileSpec(lpfile);
				m_szPath = lpfile;
				strcpy(lpfile,PathFindFileName(filename));
				PathRemoveExtension(lpfile);
				m_szFileName.Format("%s_%d",lpfile,m_channel);
				pExtension = PathFindExtension(filename);
				m_szExtension = pExtension?pExtension:"";
			}
			else
#endif
			{
				CString		suffix;
				CString     szFilter;
				if(m_recordtype == 0)
				{
					suffix = "asf";
				}
				else if (m_recordtype == 1)
				{
					suffix = "mp4";
				}
				else
				{
					suffix = "264";
				}
				szFilter.Format("%s Files(*.%s)|*.%s|",suffix,suffix,suffix);
				
				CFileDialog dlg(FALSE, 
					suffix,
					NULL, 
					OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
					szFilter,
					this);
				if( dlg.DoModal() == IDCANCEL )
					return -1;
				
				//如路径选择为"E:\\test\\video.wmv"
				m_szSaveFileName = dlg.GetPathName();
				strcpy(lpfile,dlg.GetPathName());
				PathRemoveFileSpec(lpfile);
				m_szPath = lpfile;
				strcpy(lpfile,dlg.GetFileName());
				PathRemoveExtension(lpfile);
				m_szFileName.Format("%s_%d",lpfile,m_channel);
				m_szExtension.Format(".%s",dlg.GetFileExt());
			}
            sprintf(lpfile,"%s\\%s%s",m_szPath,m_szFileName,m_szExtension);
            sprintf(lpDir,"%s",m_szPath);
            sprintf(szFileName,"%s%s",m_szFileName,m_szExtension);
        }
        else
#endif
        {
#ifndef CONTROL_TYPE_DXHJ
            sprintf(lpDir,"%c:\\%04d%02d%02d",
            m_diskadmin.devlist[m_diskadmin.chudev],dwTime.wYear,dwTime.wMonth,dwTime.wDay);		    
		    CreateDirectory(lpDir,NULL);
#else
            sprintf(lpDir,m_szPath);
#endif
#ifdef USER_CUSTOMRECDIR
			CFileDialogST	dlg;
			int				nRetValue;
			CString         lpstr;
			lpstr = "";
			nRetValue = dlg.SelectFolder(lpstr, NULL,
				BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS, this);
			if (nRetValue == IDOK)
			{
				sprintf(lpDir, "%s", dlg.GetSelectedFolder());
			}
			else
			{
				return FALSE;
			}
#endif
#ifdef CONTROL_TYPE_DXHJ
            if(m_recordtype == 0)
		    {
                sprintf(lpfile,"%s\\%s_%02d%02d%02d.asf",
					m_szPath,
				    m_szFileName,
				    dwTime.wHour,dwTime.wMinute,dwTime.wSecond);

                sprintf(szFileName,"%s_%02d%02d%02d.asf",
                    m_szFileName,
                    dwTime.wHour,dwTime.wMinute,dwTime.wSecond);
		    }
		    else
		    {
                sprintf(lpfile,"%s\\%s_%02d%02d%02d%s",
				    m_szPath,
					m_szFileName,
				    dwTime.wHour,dwTime.wMinute,dwTime.wSecond,m_szExtension);

                sprintf(szFileName,"%s_%02d%02d%02d%s",
					m_szFileName,
                    dwTime.wHour,dwTime.wMinute,dwTime.wSecond,m_szExtension);
            }
#else
		    if(m_recordtype == 0)
		    {
			    sprintf(lpfile,"%s\\%s_%d_%02d%02d%02d.asf",
				    lpDir,
				    m_servername,m_channel+1,
				    dwTime.wHour,dwTime.wMinute,dwTime.wSecond);

                sprintf(szFileName,"%s_%d_%02d%02d%02d.asf",
                    m_servername,m_channel+1,
				    dwTime.wHour,dwTime.wMinute,dwTime.wSecond);
		    }
		    else if (m_recordtype == 1)
			{
				sprintf(lpfile,"%s\\%s_%d_%02d%02d%02d.mp4",
					lpDir,
					m_servername,m_channel+1,
					dwTime.wHour,dwTime.wMinute,dwTime.wSecond);
				
                sprintf(szFileName,"%s_%d_%02d%02d%02d.mp4",
                    m_servername,m_channel+1,
					dwTime.wHour,dwTime.wMinute,dwTime.wSecond);
			}
			else
		    {
			    sprintf(lpfile,"%s\\%s_%d_%02d%02d%02d.264",
				    lpDir,
				    m_servername,m_channel+1,
				    dwTime.wHour,dwTime.wMinute,dwTime.wSecond);

                sprintf(szFileName,"%s_%d_%02d%02d%02d.264",
                    m_servername,m_channel+1,
				    dwTime.wHour,dwTime.wMinute,dwTime.wSecond);
		    }
#endif
       }

		if( m_recordtype == 0 )
		{
			if(VSNET_ClientStartASFFileCap(m_hChHandle,lpfile,FALSE))
			{
				m_diskover.bIsRecord  = TRUE;
				m_diskover.recordtime = timeGetTime();
				m_diskover.timerid    = SetTimer(TIMERID_DISKCHECK,1000 * 10,0);
				sprintf(lpfile,"%s\\index",lpDir);
				fpIndex = fopen(lpfile,"ab");
				if(fpIndex)
				{
					strcpy(RecIndex.sername,m_servername);
					RecIndex.ch     = (unsigned char)m_channel;
					RecIndex.year   = dwTime.wYear;
					RecIndex.month  = (unsigned char)dwTime.wMonth;
					RecIndex.day    = (unsigned char)dwTime.wDay;
					RecIndex.hour   = (unsigned char)dwTime.wHour;
					RecIndex.minute = (unsigned char)dwTime.wMinute;
					RecIndex.second = (unsigned char)dwTime.wSecond;
					RecIndex.revtype= 0;
#ifdef USER_CUSTOMFILENAME
                    strcpy(RecIndex.filename,szFileName);
#endif
                    fwrite(&RecIndex,sizeof(FLATFISH_RECINDEX),1,fpIndex);
					fclose(fpIndex);
				}
				return 0;
			}
		}
		else
		{
			if(VSNET_ClientStartMp4Capture(m_hChHandle,lpfile))
			{
				m_diskover.bIsRecord  = TRUE;
				m_diskover.recordtime = timeGetTime();
				m_diskover.timerid    = SetTimer(TIMERID_DISKCHECK,1000 * 10,0);
				sprintf(lpfile,"%s\\index",lpDir);
				fpIndex = fopen(lpfile,"ab");
				if(fpIndex)
				{
					strcpy(RecIndex.sername,m_servername);
					RecIndex.ch     = (unsigned char)m_channel;
					RecIndex.year   = dwTime.wYear;
					RecIndex.month  = (unsigned char)dwTime.wMonth;
					RecIndex.day    = (unsigned char)dwTime.wDay;
					RecIndex.hour   = (unsigned char)dwTime.wHour;
					RecIndex.minute = (unsigned char)dwTime.wMinute;
					RecIndex.second = (unsigned char)dwTime.wSecond;
					RecIndex.revtype= 0;
#ifdef USER_CUSTOMFILENAME
                    strcpy(RecIndex.filename,szFileName);
#endif
					fwrite(&RecIndex,sizeof(FLATFISH_RECINDEX),1,fpIndex);
					fclose(fpIndex);
				}
				return 0;
			}
		}
	}
	else
	{
		if(m_diskover.timerid)
			KillTimer(m_diskover.timerid);
		m_diskover.timerid = 0;
		if(m_diskover.hThread)
		{
			WaitForSingleObject(m_diskover.hThread,10);
			CloseHandle(m_diskover.hThread);
			m_diskover.hThread = NULL;
		}
		if(m_hChHandle)
		{
			if(m_recordtype == 0)
				VSNET_ClientStopCapture(m_hChHandle);
			else
				VSNET_ClientStopMp4Capture(m_hChHandle);
		}
	}
	return -1;
}

BOOL CNetViewXCtrl::InterStartView(BOOL bDDNS /* = FALSE */)
{
	if(m_hChHandle) return TRUE;

	if(m_OptString[0] != '\0')
	{
		m_OptString[0] = '\0';
		//Invalidate();
		PostMessage(WM_INVALIDATE, 0, 0);
	}
	STOP_RELINKTIMER();
	CHANNEL_CLIENTINFO pLinkInfo;
	char sername[24],username[20],password[20],url[40];
	sprintf(sername,"%s",m_servername);
	sprintf(url,"%s",m_url);
	sprintf(username,"%s",m_username);
	sprintf(password,"%s",m_password);

	pLinkInfo.m_sername    = sername;
	pLinkInfo.m_username   = username;
	pLinkInfo.m_password   = password;
	pLinkInfo.m_tranType   = (WORD)m_trantype;
	pLinkInfo.m_playstart  = m_playstart;
	pLinkInfo.m_ch		   = (BYTE)m_channel;
	if (m_pFullScreenWnd && m_pFullScreenWnd->IsWindowVisible())
	{
		pLinkInfo.m_hVideohWnd = m_pFullScreenWnd->m_hWnd;
		pLinkInfo.m_hChMsgWnd  = m_pFullScreenWnd->m_hWnd;
	}
	else
	{
		pLinkInfo.m_hVideohWnd = m_hWnd;
		pLinkInfo.m_hChMsgWnd  = m_hWnd;
	}
	pLinkInfo.m_nChmsgid   = NET_MSG_ID;
	pLinkInfo.m_buffnum	   = m_buffernum;
	pLinkInfo.m_useoverlay = FALSE;//m_bUseOverlay;
	pLinkInfo.nColorKey    = FACE_COLOR;
	pLinkInfo.m_messagecallback = NULL;
	pLinkInfo.context = NULL;
	m_curchannel = m_channel;

	if(!bDDNS)
	{
		m_hChHandle = VSNET_ClientStart(url,&pLinkInfo,(WORD)m_wServerPort, m_streamtype);
	}
	else
	{
		m_hChHandle = VSNET_InfoClientStart(url,&pLinkInfo,(WORD)(m_wServerPort), m_streamtype);
	}

	if(m_hChHandle == -1)
	{
		sprintf(m_OptString,"connect server error...");
		//Invalidate();
		PostMessage(WM_INVALIDATE, 0, 0);
		return FALSE;
	}
	else
	{
		sprintf(m_OptString,"connecting...");
		VSNET_ClientSetDelayTime(m_hChHandle,m_delaytime);
		if(m_PISTag >= 0)
		{
			VSNET_ClientPreventImageSplit(m_hChHandle, m_PISTag);
		}
	}
// 	m_hMessageParam = VSNET_ClientMessageOpen((char*)(LPCTSTR)m_servername,
// 		                                      (char*)(LPCTSTR)m_url,
// 		                                      (char*)(LPCTSTR)m_username,
// 		                                      (char*)(LPCTSTR)m_password,
// 		                                      (WORD)m_wServerPort);
	
	m_bdisplay = 0;
	//Invalidate();
	PostMessage(WM_INVALIDATE, 0, 0);
	return TRUE;
}
void CNetViewXCtrl::InterStopView()
{
	if(m_OptString[0] != '\0')
	{
		m_OptString[0] = '\0';
		Invalidate();
	}
	STOP_RELINKTIMER();
	ChannelSwitch(FALSE,1);

	StopTalk();
	InterRecord(FALSE);
	if(m_hChHandle)
	{
		if(m_bMotionTest && m_bLinkOk)
		{
			char sername[24],username[20],password[20],url[40];
			sprintf(sername,"%s",m_servername);
			sprintf(url,"%s",m_url);
			sprintf(username,"%s",m_username);
			sprintf(password,"%s",m_password);
			VSNET_ClientMotionTest(sername,url,(char)m_channel,username,password,FALSE,(WORD)m_wServerPort);
		}
		VSNET_ClientStop(m_hChHandle);
		m_hChHandle = 0;
	}
	if(m_hMessageParam != -1)
	{
		VSNET_ClientMessageClose(m_hMessageParam);
		m_hMessageParam = -1;
	}
	//m_bIsMoutePTZCtrl = FALSE;
	m_bMotionEdit = m_bLinkOk = FALSE;
	m_bVideoMaskEdit = m_bVideoMaskBtnDown = FALSE;

	if(m_OptString[0] != '\0')
	{
		m_OptString[0] = '\0';
		Invalidate();
	}

}
void CNetViewXCtrl::SearchFile(long year, long month, long day, long s_hour, long s_minute, long e_hour, long e_minute)
{
	DISK_SEARCHINFO pInfo;
	pInfo.year  = year;
	pInfo.month = month;
	pInfo.day   = day;
	pInfo.hours  = s_hour;
	pInfo.minutes= s_minute;
	pInfo.hourd  = e_hour;
	pInfo.minuted= e_minute;

#ifdef USER_CUSTOMFILENAME
    CDirectoryDialog   dlg;
    dlg.m_strIniKeyName.LoadString(IDS_STRING201);
    m_szLastSearchDir = dlg.ShowDirectoryTree(m_szLastSearchDir);
    if( m_szLastSearchDir.GetLength() > 0 )
        findfile_indir((char*)(LPCTSTR)m_szLastSearchDir,NULL,&pInfo);
#else
	for(int i=0;i<m_diskadmin.totaldevs;i++)
	{
		findfile_indev(m_diskadmin.devlist[i],&pInfo);
	}
#endif
}

void CNetViewXCtrl::VideoMaskEnable(short bEnable)
{	
	if(m_hChHandle)
	{
		CHANNVIDEOMASK m_channvmask;
		VSNETVIDEOMASK m_maskarea;

		char sername[24],url[40],username[20],password[20];
		sprintf(sername,"%s",m_servername);
		sprintf(url,"%s",m_url);
		sprintf(username,"%s",m_username);
		sprintf(password,"%s",m_password);
		
		float w_off,h_off;
		RECT rect;
		GetClientRect(&rect);
		w_off = (float)(rect.right  - rect.left) / (float)704;
		h_off = (float)(rect.bottom - rect.top)  / (float)576;
		
		for(int i=0;i<4;i++)
		{
			if(m_vmask[i].m_width < 0)
			{
				m_vmask[i].m_x = m_vmask[i].m_x + m_vmask[i].m_width;
				m_vmask[i].m_width = - m_vmask[i].m_width;
			}
			if(m_vmask[i].m_height < 0)
			{
				m_vmask[i].m_y = m_vmask[i].m_y + m_vmask[i].m_height;
				m_vmask[i].m_height = - m_vmask[i].m_height;
			}
			
			m_vmask[i].m_x = m_vmask[i].m_x < 0 ? - m_vmask[i].m_x : m_vmask[i].m_x;
			m_vmask[i].m_y = m_vmask[i].m_y < 0 ? - m_vmask[i].m_y : m_vmask[i].m_y;
			
			if((m_vmask[i].m_x + m_vmask[i].m_width) > rect.right)
			{
				m_vmask[i].m_width = rect.right - m_vmask[i].m_x;
			}
			if((m_vmask[i].m_y + m_vmask[i].m_height) > rect.bottom)
			{
				m_vmask[i].m_height = rect.bottom - m_vmask[i].m_y;
			}
		}
		
		m_maskarea.m_bmask = m_channvmask.m_bmask = (int)bEnable;
		for(i=0;i<4;i++)
		{
			m_maskarea.m_maskarea[i].m_x = (short)((float)m_vmask[i].m_x / w_off);
			m_maskarea.m_maskarea[i].m_y = (short)((float)m_vmask[i].m_y / h_off);
			if(m_vmask[i].m_width < 10 && m_vmask[i].m_height < 10)
			{
				m_maskarea.m_maskarea[i].m_width = 0;
				m_maskarea.m_maskarea[i].m_height = 0;
			}
			else
			{
				m_maskarea.m_maskarea[i].m_width  = (short)((float)m_vmask[i].m_width / w_off);
				m_maskarea.m_maskarea[i].m_height = (short)((float)m_vmask[i].m_height / h_off);
			}
		}

		if(m_bLinkOk)
		{
			int	iRet;

			LONG m_hParam = VSNET_ClientMessageOpen(sername,url,username,password,(WORD)m_wServerPort);
			if( m_hParam != -1 )
			{
				iRet = VSNET_ClientMessageOpt(m_hParam,MESSAGE_CMD_SETVIDEOMASKAREA,m_channel,&m_maskarea,NULL,NULL); 
				if( !iRet )
				{
					m_channvmask.m_x = (short)((float)m_vmask[0].m_x / w_off);
					m_channvmask.m_y = (short)((float)m_vmask[0].m_y / h_off);
					if(m_vmask[0].m_width < 10 && m_vmask[0].m_height < 10)
					{
						m_channvmask.m_width  = 0;
						m_channvmask.m_height = 0;
					}
					else
					{
						m_channvmask.m_width  = (short)((float)m_vmask[0].m_width / w_off);
						m_channvmask.m_height = (short)((float)m_vmask[0].m_height / h_off);	
					}
					TRACE("Set Chann VMask x:%d y:%d width:%d height:%d\n",
						m_channvmask.m_x,
						m_channvmask.m_y,
						m_channvmask.m_width,
						m_channvmask.m_height);
					iRet = VSNET_ClientMessageOpt(m_hParam,MESSAGE_CMD_SETVIDEOMASK,m_channel,&m_channvmask,NULL,NULL);
				}
				VSNET_ClientMessageClose(m_hParam);
			}
		}
	}
}

void CNetViewXCtrl::VideoMaskEdit(short bEnable)
{
	m_bVideoMaskEdit = bEnable;
	m_bVideoMaskBtnDown = m_bVideoMaskEdit ? m_bVideoMaskBtnDown : FALSE;
	if( !m_bVideoMaskEdit )
		Invalidate();
}

void CNetViewXCtrl::OnLButtonUp(UINT nFlags, CPoint point) 
{
	if(m_bMotionBtnDown)
	{
		int	x,y,left,right,top,bottom;
		RECT rect;
		GetClientRect(&rect);

		m_mRbPoint.x = point.x < 0 ? 0 : point.x;
		m_mRbPoint.x = point.x > rect.right ? rect.right-1: m_mRbPoint.x;
		m_mRbPoint.y = point.y < 0 ? 0 : point.y;
		m_mRbPoint.y = point.y > rect.bottom ? rect.bottom-1: m_mRbPoint.y;


		left  = (m_mLtPoint.y<m_mRbPoint.y?m_mLtPoint.y:m_mRbPoint.y)/m_hblock;
		right = (m_mLtPoint.y<m_mRbPoint.y?m_mRbPoint.y:m_mLtPoint.y)/m_hblock;
		top   = (m_mLtPoint.x<m_mRbPoint.x?m_mLtPoint.x:m_mRbPoint.x)/m_wblock;
		bottom= (m_mLtPoint.x<m_mRbPoint.x?m_mRbPoint.x:m_mLtPoint.x)/m_wblock;

		TRACE("left:%d,right:%d,top:%d,bottom:%d.\n",left,right,top,bottom);

		x = left;
		do
		{
			y = top;
			do
			{
				m_ChMotion.m_detect[x][y] = !m_ChMotion.m_detect[x][y];
				y++;
			}while(y<=bottom);
			x++;
		}while(x<=right);

		m_bMotionBtnDown   = FALSE;
		Invalidate();
	}
	if(m_bVideoMaskBtnDown)
		m_bVideoMaskBtnDown = FALSE;
	
	COleControl::OnLButtonUp(nFlags, point);
}
#if 1
void CNetViewXCtrl::SetGangBandrate(long baud)
{
	SERIAL485_PARAM s_param485;
	char sername[24],url[40],username[20],password[20];
	sprintf(sername,"%s",m_servername);
	sprintf(url,"%s",m_url);
	sprintf(username,"%s",m_username);
	sprintf(password,"%s",m_password);

	VSNET_ClientGetSerial485Param(sername,url,(char)m_channel,username,password,&s_param485,(WORD)m_wServerPort);
	s_param485.m_baudrate = baud;
	VSNET_ClientSetSerial485Param(sername,url,(char)m_channel,username,password,&s_param485,(WORD)m_wServerPort);
	//m_setgangband = TRUE;
}
#endif
void CNetViewXCtrl::SetTalkChannel()
{
	if(m_hChHandle == NULL) return;
#if 0
	if(!m_setgangband)
	{
		SetGangBandrate(9600);
	}
#endif
	BYTE sendbuff[6];
	sendbuff[0] = 0xBB;
	sendbuff[1] = 0x04;
	sendbuff[2] = 0xD0;
	sendbuff[3] = 0x02;
	sendbuff[4] = (BYTE)m_curchannel;
	sendbuff[5] = sendbuff[2] + sendbuff[3] + sendbuff[4];
	VSNET_ClientSerialSend(m_hChHandle,0,sendbuff,6);
}

void CNetViewXCtrl::SwitchGangChannel(short ch) 
{
	if(m_hChHandle == NULL) return;
#if 0
	if(!m_setgangband)
	{
		SetGangBandrate(9600);
	}
#endif
	BYTE sendbuff[6];
	sendbuff[0] = 0xBB;
	sendbuff[1] = 0x04;
	sendbuff[2] = 0xD0;
	sendbuff[3] = 0x01;
	sendbuff[4] = (BYTE)m_curchannel + (((BYTE)ch) << 4);
	sendbuff[5] = sendbuff[2] + sendbuff[3] + sendbuff[4];
	VSNET_ClientSerialSend(m_hChHandle,0,sendbuff,6);
}

BOOL CNetViewXCtrl::Transparent(long pData, short size) 
{
	int i;
	if(size < 0 || size > 4 || m_translen + size >= MAX_TRANSBUFF)
		return FALSE;
	for(i=0;i<size;i++)
	{
		m_transbuff[m_translen + size - i - 1] = ((pData >> (8 * i)) & 0xff);	
	}
	m_translen += size;
	return TRUE;
}

void CNetViewXCtrl::OnDelaytimeChanged() 
{
	if(m_hChHandle == NULL) return;
	VSNET_ClientSetDelayTime(m_hChHandle,m_delaytime);
	SetModifiedFlag();
}


#ifdef L_IMPL_OBJECTSAFETY 
// Implementation of IObjectSafety 
STDMETHODIMP CNetViewXCtrl::XObjectSafety::GetInterfaceSafetyOptions(REFIID riid,
																	 DWORD __RPC_FAR *pdwSupportedOptions,
																	 DWORD __RPC_FAR *pdwEnabledOptions) 
{ 
	METHOD_PROLOGUE_EX(CNetViewXCtrl, ObjectSafety)
	if (!pdwSupportedOptions || !pdwEnabledOptions) 
	{ 
		return E_POINTER; 
	} 
	*pdwSupportedOptions = INTERFACESAFE_FOR_UNTRUSTED_CALLER | INTERFACESAFE_FOR_UNTRUSTED_DATA; 
	*pdwEnabledOptions = 0; 
	
	if (NULL == pThis->GetInterface(&riid)) 
	{ 
		TRACE("Requested interface is not supported.\n"); 
		return E_NOINTERFACE; 
	} 
	
	// What interface is being checked out anyhow? 
	OLECHAR szGUID[39]; 
	int i = StringFromGUID2(riid, szGUID, 39); 
	
	if (riid == IID_IDispatch) 
	{ 
		// Client wants to know if object is safe for scripting 
		*pdwEnabledOptions = INTERFACESAFE_FOR_UNTRUSTED_CALLER; 
		return S_OK; 
	} 
	else if(riid == IID_IPersistPropertyBag
		|| riid == IID_IPersistStreamInit
		|| riid == IID_IPersistStorage
		|| riid == IID_IPersistMemory) 
	{ 
		// Those are the persistence interfaces COleControl derived controls support 
		// as indicated in AFXCTL.H 
		// Client wants to know if object is safe for initializing from persistent data 
		*pdwEnabledOptions = INTERFACESAFE_FOR_UNTRUSTED_DATA; 
		return S_OK; 
	} 
	else 
	{ 
		// Find out what interface this is, and decide what options to enable 
		TRACE("We didn’t account for the safety of this interface, and it’s one we support...\n"); 
		return E_NOINTERFACE; 
	}
} 

STDMETHODIMP CNetViewXCtrl::XObjectSafety::SetInterfaceSafetyOptions(REFIID riid,
																		DWORD dwOptionSetMask,
																		DWORD dwEnabledOptions) 
{ 
	METHOD_PROLOGUE_EX(CNetViewXCtrl, ObjectSafety) 

	OLECHAR szGUID[39]; 
	// What is this interface anyway? 
	// We can do a quick lookup in the registry under HKEY_CLASSES_ROOT\Interface 
	int i = StringFromGUID2(riid, szGUID, 39); 
	if (0 == dwOptionSetMask && 0 == dwEnabledOptions) 
	{ 
		// the control certainly supports NO requests through the specified interface 
		// so it’s safe to return S_OK even if the interface isn’t supported. 
		return S_OK; 
	} 
	
	// Do we support the specified interface? 
	if (NULL == pThis->GetInterface(&riid)) 
	{
		TRACE1("%s is not support.\n", szGUID); 
		return E_FAIL; 
	} 
	
	
	if (riid == IID_IDispatch) 
	{ 
		TRACE("Client asking if it’s safe to call through IDispatch.\n"); 
		TRACE("In other words, is the control safe for scripting?\n"); 
		if (INTERFACESAFE_FOR_UNTRUSTED_CALLER == dwOptionSetMask && INTERFACESAFE_FOR_UNTRUSTED_CALLER == dwEnabledOptions) 
		{ 
			return S_OK; 
		}
		else 
		{ 
			return E_FAIL; 
		} 
	} 
	else if( riid == IID_IPersistPropertyBag
		|| riid == IID_IPersistStreamInit
		|| riid == IID_IPersistStorage
		|| riid == IID_IPersistMemory) 
	{
		TRACE("Client asking if it’s safe to call through IPersist*.\n"); 
		TRACE("In other words, is the control safe for initializing from persistent data?\n"); 
		
		if (INTERFACESAFE_FOR_UNTRUSTED_DATA == dwOptionSetMask && INTERFACESAFE_FOR_UNTRUSTED_DATA == dwEnabledOptions) 
		{ 
			return NOERROR; 
		} 
		else 
		{ 
			return E_FAIL; 
		} 
	} 
	else 
	{ 
		TRACE1("We didn’t account for the safety of %s, and it’s one we support...\n", szGUID); 
		return E_FAIL; 
	} 
} 

STDMETHODIMP_(ULONG) CNetViewXCtrl::XObjectSafety::AddRef()
{
	METHOD_PROLOGUE_EX_(CNetViewXCtrl, ObjectSafety) 
	return (ULONG)pThis->ExternalAddRef(); 
} 

STDMETHODIMP_(ULONG) CNetViewXCtrl::XObjectSafety::Release()
{
	METHOD_PROLOGUE_EX_(CNetViewXCtrl, ObjectSafety) 
	return (ULONG)pThis->ExternalRelease(); 
} 

STDMETHODIMP CNetViewXCtrl::XObjectSafety::QueryInterface(REFIID iid, LPVOID* ppvObj) 
{ 
	METHOD_PROLOGUE_EX_(CNetViewXCtrl, ObjectSafety) 
	return (HRESULT)pThis->ExternalQueryInterface(&iid, ppvObj); 
} 

#endif // L_IMPL_OBJECTSAFETY 


void CNetViewXCtrl::StartSerial(short port, long band, short checkbit, short databit, short stopbit, short flowctrl)
{
	if(m_control == NULL)
	{
		m_control = new CServerControl();
		m_control->m_server = this;
        m_control->m_iSerialPort = port;
        m_control->m_SerialInfo.baudrate = band;
        m_control->m_SerialInfo.checkbit = checkbit;
        m_control->m_SerialInfo.databit = databit;
        m_control->m_SerialInfo.stopbit = stopbit;
        m_control->m_SerialInfo.flowcontrol = flowctrl;
		m_control->StartThread(TRUE);
	}
	else
	{
		m_control->StartThread(TRUE);
	}
}

void CNetViewXCtrl::StopSerial() 
{
	if(m_control)
	{
		delete m_control;
	}
	m_control = NULL;
}

void CNetViewXCtrl::GetInfo(LPSTR url,LPSTR sername,LPSTR username,LPSTR password,WORD *port) 
{
	sprintf(url,"%s",m_url);
	sprintf(sername,"%s",m_servername);
	sprintf(username,"%s",m_username);
	sprintf(password,"%s",m_password);
	*port = m_wServerPort;
}

LRESULT CNetViewXCtrl::OnSerial(WPARAM wParam,LPARAM lParam) 
{
// 	unsigned char  i,j;
// 	double data;
//     CString lpstr;
// 
// 	if(flag == 1)
// 	{
// 		i = ((value & 0xff00) >> 8) & 0x7f;
// 		j = (((i & 0xf0) >> 4) * 10) + (i & 0x0f); 
// 		if( ((value & 0xff00) >> 8) & 0x80)
// 			data = -1 * (j +  (0.1 * (value & 0xff)));
// 		else
// 			data = j +  (0.1 * (value & 0xff));
// 
// 		lpstr.Format("%3.2f℃",data);	
// 		FireTempNotify(lpstr);
// 	}
// 	else
// 	{
// 		i = (value & 0xff00) >> 8;
// 		j = (((i & 0xf0) >> 4) * 10) + (i & 0x0f); 
// 
// 		data = j +  (0.1 * (value & 0xff));
// 		lpstr.Format("%3.2f%%",data);
// 		FireHumNotify(lpstr);
// 	}
    
    CString strRec;
    CString strtmp;

    strRec.Empty();
    for (int i=0; i<lParam; i++)
    {
        strtmp.Format("%02x ", ((unsigned char *)wParam)[i]);
        strRec += strtmp;
    }

    FireSerialReceiveString(strRec.GetBuffer(0));

	return 0;
}

short CNetViewXCtrl::StartServerRecord() 
{
	int iRet;
	char sername[24],username[20],password[20],url[40];
	sprintf(sername,"%s",m_servername);
	sprintf(url,"%s",m_url);
	sprintf(username,"%s",m_username);
	sprintf(password,"%s",m_password);

	iRet = VSNET_StartServerRecord(sername,url,(char)m_channel,username,password,1,m_wServerPort);
	if(iRet)
	{
		m_bOnServerRecv |= 0x01;
		FireServerRecordStatus(m_bOnServerRecv);
	}
	return iRet;
}

short CNetViewXCtrl::StopServerRecord() 
{
	int iRet;
	char sername[24],username[20],password[20],url[40];
	memset(&m_filedata,0,sizeof(VSNETPLAY_FILE_DATA));

	sprintf(sername,"%s",m_servername);
	sprintf(url,"%s",m_url);
	sprintf(username,"%s",m_username);
	sprintf(password,"%s",m_password);
	
	iRet = VSNET_StopServerRecord(sername,url,(char)m_channel,username,password,m_wServerPort,&m_filedata);
	if(iRet)
	{
		m_bOnServerRecv &= (~0x01);
		FireServerRecordStatus(m_bOnServerRecv);

		if(m_filedata.m_filenum > 0) iRet = m_filedata.m_filenum;
	}
	return iRet;
}

BOOL CNetViewXCtrl::TransparentSend() 
{
	if(m_hChHandle == NULL) return FALSE;
	if(m_translen > 0)
	{
		VSNET_ClientSerialSend(m_hChHandle,0,m_transbuff,m_translen);
		m_translen = 0;
	}
	return TRUE;
}

BOOL CNetViewXCtrl::CaptureJpeg(LPCTSTR filename) 
{
	strcpy(m_jpegfilename,filename);
	if(m_jpegHandle == -1)
		CaptureJpegStart();

	if(m_jpegHandle != -1)
	{
		return VSNET_ClientJpegCapSingle(m_jpegHandle,m_channel,90);
	}
	return FALSE;
}

BOOL CNetViewXCtrl::CaptureJpegStart() 
{
	char sername[24],username[20],password[20],url[40];
	sprintf(sername,"%s",m_servername);
	sprintf(url,"%s",m_url);
	sprintf(username,"%s",m_username);
	sprintf(password,"%s",m_password);
	
	if(m_jpegHandle != -1)
	{
		VSNET_ClientJpegCapStop(m_jpegHandle);
		m_jpegHandle = -1;
	}
	m_jpegerror = FALSE;
	m_jpegHandle = VSNET_ClientJpegCapStart(sername,url,username,password,m_wServerPort,s_jpegdatacallback,this);
	if(m_jpegHandle != -1) 
	{
		return TRUE;
	}
	else return FALSE;
}

BOOL CNetViewXCtrl::CaptureJpegStop() 
{
	if(m_jpegHandle != -1)
	{
		VSNET_ClientJpegCapStop(m_jpegHandle);
		m_jpegHandle = -1;
	}
	m_jpegerror = FALSE;
	return TRUE;
}

int CNetViewXCtrl::OnCreate(LPCREATESTRUCT lpCreateStruct) 
{
	if (COleControl::OnCreate(lpCreateStruct) == -1)
		return -1;
	
    m_dlgMail = new CDlgMailTest;
    m_dlgMail->Create(IDD_DLG_MAILTEST);
    m_dlgMail->ShowWindow(SW_HIDE);

	SetTimer(TIMERID_SYS, 1000, NULL);
	SetTimer(TIMERID_JPEGRELINK,1000,NULL);
	
#if defined(PROTYPE_LOGO)
	AfxEnableControlContainer();
	try
	{
		char filename[MAX_PATH],preix[MAX_PATH];
		RECT rect;
		rect.left = rect.top = 0;
		rect.right = rect.bottom = 10;
		m_flash = new CShockwaveFlash();
		if(m_flash->Create(NULL,WS_CHILD,rect,this,IDB_FALSH))
		{
			HRSRC   myres = FindResource(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDR_SWF1),"SWF");  
			HGLOBAL gl = LoadResource(AfxGetInstanceHandle(),myres);  
			LPVOID  lp = LockResource(gl);
			GetTempPath(MAX_PATH,filename);
			sprintf(preix,"logo_%d.swf",this);
			strcat(filename,preix);
			HANDLE  fp = CreateFile(filename,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,0,NULL);
			if(fp)
			{
				DWORD   a;   
				WriteFile(fp,lp,SizeofResource(AfxGetInstanceHandle(),myres),&a,NULL);   
				CloseHandle(fp);
			}
			FreeResource(gl);
			m_flash->LoadMovie(0,filename);
			m_flash->SetLoop(TRUE);
			DeleteFile(filename);
		}
		else
		{
			if(m_flash) delete m_flash;
			m_flash = NULL;
		}
	}
	catch(...)
	{
		if(m_flash) delete m_flash;
		m_flash = NULL;
	}
#endif
	return 0;
}

BOOL CNetViewXCtrl::SetWaitTime(short waittime, short retrynum) 
{
	if(waittime > 0 && retrynum > 0)
	{
		VSNET_ClientWaitTime(waittime,retrynum);
		return TRUE;
	}
	return FALSE;
}

BOOL CNetViewXCtrl::SyncTime(long year, long month, long day, long hour, long minute, long second) 
{
	TIME_PARAM  timeparam;
	char sername[24],username[20],password[20],url[40];
	sprintf(sername,"%s",m_servername);
	sprintf(url,"%s",m_url);
	sprintf(username,"%s",m_username);
	sprintf(password,"%s",m_password);
	
	CTime nowtime(year,month,day,hour,minute,second);
	memset(&timeparam,0,sizeof(TIME_PARAM));
	timeparam.m_year = (unsigned short)year;
	timeparam.m_month = (unsigned char)month;
	timeparam.m_dayofmonth = (unsigned char)day;
	timeparam.m_dayofweek = (unsigned char)(nowtime.GetDayOfWeek() - 1);
	timeparam.m_hour = (unsigned char)hour;
	timeparam.m_minute = (unsigned char)minute;
	timeparam.m_second = (unsigned char)second;
	return VSNET_ClientSetSystime(sername,url,username,password,&timeparam,m_wServerPort);
}

BOOL CNetViewXCtrl::TransparentSendEx(short channel) 
{
	if(m_hChHandle == NULL) return FALSE;
	if(m_translen > 0)
	{
		VSNET_ClientSerialSend(m_hChHandle,channel,m_transbuff,m_translen);
		m_translen = 0;
	}
	return TRUE;
}

short CNetViewXCtrl::ReadRecordFile() 
{
	int i;
	CString filetime;
	if(m_filedata.m_filenum < 1) return -1;
	for(i=0;i<m_filedata.m_filenum;i++)
	{
		filetime.Format("%04d-%02d-%02d %02d:%02d:%02d",
			m_filedata.m_filedata[i].struStartTime.m_year,
			m_filedata.m_filedata[i].struStartTime.m_month,
			m_filedata.m_filedata[i].struStartTime.m_day,
			m_filedata.m_filedata[i].struStartTime.m_hour,
			m_filedata.m_filedata[i].struStartTime.m_minute,
			m_filedata.m_filedata[i].struStartTime.m_second);
		FireRecordFileNotify(m_filedata.m_filedata[i].m_channel,
			filetime,m_filedata.m_filedata[i].sFileName,
			m_filedata.m_filedata[i].dwFileSize);
	}
	return 0;
}

BSTR CNetViewXCtrl::StartClientRecord() 
{
	CString strResult;
	int iRet;
	char sername[24],username[20],password[20],url[40],filename[MAX_PATH]="";
	sprintf(sername,"%s",m_servername);
	sprintf(url,"%s",m_url);
	sprintf(username,"%s",m_username);
	sprintf(password,"%s",m_password);

	strResult.Empty();
	iRet = VSNET_StartClientRecord(sername,url,(char)m_channel,username,password,m_wServerPort,filename);
	if(iRet)
	{
		strResult = filename; 
	}
	return strResult.AllocSysString();
}

short CNetViewXCtrl::StopClientRecord() 
{
	int iRet;
	char sername[24],username[20],password[20],url[40];

	sprintf(sername,"%s",m_servername);
	sprintf(url,"%s",m_url);
	sprintf(username,"%s",m_username);
	sprintf(password,"%s",m_password);
	
	iRet = VSNET_StopClientRecord(sername,url,(char)m_channel,username,password,m_wServerPort);
	return iRet;
}

void CNetViewXCtrl::SetRecordType(short type) 
{
	m_recordtype = type;
}

BOOL CNetViewXCtrl::SendBankInfo(LPCTSTR personnum, LPCTSTR boxnum, short recvnum, short sendnum) 
{
	if(m_hChHandle)
	{
		SYSTEMTIME timenow;
		NETRVS_BANKINFO bankinfo;
		GetLocalTime(&timenow);
		memset(&bankinfo,0,sizeof(NETRVS_BANKINFO));
		bankinfo.m_nyear = timenow.wYear;
		bankinfo.m_nmonth = (unsigned char)timenow.wMonth;
		bankinfo.m_nday = (unsigned char)timenow.wDay;
		bankinfo.m_nhour = (unsigned char)timenow.wHour;
		bankinfo.m_nminute = (unsigned char)timenow.wMinute;
		bankinfo.m_nsecond = (unsigned char)timenow.wSecond;
		strcpy(bankinfo.m_peplenum,personnum);
		strcpy(bankinfo.m_boxnum,boxnum);
		bankinfo.m_recvnum = recvnum;
		bankinfo.m_sendnum = sendnum;
		return VSNET_ClientSendBankInfo(m_hChHandle,&bankinfo);
	}
	return FALSE;
}

void CNetViewXCtrl::SetRecordPackTime(short packtime) 
{
	int				    iRet = 0;

    packtime = packtime > RECORD_PACK_MAXMINS?RECORD_PACK_MAXMINS:packtime;
    packtime = packtime < RECORD_PACK_MINMINS?RECORD_PACK_MINMINS:packtime;
    m_recordpacktime = packtime * 10 * 6000;

#if 0  
    VSNETRECORDPARAM	m_recordparam;
    memset(&m_recordparam,0,sizeof(VSNETRECORDPARAM));
    m_recordparam.m_packet_time = packtime;

	LONG m_hParam = VSNET_ClientMessageOpen((char*)(LPCTSTR)m_servername,
                                            (char*)(LPCTSTR)m_url,
                                            (char*)(LPCTSTR)m_username,
                                            (char*)(LPCTSTR)m_password,
                                            (WORD)m_wServerPort);
	if( m_hParam != -1 )
	{
		iRet = VSNET_ClientMessageOpt(m_hParam,MESSAGE_CMD_SETRECORDPARAM,m_channel,&m_recordparam,NULL,NULL); 
		VSNET_ClientMessageClose(m_hParam);
	}
#endif
}

BOOL CNetViewXCtrl::SetAudioVolume(long volume)
{
	if(m_hChHandle)
	{
		if (VSNET_ClientAudioVolume(m_hChHandle,(WORD)volume))
		{
			m_bSetVolume	= TRUE;
			m_volume		= volume;
			return TRUE;
		}
	}
	return FALSE;
}

void CNetViewXCtrl::GetVideoMaskParam()
{
	char sername[24],username[20],password[20],url[40];	
	VSNETVIDEOMASK	m_maskarea;
	CHANNVIDEOMASK	m_channvmask;
	int				iRet;

	memset(&m_maskarea,0,sizeof(VSNETVIDEOMASK));
	memset(&m_channvmask,0,sizeof(CHANNVIDEOMASK));
	memset(&m_vmask,0,sizeof(m_vmask));

	sprintf(sername,"%s",m_servername);
	sprintf(url,"%s",m_url);
	sprintf(username,"%s",m_username);
	sprintf(password,"%s",m_password);

	LONG m_hParam = VSNET_ClientMessageOpen(sername,url,username,password,(WORD)m_wServerPort);
	if( m_hParam != -1 )
	{
		iRet = VSNET_ClientMessageOpt(m_hParam,MESSAGE_CMD_GETVIDEOMASKAREA,m_channel,&m_maskarea,NULL,NULL); 
		if( iRet )
		{
			memcpy(m_vmask,m_maskarea.m_maskarea,sizeof(m_vmask));
			FireVideoMaskParam(m_maskarea.m_bmask?TRUE:FALSE,4);
		}
		else
		{
			iRet = VSNET_ClientMessageOpt(m_hParam,MESSAGE_CMD_GETVIDEOMASK,m_channel,&m_channvmask,NULL,NULL);
			if( iRet )
			{
				m_vmask[0].m_x = m_channvmask.m_x;
				m_vmask[0].m_y = m_channvmask.m_y;
				m_vmask[0].m_width = m_channvmask.m_width;
				m_vmask[0].m_height = m_channvmask.m_height;
				FireVideoMaskParam(m_channvmask.m_bmask?TRUE:FALSE,1);
			}
		}
		VSNET_ClientMessageClose(m_hParam);
	}
	
	m_curmaskarea = 0;
	float w_off,h_off;
	RECT rect;
	GetClientRect(&rect);
	w_off = (float)(rect.right  - rect.left) / (float)704;
	h_off = (float)(rect.bottom - rect.top)  / (float)576;
	m_maskmax_w  = (int)((float)352 * w_off);
	m_maskmax_h  = (int)((float)288 * h_off);

	for(int i=0;i<4;i++)
	{
		m_vmask[i].m_x = (short)(((float)m_vmask[i].m_x) * w_off);
		m_vmask[i].m_y = (short)(((float)m_vmask[i].m_y) * h_off);
		m_vmask[i].m_width = (short)(((float)m_vmask[i].m_width) * w_off);
		m_vmask[i].m_height = (short)(((float)m_vmask[i].m_height) * h_off);
	}

	m_vmask_x = m_vmask[m_curmaskarea].m_x;
	m_vmask_y = m_vmask[m_curmaskarea].m_y;
	m_vmask_w = m_vmask[m_curmaskarea].m_width;
	m_vmask_h = m_vmask[m_curmaskarea].m_height;
}

BOOL CNetViewXCtrl::SetCurMaskArea(short area)
{
	if( !m_bVideoMaskEdit || 
		area < 0 ||
		area >= MAX_VIDEOMASK_AREA )
		return FALSE;

	m_curmaskarea = area;
	m_vmask_x = m_vmask[m_curmaskarea].m_x;
	m_vmask_y = m_vmask[m_curmaskarea].m_y;
	m_vmask_w = m_vmask[m_curmaskarea].m_width;
	m_vmask_h = m_vmask[m_curmaskarea].m_height;

	return TRUE;
}

BOOL CNetViewXCtrl::FlipVideo()
{
    if(m_hChHandle)
    {
        if(VSNET_ClientFlipVideo(m_hChHandle))
        {
            m_bFlipVideo = !m_bFlipVideo;
            return TRUE;
        }
    }
    return FALSE;
}

BOOL CNetViewXCtrl::FlipVideoH() 
{
    if(m_hChHandle)
    {
        if(VSNET_ClientFlipVideoH(m_hChHandle))
        {
            m_bFlipVideoH = !m_bFlipVideoH;
            return TRUE;
        }
    }
	
	return TRUE;
}

BOOL CNetViewXCtrl::GetDiskState()
{
    BOOL        iRet;
    VSDISKSTATE diskState;
    BOOL        hdState[2] = {FALSE,FALSE};

    iRet = VSNET_GetDiskState((char*)(LPCTSTR)m_servername,
                              (char*)(LPCTSTR)m_url,
                              (char*)(LPCTSTR)m_username,
                              (char*)(LPCTSTR)m_password,
                              &diskState,
                              m_wServerPort);
    if( iRet )
    {
        for(int index = 0; index<diskState.m_hds && (index<2); index++)
        {
            hdState[index] = diskState.m_hdstate[index] == 0;
        }
    }
    FireDiskStatus(hdState[0],hdState[1]);

    return iRet;
}

BOOL CNetViewXCtrl::GetRecordPackTime()
{
	VSNETRECORDPARAM	m_recordparam;
	int				    iRet = 0;

	memset(&m_recordparam,0,sizeof(VSNETRECORDPARAM));

	LONG m_hParam = VSNET_ClientMessageOpen((char*)(LPCTSTR)m_servername,
                                            (char*)(LPCTSTR)m_url,
                                            (char*)(LPCTSTR)m_username,
                                            (char*)(LPCTSTR)m_password,
                                            (WORD)m_wServerPort);
	if( m_hParam != -1 )
	{
		iRet = VSNET_ClientMessageOpt(m_hParam,MESSAGE_CMD_GETRECORDPARAM,m_channel,&m_recordparam,NULL,NULL); 
		if( iRet )
		{
            m_recordparam.m_packet_time = m_recordparam.m_packet_time > RECORD_PACK_MAXMINS?RECORD_PACK_MAXMINS:m_recordparam.m_packet_time;
            m_recordparam.m_packet_time = m_recordparam.m_packet_time < RECORD_PACK_MINMINS?RECORD_PACK_MINMINS:m_recordparam.m_packet_time;
            m_recordpacktime = m_recordparam.m_packet_time * 60 * 1000;
		}
		else
		{
            m_recordpacktime = FILE_PACKTIME;
		}
		VSNET_ClientMessageClose(m_hParam);
	}

    return iRet;
}

BOOL CNetViewXCtrl::CleanMaskArea(short area)
{
	if( !m_bVideoMaskEdit || 
		area < 0 ||
		area >= MAX_VIDEOMASK_AREA )
		return FALSE;
	
	m_vmask[area].m_x	   = 0;
	m_vmask[area].m_y	   = 0;
	m_vmask[area].m_width  = 0;
	m_vmask[area].m_height = 0;

	if( m_curmaskarea == area )
	{
		m_vmask_x = m_vmask[area].m_x;
		m_vmask_y = m_vmask[area].m_y;
		m_vmask_w = m_vmask[area].m_width;
		m_vmask_h = m_vmask[area].m_height;
	}
	Invalidate();
	return TRUE;
}

BOOL CNetViewXCtrl::ServerCapturePic() 
{
	char url[40];
	char sername[40];
	char username[40],password[40];
	WORD port;
	
	if(!VSNET_ClientInfoGetIPHandle(m_hChHandle,url,&port) )
	{
		return FALSE;
	}
	sprintf(sername,"%s",m_servername);
	sprintf(username,"%s",m_username);
	sprintf(password,"%s",m_password);
	BOOL iRet = VSNET_ServerCapJPEG(sername,
		url, (char)m_channel,
		username,password,
		80,port);
	if(!iRet)
		return FALSE;
	
	return TRUE;
}

BOOL CNetViewXCtrl::TranCtrl(long ctrlcode)
{
    if(m_hChHandle)
	{
//        return VSNET_ClientTranCtrl(m_hChHandle,ctrlcode);
	}
	return FALSE;
}

BOOL CNetViewXCtrl::GetSwitchScreenName()
{
    VSNETSWITCHSCREENNAME	m_switchScreen;
	int				        iRet = 0;

	memset(&m_switchScreen,0,sizeof(m_switchScreen));

	LONG m_hParam = VSNET_ClientMessageOpen((char*)(LPCTSTR)m_servername,
                                            (char*)(LPCTSTR)m_url,
                                            (char*)(LPCTSTR)m_username,
                                            (char*)(LPCTSTR)m_password,
                                            (WORD)m_wServerPort);
	if( m_hParam != -1 )
	{
		iRet = VSNET_ClientMessageOpt(m_hParam,MESSAGE_CMD_GETSWITCHSCREENNAME,m_channel,&m_switchScreen,NULL,NULL); 
		if( iRet )
		{
            FireSwitchScreenName(m_switchScreen.m_name[0],
                                 m_switchScreen.m_name[1],
                                 m_switchScreen.m_name[2],
                                 m_switchScreen.m_name[3],
                                 m_switchScreen.m_name[4],
                                 m_switchScreen.m_name[5],
                                 m_switchScreen.m_name[6],
                                 m_switchScreen.m_name[7],
                                 m_switchScreen.m_name[8]);
		}
		else
		{
            FireSwitchScreenName("",
                                 "",
                                 "",
                                 "",
                                 "",
                                 "",
                                 "",
                                 "",
                                 "");
		}
		VSNET_ClientMessageClose(m_hParam);
	}

    return iRet;
}

short CNetViewXCtrl::GetChannelOsd() 
{
	int iRet1;

	memset(&m_channosd,0,sizeof(CHANNOSD));
	iRet1 = VSNET_ClientMessageOpt(m_hMessageParam,MESSAGE_CMD_GETCHANNELOSD,m_channel,&m_channosd,NULL,NULL);
	FireChannelOsd(m_channosd.m_time.nFormat, m_channosd.m_time.x, m_channosd.m_time.y
		, m_channosd.m_bits.bShow, m_channosd.m_bits.x, m_channosd.m_bits.y
		, m_channosd.m_tital[0].lpString, m_channosd.m_tital[0].x, m_channosd.m_tital[0].y
		, m_channosd.m_tital[1].lpString, m_channosd.m_tital[1].x, m_channosd.m_tital[1].y);
	
	return iRet1;
}

short CNetViewXCtrl::SetChannelOsd(short timeindex, short timex, short timey, short bitrateindex, short bitratex, short bitratey, LPCTSTR title1str, short title1x, short title1y, LPCTSTR title2str, short title2x, short title2y) 
{
	int iRet1;

	m_channosd.m_time.nFormat = timeindex;
	m_channosd.m_time.x = timex;
	m_channosd.m_time.y = timey;
	m_channosd.m_bits.bShow = bitrateindex;
	m_channosd.m_bits.x = bitratex;
	m_channosd.m_bits.y = bitratey;
	strcpy(m_channosd.m_tital[0].lpString, title1str);
	m_channosd.m_tital[0].x = title1x;
	m_channosd.m_tital[0].y = title1y;
	strcpy(m_channosd.m_tital[1].lpString, title2str);
	m_channosd.m_tital[1].x = title2x;
	m_channosd.m_tital[1].y = title2y;
	iRet1 = VSNET_ClientMessageOpt(m_hMessageParam, MESSAGE_CMD_SETCHANNELOSD,m_channel,&m_channosd,NULL,NULL);
	
	return iRet1;
}

short CNetViewXCtrl::GetChannelEncParam() 
{
	int type;
	int iRet1;

    memset(&m_channparam,0,sizeof(CHANNELPARAM));
	memset(&m_channparamex,0,sizeof(CHANNELPARAMEX));
	iRet1 = VSNET_ClientMessageOpt(m_hMessageParam,MESSAGE_GETCHANNELPARAM,m_channel,&m_channparam,&m_channparamex,&type);
	if (type)
	{
		FireChannelEncParam(m_channparamex.m_encodeType, m_channparamex.m_bitratetype, m_channparamex.m_maxbitrates
			, m_channparamex.m_maxqueue, m_channparamex.m_minqueue, m_channparamex.m_videoFrameRate
			, m_channparamex.m_streamType, m_channparamex.m_Iinterval);
	}
	else
	{
		FireChannelEncParam(m_channparam.m_encodeType, m_channparam.m_bitratetype, m_channparam.m_maxbitrates
			, m_channparam.m_maxqueue, m_channparam.m_minqueue, m_channparam.m_videoFrameRate
			, m_channparam.m_streamType, m_channparam.m_Iinterval);
	}
	
	return iRet1;
}

short CNetViewXCtrl::SetChannelEncParam(short encodetype, short bitratetype, short maxbitrate, short maxqueue, short minqueue, short framerate, short streamtype, short iinterval) 
{
	int iRet1;

	m_channparam.m_encodeType = encodetype;
	m_channparam.m_bitratetype = bitratetype;
	m_channparam.m_maxbitrates = maxbitrate;
	m_channparam.m_maxqueue = maxqueue;
	m_channparam.m_minqueue = minqueue;
	m_channparam.m_videoFrameRate = framerate;
	m_channparam.m_streamType = streamtype;
	m_channparam.m_Iinterval = iinterval;

	m_channparamex.m_encodeType = encodetype;
	m_channparamex.m_bitratetype = bitratetype;
	m_channparamex.m_maxbitrates = maxbitrate;
	m_channparamex.m_maxqueue = maxqueue;
	m_channparamex.m_minqueue = minqueue;
	m_channparamex.m_videoFrameRate = framerate;
	m_channparamex.m_streamType = streamtype;
	m_channparamex.m_Iinterval = iinterval;

	iRet1 = VSNET_ClientMessageOpt(m_hMessageParam,MESSAGE_SETCHANNELPARAM,m_channel,&m_channparam,&m_channparamex,NULL);
	
	return iRet1;
}

short CNetViewXCtrl::GetViParam() 
{
	int iRet1;

	memset(&m_viparam,0,sizeof(CHANNVIPARAM));
	iRet1 = VSNET_ClientMessageOpt(m_hMessageParam,MESSAGE_CMD_GETVIPARAM,m_channel,&m_viparam,NULL,NULL);
	FireViParam(m_viparam.m_bri, m_viparam.m_con, m_viparam.m_sat, m_viparam.m_hue);

	return iRet1;
}

short CNetViewXCtrl::SetViParam(short bri, short con, short sat, short hue) 
{
	int iRet1;

	m_viparam.m_bri = (unsigned char)bri;
	m_viparam.m_con = (unsigned char)con;
	m_viparam.m_sat = (unsigned char)sat;
	m_viparam.m_hue = (unsigned char)hue;
	iRet1 = VSNET_ClientMessageOpt(m_hMessageParam,MESSAGE_CMD_SETVIPARAM,m_channel,&m_viparam,NULL,NULL);
	
	return iRet1;
}

short CNetViewXCtrl::SaveParam() 
{
	int iRet1;
	iRet1 = VSNET_ClientMessageOpt(m_hMessageParam,MESSAGE_CMD_SAVEPARA,0,NULL,NULL,NULL);
	
	return iRet1;
}

short CNetViewXCtrl::RestartDevice() 
{
	int iRet1;
	iRet1 = VSNET_ClientMessageOpt(m_hMessageParam,MESSAGE_CMD_RESET,0,NULL,NULL,NULL);
	
	return iRet1;
}

typedef struct
{
	char	m_servername[64];
	char	m_url[64];
	char	m_username[64];
	char	m_password[64];
	DWORD	m_port;
	CNetViewXCtrl *m_pctrl;
}GETWIFIPARAM;

static DWORD s_thread_getwifi(GETWIFIPARAM *pParam)
{
	CString strResult;
	char zero = 'b';
	char t = 9;//表示转义字符'\t'
	
	char m_csername[100];
	char m_cserurl[100];
	char m_cusername[100];
	char m_cpasswords[100];
	sprintf(m_csername, "%s", pParam->m_servername);
	sprintf(m_cserurl, "%s", pParam->m_url);
	sprintf(m_cusername, "%s", pParam->m_username);
	sprintf(m_cpasswords, "%s", pParam->m_password);
	
	VSNETWIFISSIDLIST m_useableWifi;
	BOOL bRst = VSNET_ClientWifiSearch(m_csername, m_cserurl, m_cusername, m_cpasswords, &m_useableWifi, pParam->m_port);
	if(bRst)
	{
		CString str;
		int iSel;
		str.Format("%c", zero + m_useableWifi.m_ssidnum);
		strResult += str;
		
		for(int i = 0; i < MAX_SSIDNUM; i++)
		{
			if(i < m_useableWifi.m_ssidnum)
			{
				iSel = m_useableWifi.m_ssidinfo[i].m_wifiencmode;
				iSel = (iSel == 8) ? 4 : iSel;
				str.Format("%c", zero + iSel);
			}
			else
			{
				str.Format("%c", zero + (-1));
			}
			strResult += str;
		}
		
		for(i = 0; i < MAX_SSIDNUM; i++)
		{
			if(i < m_useableWifi.m_ssidnum)
			{
				str.Format("%s%c", m_useableWifi.m_ssidinfo[i].m_wifissid, t);
			}
			else
			{
				str.Format("%c", t);
			}
			strResult += str;
		}
	}
	else
	{
		strResult.Format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c", t, t, t, t, t, t, t, t, t, t, t, t, t, t, t, t, t, t, t, t, t, t, t, t, t, t, t, t, t, t, t, t, t, t, t, t, t, t, t, t);
	}
	//测试用
	//strResult.Format("ebcdaaaaaaaXXX%cYYY%cZZZ%c%c%c%c%c%c%c%c", t, t, t, t, t, t, t, t, t, t);
	pParam->m_pctrl->m_sUseableWifiList = strResult;
	::PostMessage(pParam->m_pctrl->m_hWnd, WM_USEABLEWIFI, 0, 0);
	delete pParam;
	pParam = NULL;
	return 0;
}

LRESULT CNetViewXCtrl::OnWMUseableWifi(WPARAM wParam,LPARAM lParam)
{
	FireUseableWifi((LPCTSTR)m_sUseableWifiList);
	return 1;
}

BSTR CNetViewXCtrl::GetUseableWifi() 
{
	ULONG ID;
	GETWIFIPARAM *m_pParam = new GETWIFIPARAM();
	sprintf(m_pParam->m_servername, "%s", m_servername);
	sprintf(m_pParam->m_url, "%s", m_url);
	sprintf(m_pParam->m_username, "%s", m_username);
	sprintf(m_pParam->m_password, "%s", m_password);
	m_pParam->m_port = m_wServerPort;
	m_pParam->m_pctrl = this;
	CString strResult;
	HANDLE m_hget = CreateThread(0,1024*10,
		(LPTHREAD_START_ROUTINE)s_thread_getwifi,
		m_pParam, 0, &ID);
	strResult = "Please wait for result event.";
	return strResult.AllocSysString();
}

BOOL CNetViewXCtrl::ChooseVideoInput(short input)
{
	BOOL iRet = FALSE;

	LONG m_hParam = VSNET_ClientMessageOpen((char*)(LPCTSTR)m_servername,
                                            (char*)(LPCTSTR)m_url,
                                            (char*)(LPCTSTR)m_username,
                                            (char*)(LPCTSTR)m_password,
                                            (WORD)m_wServerPort);
	if (m_hParam != -1)
	{
		iRet = VSNET_ClientMessageOpt(m_hParam,MESSAGE_CMD_CHOOSEVIDEOINPUT,m_channel,&input,NULL,NULL); 
		VSNET_ClientMessageClose(m_hParam);
	}

    return iRet;
}

BOOL CNetViewXCtrl::PtzLock(BOOL bLock, long nPriority, long lockTime) 
{
	// TODO: Add your dispatch handler code here
	int iRet  = 0;
	if( bLock )
	{
		iRet = VSNET_ClientSetPTZLockTime(
			(char*)(LPCTSTR)m_servername,
			(char*)(LPCTSTR)m_url,
			m_channel,
			(char*)(LPCTSTR)m_username,
			(char*)(LPCTSTR)m_password,
			(int)lockTime,
			(WORD)m_wServerPort);
		TRACE("decoder:%s ch:%d Set Ptz Lock Time:%d %s.\n",m_servername,m_channel,lockTime,iRet?"Success":"Faild");
		
		if( iRet )
		{
			iRet = VSNET_ClientPTZLock(
				(char*)(LPCTSTR)m_servername,
				(char*)(LPCTSTR)m_url,
				m_channel,
				(char*)(LPCTSTR)m_username,
				(char*)(LPCTSTR)m_password,
				TRUE,
				nPriority,
				(WORD)m_wServerPort);
			TRACE("decoder:%s ch:%d Set Ptz Lock %s.\n",m_servername,m_channel,iRet==0?"Success":iRet==-109?"Not Right":"Faild");
			return iRet == 0;
		}
	}
	else
	{
		iRet = VSNET_ClientPTZLock(
			(char*)(LPCTSTR)m_servername,
			(char*)(LPCTSTR)m_url,
			m_channel,
			(char*)(LPCTSTR)m_username,
			(char*)(LPCTSTR)m_password,
			FALSE,
			nPriority,
			(WORD)m_wServerPort);
		TRACE("decoder:%s ch:%d Set Ptz UnLock %s.\n",m_servername,m_channel,iRet==0?"Success":iRet==-109?"Not Right":"Faild");
	
		return iRet == 0;
	}
	return 0;
}

LRESULT CNetViewXCtrl::OnJPEGEventMsg(WPARAM wParam,LPARAM lParam)
{
	FireJPEGEvent(TRUE);
	return 1;
}

LRESULT CNetViewXCtrl::OnJPEGDataMsg(WPARAM wParam,LPARAM lParam)
{
	FireJPEGData((BSTR FAR*)wParam,lParam);
	return 1;
}

BOOL CNetViewXCtrl::SetDeviceName(LPCTSTR lpName) 
{
	// TODO: Add your dispatch handler code here
	WHOLEPARAM whole_param;
	memset(&whole_param,0,sizeof(whole_param));
	/*
	int iret = VSNET_ClientMessageOpt(m_hMessageParam,MESSAGE_CMD_GETGLOBALPARAM,0,&whole_param);
	if(iret)
	{
		sprintf(whole_param.m_servername,"%s",lpName);
		iret = VSNET_ClientMessageOpt(m_hMessageParam,MESSAGE_CMD_SETGLOBALPARAM,0,&whole_param);
		if(iret)
		{
			return TRUE;
		}
	}
	*/
	if(!VSNET_ClientGetWholePara((char*)(LPCTSTR)m_servername,(char*)(LPCTSTR)m_url,
		(char*)(LPCTSTR)m_username,(char*)(LPCTSTR)m_password,&whole_param,m_wServerPort))
	{
		TRACE("get whole param failed!");
		return FALSE;
	}
	sprintf(whole_param.m_servername,"%s",lpName);
	if(!VSNET_ClientSetWholePara((char*)(LPCTSTR)m_servername,(char*)(LPCTSTR)m_url,
		(char*)(LPCTSTR)m_username,(char*)(LPCTSTR)m_password,&whole_param,m_wServerPort))
	{
		TRACE("set whole param failed!");
		return FALSE;
	}
	
	if(!VSNET_ClientSaveServerPara((char*)(LPCTSTR)m_servername,(char*)(LPCTSTR)m_url,
		(char*)(LPCTSTR)m_username,(char*)(LPCTSTR)m_password,m_wServerPort))
		return FALSE;

	if(!VSNET_ClientResetServer((char*)(LPCTSTR)m_servername,(char*)(LPCTSTR)m_url,
		(char*)(LPCTSTR)m_username,(char*)(LPCTSTR)m_password,m_wServerPort))
		return FALSE;

	return TRUE;
}


BOOL CNetViewXCtrl::PISNow(BOOL bStartPIS) 
{
	// TODO: Add your dispatch handler code here
	if(m_hChHandle > 0)
		return VSNET_ClientPreventImageSplit(m_hChHandle, bStartPIS);
	else
		return FALSE;
}

BOOL CNetViewXCtrl::PISNexttime(BOOL bStartPIS) 
{
	// TODO: Add your dispatch handler code here
	m_PISTag = bStartPIS;
	return TRUE;
}

long CNetViewXCtrl::StartDDNSConnect() 
{
	if(m_hChHandle) return 0;
	
	CHANNEL_CLIENTINFO pLinkInfo;
	char sername[24],username[20],password[20],url[40];
	sprintf(sername,"%s",m_servername);
	sprintf(url,"%s",m_url);
	sprintf(username,"%s",m_username);
	sprintf(password,"%s",m_password);

	pLinkInfo.m_buffnum    = m_buffernum;
	pLinkInfo.m_ch         = (BYTE)m_channel;
	pLinkInfo.m_hChMsgWnd  = m_hWnd;
	pLinkInfo.m_hVideohWnd = m_hWnd;
	pLinkInfo.m_nChmsgid   = NET_MSG_ID;
	pLinkInfo.m_password   = password;
	pLinkInfo.m_playstart  = FALSE;
	pLinkInfo.m_sername    = sername;
	pLinkInfo.m_tranType   = (WORD)m_trantype;
	pLinkInfo.m_useoverlay = FALSE;
	pLinkInfo.m_username   = username;
	pLinkInfo.nColorKey    = FACE_COLOR;
	pLinkInfo.context      = NULL;
	pLinkInfo.m_messagecallback = NULL;
	m_curchannel = m_channel;
	m_hChHandle = VSNET_InfoClientStart(url,&pLinkInfo,(WORD)(m_wServerPort), m_streamtype);
	if(m_hChHandle == -1)
	{
		sprintf(m_OptString,"connect server error...");
	}
	else
	{
		sprintf(m_OptString,"connecting...");
		VSNET_ClientSetDelayTime(m_hChHandle,m_delaytime);
	}

	m_playstart  = FALSE;
	m_bSetVolume = FALSE;
	Invalidate();

	return 0;
}

BOOL CNetViewXCtrl::StartDDNSView() 
{
	m_nRelinkNum  = TRUE;
	m_playstart	  = TRUE;
	m_bSetVolume  = FALSE;
	
	
	if ( !InterStartView(TRUE) )
	{
		m_playstart = FALSE;
		return FALSE;
	}
	else
	{
		//修改m_sername的默认值
// 		WHOLEPARAM		m_wholeparam;
// 		int iRet = VSNET_ClientMessageOpt(m_hMessageParam, MESSAGE_CMD_GETGLOBALPARAM,0,&m_wholeparam,NULL,NULL);
// 		if(iRet)
// 		{
// 			m_servername.Format("%s", m_wholeparam.m_servername);
// 		}
// 		else
// 		{
// 		}
		return TRUE;
	}
}

BOOL CNetViewXCtrl::IsFullScreen() 
{
	if (m_pFullScreenWnd == NULL)	return FALSE;

	return m_pFullScreenWnd->IsWindowVisible();
}

void CNetViewXCtrl::SendSerialString(LPCSTR pBuff) 
{
	// TODO: Add your dispatch handler code here
    if (m_control != NULL && m_control->m_hSerialHandle != NULL)
    {
        CString strtmp;
        int     pos = -1;
        int     num = 0;
        CString temp;

        strtmp.Format("%s", pBuff);
        pos = strtmp.Find(' ');

        if (pos != -1)
        {
            //16进制发送
            TRACE("Hex: ");
            do
            {
                temp = strtmp.Left(pos);
                sscanf(temp, "%x", m_control->m_SendData+num);
                TRACE("0X%02x ", m_control->m_SendData[num]);
                strtmp.Delete(0, pos+1);
                pos = strtmp.Find(' ');
                num++;
            }
            while (pos != -1);

            sscanf(strtmp, "%x", m_control->m_SendData+num);
            TRACE("0X%02x\n", m_control->m_SendData[num]);
            m_control->m_SendLength = num+1;
        }
        else
        {
            strtmp.Format("%s", pBuff);
            memcpy(m_control->m_SendData, strtmp.GetBuffer(0), strtmp.GetLength());
            m_control->m_SendLength = strtmp.GetLength();
            TRACE("String: %s\n", pBuff);
        }
    }
}

void CNetViewXCtrl::OnStreamtypeChanged() 
{
	// TODO: Add notification handler code

	SetModifiedFlag();
}

void CNetViewXCtrl::OnRButtonDown(UINT nFlags, CPoint point) 
{
	if(nFlags == MK_RBUTTON)
		FireRButtonDown(m_url,(unsigned long)m_channel);
	
	COleControl::OnRButtonDown(nFlags, point);
}

void CNetViewXCtrl::OnRButtonUp(UINT nFlags, CPoint point) 
{
//	if(nFlags == MK_RBUTTON)
		FireRButtonUp(m_url,(unsigned long)m_channel);
	
	COleControl::OnRButtonUp(nFlags, point);
}

void CNetViewXCtrl::MailTest(short testnum) 
{
	// TODO: Add your dispatch handler code here
    CRect rect;
    BOOL bRet = FALSE;
    char recvBuff[LAN_NET_MSG_SIZE];
    LONG hMessageParam = -1;
    
    memset(recvBuff, 0, LAN_NET_MSG_SIZE);
    int nScreenWidth = GetSystemMetrics(SM_CXSCREEN);
	int nScreenHeight = GetSystemMetrics(SM_CYSCREEN);
    m_dlgMail->GetWindowRect(&rect);
	rect.OffsetRect(-rect.TopLeft());
    int x = (nScreenWidth - rect.Width()) / 2;
	int y = (nScreenHeight - rect.Height()) / 2;
	rect.OffsetRect(x, y);
    m_dlgMail->MoveWindow(&rect, TRUE);
    m_dlgMail->ShowWindow(SW_SHOW);

    hMessageParam = VSNET_ClientMessageOpen((char*)(LPCTSTR)m_servername,
                                            (char*)(LPCTSTR)m_url,
                                            (char*)(LPCTSTR)m_username,
                                            (char*)(LPCTSTR)m_password,
      	                                    (WORD)m_wServerPort);

	TRACE("MailTest VSNET_ClientMessageOpen %s.\n", hMessageParam == -1 ? "Failed" : "Success");
    if (hMessageParam != -1)
    {
        bRet = VSNET_ClientMessageOpt(hMessageParam, 
                                      MESSAGE_CMD_MAILTEST, 
                                      testnum, 
                                      recvBuff);
        TRACE("MailTest VSNET_ClientMessageOpt %s.\n", bRet ? "Success" : "Failed");
        VSNET_ClientMessageClose(hMessageParam);
    }

    m_dlgMail->SetShowText(bRet, recvBuff);
}

long CNetViewXCtrl::GetConnectIPNumber() 
{
	// TODO: Add your dispatch handler code here

	int number = 0;
	TCHAR ip[15];
	DWORD channs;
	
	char sername[24],username[20],password[20],url[40];
	sprintf(sername,"%s",m_servername);
	sprintf(url,"%s",m_url);
	sprintf(username,"%s",m_username);
	sprintf(password,"%s",m_password);
	
	DWORD alarmins;
	DWORD alarmouts;
	
	if(VSNET_ClientGetChannelAmount
		(sername,url,&channs,&alarmins,&alarmouts,m_wServerPort))
	{
		CONNECTIP pConnecIP ={0};
		for(DWORD i = 0; i!=channs; ++i)
		{			
			if(!VSNET_ClientGetConnectIP				
				(sername,url,username,password,&pConnecIP,m_wServerPort))
			{
				return -1;
			}
			for(int j = 0; j!=pConnecIP.m_chanuser[i];++j)
			{
				wsprintf(ip,_T("%d.%d.%d.%d"),pConnecIP.m_chanIP[i][j][0],
					pConnecIP.m_chanIP[i][j][1],pConnecIP.m_chanIP[i][j][2],
					pConnecIP.m_chanIP[i][j][3]);
				FireConnectIPAddr(ip);
				//MessageBox(ip);
				++number;				
			}
		}		
	}
	else
	{
		return -1;
	}  
	
	return number;
}

BOOL CNetViewXCtrl::PreTranslateMessage(MSG* pMsg) 
{
	// TODO: Add your specialized code here and/or call the base class
	if (m_pFullScreenWnd && m_pFullScreenWnd->IsWindowVisible())
	{
		m_pFullScreenWnd->PreTranslateMessage(pMsg);
	}
	
	return COleControl::PreTranslateMessage(pMsg);
}

int CNetViewXCtrl::RelinkTalk()
{
	//停止对讲
	StopTalk();

	char url[40],sername[24];
	char username[20],password[20];
	sprintf(url,"%s",m_url);
	sprintf(sername,"%s",m_servername);
	sprintf(username,"%s",m_username);
	sprintf(password,"%s",m_password);

	//开启对讲
	if(m_hChHandle == 0) return-1;
	m_talkhandle = VSNET_ClientTalkBothwayStart(url, m_channel, username, password, (WORD)m_wServerPort, TalkEncCallBack, sername,m_hWnd,8000,this);//启用新的双向对讲函数
	if (m_talkhandle > 0)
	{
		m_bIsnewTalk = TRUE;
	}
	else
	{
		m_talkhandle = VSNET_ClientTalkExchangeStart(url,username,password,(WORD)m_wServerPort,TalkEncCallBack,sername,8000,this);//启用老的双向对讲函数
		m_bIsnewTalk = FALSE;
	}
	TRACE("打开双向对讲%s!", m_talkhandle < 0 ? "失败":"成功");
	if (m_talkhandle < 0)
	{
		FireTalkStatus(0);
		if(m_talkhandle == -1)
			return -1;
		else if(m_talkhandle == -2)
			return -2;
		else if(m_talkhandle == -102)
			return -102;
		else if(m_talkhandle == -104)
			return -104;
	}
	else
	{
		if (m_bIsnewTalk)
		{
			FireTalkStatus(2);
		}
		else
		{
			FireTalkStatus(1);
		}
	}
	return 1;
}


long CNetViewXCtrl::SharpeVideo(long iSharpeVideo) 
{
	// TODO: Add your dispatch handler code here
	if (m_hChHandle > 0)
	{
		return VSNET_ClientSharpeVideo(m_hChHandle, iSharpeVideo);
	}
	return 0;
}
