// Original Features from the .NET Sample Client implementation, not needed for this OPC UA Client

        /*
         * public Tree GetRootNode(LabelViewModel textInfo)
         * {
         *  ReferenceDescriptionCollection references;
         *  Byte[] continuationPoint;
         *  Tree browserTree = new Tree();
         *
         *  try
         *  {
         *      session.Browse(
         *          null,
         *          null,
         *          ObjectIds.ObjectsFolder,
         *          0u,
         *          BrowseDirection.Forward,
         *          ReferenceTypeIds.HierarchicalReferences,
         *          true,
         *          0,
         *          out continuationPoint,
         *          out references);
         *
         *      browserTree.currentView.Add(new ListNode { id = ObjectIds.ObjectsFolder.ToString(), NodeName = "Root", children = (references?.Count != 0) });
         *
         *      return browserTree;
         *  }
         *  catch
         *  {
         *      Disconnect(session);
         *      return null;
         *  }
         * }
         *
         * public Tree GetChildren(string node)
         * {
         *  ReferenceDescriptionCollection references;
         *  Byte[] continuationPoint;
         *  Tree browserTree = new Tree();
         *
         *  try
         *  {
         *      session.Browse(
         *          null,
         *          null,
         *          node,
         *          0u,
         *          BrowseDirection.Forward,
         *          ReferenceTypeIds.HierarchicalReferences,
         *          true,
         *          0,
         *          out continuationPoint,
         *          out references);
         *
         *      if (references != null)
         *      {
         *          foreach (var nodeReference in references)
         *          {
         *              ReferenceDescriptionCollection childReferences = null;
         *              Byte[] childContinuationPoint;
         *
         *              session.Browse(
         *                  null,
         *                  null,
         *                  ExpandedNodeId.ToNodeId(nodeReference.NodeId, session.NamespaceUris),
         *                  0u,
         *                  BrowseDirection.Forward,
         *                  ReferenceTypeIds.HierarchicalReferences,
         *                  true,
         *                  0,
         *                  out childContinuationPoint,
         *                  out childReferences);
         *
         *              INode currentNode = null;
         *              try
         *              {
         *                  currentNode = session.ReadNode(ExpandedNodeId.ToNodeId(nodeReference.NodeId, session.NamespaceUris));
         *              }
         *              catch (Exception)
         *              {
         *                  // skip this node
         *                  continue;
         *              }
         *
         *              byte currentNodeAccessLevel = 0;
         *              byte currentNodeEventNotifier = 0;
         *              bool currentNodeExecutable = false;
         *
         *              VariableNode variableNode = currentNode as VariableNode;
         *              if (variableNode != null)
         *              {
         *                  currentNodeAccessLevel = variableNode.UserAccessLevel;
         *                  currentNodeAccessLevel = (byte)((uint)currentNodeAccessLevel & ~0x2);
         *              }
         *
         *              ObjectNode objectNode = currentNode as ObjectNode;
         *              if (objectNode != null)
         *              {
         *                  currentNodeEventNotifier = objectNode.EventNotifier;
         *              }
         *
         *              ViewNode viewNode = currentNode as ViewNode;
         *              if (viewNode != null)
         *              {
         *                  currentNodeEventNotifier = viewNode.EventNotifier;
         *              }
         *
         *              MethodNode methodNode = currentNode as MethodNode;
         *              if (methodNode != null)
         *              {
         *                  currentNodeExecutable = methodNode.UserExecutable;
         *              }
         *
         *              browserTree.currentView.Add(new ListNode()
         *              {
         *                  id = nodeReference.NodeId.ToString(),
         *                  NodeName = nodeReference.DisplayName.Text.ToString(),
         *                  nodeClass = nodeReference.NodeClass.ToString(),
         *                  accessLevel = currentNodeAccessLevel.ToString(),
         *                  eventNotifier = currentNodeEventNotifier.ToString(),
         *                  executable = currentNodeExecutable.ToString(),
         *                  children = (references?.Count != 0),
         *                  ImageUrl = (nodeReference.NodeClass.ToString() == "Variable") ? "folderOpen.jpg" : "folder.jpg"
         *              });
         *              if (browserTree.currentView[0].ImageUrl == null)
         *              {
         *                  browserTree.currentView[0].ImageUrl = "";
         *              }
         *          }
         *          if (browserTree.currentView.Count == 0)
         *          {
         *              INode currentNode = session.ReadNode(new NodeId(node));
         *
         *              byte currentNodeAccessLevel = 0;
         *              byte currentNodeEventNotifier = 0;
         *              bool currentNodeExecutable = false;
         *
         *              VariableNode variableNode = currentNode as VariableNode;
         *
         *              if (variableNode != null)
         *              {
         *                  currentNodeAccessLevel = variableNode.UserAccessLevel;
         *                  currentNodeAccessLevel = (byte)((uint)currentNodeAccessLevel & ~0x2);
         *              }
         *
         *              ObjectNode objectNode = currentNode as ObjectNode;
         *
         *              if (objectNode != null)
         *              {
         *                  currentNodeEventNotifier = objectNode.EventNotifier;
         *              }
         *
         *              ViewNode viewNode = currentNode as ViewNode;
         *
         *              if (viewNode != null)
         *              {
         *                  currentNodeEventNotifier = viewNode.EventNotifier;
         *              }
         *
         *              MethodNode methodNode = currentNode as MethodNode;
         *
         *              if (methodNode != null )
         *              {
         *                  currentNodeExecutable = methodNode.UserExecutable;
         *              }
         *
         *              browserTree.currentView.Add(new ListNode()
         *              {
         *                  id = node,
         *                  NodeName = currentNode.DisplayName.Text.ToString(),
         *                  nodeClass = currentNode.NodeClass.ToString(),
         *                  accessLevel = currentNodeAccessLevel.ToString(),
         *                  eventNotifier = currentNodeEventNotifier.ToString(),
         *                  executable = currentNodeExecutable.ToString(),
         *                  children = false,
         *                  ImageUrl = null
         *              });
         *          }
         *      }
         *      return browserTree;
         *  }
         *  catch
         *  {
         *      Disconnect(session);
         *      return null;
         *  }
         * } */
        #endregion

        #region custom VariableWrite Method
        /// <summary>
        /// Returns the ServiceResult from the ResponseHeader of the Variable Write Operation
        /// </summary>
        /// <param name="value">The int value that is to be written to the Node in the Server Namespace.</param>
        /// <param name="nodeId">The NodeId of the Node where the value shall be written.</param>
        public ResponseHeader VariableWrite(UInt16 value, string nodeId)
        {
            if (session != null)
            {
                if (session.Connected)
                {
                    StatusCodeCollection     results         = null;
                    DiagnosticInfoCollection diagnosticInfos = null;
                    // create a new WriteValueCollection (needed to call the Write Mehtod of the session)
                    WriteValueCollection nodesToWrite = new WriteValueCollection();
                    nodesToWrite.Add(new WriteValue
                    {
                        // NodeId of the Node to write
                        NodeId = NodeId.Parse(nodeId),
                        // We want to write the Value of the Node
                        AttributeId = Attributes.Value,
                        Value       = new DataValue()
                        {
                            WrappedValue = value
                        }
                    });
                    // Actually write the Data. The method session.Write returns the responseHeader of the Write request response which is passed as the return value of this Method (VariableWrite)
                    ResponseHeader responseHeader = session.Write(null, nodesToWrite, out results, out diagnosticInfos);
                    return(responseHeader);
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                return(null);
            }
        }
Beispiel #2
0
        public static async Task <DataValue[]> ReadVar(int node, string[] VarNames)
        {
            try
            {
                ReadValueId[] valuesToRead = new ReadValueId[VarNames.Length];
                for (int i = 0; i < VarNames.Length; i++)
                {
                    valuesToRead[i] = new ReadValueId
                    {
                        // you can parse the nodeId from a string.
                        NodeId = NodeId.Parse("ns=" + node.ToString() + ";s=" + VarNames[i]),
                        // variable class nodes have a Value attribute.
                        AttributeId = AttributeIds.Value
                    };
                }

                var readRequest = new ReadRequest
                {
                    NodesToRead = valuesToRead
                };
                // send the ReadRequest to the server.
                var readResult = await channel.ReadAsync(readRequest);

                return(readResult.Results);
            }
            catch (Exception ex)
            {
                //await channel.AbortAsync();
                return(null);
            }
        }
Beispiel #3
0
        public static async Task <object> WriteVar(int node, KeyValuePair <string, object>[] ValuesToSet)
        {
            try
            {
                WriteValue[] valuesToWrite = new WriteValue[ValuesToSet.Length];
                for (int i = 0; i < ValuesToSet.Length; i++)
                {
                    valuesToWrite[i] = new WriteValue
                    {
                        // you can parse the nodeId from a string.
                        NodeId = NodeId.Parse("ns=" + node.ToString() + ";s=" + ValuesToSet[i].Key),
                        // variable class nodes have a Value attribute.
                        AttributeId = AttributeIds.Value,
                        Value       = new DataValue(ValuesToSet[i].Value)
                    };
                }


                var writeRequest = new WriteRequest
                {
                    NodesToWrite = valuesToWrite
                };
                // send the ReadRequest to the server.
                var writeResult = await channel.WriteAsync(writeRequest);

                return(writeResult);
            }
            catch (Exception ex)
            {
                //await channel.AbortAsync();
                return(null);
            }
        }
Beispiel #4
0
        private bool TryGetBinaryEncodingId(NodeId dataTypeId, out NodeId binaryId)
        {
            if (_binaryEncodings.TryGetValue(dataTypeId, out binaryId))
            {
                return(true);
            }

            // Special case for Siemens
            if (_namespaceUris.Length > dataTypeId.NamespaceIndex &&
                _namespaceUris[dataTypeId.NamespaceIndex] == "http://www.siemens.com/simatic-s7-opcua")
            {
                var idString       = dataTypeId.ToString();
                var binaryIdString = idString.Replace("s=DT_\"", "s=TE_\"");

                if (idString != binaryIdString)
                {
                    binaryId = NodeId.Parse(binaryIdString);
                }
                else
                {
                    binaryId = null;
                }
            }

            return(binaryId != null);
        }
        public async Task Read()
        {
            var channel = new UaTcpSessionChannel(
                this.localDescription,
                this.certificateStore,
                new AnonymousIdentity(),
                EndpointUrl,
                loggerFactory: this.loggerFactory);

            await channel.OpenAsync();

            Console.WriteLine($"Opened session with endpoint '{channel.RemoteEndpoint.EndpointUrl}'.");
            Console.WriteLine($"SecurityPolicy: '{channel.RemoteEndpoint.SecurityPolicyUri}'.");
            Console.WriteLine($"SecurityMode: '{channel.RemoteEndpoint.SecurityMode}'.");
            Console.WriteLine($"Activated session '{channel.SessionId}'.");

            var readRequest = new ReadRequest {
                NodesToRead = new[] { new ReadValueId {
                                          NodeId = NodeId.Parse(VariableIds.Server_ServerStatus), AttributeId = AttributeIds.Value
                                      } }
            };
            var readResult = await channel.ReadAsync(readRequest);

            var serverStatus = readResult.Results[0].GetValueOrDefault <ServerStatusDataType>();

            Console.WriteLine("Server status:");
            Console.WriteLine("  ProductName: {0}", serverStatus.BuildInfo.ProductName);
            Console.WriteLine("  SoftwareVersion: {0}", serverStatus.BuildInfo.SoftwareVersion);
            Console.WriteLine("  ManufacturerName: {0}", serverStatus.BuildInfo.ManufacturerName);
            Console.WriteLine("  State: {0}", serverStatus.State);
            Console.WriteLine("  CurrentTime: {0}", serverStatus.CurrentTime);

            Console.WriteLine($"Closing session '{channel.SessionId}'.");
            await channel.CloseAsync();
        }
Beispiel #6
0
        public void UpdateDuplicatedNodeIdTest()
        {
            Mock <IAddressSpaceBuildContext> _asMock = new Mock <IAddressSpaceBuildContext>();
            UANodeContext _newNode = new UANodeContext(NodeId.Parse("ns=1;i=11"), _asMock.Object);
            Mock <IBuildErrorsHandling> _traceMock   = new Mock <IBuildErrorsHandling>();
            List <TraceMessage>         _traceBuffer = new List <TraceMessage>();

            _traceMock.Setup(x => x.TraceEvent(It.IsAny <TraceMessage>())).Callback <TraceMessage>(x => _traceBuffer.Add(x));
            _newNode.Log = _traceMock.Object;
            UAVariable _nodeFactory = new UAVariable()
            {
                NodeId       = "ns=1;i=47",
                BrowseName   = "EURange",
                ParentNodeId = "ns=1;i=43",
                DataType     = "i=884",
                DisplayName  = new XML.LocalizedText[] { new XML.LocalizedText()
                                                         {
                                                             Value = "EURange"
                                                         } }
            };

            _newNode.Update(_nodeFactory, x => Assert.Fail());
            _newNode.Update(_nodeFactory, x => Assert.Fail());
            Assert.AreEqual <int>(1, _traceBuffer.Count);
            Assert.AreEqual <string>(_traceBuffer[0].BuildError.Identifier, BuildError.NodeIdDuplicated.Identifier);
        }
Beispiel #7
0
 internal static void GetParameters(this XML.DataTypeDefinition dataTypeDefinition, IDataTypeDefinitionFactory dataTypeDefinitionFactory, IAddressSpaceBuildContext nodeContext, Action <TraceMessage> traceEvent)
 {
     if (dataTypeDefinition is null)
     {
         return;
     }
     //xsd comment  < !--BaseType is obsolete and no longer used.Left in for backwards compatibility. -->
     //definition.BaseType = modelContext.ExportBrowseName(dataTypeDefinition.BaseType, DataTypes.BaseDataType);
     dataTypeDefinitionFactory.IsOptionSet  = dataTypeDefinition.IsOptionSet;
     dataTypeDefinitionFactory.IsUnion      = dataTypeDefinition.IsUnion;
     dataTypeDefinitionFactory.Name         = null; //TODO UADataType.Definition.Name wrong value #341 modelContext.ExportBrowseName( dataTypeDefinition.Name, DataTypes.BaseDataType);
     dataTypeDefinitionFactory.SymbolicName = dataTypeDefinition.SymbolicName;
     if (dataTypeDefinition.Field == null || dataTypeDefinition.Field.Length == 0)
     {
         return;
     }
     foreach (XML.DataTypeField _item in dataTypeDefinition.Field)
     {
         IDataTypeFieldFactory _nP = dataTypeDefinitionFactory.NewField();
         _nP.Name         = _item.Name;
         _nP.SymbolicName = _item.SymbolicName;
         _item.DisplayName.ExportLocalizedTextArray(_nP.AddDisplayName);
         _nP.DataType        = nodeContext.ExportBrowseName(NodeId.Parse(_item.DataType), DataTypes.BaseDataType);
         _nP.ValueRank       = _item.ValueRank.GetValueRank(traceEvent);
         _nP.ArrayDimensions = _item.ArrayDimensions;
         _nP.MaxStringLength = _item.MaxStringLength;
         _item.Description.ExportLocalizedTextArray(_nP.AddDescription);
         _nP.Value      = _item.Value;
         _nP.IsOptional = _item.IsOptional;
     }
 }
Beispiel #8
0
        public void RemoveInheritedValuesTest()
        {
            UAVariable _derivedNode = new UAVariable()
            {
                NodeId      = "ns=1;i=47", BrowseName = "EURange", ParentNodeId = "ns=1;i=43", DataType = "i=884",
                DisplayName = new XML.LocalizedText[] { new XML.LocalizedText()
                                                        {
                                                            Value = "EURange"
                                                        } }
            };
            UANode _baseNode = new UAVariable()
            {
                NodeId      = "i=17568", BrowseName = "EURange", ParentNodeId = "i=15318", DataType = "i=884",
                DisplayName = new XML.LocalizedText[] { new XML.LocalizedText()
                                                        {
                                                            Value = "EURange"
                                                        } }
            };
            Mock <IAddressSpaceBuildContext> _asMock = new Mock <IAddressSpaceBuildContext>();
            IUANodeContext _derivedNodeContext       = new UANodeContext(NodeId.Parse("ns=1;i=47"), _asMock.Object);

            _derivedNodeContext.Update(_derivedNode, x => Assert.Fail());
            UANodeContext _baseNodeContext = new UANodeContext(NodeId.Parse("i=17568"), _asMock.Object);

            _baseNodeContext.Update(_baseNode, x => Assert.Fail());
            _derivedNodeContext.RemoveInheritedValues(_baseNodeContext);
            Assert.AreEqual <string>("EURange", _derivedNode.BrowseName);
            Assert.IsNull(_derivedNode.DataType);
            Assert.IsNull(_derivedNode.Description);
        }
Beispiel #9
0
        public void ExportBrowseNameTest()
        {
            UANodeSet _tm = TestData.CreateNodeSetModel();
            Mock <IAddressSpaceBuildContext> _asMock = new Mock <IAddressSpaceBuildContext>();

            _asMock.Setup(x => x.GetNamespace(0)).Returns <ushort>(x => "tempuri.org");
            UANode _nodeFactory = new UAVariable()
            {
                NodeId       = "ns=1;i=47",
                BrowseName   = "EURange",
                ParentNodeId = "ns=1;i=43",
                DataType     = "i=884",
                DisplayName  = new XML.LocalizedText[] { new XML.LocalizedText()
                                                         {
                                                             Value = "EURange"
                                                         } }
            };
            UANodeContext _node = new UANodeContext(NodeId.Parse("ns=1;i=47"), _asMock.Object);

            _node.Update(_nodeFactory, x => Assert.Fail());
            XmlQualifiedName _resolvedName = _node.ExportNodeBrowseName();

            _asMock.Verify(x => x.GetNamespace(0), Times.Once);
            Assert.IsNotNull(_resolvedName);
            Assert.AreEqual <string>("tempuri.org:EURange", _resolvedName.ToString());
        }
        public async Task ConditionRefreshAsync()
        {
            var response = new CallResponse
            {
                Results = new CallMethodResult[]
                {
                    new CallMethodResult
                    {
                        StatusCode = StatusCodes.BadAttributeIdInvalid
                    }
                }
            };
            var channel = new TestRequestChannel(response);

            var ret = await channel.ConditionRefreshAsync(subscriptionId : 100);

            ret
            .Should().Be((StatusCode)StatusCodes.BadAttributeIdInvalid);

            channel.Request
            .Should().BeEquivalentTo(new
            {
                MethodsToCall = new[]
                {
                    new
                    {
                        ObjectId       = NodeId.Parse(ObjectTypeIds.ConditionType),
                        MethodId       = NodeId.Parse(MethodIds.ConditionType_ConditionRefresh),
                        InputArguments = new Variant[] { 100u }
                    }
                }
            });
        }
Beispiel #11
0
        private void OkBTN_Click(object sender, EventArgs e)
        {
            NodeId viewId = null;

            try
            {
                viewId = NodeId.Parse(ViewIdTB.Text);
            }
            catch (Exception)
            {
                MessageBox.Show("Please enter a valid node id for the view id.", this.Text);
            }

            try
            {
                ViewDescription view = null;

                if (!NodeId.IsNull(viewId) || ViewTimestampCK.Checked || ViewVersionCK.Checked)
                {
                    view = new ViewDescription();

                    view.ViewId      = viewId;
                    view.Timestamp   = DateTime.MinValue;
                    view.ViewVersion = 0;

                    if (ViewTimestampCK.Checked && ViewTimestampDP.Value > ViewTimestampDP.MinDate)
                    {
                        view.Timestamp = ViewTimestampDP.Value;
                    }

                    if (ViewVersionCK.Checked)
                    {
                        view.ViewVersion = (uint)ViewVersionNC.Value;
                    }
                }

                m_browser.View = view;
                m_browser.MaxReferencesReturned = (uint)MaxReferencesReturnedNC.Value;
                m_browser.BrowseDirection       = (BrowseDirection)BrowseDirectionCB.SelectedItem;
                m_browser.NodeClassMask         = (int)NodeClass.View | (int)NodeClass.Object;
                m_browser.ReferenceTypeId       = ReferenceTypeCTRL.SelectedTypeId;
                m_browser.IncludeSubtypes       = IncludeSubtypesCK.Checked;
                m_browser.NodeClassMask         = 0;

                int nodeClassMask = 0;

                foreach (NodeClass nodeClass in NodeClassList.CheckedItems)
                {
                    nodeClassMask |= (int)nodeClass;
                }

                m_browser.NodeClassMask = nodeClassMask;

                DialogResult = DialogResult.OK;
            }
            catch (Exception exception)
            {
                GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception);
            }
        }
        public async Task Polling()
        {
            var channel = new UaTcpSessionChannel(
                this.localDescription,
                this.certificateStore,
                new AnonymousIdentity(),
                EndpointUrl,
                loggerFactory: this.loggerFactory);

            await channel.OpenAsync();

            Console.WriteLine($"Opened session with endpoint '{channel.RemoteEndpoint.EndpointUrl}'.");
            Console.WriteLine($"SecurityPolicy: '{channel.RemoteEndpoint.SecurityPolicyUri}'.");
            Console.WriteLine($"SecurityMode: '{channel.RemoteEndpoint.SecurityMode}'.");
            Console.WriteLine($"Activated session '{channel.SessionId}'.");


            var readRequest = new ReadRequest {
                NodesToRead = new[] { new ReadValueId {
                                          NodeId = NodeId.Parse(VariableIds.Server_ServerStatus_CurrentTime), AttributeId = AttributeIds.Value
                                      } }
            };

            for (int i = 0; i < 10; i++)
            {
                var readResult = await channel.ReadAsync(readRequest);

                Console.WriteLine("Read {0}", readResult.Results[0].GetValueOrDefault <DateTime>());
                await Task.Delay(1000);
            }
            Console.WriteLine($"Closing session '{channel.SessionId}'.");
            await channel.CloseAsync();
        }
        /// <summary>
        /// Invokes the method Robot1Multiply.
        /// </summary>
        public async void Robot1Multiply()
        {
            try
            {
                // Call the method, passing the input arguments in a Variant[].
                var response = await UaTcpSessionClient.FromModel(this).CallAsync(new CallRequest
                {
                    MethodsToCall = new[]
                    {
                        new CallMethodRequest
                        {
                            ObjectId       = NodeId.Parse("ns=2;s=Robot1"),
                            MethodId       = NodeId.Parse("ns=2;s=Robot1_Multiply"),
                            InputArguments = new Variant[] { this.InputA, this.InputB }
                        }
                    }
                });

                // When the method returns, save the output argument.
                this.Result = (double)response.Results[0].OutputArguments[0];
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error calling Robot1Multiply method: {0}", ex);
            }
        }
Beispiel #14
0
        public void NodeIdDictionaryTestMethod2()
        {
            Dictionary <string, NodeId> _dc = new Dictionary <string, NodeId>();

            _dc.Add(VariableTypeIds.PropertyType.ToString(), VariableTypeIds.PropertyType);
            _dc.Add(VariableTypeIds.AnalogItemType.ToString(), VariableTypeIds.AnalogItemType);
            _dc.Add(VariableTypeIds.ArrayItemType.ToString(), VariableTypeIds.ArrayItemType);
            _dc.Add(VariableTypeIds.BaseDataVariableType.ToString(), VariableTypeIds.BaseDataVariableType);
            _dc.Add(VariableTypeIds.BaseVariableType.ToString(), VariableTypeIds.BaseVariableType);
            NodeId _id = NodeId.Null;
            string _ni = "g=09087e75-8e5e-499b-954f-f2a9603db28a";

            Assert.IsTrue(_dc.TryGetValue(VariableTypeIds.PropertyType.ToString(), out _id));
            Assert.IsFalse(_dc.TryGetValue(NodeId.Parse(_ni).ToString(), out _id));
            _id = NodeId.Parse(_ni);
            Assert.IsNotNull(_id);
            _dc.Add(_id.ToString(), _id);
            Assert.IsTrue(_dc.TryGetValue(VariableTypeIds.PropertyType.ToString(), out _id));
            NodeId _nid = NodeId.Parse(_ni);

            Assert.IsNotNull(_nid);
            Assert.AreEqual <int>(1, _dc.Where <KeyValuePair <string, NodeId> >(x => x.Key == _nid.ToString()).Count <KeyValuePair <string, NodeId> >());
            Assert.IsTrue(_dc.TryGetValue(_nid.ToString(), out _id));
            Assert.IsTrue(_dc.ContainsKey(_nid.ToString()));
        }
Beispiel #15
0
 private void Update(IVariableTypeFactory nodeDesign, UAVariableType nodeSet)
 {
     nodeDesign.ArrayDimensions = nodeSet.ArrayDimensions.ExportString(string.Empty);
     nodeDesign.DataType        = AS.ExportBrowseName(NodeId.Parse(nodeSet.DataType), DataTypes.Number);
     nodeDesign.DefaultValue    = nodeSet.Value;
     nodeDesign.ValueRank       = nodeSet.ValueRank.GetValueRank(Log.TraceEvent);
 }
Beispiel #16
0
        /// <summary>
        /// Converts the configured target node id into a OPC UA NodeId.
        /// </summary>
        public NodeId GetNodeIdFromId(string id)
        {
            String sanitizedId;
            NodeId nodeId = null;

            try
            {
                if (id.Contains("nsu="))
                {
                    Logger.Debug($"Normalizing «{id}»...");
                    sanitizedId = id.Replace(" ;", ";");
                    ExpandedNodeId expandedNodeId = ExpandedNodeId.Parse(sanitizedId);
                    nodeId = new NodeId(expandedNodeId.Identifier, (ushort)_namespaceTable.GetIndex(expandedNodeId.NamespaceUri));
                }
                else
                {
                    nodeId = NodeId.Parse(id);
                }
            }
            catch (Exception e)
            {
                Logger.Error(e, $"The NodeId has an invalid format '{id}'!");
                Environment.ExitCode = 1;
            }
            return(nodeId);
        }
Beispiel #17
0
        public void ConstructorNodeIdTest()
        {
            Mock <IAddressSpaceBuildContext> _addressSpaceMock = new Mock <IAddressSpaceBuildContext>();
            UANodeContext _toTest = new UANodeContext(NodeId.Parse("ns=1;i=11"), _addressSpaceMock.Object);

            Assert.IsNotNull(_toTest.BrowseName);
            Assert.IsTrue(new QualifiedName() == _toTest.BrowseName);
            Assert.IsFalse(_toTest.InRecursionChain);
            Assert.IsFalse(_toTest.IsProperty);
            Assert.IsFalse(((IUANodeBase)_toTest).IsPropertyVariableType);
            Assert.IsFalse(_toTest.ModelingRule.HasValue);
            Assert.IsNotNull(_toTest.NodeIdContext);
            Assert.IsTrue(_toTest.NodeIdContext.ToString() == "ns=1;i=11");
            Assert.IsNull(_toTest.UANode);
            XML.UANode _node = UnitTest.Helpers.TestData.CreateUAObject();
            int        _registerReferenceCounter = 0;

            _toTest.Update(_node, x => _registerReferenceCounter++);
            Assert.AreEqual <int>(2, _registerReferenceCounter);
            Assert.IsNotNull(_toTest.BrowseName);
            Assert.AreEqual <QualifiedName>(new QualifiedName("NewUAObject", 1), _toTest.BrowseName);
            Assert.IsFalse(_toTest.InRecursionChain);
            Assert.IsFalse(_toTest.IsProperty);
            Assert.IsFalse(((IUANodeBase)_toTest).IsPropertyVariableType);
            Assert.IsFalse(_toTest.ModelingRule.HasValue);
            Assert.IsNotNull(_toTest.NodeIdContext);
            Assert.AreEqual <string>(_toTest.NodeIdContext.ToString(), "ns=1;i=11");
            Assert.IsNotNull(_toTest.UANode);
        }
Beispiel #18
0
        private void OkBTN_Click(object sender, EventArgs e)
        {
            try
            {
                BrowsePathCollection browsePaths = new BrowsePathCollection();

                BrowsePath browsePath = new BrowsePath();

                browsePath.StartingNode = NodeId.Parse(StartNode.Text);
                browsePath.RelativePath = Opc.Ua.RelativePath.Parse(RelativePath.Text, m_session.TypeTree);

                browsePaths.Add(browsePath);

                BrowsePathResultCollection results         = null;
                DiagnosticInfoCollection   diagnosticInfos = null;

                m_session.TranslateBrowsePathsToNodeIds(
                    null,
                    browsePaths,
                    out results,
                    out diagnosticInfos);

                if (results != null && results.Count == 1)
                {
                    // NodesCTRL.SetNodeList(results[0].MatchingNodeIds);
                }
            }
            catch (Exception exception)
            {
                GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception);
            }
        }
Beispiel #19
0
        public void EqualsUAVariableTestMethod()
        {
            UAVariable _derivedNode = new UAVariable()
            {
                NodeId       = "ns=1;i=47",
                BrowseName   = "EURange",
                ParentNodeId = "ns=1;i=43",
                DataType     = "i=884",
                DisplayName  = new XML.LocalizedText[] { new XML.LocalizedText()
                                                         {
                                                             Value = "EURange"
                                                         } }
            };
            UANode _baseNode = new UAVariable()
            {
                NodeId       = "i=17568",
                BrowseName   = "EURange",
                ParentNodeId = "i=15318",
                DataType     = "i=884",
                DisplayName  = new XML.LocalizedText[] { new XML.LocalizedText()
                                                         {
                                                             Value = "EURange"
                                                         } }
            };
            Mock <IAddressSpaceBuildContext> _asMock = new Mock <IAddressSpaceBuildContext>();
            IUANodeContext _derivedNodeContext       = new UANodeContext(NodeId.Parse("ns=1;i=47"), _asMock.Object);

            _derivedNodeContext.Update(_derivedNode, x => Assert.Fail());
            UANodeContext _baseNodeContext = new UANodeContext(NodeId.Parse("i=17568"), _asMock.Object);

            _baseNodeContext.Update(_baseNode, x => Assert.Fail());
            Assert.IsTrue(_derivedNode.Equals(_baseNode));
            Assert.IsTrue(_derivedNodeContext.Equals(_baseNodeContext));
        }
        public async Task ConfirmAsync()
        {
            var condition = new AcknowledgeableCondition();
            var comment   = new LocalizedText("Comment");
            var response  = new CallResponse
            {
                Results = new CallMethodResult[]
                {
                    new CallMethodResult
                    {
                        StatusCode = StatusCodes.BadAttributeIdInvalid
                    }
                }
            };
            var channel = new TestRequestChannel(response);

            var ret = await channel.ConfirmAsync(condition, comment);

            ret
            .Should().Be((StatusCode)StatusCodes.BadAttributeIdInvalid);

            channel.Request
            .Should().BeEquivalentTo(new
            {
                MethodsToCall = new[]
                {
                    new
                    {
                        ObjectId       = condition.ConditionId,
                        MethodId       = NodeId.Parse(MethodIds.AcknowledgeableConditionType_Confirm),
                        InputArguments = new Variant[] { condition.EventId, comment }
                    }
                }
            });
        }
        /// <summary>
        /// Reads first/next level of tag tree.
        /// </summary>
        async Task <Tag> ReadTag(ReferenceDescription[] rds, UaTcpSessionChannel channel, Tag tag)
        {
            ReadValueId[] items = new ReadValueId[1];
            items[0] = new ReadValueId {
                NodeId = NodeId.Parse(rds.Last().NodeId.ToString()), AttributeId = AttributeIds.DataType
            };
            ReadRequest readRequest = new ReadRequest {
                NodesToRead = items
            };
            ReadResponse readResponse = await channel.ReadAsync(readRequest);

            if (string.IsNullOrEmpty(tag.Name))
            {
                tag = new Tag(rds.Take(rds.Length - 1).ToList());
            }
            tag.NestedName(rds.Last().DisplayName);

            if (rds.Length > 2)
            {
                tag.Group4 = rds[1].DisplayName.ToString();
            }
            if (rds.Length > 1)
            {
                tag.Group3 = rds[0].DisplayName.ToString();
            }

            if (readResponse.Results[0].Value != null)
            {
                tag.ConversionFunction = Typ(readResponse.Results[0].Value.ToString());
            }

            return(tag);
        }
        private async void OkBTN_Click(object sender, EventArgs e)
        {
            NodeId viewId = null;

            try
            {
                viewId = NodeId.Parse(ViewIdTB.Text);
            }
            catch (Exception)
            {
                MessageDlg dialog = new MessageDlg("Please enter a valid node id for the view id.");
                await dialog.ShowAsync();
            }

            try
            {
                ViewDescription view = null;

                if (!NodeId.IsNull(viewId) || ((bool)ViewTimestampCK.IsChecked || (bool)ViewVersionCK.IsChecked))
                {
                    view = new ViewDescription();

                    view.ViewId      = viewId;
                    view.Timestamp   = DateTime.MinValue;
                    view.ViewVersion = 0;

                    if ((bool)ViewTimestampCK.IsChecked && (ViewTimestampDP.Date > ViewTimestampDP.MinYear))
                    {
                        view.Timestamp = Convert.ToDateTime(ViewTimestampDP.Date);
                    }

                    if ((bool)ViewVersionCK.IsChecked)
                    {
                        view.ViewVersion = (uint)ViewVersionNC.Value;
                    }
                }

                m_browser.View = view;
                m_browser.MaxReferencesReturned = (uint)MaxReferencesReturnedNC.Value;
                m_browser.BrowseDirection       = (BrowseDirection)BrowseDirectionCB.SelectedItem;
                m_browser.NodeClassMask         = (int)NodeClass.View | (int)NodeClass.Object;
                m_browser.ReferenceTypeId       = ReferenceTypeCTRL.SelectedTypeId;
                m_browser.IncludeSubtypes       = (bool)IncludeSubtypesCK.IsChecked;
                m_browser.NodeClassMask         = 0;

                int nodeClassMask = 0;

                foreach (NodeClass nodeClass in NodeClassList.Items)
                {
                    nodeClassMask |= (int)nodeClass;
                }

                m_browser.NodeClassMask = nodeClassMask;
            }
            catch (Exception exception)
            {
                GuiUtils.HandleException(String.Empty, GuiUtils.CallerName(), exception);
            }
        }
Beispiel #23
0
        public async Task SessionTimeoutCausesFault()
        {
            // discover available endpoints of server.
            var getEndpointsRequest = new GetEndpointsRequest
            {
                EndpointUrl = EndpointUrl,
                ProfileUris = new[] { TransportProfileUris.UaTcpTransport }
            };

            Console.WriteLine($"Discovering endpoints of '{getEndpointsRequest.EndpointUrl}'.");
            var getEndpointsResponse = await UaTcpDiscoveryService.GetEndpointsAsync(getEndpointsRequest);

            var selectedEndpoint = getEndpointsResponse.Endpoints.OrderBy(e => e.SecurityLevel).Last();

            var           selectedTokenType = selectedEndpoint.UserIdentityTokens[0].TokenType;
            IUserIdentity selectedUserIdentity;

            switch (selectedTokenType)
            {
            case UserTokenType.UserName:
                selectedUserIdentity = new UserNameIdentity("root", "secret");
                break;

            default:
                selectedUserIdentity = new AnonymousIdentity();
                break;
            }

            var channel = new UaTcpSessionChannel(
                this.localDescription,
                this.certificateStore,
                selectedUserIdentity,
                selectedEndpoint,
                loggerFactory: this.loggerFactory,
                options: new UaTcpSessionChannelOptions {
                SessionTimeout = 10000
            });

            await channel.OpenAsync();

            Console.WriteLine($"Opened session with endpoint '{channel.RemoteEndpoint.EndpointUrl}'.");
            Console.WriteLine($"SecurityPolicy: '{channel.RemoteEndpoint.SecurityPolicyUri}'.");
            Console.WriteLine($"SecurityMode: '{channel.RemoteEndpoint.SecurityMode}'.");
            Console.WriteLine($"Activated session '{channel.SessionId}'.");

            // server should close session due to inactivity
            await Task.Delay(20000);

            // should throw exception
            var readRequest = new ReadRequest {
                NodesToRead = new[] { new ReadValueId {
                                          NodeId = NodeId.Parse(VariableIds.Server_ServerStatus_CurrentTime), AttributeId = AttributeIds.Value
                                      } }
            };
            await channel.ReadAsync(readRequest);

            Console.WriteLine($"Closing session '{channel.SessionId}'.");
            await channel.CloseAsync();
        }
Beispiel #24
0
        public void CalculateNodeReferencesNullFactoryTest()
        {
            Mock <IAddressSpaceBuildContext> _addressSpaceMock = new Mock <IAddressSpaceBuildContext>();
            Mock <IValidator> _validatorMoc = new Mock <IValidator>();
            IUANodeBase       _first        = new UANodeContext(NodeId.Parse("ns=1;i=11"), _addressSpaceMock.Object);

            _first.CalculateNodeReferences(null, _validatorMoc.Object);
        }
Beispiel #25
0
        public void CalculateNodeReferencesValidatorIsNullTest()
        {
            Mock <IAddressSpaceBuildContext> _addressSpaceMock = new Mock <IAddressSpaceBuildContext>();
            Mock <INodeFactory> _mockNodeFactory = new Mock <INodeFactory>();
            IUANodeBase         _first           = new UANodeContext(NodeId.Parse("ns=1;i=11"), _addressSpaceMock.Object);

            _first.CalculateNodeReferences(_mockNodeFactory.Object, null);
        }
Beispiel #26
0
            private UANodeContext NewNode(UANode newNode)
            {
                UANodeContext _newNode = new UANodeContext(NodeId.Parse(newNode.NodeId), this);

                _newNode.Update(newNode, x => { m_References.Add(x.Key, x); });
                Add2mNodesDictionary(_newNode);
                return(_newNode);
            }
        /// <summary>
        /// Finishes a drag and drop action whereas this control is used as target.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void MonitoredItems_DragDrop(object sender, DragEventArgs e)
        {
            // Retrieve the event data and create the according nodeid.
            String sNodeId = (String)e.Data.GetData(typeof(System.String));
            NodeId nodeId  = NodeId.Parse(sNodeId);

            addMonitoredItem(nodeId);
        }
Beispiel #28
0
        private NodeId ParseNodeId(string txt)
        {
            if (_alias.TryGetValue(txt, out var nodeId))
            {
                return(nodeId);
            }

            return(NodeId.Parse(txt));
        }
Beispiel #29
0
        private bool TryGetForwardId(NodeId nodeId, out NodeId forwardId)
        {
            var curId = nodeId;

            while (_parentIds.TryGetValue(curId, out var parentId))
            {
                curId = parentId;
            }

            if (curId.NamespaceIndex != 0 || curId.IdType != IdType.Numeric)
            {
                forwardId = null;
                return(false);
            }

            switch ((uint)curId.Identifier)
            {
            case 290:     // Duration
                forwardId = NodeId.Parse(DataTypeIds.Double);
                return(true);

            case 294:
                forwardId = NodeId.Parse(DataTypeIds.DateTime);
                return(true);

            case BooleanNumber:
            case SByteNumber:
            case ByteNumber:
            case Int16Number:
            case UInt16Number:
            case Int32Number:
            case UInt32Number:
            case Int64Number:
            case UInt64Number:
            case FloatNumber:
            case DoubleNumber:
            case StringNumber:
            case DateTimeNumber:
            case GuidNumber:
            case ByteStringNumber:
            case XmlElementNumber:
            case NodeIdNumber:
            case ExpandedNodeIdNumber:
            case StatusCodeNumber:
            case QualifiedNameNumber:
            case LocalizedTextNumber:
            case DataValueNumber:
            case BaseDataTypeNumber:
            case DiagnosticInfoNumber:
                forwardId = curId;
                return(forwardId != nodeId);
            }

            forwardId = null;
            return(false);
        }
Beispiel #30
0
        public void EncodeNodeId(string id)
        {
            var input    = NodeId.Parse(id);
            var expected = Opc.Ua.NodeId.Parse(id);

            EncodeDecode(
                e => e.WriteNodeId(null, input),
                d => d.ReadNodeId(null))
            .Should().Be(expected);
        }