/// <summary> /// Adds an alias to the node set. /// </summary> public void AddAlias(ISystemContext context, string alias, Opc.Ua.NodeId nodeId) { int count = 1; if (this.Aliases != null) { for (int ii = 0; ii < this.Aliases.Length; ii++) { if (this.Aliases[ii].Alias == alias) { this.Aliases[ii].Value = Export(nodeId, context.NamespaceUris); return; } } count += this.Aliases.Length; } NodeIdAlias[] aliases = new NodeIdAlias[count]; if (this.Aliases != null) { Array.Copy(this.Aliases, aliases, this.Aliases.Length); } aliases[count-1] = new NodeIdAlias() { Alias = alias, Value = Export(nodeId, context.NamespaceUris) }; this.Aliases = aliases; }
public Opc.IdentifiedResult[] WriteTags(Opc.Da.ItemValue[] items) { PLCFactory factory = new PLCFactory(opcURL); Opc.Da.ItemValue[] responseIDTags = new Opc.Da.ItemValue[1]; var results = factory.WriteTags(items); return results; }
/// <summary> /// Prompts the user to edit an array value. /// </summary> public Opc.Ua.Security.ListOfSecurityProfiles ShowDialog(Opc.Ua.Security.ListOfSecurityProfiles profiles, string caption) { if (caption != null) { this.Text = caption; } ProfilesLV.Items.Clear(); if (profiles != null) { for (int ii = 0; ii < profiles.Count; ii++) { ProfilesLV.Items.Add(profiles[ii].ProfileUri, profiles[ii].Enabled); } } if (ShowDialog() != DialogResult.OK) { return null; } Opc.Ua.Security.ListOfSecurityProfiles results = new Opc.Ua.Security.ListOfSecurityProfiles(); for (int ii = 0; ii < ProfilesLV.Items.Count; ii++) { Opc.Ua.Security.SecurityProfile profile = new Opc.Ua.Security.SecurityProfile(); profile.ProfileUri = ProfilesLV.Items[ii] as string; profile.Enabled = ProfilesLV.CheckedIndices.Contains(ii); results.Add(profile); } return results; }
/// <summary> /// Initializes the node manager. /// </summary> public FileSystemNodeManager(Opc.Ua.Server.IServerInternal server, string systemRoot) : base(server) { List<string> namespaceUris = new List<string>(); namespaceUris.Add(Namespaces.FileSystem); namespaceUris.Add(Namespaces.FileSystem + "/Instance"); NamespaceUris = namespaceUris; m_cache = new NodeIdDictionary<NodeState>(); // create the directory. string absolutePath = Utils.GetAbsoluteDirectoryPath(systemRoot, true, false, true); // create the system. m_system = new FileSystemMonitor( SystemContext, absolutePath, server.NamespaceUris.GetIndexOrAppend(namespaceUris[1]), Lock); // update the default context. SystemContext.SystemHandle = m_system; }
/// <summary> /// Initializes the node manager. /// </summary> public TestDataNodeManager(Opc.Ua.Server.IServerInternal server, ApplicationConfiguration configuration) : base(server, configuration) { // update the namespaces. List<string> namespaceUris = new List<string>(); namespaceUris.Add(Namespaces.TestData); namespaceUris.Add(Namespaces.TestData + "/Instance"); NamespaceUris = namespaceUris; // get the configuration for the node manager. m_configuration = configuration.ParseExtension<TestDataNodeManagerConfiguration>(); // use suitable defaults if no configuration exists. if (m_configuration == null) { m_configuration = new TestDataNodeManagerConfiguration(); } m_lastUsedId = m_configuration.NextUnusedId-1; // create the object used to access the test system. m_system = new TestDataSystem(this, server.NamespaceUris, server.ServerUris); // update the default context. SystemContext.SystemHandle = m_system; }
/// <summary> /// Creates a new browser object with a set of filters. /// </summary> public Browser( ISystemContext context, ViewDescription view, NodeId referenceType, bool includeSubtypes, BrowseDirection browseDirection, QualifiedName browseName, IEnumerable<IReference> additionalReferences, bool internalOnly, Opc.Ua.Client.Session client, NamespaceMapper mapper, NodeState source, NodeId rootId) : base( context, view, referenceType, includeSubtypes, browseDirection, browseName, additionalReferences, internalOnly) { m_client = client; m_mapper = mapper; m_source = source; m_rootId = rootId; m_stage = Stage.Begin; }
/// <summary> /// Fetches the event type information from the AE server. /// </summary> public void LoadTypes(Opc.Ua.Client.Session client, IServerInternal server, NamespaceMapper mapper) { TypeNodes = new NodeIdDictionary<ReferenceDescription>(); LoadTypes(client, server, mapper, Opc.Ua.ObjectTypeIds.BaseObjectType); LoadTypes(client, server, mapper, Opc.Ua.VariableTypeIds.BaseVariableType); LoadTypes(client, server, mapper, Opc.Ua.DataTypeIds.BaseDataType); LoadTypes(client, server, mapper, Opc.Ua.ReferenceTypeIds.References); }
void BrowseCTRL_MethodCalled(object sender, Opc.Ua.Sample.Controls.MethodCalledEventArgs e) { try { // TBD } catch (Exception exception) { GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } }
/// <summary> /// Gets the available servers. /// </summary> /// <param name="factory">The factory.</param> /// <param name="specification">The specification.</param> private void GetAvailableServers(Opc.Ua.Com.ServerFactory factory, Specification specification) { Uri[] serverUrls = factory.GetAvailableServers(specification); for (int ii = 0; ii < serverUrls.Length; ii++) { ComServerDescription server = factory.ParseUrl(serverUrls[ii]); // don't wrap proxies. if (ConfigUtils.CLSID_UaComDaProxyServer == server.Clsid) { continue; } if (ConfigUtils.CLSID_UaComAeProxyServer == server.Clsid) { continue; } if (ConfigUtils.CLSID_UaComHdaProxyServer == server.Clsid) { continue; } // don't wrap UA psuedo-servers. List<Guid> catids = ConfigUtils.GetImplementedCategories(server.Clsid); bool suppress = false; for (int jj = 0; jj < catids.Count; jj++) { if (catids[jj] == ConfigUtils.CATID_PseudoComServers) { suppress = true; break; } } if (suppress) { continue; } // assume regular COM server. ListViewItem item = new ListViewItem(server.ProgId); item.SubItems.Add(server.Description); item.SubItems.Add(specification.ToString()); item.Tag = new Item(specification, server); ServersLV.Items.Add(item); } }
public SamplePublisherForm( ApplicationInstance application, Opc.Ua.Sample.Controls.PublisherForm masterForm, ApplicationConfiguration configuration) : base(configuration.CreateMessageContext(), application, masterForm, configuration) { InitializeComponent(); base.BrowseCTRL.MethodCalled += new Opc.Ua.Sample.Controls.MethodCalledEventHandler(BrowseCTRL_MethodCalled); if (!configuration.SecurityConfiguration.AutoAcceptUntrustedCertificates) { configuration.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation); } }
/// <summary> /// Initializes the node manager. /// </summary> public BoilerNodeManager( Opc.Ua.Server.IServerInternal server, ApplicationConfiguration configuration) : base(server) { List<string> namespaceUris = new List<string>(); namespaceUris.Add(Namespaces.Boiler); namespaceUris.Add(Namespaces.Boiler +"/Instance"); NamespaceUris = namespaceUris; m_typeNamespaceIndex = Server.NamespaceUris.GetIndexOrAppend(namespaceUris[0]); m_namespaceIndex = Server.NamespaceUris.GetIndexOrAppend(namespaceUris[1]); m_lastUsedId = 0; m_boilers = new List<BoilerState>(); }
/// <summary> /// Fetches the event categories for the specified event type. /// </summary> private void LoadTypes(Opc.Ua.Client.Session client, IServerInternal server, NamespaceMapper mapper, NodeId parentId) { List<ReferenceDescription> references = null; // find references to subtypes. try { references = BrowseSubTypes(client, parentId); } catch (Exception e) { Utils.Trace("Could not browse subtypes of {0}. {1}", parentId, e.Message); return; } for (int ii = 0; ii < references.Count; ii++) { ReferenceDescription reference = references[ii]; // ignore absolute references. if (reference.NodeId == null || reference.NodeId.IsAbsolute) { continue; } // recursively browse until a non-UA node is found. if (reference.NodeId.NamespaceIndex == 0) { LoadTypes(client, server, mapper, (NodeId)reference.NodeId); continue; } // map the node id and browse name to local indexes. NodeId targetId = mapper.ToLocalId((NodeId)reference.NodeId); reference.NodeId = targetId; reference.BrowseName = mapper.ToLocalName(reference.BrowseName); // add non-UA node to the table. TypeNodes[targetId] = reference; server.TypeTree.AddSubtype(targetId, parentId); } }
public static void CriandoMenu() { Console.WriteLine("Selecione uma das opções abaixo: "); Console.WriteLine("1 - Criar \n2 - Deletar \n3 - Editar \n4 - Listar \n5 - Atualizar"); int index = int.Parse(Console.ReadLine()); Opcao opcaoSelecionada = (Opcao)index; switch (opcaoSelecionada) { case Opcao.Criar: Console.WriteLine("Você tem certeza de que quer criar algo?"); Console.WriteLine("1 - Sim \n2 - Não"); int indx = int.Parse(Console.ReadLine()); Opc confirmacao = (Opc)indx; if (confirmacao == Opc.Sim) { //chamar funcao que cria algo } else { //retornar pro menu } break; case Opcao.Deletar: Console.WriteLine("Você quer deletar algo."); break; case Opcao.Editar: Console.WriteLine("Você quer editar algo."); break; case Opcao.Listar: Console.WriteLine("Você quer listar algo."); break; default: Console.WriteLine("Opção inválida."); break; } }
static void UtilizandoEnum() { Console.WriteLine("Enums, o que são?"); Console.WriteLine("Enums são constantes fortamente tipadas. Elas são estáticas, ou seja não é possÃvel nem preciso acessar os seus valores instaciando um objeto utilizando a palavra reservada new. O acesso é feito a partir do nome da classe em que está contido e em seguida o nome do enum a ser utilizado. (A declaração é bem parecida com uma declaração de variável)."); Generos valor = Generos.Romance; Console.WriteLine($"Gênero: {valor} \nOutra forma de apresentar: {(Generos)7091} \nCada item no Enum tem um Ãndice: {(int)Generos.Aventura}"); Cor corFavorita = Cor.Amarelo; Cor corFavoritaJoao = Cor.Azul; Cor corFavoritaJuliana = Cor.Vermelho; Console.WriteLine((Cor)2); Console.WriteLine($"Cor favorita da Juliana: {corFavoritaJuliana} \nCor favorita do João: {corFavoritaJoao} \nCor favorita aleatória: {corFavorita}"); Opc validacao = Opc.Sim; Console.WriteLine(validacao); }
/// <summary> /// Restores a previously cached history reader. /// </summary> protected virtual HistoryDataReader RestoreDataReader(Opc.Ua.Server.ServerSystemContext context, byte[] continuationPoint) { if (context == null || context.OperationContext == null || context.OperationContext.Session == null) { return null; } HistoryDataReader reader = context.OperationContext.Session.RestoreHistoryContinuationPoint(continuationPoint) as HistoryDataReader; if (reader == null) { return null; } return reader; }
/// <summary> /// Writes the value of the specified item property. /// </summary> public Opc.IdentifiedResult Write( string itemID, PropertyID propertyID, Opc.Da.ItemValue value) { return null; }
/// <summary> /// The identifier for the Angular-AccelerationConditionType_Quality_SourceTimestamp Variable. /// </summary> public static readonly ExpandedNodeId Angular-AccelerationConditionType_Quality_SourceTimestamp = new ExpandedNodeId(Opc.Ua.MTConnect.Variables.Angular-AccelerationConditionType_Quality_SourceTimestamp, Opc.Ua.MTConnect.Namespaces.OpcUaMTConnect);
/// <summary> /// The identifier for the Angular-AccelerationConditionType_LimitState_LastTransition_Id Variable. /// </summary> public static readonly ExpandedNodeId Angular-AccelerationConditionType_LimitState_LastTransition_Id = new ExpandedNodeId(Opc.Ua.MTConnect.Variables.Angular-AccelerationConditionType_LimitState_LastTransition_Id, Opc.Ua.MTConnect.Namespaces.OpcUaMTConnect);
/// <summary> /// The identifier for the Angular-AccelerationConditionType_ConditionRefresh_InputArguments Variable. /// </summary> public static readonly ExpandedNodeId Angular-AccelerationConditionType_ConditionRefresh_InputArguments = new ExpandedNodeId(Opc.Ua.MTConnect.Variables.Angular-AccelerationConditionType_ConditionRefresh_InputArguments, Opc.Ua.MTConnect.Namespaces.OpcUaMTConnect);
/// <summary> /// Updates the value of an tag. /// </summary> private bool UpdateTagValue( UnderlyingSystemTag tag, Opc.Ua.Test.DataGenerator generator) { // don't update writeable tags. if (tag.IsWriteable) { return false; } // check if a range applies to the value. int high = 0; int low = 0; switch (tag.TagType) { case UnderlyingSystemTagType.Analog: { if (tag.EuRange != null && tag.EuRange.Length >= 2) { high = (int)tag.EuRange[0]; low = (int)tag.EuRange[1]; } break; } case UnderlyingSystemTagType.Digital: { high = 1; low = 0; break; } case UnderlyingSystemTagType.Enumerated: { if (tag.Labels != null && tag.Labels.Length > 0) { high = tag.Labels.Length-1; low = 0; } break; } } // select a value in the range. int value = -1; if (high > low) { value = (generator.GetRandomUInt16()%(high - low + 1)) + low; } // cast value to correct type or generate a random value. switch (tag.DataType) { case UnderlyingSystemDataType.Integer1: { if (value == -1) { tag.Value = generator.GetRandomSByte(); } else { tag.Value = (sbyte)value; } break; } case UnderlyingSystemDataType.Integer2: { if (value == -1) { tag.Value = generator.GetRandomInt16(); } else { tag.Value = (short)value; } break; } case UnderlyingSystemDataType.Integer4: { if (value == -1) { tag.Value = generator.GetRandomInt32(); } else { tag.Value = (int)value; } break; } case UnderlyingSystemDataType.Real4: { if (value == -1) { tag.Value = generator.GetRandomFloat(); } else { tag.Value = (float)value; } break; } case UnderlyingSystemDataType.String: { tag.Value = generator.GetRandomString(); break; } } tag.Timestamp = DateTime.UtcNow; return true; }
/// <summary> /// Verifies that the specified node exists. /// </summary> protected override NodeState ValidateNode( ServerSystemContext context, Opc.Ua.Server.NodeHandle handle, IDictionary<NodeId, NodeState> cache) { // not valid if no root. if (handle == null) { return null; } // check if previously validated. if (handle.Validated) { return handle.Node; } // lookup in operation cache. NodeState target = FindNodeInCache(context, handle, cache); if (target == null) { // TBD return null; } return ValidationComplete(context, handle, target, cache); }
/// <summary> /// Saves a history data reader. /// </summary> protected virtual void SaveDataReader(Opc.Ua.Server.ServerSystemContext context, HistoryDataReader reader) { if (context == null || context.OperationContext == null || context.OperationContext.Session == null) { return; } context.OperationContext.Session.SaveHistoryContinuationPoint(reader.Id, reader); }
/// <summary> /// Returns the history data source for a node. /// </summary> protected virtual ServiceResult GetHistoryDataSource( Opc.Ua.Server.ServerSystemContext context, BaseVariableState variable, out IHistoryDataSource datasource) { datasource = m_system.GetHistoryFile(variable); if (datasource == null) { return StatusCodes.BadNotReadable; } return ServiceResult.Good; }
/// <summary> /// Deletes the application certificate. /// </summary> private void DeleteApplicationCertificate(Opc.Ua.Security.SecuredApplication application, X509Certificate2 certificate) { ICertificateStore physicalStore = application.ApplicationCertificate.OpenStore(); try { physicalStore.Delete(certificate.Thumbprint); } catch (Exception) { MessageBox.Show("Delete application certificate failed.", "Delete Certificate", MessageBoxButtons.OK, MessageBoxIcon.Warning); } finally { physicalStore.Close(); } if (application.TrustedCertificateStore != null) { physicalStore = application.TrustedCertificateStore.OpenStore(); try { physicalStore.Delete(certificate.Thumbprint); } catch (Exception) { // ignore errors. } finally { physicalStore.Close(); } } }
public OpcAddress(Opc.Da.Item opcItem, Opc.Da.Subscription subscription) { _opcItem = opcItem; _subscription = subscription; }
private void UpdateApplicationCertificate(Opc.Ua.Security.SecuredApplication application, CertificateStoreIdentifier store, X509Certificate2 certificate) { if (!certificate.HasPrivateKey) { MessageBox.Show("Cannot use a certificate without an accessible private key.", "Import Certificate", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // check if the old certificate should be deleted. Opc.Ua.Security.CertificateIdentifier oldId = application.ApplicationCertificate; if (oldId != null) { X509Certificate2 oldCertificate = oldId.Find(); if (oldCertificate != null && oldCertificate.Thumbprint != certificate.Thumbprint) { if (new YesNoDlg().ShowDialog("Would you like to delete the old certificate?", "Delete Certificate") == DialogResult.Yes) { DeleteApplicationCertificate(application, oldCertificate); } } } // set the application name. List<string> subjectName = Utils.ParseDistinguishedName(certificate.Subject); foreach (string subjectField in subjectName) { if (subjectField.StartsWith("CN=")) { application.ApplicationName = subjectField.Substring(3); break; } } // set the application uri. string applicationUri = Utils.GetApplicationUriFromCertficate(certificate); if (applicationUri != null) { application.ApplicationUri = applicationUri; } // update the certificate. application.ApplicationCertificate = new Opc.Ua.Security.CertificateIdentifier(); application.ApplicationCertificate.StorePath = store.StorePath; application.ApplicationCertificate.StoreType = store.StoreType; application.ApplicationCertificate.SubjectName = certificate.Subject; application.ApplicationCertificate.Thumbprint = certificate.Thumbprint; // save the configuration. new Opc.Ua.Security.SecurityConfigurationManager().WriteConfiguration(application.ConfigurationFile, application); }
public DataValue(Opc.Ua.DataValue value) { m_value = value; }
/// <summary> /// The delegate used to receive data change notifications via a direct function call instead of a .NET Event. /// </summary> public void OnDataChangeNotification(Opc.Ua.Client.Subscription subscription, DataChangeNotification notification, IList<string> stringTable) { for (int ii = 0; ii < notification.MonitoredItems.Count; ii++) { MonitoredItem localItem = null; DataValue value = null; ServiceResult error = null; lock (subscription.Session) { Opc.Ua.Client.MonitoredItem monitoredItem = subscription.FindItemByClientHandle(notification.MonitoredItems[ii].ClientHandle); if (monitoredItem != null) { MonitoredItemNotification value2 = notification.MonitoredItems[ii]; if (value2.Value.StatusCode != StatusCodes.Good) { error = new ServiceResult(value2.Value.StatusCode, value2.DiagnosticInfo, stringTable); } value = value2.Value; value.WrappedValue = m_mapper.ToLocalVariant(value2.Value.WrappedValue); value.ServerTimestamp = DateTime.UtcNow; localItem = (MonitoredItem)monitoredItem.Handle; } } localItem.QueueValue(value, error); } }
/// <summary> /// Simulates a block by updating the state of the tags belonging to the condition. /// </summary> /// <param name="counter">The number of simulation cycles that have elapsed.</param> /// <param name="index">The index of the block within the system.</param> /// <param name="generator">An object which generates random data.</param> public void DoSimulation(long counter, int index, Opc.Ua.Test.DataGenerator generator) { try { TagsChangedEventHandler onTagsChanged = null; List<UnderlyingSystemTag> snapshots = new List<UnderlyingSystemTag>(); // update the tags. lock (m_tags) { onTagsChanged = OnTagsChanged; // do nothing if not monitored. if (onTagsChanged == null) { return; } for (int ii = 0; ii < m_tags.Count; ii++) { UnderlyingSystemTag tag = m_tags[ii]; UpdateTagValue(tag, generator); DataValue value = new DataValue(); value.Value = tag.Value; value.StatusCode = StatusCodes.Good; value.SourceTimestamp = tag.Timestamp; if (counter % (8 + (index%4)) == 0) { UpdateTagMetadata(tag, generator); } snapshots.Add(tag.CreateSnapshot()); } } // report any tag changes after releasing the lock. if (onTagsChanged != null) { onTagsChanged(snapshots); } } catch (Exception e) { Utils.Trace(e, "Unexpected error running simulation for block {0}", m_name); } }
/// <summary> /// The delegate used to receive event notifications via a direct function call instead of a .NET Event. /// </summary> public void OnEventNotification(Opc.Ua.Client.Subscription subscription, EventNotificationList notification, IList<string> stringTable) { for (int ii = 0; ii < notification.Events.Count; ii++) { MonitoredItem localItem = null; EventFieldList e = null; lock (subscription.Session) { Opc.Ua.Client.MonitoredItem monitoredItem = subscription.FindItemByClientHandle(notification.Events[ii].ClientHandle); if (monitoredItem != null) { e = notification.Events[ii]; for (int jj = 0; jj < e.EventFields.Count; jj++) { e.EventFields[jj] = m_mapper.ToLocalVariant(e.EventFields[jj]); } localItem = (MonitoredItem)monitoredItem.Handle; e.ClientHandle = localItem.ClientHandle; } } localItem.QueueEvent(e); } }
/// <summary> /// Updates the metadata for a tag. /// </summary> private bool UpdateTagMetadata( UnderlyingSystemTag tag, Opc.Ua.Test.DataGenerator generator) { switch (tag.TagType) { case UnderlyingSystemTagType.Analog: { if (tag.EuRange != null) { double[] range = new double[tag.EuRange.Length]; for (int ii = 0; ii < tag.EuRange.Length; ii++) { range[ii] = tag.EuRange[ii]+1; } tag.EuRange = range; } break; } case UnderlyingSystemTagType.Digital: case UnderlyingSystemTagType.Enumerated: { if (tag.Labels != null) { string[] labels = new string[tag.Labels.Length]; for (int ii = 0; ii < tag.Labels.Length; ii++) { labels[ii] = generator.GetRandomString(); } tag.Labels = labels; } break; } default: { return false; } } return true; }
/// <summary> /// The identifier for the Angular-AccelerationConditionType ObjectType. /// </summary> public static readonly ExpandedNodeId Angular-AccelerationConditionType = new ExpandedNodeId(Opc.Ua.MTConnect.ObjectTypes.Angular-AccelerationConditionType, Opc.Ua.MTConnect.Namespaces.OpcUaMTConnect);