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

📄 serverinfoview_2.cpp

📁 VisualC++通信编程工程实例精解 Chapter 2 Example 1 MSCOMM控件编程实例 Example 2 基于Windows API的虚拟终端实现 Example 3
💻 CPP
📖 第 1 页 / 共 2 页
字号:
						else
						{
						HTREEITEM curHandle = AddV1ItemToTree(*pServerInfo);
						if( curHandle!=0 )
							pServerInfo->m_indexItem = curHandle;
						}
						CoTaskMemFree(pszProgID);
						CoTaskMemFree(pszUserType);
					}
				}//end of "for...
          }while ( hr==S_OK );
          pEnumGUID->Release();
          pServers->Release();
          return TRUE;
       }
       else // hr failed
       {
			CString msg(_T("EnumClassesOfCategories failed:"));
			m_pInfoForm->ShowInfoToList(WENHAO,strDateTime,msg);
			pServers->Release();
       }
       //pServers->Release();
   }
   return TRUE;
}

/***********************************************
     取到所有的注册表形式的OPC Server 1.0   
************************************************/
BOOL CServerInfoView::GetOPCServers10(LPTSTR node)
{
    USES_CONVERSION;//使用T2OLE()

   HKEY hk = HKEY_CLASSES_ROOT;
   if( node )
   {
      DWORD dwR = RegConnectRegistry ((LPTSTR)node, HKEY_CLASSES_ROOT, &hk);
      if( dwR != ERROR_SUCCESS )
         return FALSE;
   }

   TCHAR key[MAX_KEYLEN];
   DWORD size = MAX_KEYLEN;
   FILETIME ft;
   for( int index=0; RegEnumKeyEx(hk, index, key, &size, 0, NULL, NULL, &ft)==ERROR_SUCCESS; index++)
   {
      HKEY hProgID=0;
      if(RegOpenKeyEx(hk, key, 0, KEY_QUERY_VALUE, &hProgID )==ERROR_SUCCESS )
      {
         // Find OPC key
         HKEY hOPC=0;
         if(RegOpenKeyEx(hProgID, _T("OPC"), 0, KEY_QUERY_VALUE, &hOPC)==ERROR_SUCCESS )
         {
            // Found OPC key, save this information
            CLSID clsid;
            DWORD type=REG_SZ;
            HKEY hCLSID=0;
            if(RegOpenKeyEx(hProgID, _T("CLSID"), 0, KEY_QUERY_VALUE, &hCLSID)==ERROR_SUCCESS )
            {
                TCHAR clsidString[MAX_KEYLEN];
                size=MAX_KEYLEN;
                if(RegQueryValueEx(hCLSID, key, 0, &type, (BYTE*)clsidString, &size )==ERROR_SUCCESS )
                {
					HRESULT hr;
                    hr = CLSIDFromString( T2OLE(clsidString), &clsid );
                    if( FAILED(hr))
                    {
						MessageBox( _T("CLSIDFromString: "),"错误信息",MB_OK|MB_ICONINFORMATION );
						continue;
                    }
                }
				else//将ProgID转换成clsid
					CLSIDFromProgID(T2OLE(key),&clsid);
            }//end of if( RegOpenKeyEx(hProgID...
			if( FindThisCLSID(node,clsid)==FALSE )
			{
				TCHAR desc[MAX_KEYLEN];
				size=MAX_KEYLEN;
				RegQueryValueEx(hOPC, key, 0, &type, (BYTE*)desc, &size);
				OPCServerInfo* pServerInfo = new OPCServerInfo(T2OLE(key), L"", clsid );
				pServerInfo->m_nodeName = node;
				m_vServers.AddTail( pServerInfo );
				//填入树中
				HTREEITEM curHandle = AddV1ItemToTree(*pServerInfo);
				if( curHandle!=0 )
					pServerInfo->m_indexItem = curHandle;
				RegCloseKey( hOPC );
			}
         }
         RegCloseKey( hProgID );
      }
      size = MAX_KEYLEN;
   }//end of "for...
	//RegCloseKey( hk );

   return TRUE;
}

//找到当前选择的OPC服务器的信息.
OPCServerInfo *CServerInfoView::GetSelectedServerInfo(void)
{
	OPCServerInfo *pInfo = NULL;
	HTREEITEM item = m_server.GetSelectedItem();
	if( item==NULL )return pInfo;
	POSITION pos = m_vServers.GetHeadPosition();
	while( pos )
	{
		OPCServerInfo* pServerInfo = m_vServers.GetNext(pos);
		if( pServerInfo->m_indexItem==item )
		{
			pInfo = pServerInfo;
			break;
		}
	}
	return pInfo;
}


//连接OPC服务器
BOOL CServerInfoView::ConnectOPCServer(OPCServerInfo *pServer)
{
	USES_CONVERSION;
	ASSERT( !opcServer.IsOk() );
	HRESULT hr = S_OK;
	CWaitCursor wait;
   // Create a running object from the class ID
   // (CLSCTX_ALL will allow in-proc, local and remote)
   LPUNKNOWN pUnkn = NULL;
   if( pServer->m_nodeName.CompareNoCase(m_strLocalName)==0 )//local
   {
      hr = CoCreateInstance(pServer->m_clsid, NULL, CLSCTX_ALL, IID_IUnknown, (LPVOID *)&pUnkn);
      if( FAILED(hr) || pUnkn == NULL)
      {
         CString msg;
         msg.Format("CoCreateInstance:Error connecting to OPC server %s.", pServer->m_nodeName );
		 m_pInfoForm->ShowInfoToList(GANTANHAO,1,msg);
         return FALSE;
      }
   }
   else  // use the node name
   {
      COSERVERINFO si;
      MULTI_QI  qi;

      si.dwReserved1 = 0;
	  //notice:hehj GetBuffer(0)
      si.pwszName = T2OLE(pServer->m_nodeName.GetBuffer(0));
      si.pAuthInfo = NULL;
      si.dwReserved2 = 0;

      qi.pIID = &IID_IOPCServer;
      qi.pItf = NULL;
      qi.hr = 0;

      hr = CoCreateInstanceEx(pServer->m_clsid, NULL, CLSCTX_REMOTE_SERVER, &si, 1, &qi);
      if (FAILED(hr)||FAILED(qi.hr))
      {
         CString msg;
         msg.Format("CoCreateInstance:Error connecting to OPC server %s.", pServer->m_nodeName );
		 m_pInfoForm->ShowInfoToList(GANTANHAO,1,msg);
         return FALSE;
      }
       pUnkn = qi.pItf;
   }

   // Get the IOPCServer interface.
   hr = opcServer.Attach( pUnkn );
   pUnkn->Release();  // Don't need this anymore.
   pUnkn = NULL;
   if( FAILED(hr) )
   {
      CString appName((LPCSTR)AFX_IDS_APP_TITLE);
      MessageBox(_T("You may not have registered the OPC Proxy dll!\n"), appName, MB_OK);
      return FALSE;
   }
   else
   {
		m_bHaveOPCConnected = TRUE;
		return TRUE;
	}
}

//设置连接点。创建组
void CServerInfoView::SetConnectPoint(void)
{
	HRESULT hr = S_OK;
	hr = AtlAdvise( opcServer, shutdownCP->GetUnknown(),IID_IOPCShutdown, &dwShutdownConnection );

   // Create a single group that will contain all the items
   FLOAT deadband = 0.0;
   DWORD rate;
   hr = opcServer.AddGroup( L"OPCNet", TRUE, 2000,  // name, active, rate
                             1324, NULL, &deadband,  // handle, bias, band
                             0, &groupHandle, &rate,
                             IID_IOPCGroupStateMgt,   // interface to return
                             opcGroup );              // this holds the group ptr
   if( FAILED(hr) )
   {
	   m_pInfoForm->ShowInfoToList(GANTANHAO,1,"创建组失败");
		return;
   }

   // OPC 2.0 ConnectionPoints
   hr = AtlAdvise( opcGroup, callbackCP->GetUnknown(),IID_IOPCDataCallback, &dwConnection1 );
   if( SUCCEEDED(hr) )  // This server supports 2.0
      usingCP = TRUE;

   if( !usingCP )
   {
      // OPC 1.0 data advise format
      FORMATETC formatEtc ;
      formatEtc.tymed =  TYMED_HGLOBAL;
      formatEtc.ptd = NULL;
      formatEtc.dwAspect = DVASPECT_CONTENT;
      formatEtc.lindex = -1;
      // IAdviseSink is an interface on OUR object that is passed to
      // the server for callbacks
      IAdviseSink *pAdviseSink = NULL;
      hr = testSink->QueryInterface(IID_IAdviseSink, (LPVOID *)&pAdviseSink);
      if( FAILED(hr) )
      {
		m_pInfoForm->ShowInfoToList(GANTANHAO,1,"IAdviseSink error");
         opcGroup.Detach();
         opcServer.Detach();
         return;
      }

      // Get an IDataObject interface on the group
      DataObject dataObject;
      hr = dataObject.Attach( opcGroup );
      if(FAILED(hr) || !dataObject.IsOk() )
      {
         //  some servers don't do this, so don't quit altogether
         MessageBox( _T("IDataObject not supported by this server\nNo data notifications will take place"), _T("H504"), MB_OK );
         return;
      }

      // Register our IAdvise with the group
      // Need to register both formats: data change, and write complete
      formatEtc.cfFormat = OPCSTMFORMATWRITECOMPLETE ;
      hr = dataObject.DAdvise(&formatEtc,
                                ADVF_PRIMEFIRST,    // ADVF flag
                                pAdviseSink,
                                &dwConnection2);
      if( FAILED(hr) )
      {
  		m_pInfoForm->ShowInfoToList(GANTANHAO,1,"IDataObject::DAdvise: ");
         return;
      }

#ifdef DATATIMEFORMAT
      formatEtc.cfFormat = OPCSTMFORMATDATATIME ;
#else
      formatEtc.cfFormat = OPCSTMFORMATDATA ;
#endif // DATATIMEFORMAT
      hr = dataObject.DAdvise(&formatEtc,
                                ADVF_PRIMEFIRST,    // ADVF flag
                                pAdviseSink,
                                &dwConnection1);
      pAdviseSink->Release();
      if( FAILED(hr) )
      {
  		m_pInfoForm->ShowInfoToList(GANTANHAO,1,"IDataObject::DAdvise: ");
         return;
      }
   }
}

⌨️ 快捷键说明

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