OPC客户端的进程安全初始化

  现场OPC客户端无法获取远程OPC Server列表,也无法连接OPC Server,经查调用CoCreateInstanceEx()创建IID_IOPCServerList接口正常,但调用IOPCServerList->EnumClassesOfCategories()时返回0x80070532错误,可是用PI的OPC-Tool测试OPC Server的各项操作正常,于是被迫周末加班一天,发现是未对OPC客户端的进程进行安全初始化造成的:

HRESULT hr = ::CoInitializeSecurity(
		NULL,                    // points to security descriptor
		-1,                     // count of entries in asAuthSvc
		NULL,                    // array of names to register
		NULL,                    // reserved for future use
		RPC_C_AUTHN_LEVEL_NONE, // the default authentication level for proxies
		RPC_C_IMP_LEVEL_IMPERSONATE,// the default impersonation level for proxies
		NULL,                    // used only on Windows 2000
		EOAC_NONE,              // additional client or server-side capabilities
		NULL                     // reserved for future use
		);

  该代码只需要加入到CxxxxApp::InitInstance()中即可。

   如果用Delphi开发的OPC客户端,则可以在主程序的OnCreate事件中调用以下的OPCInitSecurity()函数即可:

function OPCInitSecurity: HResult;
const
  RPC_C_AUTHN_LEVEL_NONE = 1;
  RPC_C_IMP_LEVEL_IMPERSONATE = 3;
  EOAC_NONE = 0;
begin
    Result := CoInitializeSecurity(
	    nil,                    // points to security descriptor
	    -1,                     // count of entries in asAuthSvc
	    nil,                    // array of names to register
	    nil,                    // reserved for future use
	    RPC_C_AUTHN_LEVEL_NONE, // the default authentication level for proxies
	    RPC_C_IMP_LEVEL_IMPERSONATE,// the default impersonation level for proxies
	    nil,                    // used only on Windows 2000
	    EOAC_NONE,              // additional client or server-side capabilities
	    nil                     // reserved for future use
	    );
end;

  

  总结:

  1. 周末加班很郁闷,独自一个人加班更加郁闷;
  2. PI OPC-Tool界面很丑陋,但兼容性很强大,多次发现我们的OPC客户端无法正常工作,PI OPC-Tool畅通无阻,搞得现在现场OPC客户端一出现问题,工程师先用这个工具测试,正常,找我;不正常,自己鼓捣先;
  3. 通过DCOM访问OPC Server必须调用CoInitializeSecurity(),否则在不同的计算机上可能会出现不同的错误现象,但根源问题殊途同归;
  4. OPC工业现场必备垃圾;
原文地址:https://www.cnblogs.com/heqing/p/3562031.html