⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 asynopcdlg.cpp

📁 最简单的VC编写的OPC客户端程序
💻 CPP
📖 第 1 页 / 共 2 页
字号:
// AsynOpcDlg.cpp : implementation file
//
//--------------------------------------------------------- 
// (c) COPYRIGHT 2003,2004 http://www.opc-china.com INC.
// ALL RIGHTS RESERVED
// Original Author:Jigang Si
// Original Author Email:economic@126.com 
//--------------------------------------------------------- 
#include "stdafx.h"
#include "AsynOpc.h"
#include "AsynOpcDlg.h"
#include "callback.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
extern float value[MAXITEMNUM];
extern CString quility[MAXITEMNUM];
extern CString timestamp[MAXITEMNUM];
extern float readValue[MAXITEMNUM];
extern CString readQulity[MAXITEMNUM];
extern CString readTS[MAXITEMNUM];
extern HRESULT writeRes[MAXITEMNUM];
extern int changeFlag,readFlag,writeFlag;
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

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

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

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

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

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CAsynOpcDlg dialog

CAsynOpcDlg::CAsynOpcDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CAsynOpcDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CAsynOpcDlg)
	m_writeValue = 0.0;
	m_writeResult = _T("");
	m_readTS = _T("");
	m_readValue = 0.0;
	m_readQulity = _T("");
	m_dataValue = 0.0;
	m_dataTS = _T("");
	m_dataQulity = _T("");
	m_bChkGroupAct = FALSE;
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CAsynOpcDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAsynOpcDlg)
	DDX_Text(pDX, IDC_WRITEVALUE, m_writeValue);
	DDX_Text(pDX, IDC_WRITERESULT, m_writeResult);
	DDX_Text(pDX, IDC_TIMESTAMP, m_readTS);
	DDX_Text(pDX, IDC_READVALUE, m_readValue);
	DDX_Text(pDX, IDC_QUALITY, m_readQulity);
	DDX_Text(pDX, IDC_DATAVALUE, m_dataValue);
	DDX_Text(pDX, IDC_DATATIMESTAMP, m_dataTS);
	DDX_Text(pDX, IDC_DATAQUALITY, m_dataQulity);
	DDX_Check(pDX, IDC_CHECK_ACTIVATEGROUP, m_bChkGroupAct);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAsynOpcDlg, CDialog)
	//{{AFX_MSG_MAP(CAsynOpcDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_START, OnStart)
	ON_BN_CLICKED(IDC_READ, OnRead)
	ON_BN_CLICKED(IDC_WRITE, OnWrite)
	ON_BN_CLICKED(IDC_CHECK_ACTIVATEGROUP, OnCheckActivategroup)
	ON_BN_CLICKED(IDC_STOP, OnStop)
	ON_WM_TIMER()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CAsynOpcDlg message handlers

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

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

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

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	changeFlag=readFlag=writeFlag=0;
	SetTimer(1,1000,NULL);
	return TRUE;  // return TRUE  unless you set the focus to a control
}

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

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CAsynOpcDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CAsynOpcDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}
/* 创建远程OPC服务器,添加组对象,添加项,设置回调*/
void CAsynOpcDlg::OnStart() 
{
	// TODO: Add your control notification handler code here
	HRESULT		r1;
	CLSID		clsid;
	LONG		TimeBias = 0;
	FLOAT		PercentDeadband = 0.0;
	DWORD		RevisedUpdateRate;
	CString		szErrorText;
	m_ItemResult = NULL;
	//	初始化COM库
	r1 = CoInitializeEx(NULL,COINIT_MULTITHREADED);
	if (r1 != S_OK)
	{	if (r1 == S_FALSE)
		{
			AfxMessageBox("COM库已经初始化");
		}
		else
		{
			AfxMessageBox("COM库初始化失败");			
			return;
		}
	}	
	//	通过ProgID,查找注册表中的相关CLSID
//	r1 = CLSIDFromProgID(L"Intellution.OPCiFIX", &clsid);//OPCDA.Opc.1
	r1 = CLSIDFromProgID(L"OPCDA.Opc.1", &clsid);
	if (r1 != S_OK)
	{	
		AfxMessageBox("获取CLSID失败");
		CoUninitialize();
		return;
	}
	
	memset(m_arrMultiQI,0,sizeof(m_arrMultiQI));
	m_arrMultiQI [0].pIID		= &IID_IOPCServer;
	m_arrMultiQI [1].pIID		= &IID_IConnectionPointContainer;
	m_arrMultiQI [2].pIID		= &IID_IOPCItemProperties;
	m_arrMultiQI [3].pIID		= &IID_IOPCBrowseServerAddressSpace;
	m_arrMultiQI [4].pIID		= &IID_IOPCServerPublicGroups;
	m_arrMultiQI [5].pIID		= &IID_IPersistFile;
	COSERVERINFO tCoServerInfo;
	ZeroMemory (&tCoServerInfo, sizeof (tCoServerInfo));

	CString m_strRemoteMachine="127.0.0.1";
	int nSize = m_strRemoteMachine.GetLength () * sizeof (WCHAR);
	tCoServerInfo.pwszName = new WCHAR [nSize];
	mbstowcs (tCoServerInfo.pwszName, m_strRemoteMachine, nSize);
	r1 = CoCreateInstanceEx (
				clsid,										// CLSID
				NULL,										// No aggregation
				CLSCTX_REMOTE_SERVER,						// connect to local, inproc and remote servers
				&tCoServerInfo,								// remote machine name 
				sizeof (m_arrMultiQI) / sizeof (MULTI_QI),	// number of IIDS to query		
				m_arrMultiQI);								// array of IID pointers to query

	// COM requires us to free memory allocated for [out] and [in/out]
	// arguments (i.e. name string).
	delete [] tCoServerInfo.pwszName;
	if (r1 == S_FALSE)
	{	
		AfxMessageBox("创建远程OPC服务器对象失败");
		m_IOPCServer = NULL;
		CoUninitialize();
		return;
	}
	if (SUCCEEDED (m_arrMultiQI [0].hr))
	{
		m_IOPCServer = (IOPCServer *)m_arrMultiQI [0].pItf;
	}

	//添加一个group对象,并查询IOPCItemMgt接口
	r1=m_IOPCServer->AddGroup(L"grp1",			//	[in] group name
						TRUE,					//	[in] active
						500,					//	[in] request this Update Rate from Server
						1,						//	[in] Client handle
						&TimeBias,				//	[in] no time interval to system UTC time
						&PercentDeadband,		//	[in] no deadband, so all data changes are reported	
						LOCALE_ID,				//	[in] Server uses English language for text values
						&m_GrpSrvHandle,		//	[out] Server handle to identify this group in later calls
						&RevisedUpdateRate,		//	[out] the answer form the Server to the requested update rate
					    IID_IOPCItemMgt,		//	[in] requested interface type of the group object
						(LPUNKNOWN*)&m_IOPCItemMgt);	//	[out] pointer to the requested interface
	
	if (r1 == OPC_S_UNSUPPORTEDRATE)
	{	
		AfxMessageBox("请求的刷新速率与实际的刷新速率不一致");
	}
	else
		if (FAILED(r1))
		{
			AfxMessageBox("不能为服务器添加group对象");
			m_IOPCServer->Release();
			m_IOPCServer = NULL;
			CoUninitialize();		
			return;
		}

	//	为AddItem定义item表的参数
	m_Items[0].szAccessPath		  = L"";			//	Accesspath not needed
	m_Items[0].szItemID			  = szItemID;		//	ItemID, see above
	m_Items[0].bActive			  = TRUE;			
	m_Items[0].hClient			  = 1;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -