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

📄 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()
	ON_BN_CLICKED(IDC_RADIO_GROUP1, OnRadioGroup1)
	ON_BN_CLICKED(IDC_RADIO_GROUP2, OnRadioGroup2)
	//}}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 = CoInitialize(NULL);
	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;
	}
	//创建OPC服务器对象,并查询对象的IID_IOPCServer接口
	r1 = CoCreateInstance (clsid, NULL, CLSCTX_LOCAL_SERVER ,IID_IOPCServer, (void**)&m_IOPCServer);
	if (r1 != S_OK)
	{	
		AfxMessageBox("创建OPC服务器对象失败");
		m_IOPCServer = NULL;
		CoUninitialize();
		return;
	}
	//添加一个group对象,并查询IOPCItemMgt接口
	r1=m_IOPCServer->AddGroup(L"grp1",			//	[in] group name
						FALSE,					//	[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			  = szItemID0;		//	ItemID, see above
	m_Items[0].bActive			  = TRUE;			
	m_Items[0].hClient			  = 1;
	m_Items[0].dwBlobSize		  = 0;
	m_Items[0].pBlob			  = NULL;
	m_Items[0].vtRequestedDataType = 0;				//	return values in native (cannonical) datatype 
													//	defined by the item itself

	r1 = m_IOPCItemMgt->AddItems(1,				   //	[in] add one item
							m_Items,				//	[in] see above
							&m_ItemResult,			//	[out] array with additional information about the item
							&m_pErrors);			//	[out] tells which of the items was successfully added.
													//	For any item which failed it provides a reason

	if ( (r1 != S_OK) && (r1 != S_FALSE) )
	{	
		AfxMessageBox("AddItems失败");		
		m_IOPCItemMgt->Release();
		m_IOPCItemMgt = NULL;
		m_GrpSrvHandle = NULL;
		m_IOPCServer->Release();
		m_IOPCServer = NULL;
		CoUninitialize();		
		return;
	}
	else if(r1==S_OK)
	{	
		AfxMessageBox("第一个Group-AddItems()成功");		
	}
	
	//	检测Item的可读写性
	if (m_ItemResult[0].dwAccessRights != (OPC_READABLE + OPC_WRITEABLE))
	{
		AfxMessageBox("Item不可读,也不可写,请检查服务器配置");
	}
	
	//添加第二个group对象,并查询IOPCItemMgt接口
	r1=m_IOPCServer->AddGroup(L"grp2",			//	[in] group name
						TRUE,					//	[in] active
						1000,					//	[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;
		}
	else
	{
		r1 = m_IOPCItemMgt->AddItems(1,				   //	[in] add one item
							m_Items,				//	[in] see above
							&m_ItemResult,			//	[out] array with additional information about the item
							&m_pErrors);			//	[out] tells which of the items was successfully added.
													//	For any item which failed it provides a reason

		if ( (r1 != S_OK) && (r1 != S_FALSE) )
		{	
			AfxMessageBox("AddItems失败");		
			m_IOPCItemMgt->Release();
			m_IOPCItemMgt = NULL;
			m_GrpSrvHandle = NULL;
			m_IOPCServer->Release();
			m_IOPCServer = NULL;
			CoUninitialize();		
			return;
		}
		else if(r1==S_OK)
		{	
			AfxMessageBox("第二个Group-AddItems()成功");		
		}
	}
	
	//查询group对象的异步接口
	r1 = m_IOPCItemMgt->QueryInterface(IID_IOPCAsyncIO2, (void**)&m_IOPCAsyncIO2);
	if (r1 < 0)
	{	
		AfxMessageBox("IOPCAsyncIO2没有发现,错误的查询!");
		CoTaskMemFree(m_ItemResult);
		m_IOPCItemMgt->Release();
		m_IOPCItemMgt = NULL;
		m_GrpSrvHandle = NULL;
		m_IOPCServer->Release();
		m_IOPCServer = NULL;
		CoUninitialize();
		return;
	}	
	//获得IOPCGroupStateMgt接口

⌨️ 快捷键说明

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