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

📄 opc clientdoc.cpp

📁 一个opc服务器
💻 CPP
📖 第 1 页 / 共 3 页
字号:
         {
            CoTaskMemFree( pErrors );
         }
#endif // FULL_TEST
      }
   }
   else
   {
      OPCAsyncIO opcAsyncIO;
      if( opcAsyncIO.Attach( opcGroup ) == S_OK )
      {
         HRESULT hr = opcAsyncIO.Read(dwConnection1, OPC_DS_CACHE, 1, &pCurrentItem->hServerHandle, &transactionID, &pErrors);
         if( SUCCEEDED(hr) )
         {
            if( FAILED(pErrors[0]) )
            {
               ReportError( _T("Async Read: "), pErrors[0] );
            }
            CoTaskMemFree( pErrors );
         }
         else
         {
            ReportError( _T("Async Read: "), hr );
         }
#ifdef FULL_TEST
         hr = opcAsyncIO.Read(dwConnection1, OPC_DS_DEVICE, 1, &pCurrentItem->hServerHandle, &transactionID, &pErrors);
         if( SUCCEEDED(hr) )
         {
            CoTaskMemFree( pErrors );
         }
         hr = opcAsyncIO.Read(dwConnection1, OPC_DS_CACHE, 1, &pCurrentItem->hServerHandle, &transactionID, &pErrors);
         if( SUCCEEDED(hr) )
         {
            CoTaskMemFree( pErrors );
         }
         // ask for a few this time (it doesn't matter that its the same one)
         OPCHANDLE serverHandles[3];
         for( int i=0; i<3; i++ )
            serverHandles[i] = pCurrentItem->hServerHandle;
         hr = opcAsyncIO.Read(dwConnection1, OPC_DS_DEVICE, 3, serverHandles, &transactionID, &pErrors);
         if( SUCCEEDED(hr) )
         {
            CoTaskMemFree( pErrors );
         }
#endif // FULL_TEST
      }
   }
   UpdateAllViews(NULL);
}

void OPCClientDoc::OnUpdateOpcReaditem(CCmdUI* pCmdUI)
{
   pCmdUI->Enable( opcServer.IsOk() && pCurrentItem );
}

//*******************************************************************
// Refresh causes all items to be advised immediately.
void OPCClientDoc::OnOpcRefresh()
{
   //CWaitCursor wait;
	
	
   if( usingCP )
   {
      OPCAsyncIO2 opcAsyncIO2;
      if( opcAsyncIO2.Attach( opcGroup ) == S_OK )
      {
         // test both Device and Cache data sources
         // This should cause the server to queue a refresh while one is going on.
         transactionID = 2;   // any number the client wants
         HRESULT hr = opcAsyncIO2.Refresh2(OPC_DS_CACHE, transactionID, &transactionID);
         if( FAILED(hr) )
         {
            //ReportError( _T("Refresh2: "), hr );
            return;
         }
   #ifdef FULL_TEST
         transactionID = 3;   // any number the client wants
         hr = opcAsyncIO2.Refresh2(OPC_DS_CACHE, transactionID, &transactionID);
         if( FAILED(hr) )
         {
            //ReportError( _T("Refresh: "), hr );
            return;
         }
   #endif // FULL_TEST
      }
   }
   else
   {
      OPCAsyncIO opcAsyncIO;
      if( opcAsyncIO.Attach( opcGroup ) == S_OK )
      {
         // test both Device and Cache data sources
         // This should cause the server to queue a refresh while one is going on.
         HRESULT hr = opcAsyncIO.Refresh(dwConnection1, OPC_DS_DEVICE, &transactionID);
         if( FAILED(hr) )
         {
            //ReportError( _T("Refresh: "), hr );
            return;
         }
   #ifdef FULL_TEST
         hr = opcAsyncIO.Refresh(dwConnection1, OPC_DS_CACHE, &transactionID);
         if( FAILED(hr) )
         {
            //ReportError( _T("Refresh: "), hr );
            return;
         }
   #endif // FULL_TEST
      }
   }
}

void OPCClientDoc::OnUpdateOpcRefresh(CCmdUI* pCmdUI)
{
   pCmdUI->Enable( opcServer.IsOk() );
}


//*******************************************************************
void OPCClientDoc::OnOpcRemoveitem()
{
   OPCItemMgt itemMgt;
   HRESULT hr = itemMgt.Attach( opcGroup );
   if( SUCCEEDED(hr) )
   {
      HRESULT *pErrors=0;
      OPCHANDLE handle = pCurrentItem->hServerHandle;
      hr = itemMgt.RemoveItems( 1, &handle, &pErrors );
      if( SUCCEEDED(hr) )
         CoTaskMemFree( pErrors );
      POSITION pos = items.Find( pCurrentItem );
      items.RemoveAt( pos );
      delete pCurrentItem;
      pCurrentItem = NULL;
      UpdateAllViews(NULL);
   }
}

void OPCClientDoc::OnUpdateOpcRemoveitem(CCmdUI* pCmdUI)
{
   pCmdUI->Enable( opcServer.IsOk() && pCurrentItem );
}

//*******************************************************************
CString OPCClientDoc::GetErrorString(LPCTSTR description, HRESULT error)
{
   CString temp(description);
   temp += _T(" ");
   TCHAR msg[MAX_PATH*5];
   DWORD ok = FormatMessage( FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
                  NULL,
                  error,
                  MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL),
                  msg, MAX_PATH, NULL );
   if( ok )
   {
      TRACE(msg);
      TRACE(_T("\n"));
      temp += msg;
      return temp;
   }

   // else try the server
   LPWSTR pString = NULL;
   if( opcServer.IsOk() )
   {
      HRESULT hr = opcServer.GetErrorString( error, LOCALE_SYSTEM_DEFAULT, &pString );
      if( SUCCEEDED(hr) )
      {
         temp += pString;
         TRACE(temp);
         CoTaskMemFree( pString );
      }
      else
         temp += _T("OPC Server failed GetErrorString.");
   }
   else
      temp += _T("Unknown Error.");
   return temp;
}

//*******************************************************************
void OPCClientDoc::ReportError(LPCTSTR description, HRESULT error)
{
   CString msg( GetErrorString(description,error) );
   CString appName((LPCSTR)AFX_IDS_APP_TITLE);
   MessageBox(0, msg, appName, MB_OK);
   CString pFileName = "log.txt";
   CFile f;
   CString msd;
   msd = msg + appName;
   
   if( !f.Open( pFileName, CFile::modeCreate | CFile::modeWrite ) ) {
   #ifdef _DEBUG
      afxDump << "Unable to open file" << "\n";
      exit( 1 );
   #endif
}
   CArchive ar(&f, CArchive::store);
   if (ar.IsStoring())
	   ar<< msd;


}

//**************************************************************************
//
// VariantToString() convert the value to String format
//
//**************************************************************************
void VariantToString(VARIANT value, CString& strText)
{
    switch(value.vt)
    {
        case VT_BOOL:
            strText = value.boolVal ? _T("On") : _T("Off");
            break;
        case VT_UI1:
            strText.Format( _T("%hd"), (USHORT)value.bVal );
            break;
        case VT_UI2:
            strText.Format( _T("%d"), value.uiVal );
            break;
		case VT_I1: // 2003-4-30 16:19, kking
			strText.Format( _T("char (%d)"), value.cVal );
            break;
        case VT_I2:
            strText.Format( _T("%hd"), value.iVal );
            break;
        case VT_I4:
            strText.Format( _T("%d"), value.lVal );
            break;
        case VT_UI4:
            strText.Format( _T("%d"), value.ulVal );
            break;
        case VT_R4:
            strText.Format( _T("%g"), value.fltVal );
            break;
        case VT_R8:
            strText.Format( _T("%g"), value.dblVal );
            break;
        case VT_BSTR:
            strText = value.bstrVal;
            break;
        default: // Arrays of simple types
        {
            if( (value.vt & VT_ARRAY)==VT_ARRAY )
            {
                CString temp;
                SAFEARRAY* pArray = value.parray;
                LONG lBound = 0, uBound = 0;
                SafeArrayGetLBound( pArray, 1, &lBound );
                SafeArrayGetUBound( pArray, 1, &uBound );
                for( long element=lBound; element<=uBound; element++ )
                {
                    if( !strText.IsEmpty() )
                        strText += _T(", ");
                    switch( value.vt & ~VT_ARRAY )
                    {
                    case VT_BOOL:
                        {
                            VARIANT_BOOL b=0;
                            SafeArrayGetElement(pArray, &element, &b);
                            temp = b ? _T("1") : _T("0");
                        }
                        break;
                    case VT_UI1:
                        {
                            BYTE b=0;
                            SafeArrayGetElement(pArray, &element, &b);
                            temp.Format( _T("%hd"), b );
                        }
                        break;
                    case VT_UI2:
                    case VT_I2:
                        {
                            short b=0;
                            SafeArrayGetElement(pArray, &element, &b);
                            temp.Format( _T("%hd"), b );
                        }
                        break;
                    case VT_I4:
                        {
                            long b=0;
                            SafeArrayGetElement(pArray, &element, &b);
                            temp.Format( _T("%d"), b );
                        }
                        break;
                    case VT_R4:
                        {
                            float d=0;
                            SafeArrayGetElement(pArray, &element, &d);
                            temp.Format( _T("%g"), d );
                        }
                        break;
                    case VT_R8:
                        {
                            double d=0;
                            SafeArrayGetElement(pArray, &element, &d);
                            temp.Format( _T("%g"), d );
                        }
                        break;
                    case VT_BSTR:
                        {
                            BSTR b;
                            SafeArrayGetElement(pArray, &element, &b);
                            temp = b;
                        }
                        break;
                    }
                    strText += temp;
                }
            }
            else
                strText = _T("?");
        }
    }
}

void OPCClientDoc::OnOpcTestSyncRead() 
{
	//HRESULT *pErrors;
	//CWaitCursor wait;
	// also test sync read since data is returned differently

	/*CTestDlg dlg;
	if(dlg.DoModal() != IDOK)
		return;*/

	/*FILETIME ft_s, ft_e;
	CoFileTimeNow(&ft_s);
	Sleep(1);
	CoFileTimeNow(&ft_e);

	for(unsigned int i = 0; i < dlg.m_nTimes; i ++)
	{
		OPCSyncIO opcSyncIO;
		if( opcSyncIO.Attach( opcGroup ) == S_OK )
		{
			OPCITEMSTATE* pItemState;
			HRESULT hr = opcSyncIO.Read(OPC_DS_DEVICE, 1, &pCurrentItem->hServerHandle, &pItemState, &pErrors);
			if( SUCCEEDED(hr) )
			{
				if( FAILED(pErrors[0]) )
				{
					ReportError( _T("Sync Read: "), pErrors[0] );
					break;
				}
				else
				{
					pCurrentItem->quality = pItemState->wQuality;
					pCurrentItem->value = pItemState->vDataValue;
				}
				VariantClear( &pItemState->vDataValue );
				CoTaskMemFree( pItemState );
				CoTaskMemFree( pErrors );
			}
			else
			{
				ReportError( _T("Sync Read: "), hr );
				break;
			}
		}
	}

	CoFileTimeNow(&ft_e);

	CString tmp;
	CTime ct_s(ft_s);
	int mSec_s = (ft_s.dwLowDateTime % 10000000) / 10000;
	tmp.Format(_T(".%d"), mSec_s);
	CString str_stime = ct_s.Format("%Y-%m-%d %H:%M:%S") + tmp;

	CTime ct_e(ft_e);
	int mSec_e = (ft_e.dwLowDateTime % 10000000) / 10000;
	tmp.Format(_T(".%d"), mSec_e);
	CString str_etime = ct_e.Format("%Y-%m-%d %H:%M:%S") + tmp;

	CTimeSpan tspan = ct_e - ct_s;
	CString strHead;
	strHead.Format(_T("%d Sync read executed in %.3f seconds."),
		dlg.m_nTimes, tspan.GetSeconds() + (mSec_e - mSec_s) / 1000.0);
	AfxMessageBox(strHead + "\r\nStart at: " + str_stime + "\r\nStop at:  " + str_etime);}*/
}

void OPCClientDoc::OnUpdateOpcTestSyncRead(CCmdUI* pCmdUI) 
{
   pCmdUI->Enable( opcServer.IsOk() && pCurrentItem );
}

void OPCClientDoc::OnOpcMisc() 
{
	FILETIME ft_s, ft_e;
	CoFileTimeNow(&ft_s);
	Sleep(1000);
	CoFileTimeNow(&ft_e);
}

void OPCClientDoc::connect()
{
   OnOpcConnect();
   OnOpcAdditem();
   OnOpcReaditem();
   //OnUpdateOpcReaditem(CCmdUI* pCmdUI);
}


void OPCClientDoc::close()
{
   AfxOleUnlockApp();
   if( opcServer.IsOk() )
      OnOpcDisconnect();
   testSink->Release(); // OLE should clean this up, but may not have time!
   callbackCP->Release();
   shutdownCP->Release();
}

⌨️ 快捷键说明

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