//====================================================================== // IOpcFactory /// <summary> /// Creates a new instance of the server. /// </summary> public override IOpcServer CreateInstance(OpcUrl url, OpcConnectData connectData) { object comServer = Connect(url, connectData); if (comServer == null) { return(null); } Server server = null; Type interfaceType = null; try { if (String.IsNullOrEmpty(url.Scheme)) { throw new NotSupportedException(String.Format("The URL scheme '{0}' is not supported.", url.Scheme)); } // DA else if (url.Scheme == OpcUrlScheme.DA) { // Verify that it is a DA server. if (!typeof(OpcRcw.Da.IOPCServer).IsInstanceOfType(comServer)) { interfaceType = typeof(OpcRcw.Da.IOPCServer); throw new NotSupportedException(); } // DA 3.00 if (!ForceDa20Usage && typeof(OpcRcw.Da.IOPCBrowse).IsInstanceOfType(comServer) && typeof(OpcRcw.Da.IOPCItemIO).IsInstanceOfType(comServer)) { server = new Technosoftware.DaAeHdaClient.Com.Da.Server(url, comServer); } // DA 2.XX else if (typeof(OpcRcw.Da.IOPCItemProperties).IsInstanceOfType(comServer)) { server = new Technosoftware.DaAeHdaClient.Com.Da20.Server(url, comServer); } else { interfaceType = typeof(OpcRcw.Da.IOPCItemProperties); throw new NotSupportedException(); } } // AE else if (url.Scheme == OpcUrlScheme.AE) { // Verify that it is a AE server. if (!typeof(OpcRcw.Ae.IOPCEventServer).IsInstanceOfType(comServer)) { interfaceType = typeof(OpcRcw.Ae.IOPCEventServer); throw new NotSupportedException(); } server = new Technosoftware.DaAeHdaClient.Com.Ae.Server(url, comServer); } // HDA else if (url.Scheme == OpcUrlScheme.HDA) { // Verify that it is a HDA server. if (!typeof(OpcRcw.Hda.IOPCHDA_Server).IsInstanceOfType(comServer)) { interfaceType = typeof(OpcRcw.Hda.IOPCHDA_Server); throw new NotSupportedException(); } server = new Technosoftware.DaAeHdaClient.Com.Hda.Server(url, comServer); } // All other specifications not supported yet. else { throw new NotSupportedException(String.Format("The URL scheme '{0}' is not supported.", url.Scheme)); } } catch (NotSupportedException e) { Utilities.Interop.ReleaseServer(server); server = null; if (interfaceType != null) { StringBuilder message = new StringBuilder(); message.AppendFormat("The COM server does not support the interface "); message.AppendFormat("'{0}'.", interfaceType.FullName); message.Append("\r\n\r\nThis problem could be caused by:\r\n"); message.Append("- incorrectly installed proxy/stubs.\r\n"); message.Append("- problems with the DCOM security settings.\r\n"); message.Append("- a personal firewall (sometimes activated by default).\r\n"); throw new NotSupportedException(message.ToString()); } throw e; } catch (Exception e) { Utilities.Interop.ReleaseServer(server); server = null; throw e; } // initialize the wrapper object. if (server != null) { server.Initialize(url, connectData); } return(server); }
/// <summary> /// Initializes the object with a factory and a default OpcUrl. /// </summary> /// <param name="factory">The OpcFactory used to connect to remote servers.</param> /// <param name="url">The network address of a remote server.</param> public TsCAeServer(OpcFactory factory, OpcUrl url) : base(factory, url) { }
/// <summary> /// Connects to the specified COM server. /// </summary> public static object Connect(OpcUrl url, OpcConnectData connectData) { // parse path to find prog id and clsid. string progID = url.Path; string clsid = null; int index = url.Path.IndexOf('/'); if (index >= 0) { progID = url.Path.Substring(0, index); clsid = url.Path.Substring(index + 1); } // look up prog id if clsid not specified in the url. Guid guid; if (clsid == null) { // use OpcEnum to lookup the prog id. guid = new ServerEnumerator().CLSIDFromProgID(progID, url.HostName, connectData); // check if prog id is actually a clsid string. if (guid == Guid.Empty) { try { guid = new Guid(progID); } catch { throw new OpcResultException(new OpcResult((int)OpcResult.CO_E_CLASSSTRING.Code, OpcResult.FuncCallType.SysFuncCall, null), String.Format("Could not connect to server {0}", progID)); } } } // convert clsid string to a guid. else { try { guid = new Guid(clsid); } catch { throw new OpcResultException(new OpcResult((int)OpcResult.CO_E_CLASSSTRING.Code, OpcResult.FuncCallType.SysFuncCall, null), String.Format("Could not connect to server {0}", progID)); } } // get the credentials. OpcUserIdentity credentials = (connectData != null) ? connectData.UserIdentity : null; // instantiate the server using CoCreateInstanceEx. if (connectData == null || connectData.LicenseKey == null) { try { return(Utilities.Interop.CreateInstance(guid, url.HostName, credentials)); } catch (Exception e) { throw new OpcResultException(OpcResult.CO_E_CLASSSTRING, e.Message, e); } } // instantiate the server using IClassFactory2. else { try { return(null); //return Technosoftware.DaAeHdaClient.Utilities.Interop.CreateInstanceWithLicenseKey(guid, url.HostName, credentials, connectData.LicenseKey); } catch (Exception e) { throw new OpcResultException(OpcResult.CO_E_CLASSSTRING, e.Message, e); } } }
/// <summary> /// Reads the server details from the enumerator. /// </summary> OpcUrl CreateUrl(OpcSpecification specification, Guid clsid) { // initialize the server url. OpcUrl url = new OpcUrl(); url.HostName = m_host; url.Port = 0; url.Path = null; if (specification == OpcSpecification.OPC_DA_30) { url.Scheme = OpcUrlScheme.DA; } else if (specification == OpcSpecification.OPC_DA_20) { url.Scheme = OpcUrlScheme.DA; } else if (specification == OpcSpecification.OPC_DA_10) { url.Scheme = OpcUrlScheme.DA; } else if (specification == OpcSpecification.OPC_AE_10) { url.Scheme = OpcUrlScheme.AE; } else if (specification == OpcSpecification.OPC_HDA_10) { url.Scheme = OpcUrlScheme.HDA; } try { // fetch class details from the enumerator. string progID = null; string description = null; string verIndProgID = null; m_server.GetClassDetails( ref clsid, out progID, out description, out verIndProgID); // create the server URL path. if (verIndProgID != null) { url.Path = String.Format("{0}/{1}", verIndProgID, "{" + clsid.ToString() + "}"); } else if (progID != null) { url.Path = String.Format("{0}/{1}", progID, "{" + clsid.ToString() + "}"); } } catch (Exception) { // bad value in registry. } finally { // default to the clsid if the prog is not known. if (url.Path == null) { url.Path = String.Format("{0}", "{" + clsid.ToString() + "}"); } } // return the server url. return(url); }
/// <summary> /// Returns a list of servers that support the specified specification on the specified host. /// </summary> public OpcServer[] GetAvailableServers(OpcSpecification specification, string host, OpcConnectData connectData) { lock (this) { NetworkCredential credentials = (connectData != null)?connectData.GetCredential(null, null):null; // connect to the server. m_server = (IOPCServerList2)Interop.CreateInstance(CLSID, host, credentials); m_host = host; try { ArrayList servers = new ArrayList(); // convert the interface version to a guid. Guid catid = new Guid(specification.Id); // get list of servers in the specified specification. IOPCEnumGUID enumerator = null; m_server.EnumClassesOfCategories( 1, new Guid[] { catid }, 0, null, out enumerator); // read clsids. Guid[] clsids = ReadClasses(enumerator); // release enumerator object. Interop.ReleaseServer(enumerator); enumerator = null; // fetch class descriptions. foreach (Guid clsid in clsids) { Factory factory = new Factory(); try { OpcUrl url = CreateUrl(specification, clsid); OpcServer server = null; if (specification == OpcSpecification.OPC_DA_30) { server = new TsCDaServer(factory, url); } else if (specification == OpcSpecification.OPC_DA_20) { server = new TsCDaServer(factory, url); } else if (specification == OpcSpecification.OPC_AE_10) { server = new TsCAeServer(factory, url); } else if (specification == OpcSpecification.OPC_HDA_10) { server = new TsCHdaServer(factory, url); } servers.Add(server); } catch (Exception) { // ignore bad clsids. } } return((OpcServer[])servers.ToArray(typeof(OpcServer))); } finally { // free the server. Interop.ReleaseServer(m_server); m_server = null; } } }
/// <summary> /// Loads the configuration for the current server. /// </summary> private bool OnLoad(bool prompt, OpcUrl url) { Stream stream = null; try { Cursor = Cursors.WaitCursor; // prompt user to select a configuration file. if (prompt) { OpenFileDialog dialog = new OpenFileDialog(); dialog.CheckFileExists = true; dialog.CheckPathExists = true; dialog.DefaultExt = ".config"; dialog.Filter = "Config Files (*.config)|*.config|All Files (*.*)|*.*"; dialog.Multiselect = false; dialog.ValidateNames = true; dialog.Title = "Open Server Configuration File"; dialog.FileName = mConfigFile_; if (dialog.ShowDialog() != DialogResult.OK) { return(false); } // save the new config file name. mConfigFile_ = dialog.FileName; } // disconnect from current server. OnDisconnect(); // open configuration file. stream = new FileStream(mConfigFile_, FileMode.Open, FileAccess.Read, FileShare.Read); // deserialize the server object. TsCCpxComplexTypeCache.Server = server_ = (TsCDaServer) new BinaryFormatter().Deserialize(stream); // overrided default url. if (url != null) { server_.Url = url; } // connect to new server. OnConnect(); // load succeeded. return(true); } catch (Exception e) { if (prompt) { MessageBox.Show(e.Message); } return(false); } finally { // close the stream. if (stream != null) { stream.Close(); } Cursor = Cursors.Default; } }
/// <summary> /// Initializes the object with an ItemIdentifier object and url. /// </summary> public TsCAeItemUrl(OpcItem item, OpcUrl url) : base(item) { Url = url; }
public static void Start() { var servers = GetOpcDaServers(); OpcDaServers = ConfigurationCashHelper.SystemConfiguration.AutomationConfiguration.OpcDaTsServers.ToArray(); foreach (var server in OpcDaServers) { if (!servers.Any(x => x.Url == server.Url)) { Notifier.UILog(string.Format("Не удалось запусть OPC DA сервер {0}. Сервер не найден", server.Url), true); //MainViewModel.SetReportAddress("<Ошибка>"); continue; } var url = new OpcUrl(OpcSpecification.OPC_DA_20, OpcUrlScheme.DA, server.Url); var opcServer = new TsCDaServer(); try { opcServer.Connect(url, null); opcServer.ServerShutdownEvent += reason => { var srv = _Servers.FirstOrDefault(x => x.Item1.ServerName == opcServer.ServerName); if (srv != null) { try { srv.Item1.CancelSubscription(srv.Item2); } catch { } // Ищем все теги для данного сервера у удаляем их var tags = _tags.Where(t => t.ServerName == opcServer.ServerName); foreach (var tag in tags) { _tags.Remove(tag); } _Servers.Remove(srv); } }; // Создаём объект подписки var id = Guid.NewGuid().ToString(); var subscriptionState = new TsCDaSubscriptionState { Name = id, ClientHandle = id, Deadband = 0, UpdateRate = 1000, KeepAlive = 10000 }; var subscription = (TsCDaSubscription)opcServer.CreateSubscription(subscriptionState); _Servers.Add(Tuple.Create<TsCDaServer, TsCDaSubscription>(opcServer, subscription)); // Добавляем в объект подписки выбранные теги List<TsCDaItem> list = server.Tags.Select(tag => new TsCDaItem { ItemName = tag.ElementName, ClientHandle = tag.ElementName // Уникальный Id определяемый пользователем }).ToList(); // Добавляем теги и проверяем результат данной операции var results = subscription.AddItems(list.ToArray()); var errors = results.Where(result => result.Result.IsError()); if (errors.Count() > 0) { StringBuilder msg = new StringBuilder(); msg.Append("Не удалось добавить теги для подписки. Возникли ошибки в тегах:"); foreach (var error in errors) { msg.Append(String.Format("ItemName={0} ClientHandle={1} Description={2}; ", error.ItemName, error.ClientHandle, error.Result.Description())); } //throw new InvalidOperationException(msg.ToString()); } subscription.DataChangedEvent += EventHandler_Subscription_DataChangedEvent; _tags.AddRange(server.Tags.Select(tag => new OpcDaTagValue { ElementName = tag.ElementName, TagId = tag.TagId, Uid = tag.Uid, Path = tag.Path, TypeNameOfValue = tag.TypeNameOfValue, AccessRights = tag.AccessRights, ScanRate = tag.ScanRate, ServerId = server.Uid, ServerName = server.ServerName })); } catch (Exception ex) { Notifier.UILog(ex.Message, true); } } }
public static OpcServerStatus GetServerStatus(OpcDaServer server) { var opcServer = _Servers.FirstOrDefault(x => x.Item1.ServerName == server.ServerName); if (opcServer == null) { var srv = GetOpcDaServers().FirstOrDefault(s => s.ServerName == server.ServerName); if (srv != null) { var url = new OpcUrl(OpcSpecification.OPC_DA_20, OpcUrlScheme.DA, server.Url); var opcSrv = new TsCDaServer(); try { opcSrv.Connect(url, null); var result = opcSrv.GetServerStatus(); opcSrv.Disconnect(); return result; } catch { return null; } } else return null; } else { return opcServer.Item1.IsConnected ? opcServer.Item1.GetServerStatus() : null; } }
/// <summary> /// Initializes the object. /// </summary> internal Server() { url_ = null; server_ = null; callback_ = new Callback(this); }
void OnConnect() { _activeOpcServer = new TsCDaServer(); var opcUrl = new OpcUrl(OpcSpecification.OPC_DA_20, OpcUrlScheme.DA, SelectedOpcServer.Url.ToString()); _activeOpcServer.Connect(opcUrl, null); // во второй параметр передаются данные для // авторизации пользователя на удалённом сервере _activeOpcServer.ServerShutdownEvent += EventHandler_activeOpcServer_ServerShutdownEvent; }
/// <summary> /// Initializes the object. /// </summary> internal Server() { _url = null; m_server = null; callback_ = new Callback(this); }