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

📄 group.cpp

📁 KepWare的OPC Client 示例.面向C
💻 CPP
📖 第 1 页 / 共 5 页
字号:

	// There is no sence in building a request unless we are connected to
	// the OPC Server and have a pointer to the IOPCAsyncIO interface.
	if (m_pServer->IsConnected () && m_pIAsync)
		{
		ASSERT (m_dwCookieRead != 0);
	
		OPCDATASOURCE dwSource	= bDeviceRead ? OPC_DS_DEVICE : OPC_DS_CACHE;
		DWORD dwTransID = 0;
		HRESULT hr = E_FAIL;

		// Wrap request processing in exception hander in case we get
		// a bad pointer - Not really needed in this case, but this keeps
		// same code structure as other operations:
		try
			{
			// Issue refresh request using IOPCAsyncIO interface:
			hr = m_pIAsync->Refresh (
					m_dwCookieRead,	// Cookie returned from DAdvise
					dwSource,		// Source (device or cache)
					&dwTransID);	// Server generated transaction id

			// Log results:
			if (SUCCEEDED (hr))
				{
				// Log request succeeded message.  Log different message for device and
				// cache refres.
				LogMsg (bDeviceRead ? IDS_ASYNC10_REFRESHDEVICE_SUCCESS : IDS_ASYNC10_REFRESHCACHE_SUCCESS, 
					dwTransID, GetName ());
				}
			else
				{
				// Log request faild messgae.  Log different message for device and 
				// cache refreshes:
				LogMsg (bDeviceRead ? IDS_ASYNC10_REFRESHDEVICE_FAILURE : IDS_ASYNC10_REFRESHCACHE_FAILURE, 
					GetName (), hr);
				}
			}
		
		catch (...)
			{
			// Probably hit a bad pointer.  Try to process next item.
			TRACE (_T("OTC: RefreshAsync10 exception handler invoked\r\n"));

			if (m_pServer->IsConnected ())
				{
				// We not disconnected so why was an exception thrown?
				ASSERT (FALSE);
				}
			}
		}
	}

// **************************************************************************
// WriteAsync10 ()
//
// Description:
//	Perform an asynchronous 1.0 write for specified items.
//
// Parameters:
//	CObArray		&cItemList	Array of items to read.
//	CStringArray	&cValues	Array of values to write.
//	DWORD			cdwItems	Number of items in cItemList.
//
// Returns:
//  void
// **************************************************************************
void CKGroup::WriteAsync10 (CObArray &cItemList, CStringArray &cValues, DWORD cdwItems)
	{
	ASSERT (cdwItems > 0);
	
	// There is no sence in building a request unless we are connected to
	// the OPC Server and have a pointer to the IOPCAsyncIO interface.
	if (m_pServer->IsConnected () && m_pIAsync)
		{
		ASSERT (m_dwCookieWrite != 0);

		DWORD dwIndex		= 0;
		CKItem *pItem		= NULL;
		OPCHANDLE *phServer = NULL;
		VARIANT *pValues	= NULL;
		HRESULT *pErrors	= NULL;
		HRESULT hr			= E_FAIL;
		DWORD dwTransID		= 0;
		DWORD cdwSuccess	= 0;
		DWORD cdwSentItems  = 0;

		// Allocate storage for server item handles and write values:
		phServer = (OPCHANDLE *) CoTaskMemAlloc (cdwItems * sizeof (OPCHANDLE));
		pValues = (VARIANT *) CoTaskMemAlloc (cdwItems * sizeof (VARIANT));

		// Return if allocation failed:
		if (phServer == NULL || pValues == NULL)
			{
			ASSERT (FALSE);
			return;
			}

		// Fill request [in] arguments:
		for (dwIndex = 0, cdwSentItems = 0; dwIndex < cdwItems; dwIndex++)
			{
			// Get pointer to item in input list:
			CKItem *pItem = (CKItem *) cItemList [dwIndex];
			ASSERT (pItem != NULL);

			// Load data for array type:
			if (pItem->GetDataType () & VT_ARRAY)
				{
				// Convert array values in string format to variant array.  If succeed,
				// set server handle:
				if (MapStringValToArrayVariant (cValues [cdwSentItems], pItem->GetValue (), &pValues [cdwSentItems]))
					phServer [cdwSentItems++] = pItem->GetServerHandle ();
				else
					{
					// Failed to convert array values in string format to variant array:
					LogMsg (IDS_WRITE_DATA_MAP_FAILED, pItem->GetItemID ());

					// Invalidate item:
					cItemList [dwIndex] = NULL;
					}
				}

			// Load data for non-array type:
			else
				{
				// Convert value in string format to variant.  If succeed, set server
				// handle:
				if (MapStringValToVariant (cValues [cdwSentItems], pValues [cdwSentItems], pItem->GetDataType ()))
					phServer [cdwSentItems++] = pItem->GetServerHandle ();
				else
					{
					// Failed ot convert value in string format to variant:
					LogMsg (IDS_WRITE_DATA_MAP_FAILED, pItem->GetItemID ());

					// Invalidate item:
					cItemList [dwIndex] = NULL;
					}
				}
			}
		
		// Wrap request processing in execption handler in case we get
		// a bad pointer:
		try
			{
			// Issue write request using IOPCAsyncIO interface:
			hr = m_pIAsync->Write (
					m_dwCookieWrite,	// DAdvise cookie returned by server for writes
					cdwSentItems,		// Number of items to write
					phServer,			// Server item handles
					pValues,			// Item data to write
					&dwTransID,			// [out] server assigned transaction ID for this request
					&pErrors);			// [out] error results

			// Check results:
			for (dwIndex = 0, cdwSentItems = 0; dwIndex < cdwSentItems; dwIndex++)
				{
				// Get pointer to item in input list:
				CKItem *pItem = (CKItem *) cItemList [dwIndex];
				
				// Continue to next item if we invalidated current item above in
				// MapStringToVariant() failure:
				if (pItem == NULL)
					continue;

				// Request succeeded and there were no errors:
				if (SUCCEEDED (hr) && (pErrors && SUCCEEDED (pErrors [cdwSentItems])))
					{
					// Increment the successful write counter:
					++cdwSuccess;
					}

				// Failure:
				else
					{
					// Request succeeded, but on or more items could not be written to:
					if (pErrors && FAILED (pErrors [cdwSentItems]))
						{
						// Log error message with error code.  (Could use GetErrorString()
						// to get user friendly error string if we wish.)
						LogMsg (IDS_ASYNC10_WRITE_FAILED, pItem->GetItemID (), GetName (),
							pErrors [cdwSentItems]);
						}

					// Request failed:
					else
						{
						// Log error message with error code.  (Could use GetErrorString()
						// to get user friendly error string if we wish.)
						LogMsg (IDS_ASYNC10_WRITE_FAILED, pItem->GetItemID (), GetName (), hr);
						}
					}

				// Increment sent items counter:
				cdwSentItems++;
				}
			}
		
		catch (...)
			{
			// Probably hit a bad pointer.  Try to process next item.
			TRACE (_T("OTC: WriteAsync10 exception handler invoked\r\n"));

			if (m_pServer->IsConnected ())
				{
				// We not disconnected so why was an exception thrown?
				ASSERT (FALSE);
				}
			}

		// COM requires us to free memory allocated for [out] and [in/out]
		// arguments (i.e. phServer, pValues, and pErrors):
		CoTaskMemFree (phServer);
		CoTaskMemFree (pValues);

		if (pErrors)
			CoTaskMemFree (pErrors);

		// Log success status:
		if (cdwSuccess > 0)
			LogMsg (IDS_ASYNC10_WRITE_SUCCESS, dwTransID, cdwSuccess, GetName ());
		}
	}

// **************************************************************************
// ReadAsync20 ()
//
// Description:
//	Perform an asynchronous 2.0 read for specified items.
//
// Parameters:
//	CObArray	&cItemList		Array of items to read.
//	DWORD		cdwItems		Number of items in cItemList.
//
// Returns:
//  void
// **************************************************************************
void CKGroup::ReadAsync20 (CObArray &cItemList, DWORD cdwItems)
	{
	ASSERT (cdwItems > 0);
	
	// There is no sence in building a request unless we are connected to
	// the OPC Server and have a pointer to the IOPCAsyncIO2 interface.
	if (m_pServer->IsConnected () && m_pIAsync2)
		{
		ASSERT (m_dwCookieDataSink20 != 0);

		DWORD dwIndex			= 0;
		CKItem *pItem			= NULL;
		OPCHANDLE *phServer		= NULL;
		DWORD dwClientTransID	= GetTickCount ();	// client provided transaction for notifications (not useful right now)
		DWORD dwCancelTransID	= 0;
		HRESULT *pErrors		= NULL;
		HRESULT hr				= E_FAIL;
		DWORD cdwSuccess		= 0;

		// Allocate storage for server item handles:
		phServer = (OPCHANDLE *) CoTaskMemAlloc (cdwItems * sizeof (OPCHANDLE));

		// Return if allocation failed:
		if (phServer == NULL)
			{
			ASSERT (FALSE);
			return;
			}

		// Fill request [in] arguments:
		for (dwIndex = 0; dwIndex < cdwItems; dwIndex++)
			{
			// Get pointer to item in input list:
			CKItem *pItem = (CKItem *) cItemList [dwIndex];
			ASSERT (pItem != NULL);

			// Set server handle:
			phServer [dwIndex] = pItem->GetServerHandle ();
			}

		// Wrap request processing in exception hander in case we get
		// a bad pointer:
		try
			{
			// Issue read request using IOPCAsyncIO2 interface:
			hr = m_pIAsync2->Read 
					(cdwItems,			// Number of items requested
					phServer,			// Item server handles	
					dwClientTransID,	// Client generated transaction id received in callback
					&dwCancelTransID,	// Server generated transaction id used for canceling this xact
					&pErrors);

			// Check results:
			for (dwIndex = 0; dwIndex < cdwItems; dwIndex++)
				{
				// Get pointer to item in input list:
				CKItem *pItem = (CKItem *) cItemList [dwIndex];
				ASSERT (pItem != NULL);

				// Request succeeded and there were no errors:
				if (SUCCEEDED (hr) && (pErrors && SUCCEEDED (pErrors [dwIndex])))
					{
					// Increment the successful read counter:
					++cdwSuccess;
					}

				// Failure:
				else
					{
					// Request succeeded, but one or more items could not be read:
					if (pErrors && FAILED (pErrors [dwIndex]))
						{
						// Log error message with error code.  (Could use GetErrorString()
						// to get user friendly error string if we wish.)
						LogMsg (IDS_ASYNC20_READ_FAILED,
							pItem->GetItemID (), GetName (), pErrors [dwIndex]);
						}

					// Request failed:
					else
						{
						// Log error message with error code.  (Could use GetErrorString()
						// to get user friendly error string if we wish.)
						LogMsg (IDS_ASYNC20_READ_FAILED,
							pItem->GetItemID (), GetName (), hr);
						}
					}
				}

			}
		
		catch (...)
			{
			// Probably hit a bad pointer.  Try to process next item.
			TRACE (_T("OTC: ReadAsync20 exception handler invoked\r\n"));

			if (m_pServer->IsConnected ())
				{
				// We not disconnected so why was an exception thrown?
				ASSERT (FALSE);
				}
			}

		// COM requires us to free memory allocated for [out] and [in/out]
		// arguments (i.e. phServer, and pErrors):
		CoTaskMemFree (phServer);

		if (pErrors)
			CoTaskMemFree (pErrors);

		// Log success status:
		if (cdwSuccess > 0)
			LogMsg (IDS_ASYNC20_READ_SUCCESS, dwClientTransID, cdwSuccess, GetName ());
		}
	}

// **************************************************************************
// RefreshAsync20 ()
//
// Description:
//	Perform an asynchronous 2.0 refresh.
//
// Parameters:
//	bool		bDeviceRead		Set to true to perform device refresh, false
//								  for cache refresh.	
//
// Returns:
//  void 
// **************************************************************************
void CKGroup::RefreshAsync20 (bool bDeviceRead)
	{
	ASSERT (m_cdwItems > 0);
	
	// There is no sence in building a request unless we are connected to
	// the OPC Server and have a pointer to the IOPCAsyncIO2 interface.
	if (m_pServer->IsConnected () && m_pIAsync2)
		{
		ASSERT (m_dwCookieDataSink20 != 0);

		OPCDATASOURCE dwSource	= bDeviceRead ? OPC_DS_DEVICE : OPC_DS_CACHE;
		DWORD dwCancelTransID		= 0;
		DWORD dwClientTransID		= GetTickCount ();	// client provided transaction for notifications (not useful right now)
		HRESULT hr = E_FAIL;

		// Wrap request processing in exception hander in case we get
		// a bad pointer - Not really needed in this case, but this keeps
		// same code structure as other operations:
		try
			{
			// Issue refresh request using IOPCAsyncIO2 interface:
			hr = m_pIAsync2->Refresh2 (
				dwSource,			// Source (device or cache)
				dwClientTransID,	// Client generated transaction id received in callback
				&dwCancelTransID);	// Server generated transaction id used for canceling this xact

			// Log results:
			if (SUCCEEDED (hr))
				{
				// Log request succeeded message.  Log different message for device and
				// cache refres.
				LogMsg (bDeviceRead ? IDS_ASYNC20_REFRESHDEVICE_SUCCESS : IDS_ASYNC20_REFRESHCACHE_SUCCESS, 
					dwClientTransID, GetName ());
				}
			else
				{
				// Log request faild messgae.  Log different message for device and 
				// cache refreshes:
				LogMsg (bDeviceRead ? IDS_ASYNC20_REFRESHDEVICE_FAILURE : IDS_ASYNC20_REFRESHCACHE_FAILURE, 
					GetName (), hr);
				}
			}
		
		catch (...)
			{
			// Probably hit a bad pointer.  Try to process next item.
			TRACE (_T("OTC: RefreshAsync20 exception handler invoked\r\n"));

			if (m_pServer->IsConnected ())
				{
				// We not disconnected so why was an exception thrown?
				ASSERT (FALSE);
				}
			}
		}
	}

// **************************************************************************
// WriteAsync20 ()

⌨️ 快捷键说明

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