public async Task ReadNodesAsync() { if (ReferenceDescriptions == null) { await BrowseFullAddressSpace(null).ConfigureAwait(false); } NodeIdCollection nodes = new NodeIdCollection( ReferenceDescriptions.Take(MaxReferences).Select(reference => ExpandedNodeId.ToNodeId(reference.NodeId, Session.NamespaceUris)) ); (IList <Node> nodeCollection, IList <ServiceResult> errors) = await Session.ReadNodesAsync(nodes).ConfigureAwait(false); Assert.NotNull(nodeCollection); Assert.NotNull(errors); Assert.AreEqual(nodes.Count, nodeCollection.Count); Assert.AreEqual(nodes.Count, errors.Count); int ii = 0; var variableNodes = new NodeIdCollection(); foreach (Node node in nodeCollection) { Assert.NotNull(node); Assert.AreEqual(ServiceResult.Good, errors[ii]); TestContext.Out.WriteLine("NodeId: {0} Node: {1}", node.NodeId, node); if (node is VariableNode) { try { variableNodes.Add(node.NodeId); var value = await Session.ReadValueAsync(node.NodeId).ConfigureAwait(false); Assert.NotNull(value); TestContext.Out.WriteLine("-- Value {0} ", value); } catch (ServiceResultException sre) { TestContext.Out.WriteLine("-- Read Value {0} ", sre.Message); } } ii++; } DataValueCollection values; (values, errors) = await Session.ReadValuesAsync(nodes).ConfigureAwait(false); Assert.NotNull(values); Assert.NotNull(errors); Assert.AreEqual(nodes.Count, values.Count); Assert.AreEqual(nodes.Count, errors.Count); (values, errors) = await Session.ReadValuesAsync(variableNodes).ConfigureAwait(false); Assert.NotNull(values); Assert.NotNull(errors); Assert.AreEqual(variableNodes.Count, values.Count); Assert.AreEqual(variableNodes.Count, errors.Count); }
/// <summary> /// Sets the nodes in the control. /// </summary> public void Initialize(Session session, NodeIdCollection nodeIds, NodeClass nodeClassMask) { if (session == null) throw new ArgumentNullException("session"); Clear(); m_session = session; m_nodeIds = nodeIds; m_nodeClassMask = (nodeClassMask == 0)?(NodeClass)Byte.MaxValue:nodeClassMask; if (nodeIds == null) { return; } foreach (NodeId nodeId in nodeIds) { INode node = m_session.NodeCache.Find(nodeId); if (node != null && (m_nodeClassMask & node.NodeClass) != 0) { AddItem(node, "Property", -1); } } AdjustColumns(); }
/// <summary> /// Read namespace table from server and find index for namespace specified in settings. /// </summary> private void ReadNamespaceFromServer() { // Read Namespace Table NodeIdCollection nodesToRead = new NodeIdCollection(); DataValueCollection results; nodesToRead.Add(Variables.Server_NamespaceArray); // Read the namespace array m_Server.ReadValues(nodesToRead, out results); if ((results.Count != 1) || (results[0].Value.GetType() != typeof(string[]))) { throw new Exception("Reading namespace table returned unexptected result"); } // Try to find the namespace URI entered by the user string[] nameSpaceArray = (string[])results[0].Value; ushort i; for (i = 0; i < nameSpaceArray.Length; i++) { if (nameSpaceArray[i] == this.settings.NamespaceUri) { m_NameSpaceIndex = i; } } // Check if the namespace was found if (m_NameSpaceIndex == 0) { throw new Exception(string.Format("Namespace {0} not found in server namespace table", this.settings.NamespaceUri)); } }
/// <summary> /// 发送心跳 /// </summary> /// <param name="heartbit"></param> public static bool SendHeartBit(bool heartbit, StationModel station, BaseProtocol protocol) { try { if (station.StationOPCServer == null || !station.StationOPCServer.Session.Connected) { return(false); } NodeIdCollection nodesToWriteHeart = new NodeIdCollection(); string comDB = station.DataWriteDB; //握手信号交互DB块 nodesToWriteHeart.Add(new NodeId(comDB + protocol.MES_PLC_Heart, station.ServerIndex)); //心跳 DataValueCollection values = new DataValueCollection(); values.Add(new DataValue(heartbit)); StatusCodeCollection codes; station.StationOPCServer.WriteValues(nodesToWriteHeart, values, out codes); foreach (StatusCode item in codes) { if (StatusCode.IsBad(item.Code)) { return(false); } } return(true); } catch (Exception ex) { LogHelper.Write("发送心跳异常:" + ex.Message, "system"); return(false); } }
/// <summary> /// 发送上线完成信号 /// </summary> public bool SendWriteDownCmd() { try { NodeIdCollection writeDowdNode = new NodeIdCollection(); // string comDB = MyStationModel.CommunicationDB;//握手信号交互DB块 string comDB = MyStationModel.DataWriteDB; //握手信号交互DB块 writeDowdNode.Add(new NodeId(comDB + MyBaseProtocol.MES_PLC_WriteDowd, ServerIndex)); //上线中 DataValueCollection values = new DataValueCollection(); values.Add(new DataValue(true)); StatusCodeCollection codes; MyServer.WriteValues(writeDowdNode, values, out codes); foreach (StatusCode item in codes) { if (StatusCode.IsBad(item.Code)) { return(false); } } return(true); } catch (Exception ex) { LogHelper.Write(ex, "system"); return(false); } }
public bool InitRepairPLCData(byte[] data) { try { string itemName = ".0,b," + data.Length; //tag数据 string dbnum = MyStationModel.RepairDataWriteDB; //写数据的DB块 NodeIdCollection writeNodecoll = new NodeIdCollection(); writeNodecoll.Add(new NodeId(dbnum + itemName, ServerIndex)); DataValueCollection values = new DataValueCollection(); values.Add(new DataValue(data)); StatusCodeCollection resultCodes; MyServer.WriteValues(writeNodecoll, values, out resultCodes); foreach (StatusCode item in resultCodes) { if (StatusCode.IsBad(item.Code)) { return(false); } } return(true); } catch (Exception ex) { LogHelper.Write("向PLC写入返修数据时出错" + ex.Message + "\r\n" + ex.StackTrace, "system"); return(false); } }
/// <summary> /// Sets the nodes in the control. /// </summary> public void Initialize(Session session, NodeIdCollection nodeIds, NodeClass nodeClassMask) { if (session == null) { throw new ArgumentNullException("session"); } Clear(); m_session = session; m_nodeIds = nodeIds; m_nodeClassMask = (nodeClassMask == 0)?(NodeClass)Byte.MaxValue:nodeClassMask; if (nodeIds == null) { return; } foreach (NodeId nodeId in nodeIds) { INode node = m_session.NodeCache.Find(nodeId); if (node != null && (m_nodeClassMask & node.NodeClass) != 0) { AddItem(node, "Property", -1); } } AdjustColumns(); }
public void ConnectServer(StationModel stationmodel, APPConfiguration appconfig, BaseProtocol baseProtocol) { if (Convert.ToBoolean(stationmodel.STN_Status)) { stationmodel.StationOPCServer = new Server(); stationmodel.StationOPCServer.CertificateEvent += new certificateValidation(my_Server_CertificateEvent); stationmodel.StationOPCServer.Connect(appconfig.OPCServerUrl); NodeIdCollection nodesNamespace = new NodeIdCollection(); DataValueCollection results; nodesNamespace.Add(Variables.Server_NamespaceArray); ushort serverNamespaceIndex = 0; stationmodel.StationOPCServer.ReadValues(nodesNamespace, out results); string[] resultArray = results[0].Value as string[]; for (int i = 0; i < resultArray.Length; i++) { if (resultArray[i].ToString().Equals("S7:")) { serverNamespaceIndex = (ushort)i; break; } } //_serverNamespaceIndex = serverNamespaceIndex; CreateMonitorItem(serverNamespaceIndex, stationmodel, baseProtocol); stationmodel.ServerIndex = serverNamespaceIndex; //opchelper = new OpcHelper(baseProtocol, stationmodel, serverNamespaceIndex); //opchelper.MyServer = stationmodel.StationOPCServer; // opcbll.myopcHelper = opchelper; } }
/// <summary> /// Helper function to writing a value to a variable. /// The function /// - reads the data type of the variable /// - converts the passed string to the data type /// - writes the value to the variable /// </summary> private void writeNewBlockValue(NodeId nodeToWrite, object valueToWrite) { try { NodeIdCollection nodesToWrite = new NodeIdCollection(); DataValueCollection values = new DataValueCollection(); StatusCodeCollection results; Variant value = new Variant(valueToWrite); nodesToWrite.Add(nodeToWrite); values.Add(new DataValue(value)); m_Server.WriteValues( nodesToWrite, values, out results); if (StatusCode.IsBad(results[0])) { throw new Exception(StatusCode.LookupSymbolicId(results[0].Code)); } } catch (Exception ex) { MessageBox.Show("Writing new block value failed:\n\n" + ex.Message); } }
public void InitOpc() { try { string url = MyAppConfig.OPCServerUrl; MyServer = new Server(); MyServer.CertificateEvent += new certificateValidation(my_Server_CertificateEvent); MyServer.Connect(url); NodeIdCollection nodesNamespace = new NodeIdCollection(); DataValueCollection results; nodesNamespace.Add(Variables.Server_NamespaceArray); ushort serverNamespaceIndex = 0; MyServer.ReadValues(nodesNamespace, out results); string[] resultArray = results[0].Value as string[]; for (int i = 0; i < resultArray.Length; i++) { if (resultArray[i].ToString().Equals("S7:")) { serverNamespaceIndex = (ushort)i; break; } } _serverNamespaceIndex = serverNamespaceIndex; InitMonitorItem(serverNamespaceIndex); } catch (Exception ex) { LogHelper.Write(ex, "BingEvent"); } }
/// <summary> /// 发送上线中信号 /// </summary> public void SendWritingCmd() { try { NodeIdCollection writingNode = new NodeIdCollection(); // string comDB = MyStationModel.CommunicationDB;//握手信号交互DB块 string comDB = MyStationModel.DataWriteDB; //握手信号交互DB块 writingNode.Add(new NodeId(comDB + MyBaseProtocol.MES_PLC_Writing, ServerIndex)); //上线中 DataValueCollection values = new DataValueCollection(); // byte[] buff = { 1 }; values.Add(new DataValue(true)); StatusCodeCollection codes; MyServer.WriteValues(writingNode, values, out codes); foreach (StatusCode item in codes) { if (StatusCode.IsBad(item.Code)) { Console.WriteLine("Error" + item.Code.ToString()); } } } catch (Exception ex) { LogHelper.Write(ex, "system"); } }
/// <summary> /// Reads the values of the two variables entered in the From. /// The NodeIds used for the Read are constructed from the identifier entered /// in the Form and the namespace index detected in the connect method /// </summary> private void btnRead_Click(object sender, EventArgs e) { try { NodeIdCollection nodesToRead = new NodeIdCollection(); DataValueCollection results; // Add the two variable NodeIds to the list of nodes to read // NodeId is constructed from // - the identifier text in the text box // - the namespace index collected during the server connect nodesToRead.Add(new NodeId(txtIdentifier1.Text, m_NameSpaceIndex)); nodesToRead.Add(new NodeId(txtIdentifier2.Text, m_NameSpaceIndex)); // Read the values m_Server.ReadValues(nodesToRead, out results); if (results.Count != 2) { throw new Exception("Reading value returned unexptected number of result"); } // Print result for first variable - check first the result code if (StatusCode.IsBad(results[0].StatusCode)) { // The node failed - print the symbolic name of the status code txtRead1.Text = StatusCode.LookupSymbolicId(results[0].StatusCode.Code); txtRead1.BackColor = Color.Red; } else { // The node succeeded - print the value as string txtRead1.Text = results[0].Value.ToString(); txtRead1.BackColor = Color.White; currentValue1 = results[0].Value; } // Print result for second variable - check first the result code if (StatusCode.IsBad(results[1].StatusCode)) { // The node failed - print the symbolic name of the status code txtRead2.Text = StatusCode.LookupSymbolicId(results[1].StatusCode.Code); txtRead2.BackColor = Color.Red; } else { // The node succeeded - print the value as string txtRead2.Text = results[1].Value.ToString(); txtRead2.BackColor = Color.White; currentValue2 = results[1].Value; } } catch (Exception ex) { MessageBox.Show("Read failed:\n\n" + ex.Message); } }
public void ReadValues() { var namespaceUris = Session.NamespaceUris; var testSet = new NodeIdCollection(GetTestSetStatic(namespaceUris)); testSet.AddRange(GetTestSetSimulation(namespaceUris)); Session.ReadValues(testSet, out DataValueCollection values, out IList <ServiceResult> errors); Assert.AreEqual(testSet.Count, values.Count); Assert.AreEqual(testSet.Count, errors.Count); }
/// <summary> /// Invokes the UnregisterNodes service. /// </summary> public virtual ResponseHeader UnregisterNodes( RequestHeader requestHeader, NodeIdCollection nodesToUnregister) { ValidateRequest(requestHeader); // Insert implementation. return(CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported)); }
/// <summary> /// Connect to the UA server and read the namespace table. /// The connect is based on the Server URL entered in the Form /// The read of the namespace table is used to detect the namespace index /// of the namespace URI entered in the Form and used for the variables to read /// </summary> private void btnConnect_Click(object sender, EventArgs e) { // Connect to the server try { // Connect with URL from Server URL text box m_Server.Connect(txtServerUrl.Text); // Toggle enable flag of buttons toggleButtons(true); } catch (Exception ex) { MessageBox.Show("Connect failed:\n\n" + ex.Message); return; } // Read Namespace Table try { NodeIdCollection nodesToRead = new NodeIdCollection(); DataValueCollection results; nodesToRead.Add(Variables.Server_NamespaceArray); // Read the namespace array m_Server.ReadValues(nodesToRead, out results); if ((results.Count != 1) || (results[0].Value.GetType() != typeof(string[]))) { throw new Exception("Reading namespace table returned unexptected result"); } // Try to find the namespace URI entered by the user string[] nameSpaceArray = (string[])results[0].Value; ushort i; for (i = 0; i < nameSpaceArray.Length; i++) { if (nameSpaceArray[i] == txtNamespaceUri.Text) { m_NameSpaceIndex = i; } } // Check if the namespace was found if (m_NameSpaceIndex == 0) { throw new Exception("Namespace " + txtNamespaceUri.Text + " not found in server namespace table"); } } catch (Exception ex) { MessageBox.Show("Reading namespace table failed:\n\n" + ex.Message); } }
public string ReadOperatorNum() { string readDb = MyStationModel.DataReadDB; NodeIdCollection readNode = new NodeIdCollection(); readNode.Add(new NodeId(readDb + ".362" + ",b," + 10, ServerIndex));//读取安东物料号 DataValueCollection valuecoll = new DataValueCollection(); MyServer.ReadValues(readNode, out valuecoll); byte[] bArray = (byte[])valuecoll[0].Value; return(ConvertHelper.ByteToString(bArray, 0, 10)); }
public string ReadPackID() { string readDb = MyStationModel.DataReadDB; NodeIdCollection readNode = new NodeIdCollection(); readNode.Add(new NodeId(readDb + ".120" + ",b," + 70, ServerIndex));//读取packid DataValueCollection valuecoll = new DataValueCollection(); MyServer.ReadValues(readNode, out valuecoll); byte[] bArray = (byte[])valuecoll[0].Value; return(ConvertHelper.ByteToString(bArray, 0, 70)); }
public string ReadQRCodeData() { string readDb = MyStationModel.DataReadDB; NodeIdCollection readNode = new NodeIdCollection(); readNode.Add(new NodeId(readDb + ".380" + ",b," + 64, ServerIndex));//读取二维码 DataValueCollection valuecoll = new DataValueCollection(); MyServer.ReadValues(readNode, out valuecoll); byte[] bArray = (byte[])valuecoll[0].Value; return(ConvertHelper.ByteToString(bArray, 0, 64)); }
public List <NodeId> RegisterNodes(List <string> nodesToRegister) { if (nodesToRegister.Count == 0) { return(new List <NodeId>()); } var nodeIdsToRegister = new NodeIdCollection(nodesToRegister.Select(x => new NodeId(x)).ToList()); _session.RegisterNodes(null, nodeIdsToRegister, out var registeredNodeIds); _registeredNodes.AddRange(registeredNodeIds); return(registeredNodeIds); }
/// <summary> /// 在240 工位 不管是返修还是正常下线 PLC那边都会把整个tag读出来,发给MES /// </summary> /// <returns></returns> public byte[] ReadRepairPlcData() { string readDb = MyStationModel.RepairDataReadDB; string dblen = "8876";//tag数据字节数 NodeIdCollection readNode = new NodeIdCollection(); readNode.Add(new NodeId(readDb + ".0" + ",b," + dblen, ServerIndex));//读整个DB块 DataValueCollection valuecoll = new DataValueCollection(); MyServer.ReadValues(readNode, out valuecoll); byte[] bArray = (byte[])valuecoll[0].Value; return(bArray); }
public NodeId RegisterNode(string nodeToRegister) { var nodeIdToRegister = new NodeIdCollection() { new NodeId(nodeToRegister) }; _session.RegisterNodes(null, nodeIdToRegister, out var registeredNode); var node = registeredNode.FirstOrDefault(); _registeredNodes.Add(node); return(node); }
public IEnumerable <DataValue> ReadHistoryProcessed(string tag, DateTime start, DateTime end, string aggregateFunction, double processingInterval, uint count = 1, bool containBound = false) { HistoryReadValueId m_nodeToContinue = new HistoryReadValueId() { NodeId = new NodeId(tag), }; AggregateConfiguration aggregate = new AggregateConfiguration(); NodeIdCollection aggregateTypes = new NodeIdCollection(); aggregateTypes.Add(new NodeId(aggregateFunction)); ReadProcessedDetails m_details = new ReadProcessedDetails { StartTime = start.ToUniversalTime(), EndTime = end.ToUniversalTime(), AggregateConfiguration = aggregate, AggregateType = aggregateTypes, ProcessingInterval = processingInterval, }; m_logger.Information("start {0}/end {0}", m_details.StartTime, m_details.EndTime); HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection(); nodesToRead.Add(m_nodeToContinue); m_session.HistoryRead( null, new ExtensionObject(m_details), TimestampsToReturn.Both, false, nodesToRead, out HistoryReadResultCollection results, out DiagnosticInfoCollection diagnosticInfos); ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); if (StatusCode.IsBad(results[0].StatusCode)) { throw new ServiceResultException(results[0].StatusCode); } HistoryData values = ExtensionObject.ToEncodeable(results[0].HistoryData) as HistoryData; foreach (var value in values.DataValues) { yield return(value); } }
/// <summary> /// Create a browse description from a node id collection. /// </summary> /// <param name="nodeIdCollection">The node id collection.</param> /// <param name="template">The template for the browse description for each node id.</param> public static BrowseDescriptionCollection CreateBrowseDescriptionCollectionFromNodeId( NodeIdCollection nodeIdCollection, BrowseDescription template) { var browseDescriptionCollection = new BrowseDescriptionCollection(); foreach (var nodeId in nodeIdCollection) { BrowseDescription browseDescription = (BrowseDescription)template.MemberwiseClone(); browseDescription.NodeId = nodeId; browseDescriptionCollection.Add(browseDescription); } return(browseDescriptionCollection); }
/// <summary> /// Writes the values. /// </summary> private void WriteValues() { try { // Prepare call to ClientAPI. NodeIdCollection nodesToWrite = new NodeIdCollection(this.listView.Items.Count); DataValueCollection values = new DataValueCollection(this.listView.Items.Count); StatusCodeCollection results = null; int i = 0; foreach (ListViewItem item in this.listView.Items) { // Values to write. String sValue = (String)item.SubItems[0].Text; // Leave current value if write value is empty. if (sValue.Length == 0) { i++; continue; } Variant variant = new Variant(Convert.ChangeType(sValue, m_currentValues[i].Value.GetType())); DataValue value = new DataValue(variant); values.Add(value); // NodeIds. String sNodeId = item.SubItems[1].Text; NodeId nodeId = new NodeId(sNodeId); nodesToWrite.Add(nodeId); i++; } // Call to ClientAPI. m_Server.WriteValues( nodesToWrite, values, out results); // Update status label. toolStripStatusLabel.Text = "Writing values succeeded."; } catch (Exception e) { // Update status label. toolStripStatusLabel.Text = "An exception occured while writing values: " + e.Message; } }
/// <inheritdoc/> public IList <Node> FetchNodes(IList <ExpandedNodeId> nodeIds) { int count = nodeIds.Count; NodeIdCollection localIds = new NodeIdCollection( nodeIds.Select(nodeId => ExpandedNodeId.ToNodeId(nodeId, m_session.NamespaceUris))); // fetch nodes and references from server. m_session.ReadNodes(localIds, out IList <Node> sourceNodes, out IList <ServiceResult> readErrors); m_session.FetchReferences(localIds, out IList <ReferenceDescriptionCollection> referenceCollectionList, out IList <ServiceResult> fetchErrors); int ii = 0; for (ii = 0; ii < count; ii++) { if (ServiceResult.IsBad(readErrors[ii])) { continue; } if (!ServiceResult.IsBad(fetchErrors[ii])) { // fetch references from server. ReferenceDescriptionCollection references = referenceCollectionList[ii]; foreach (ReferenceDescription reference in references) { // create a placeholder for the node if it does not already exist. if (!m_nodes.Exists(reference.NodeId)) { // transform absolute identifiers. if (reference.NodeId != null && reference.NodeId.IsAbsolute) { reference.NodeId = ExpandedNodeId.ToNodeId(reference.NodeId, NamespaceUris); } Node target = new Node(reference); m_nodes.Attach(target); } // add the reference. sourceNodes[ii].ReferenceTable.Add(reference.ReferenceTypeId, !reference.IsForward, reference.NodeId); } } // add to cache. m_nodes.Attach(sourceNodes[ii]); } return(sourceNodes); }
public byte[] ReadPlcData() { string readDb = MyStationModel.DataReadDB; string address = MyStationModel.DataAddress; string dblen = MyStationModel.DBLength; string len = MyStationModel.DataLength; NodeIdCollection readNode = new NodeIdCollection(); readNode.Add(new NodeId(readDb + ".0" + ",b," + dblen, ServerIndex));//读整个DB块 DataValueCollection valuecoll = new DataValueCollection(); MyServer.ReadValues(readNode, out valuecoll); byte[] bArray = (byte[])valuecoll[0].Value; return(bArray); }
/// <summary> /// Returns the node ids in the control. /// </summary> public NodeIdCollection GetNodeIds() { NodeIdCollection nodeIds = new NodeIdCollection(); foreach (ListViewItem listItem in ItemsLV.Items) { Node node = listItem.Tag as Node; if (node != null) { nodeIds.Add(node.NodeId); } } return(nodeIds); }
private void btnWrite_Click(object sender, EventArgs e) { string nodeID = txtNodeID.Text.Trim(); string writevalue = txtWriteValue.Text.Trim(); if (string.IsNullOrEmpty(nodeID)) { MessageBox.Show("请输入NodeID"); return; } if (string.IsNullOrEmpty(writevalue)) { MessageBox.Show("请输入写入的值"); return; } NodeIdCollection nic = new NodeIdCollection(); NodeId nodeid = new NodeId(nodeID); nic.Add(nodeid); DataValueCollection valueC; server.ReadValues( nic, out valueC); Variant variant = new Variant(Convert.ChangeType(writevalue, valueC[0].Value.GetType())); DataValueCollection values = new DataValueCollection(); DataValue value = new DataValue(variant); values.Add(value); StatusCodeCollection results = null; server.WriteValues( nic, values, out results); txtReadValue.Text = writevalue; txtResult.Text = "write success"; }
private void WriteValuePlus(String valueSign) { try { // 声明需要写入的数据 NodeIdCollection nodesToWrite = new NodeIdCollection(1); DataValueCollection values = new DataValueCollection(1); StatusCodeCollection results = null; Variant variant = new Variant(); DataValue value = new DataValue(); String sNodeId = ""; if (valueSign.Equals("X")) { String sValue = (MainWindow.myMotorPos.XValue + 1).ToString(); //variant = new Variant(MainWindow.myMotorPos.YValue + 1); variant = new Variant(Convert.ChangeType(sValue, m_currentXValue.Value.GetType())); value = new DataValue(variant); values.Add(value); sNodeId = "ns=2;s=Channel1.Device1.Tag1"; } else if (valueSign.Equals("Y")) { //variant = new Variant(MainWindow.myMotorPos.YValue + 1); String sValue = (MainWindow.myMotorPos.YValue + 1).ToString(); Type testType = m_currentYValue.Value.GetType(); variant = new Variant(Convert.ChangeType(sValue, m_currentYValue.Value.GetType())); value = new DataValue(variant); values.Add(value); sNodeId = "ns=2;s=Channel1.Device1.Tag2"; } NodeId nodeId = new NodeId(sNodeId); nodesToWrite.Add(nodeId); // 调用API方法 m_Server.WriteValues( nodesToWrite, values, out results); } catch (Exception ex) { MessageBox.Show("写入数据失败!错误原因:" + ex, "错误", MessageBoxButton.OK, MessageBoxImage.Error); } }
public static Entry For(NodeIdCollection nodeIds) { if (nodeIds == null) { return(new NullEntry()); } else { ArrayEntry array = new ArrayEntry(); NodeIdCollection.Enumerator e = nodeIds.GetEnumerator(); while (e.MoveNext()) { array.Add(For(e.Current)); } return(array); } }
/// <summary> /// 发送电芯NG剔料完成 /// </summary> public void SendDianXinNgOk() { try { NodeIdCollection readdownNode = new NodeIdCollection(); string comDB = MyStationModel.DataWriteDB;//握手信号交互DB块 readdownNode.Add(new NodeId(comDB + MyBaseProtocol.MES_PLC_CellRemoveOK, ServerIndex)); DataValueCollection values = new DataValueCollection(); values.Add(new DataValue(true)); StatusCodeCollection codes; MyServer.WriteValues(readdownNode, values, out codes); } catch (Exception ex) { LogHelper.Write(ex, "system"); } }
/// <summary> /// Displays the dialog. /// </summary> public NodeIdCollection ShowDialog( Session session, BrowseViewType browseView, NodeIdCollection nodesIds, NodeClass nodeClassMask) { if (session == null) throw new ArgumentNullException("session"); m_session = session; BrowseCTRL.SetView(session, browseView, null); NodeListCTRL.Initialize(session, nodesIds, nodeClassMask); if (ShowDialog() != DialogResult.OK) { return null; } return NodeListCTRL.GetNodeIds(); }
/// <summary> /// Invokes the UnregisterNodes service. /// </summary> public virtual ResponseHeader UnregisterNodes( RequestHeader requestHeader, NodeIdCollection nodesToUnregister) { ValidateRequest(requestHeader); // Insert implementation. return CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported); }
/// <summary> /// Reads an NodeId array from the stream. /// </summary> public NodeIdCollection ReadNodeIdArray(string fieldName) { bool isNil = false; NodeIdCollection values = new NodeIdCollection(); if (BeginField(fieldName, true, out isNil)) { PushNamespace(Namespaces.OpcUaXsd); while (MoveToElement("NodeId")) { values.Add(ReadNodeId("NodeId")); } // check the length. if (m_context.MaxArrayLength > 0 && m_context.MaxArrayLength < values.Count) { throw new ServiceResultException(StatusCodes.BadEncodingLimitsExceeded); } PopNamespace(); EndField(fieldName); return values; } if (isNil) { return null; } return values; }
/// <summary> /// Reads an NodeId array from the stream. /// </summary> public NodeIdCollection ReadNodeIdArray(string fieldName) { var values = new NodeIdCollection(); List<object> token = null; if (!ReadArrayField(fieldName, out token)) { return values; } for (int ii = 0; ii < token.Count; ii++) { try { m_stack.Push(token[ii]); var element = ReadNodeId(null); values.Add(element); } finally { m_stack.Pop(); } } return values; }
/// <summary> /// Returns all targets of the specified reference. /// </summary> public NodeIdCollection FindLocalNodes(NodeId sourceId, NodeId referenceTypeId, bool isInverse) { if (sourceId == null) throw new ArgumentNullException("sourceId"); if (referenceTypeId == null) throw new ArgumentNullException("referenceTypeId"); lock (m_lock) { ILocalNode source = GetManagerHandle(sourceId) as ILocalNode; if (source == null) { return null; } NodeIdCollection targets = new NodeIdCollection(); foreach (IReference reference in source.References) { if (reference.IsInverse != isInverse || !m_server.TypeTree.IsTypeOf(reference.ReferenceTypeId, referenceTypeId)) { continue; } ExpandedNodeId targetId = reference.TargetId; if (targetId.IsAbsolute) { continue; } targets.Add((NodeId)targetId); } return targets; } }
/// <summary> /// Returns the node ids in the control. /// </summary> public NodeIdCollection GetNodeIds() { NodeIdCollection nodeIds = new NodeIdCollection(); foreach (ListViewItem listItem in ItemsLV.Items) { Node node = listItem.Tag as Node; if (node != null) { nodeIds.Add(node.NodeId); } } return nodeIds; }
/// <summary> /// Invokes the UnregisterNodes service. /// </summary> public virtual ResponseHeader UnregisterNodes( RequestHeader requestHeader, NodeIdCollection nodesToUnregister) { UnregisterNodesRequest request = new UnregisterNodesRequest(); UnregisterNodesResponse response = null; request.RequestHeader = requestHeader; request.NodesToUnregister = nodesToUnregister; UpdateRequestHeader(request, requestHeader == null, "UnregisterNodes"); try { if (UseTransportChannel) { IServiceResponse genericResponse = TransportChannel.SendRequest(request); if (genericResponse == null) { throw new ServiceResultException(StatusCodes.BadUnknownResponse); } ValidateResponse(genericResponse.ResponseHeader); response = (UnregisterNodesResponse)genericResponse; } else { UnregisterNodesResponseMessage responseMessage = InnerChannel.UnregisterNodes(new UnregisterNodesMessage(request)); if (responseMessage == null || responseMessage.UnregisterNodesResponse == null) { throw new ServiceResultException(StatusCodes.BadUnknownResponse); } response = responseMessage.UnregisterNodesResponse; ValidateResponse(response.ResponseHeader); } } finally { RequestCompleted(request, response, "UnregisterNodes"); } return response.ResponseHeader; }
/// <summary> /// Begins an asynchronous invocation of the UnregisterNodes service. /// </summary> public IAsyncResult BeginUnregisterNodes( RequestHeader requestHeader, NodeIdCollection nodesToUnregister, AsyncCallback callback, object asyncState) { UnregisterNodesRequest request = new UnregisterNodesRequest(); request.RequestHeader = requestHeader; request.NodesToUnregister = nodesToUnregister; UpdateRequestHeader(request, requestHeader == null, "UnregisterNodes"); if (UseTransportChannel) { return TransportChannel.BeginSendRequest(request, callback, asyncState); } return InnerChannel.BeginUnregisterNodes(new UnregisterNodesMessage(request), callback, asyncState); }
/// <summary> /// Reads an NodeId array from the stream. /// </summary> public NodeIdCollection ReadNodeIdArray(string fieldName) { int length = ReadArrayLength(); if (length == -1) { return null; } NodeIdCollection values = new NodeIdCollection(length); for (int ii = 0; ii < length; ii++) { values.Add(ReadNodeId(null)); } return values; }
/// <summary> /// Unregisters a set of node ids. /// </summary> public virtual void UnregisterNodes( OperationContext context, NodeIdCollection nodesToUnregister) { if (nodesToUnregister == null) throw new ArgumentNullException("nodesToUnregister"); Utils.Trace( (int)Utils.TraceMasks.ServiceDetail, "MasterNodeManager.UnregisterNodes - Count={0}", nodesToUnregister.Count); // it is up to the node managers to assign the handles. /* List<bool> processedNodes = new List<bool>(new bool[itemsToDelete.Count]); for (int ii = 0; ii < m_nodeManagers.Count; ii++) { m_nodeManagers[ii].RegisterNodes( context, nodesToUnregister, processedNodes); } */ }
/// <summary> /// Finishes an asynchronous invocation of the RegisterNodes service. /// </summary> public ResponseHeader EndRegisterNodes( IAsyncResult result, out NodeIdCollection registeredNodeIds) { RegisterNodesResponse response = null; try { if (UseTransportChannel) { IServiceResponse genericResponse = TransportChannel.EndSendRequest(result); if (genericResponse == null) { throw new ServiceResultException(StatusCodes.BadUnknownResponse); } ValidateResponse(genericResponse.ResponseHeader); response = (RegisterNodesResponse)genericResponse; } else { RegisterNodesResponseMessage responseMessage = InnerChannel.EndRegisterNodes(result); if (responseMessage == null || responseMessage.RegisterNodesResponse == null) { throw new ServiceResultException(StatusCodes.BadUnknownResponse); } response = responseMessage.RegisterNodesResponse; ValidateResponse(response.ResponseHeader); } registeredNodeIds = response.RegisteredNodeIds; } finally { RequestCompleted(null, response, "RegisterNodes"); } return response.ResponseHeader; }
/// <summary> /// Gets the item handles. /// </summary> /// <param name="session">The session.</param> /// <param name="itemIds">The item ids.</param> /// <param name="clientHandles">The client handles.</param> /// <param name="validateOnly">if set to <c>true</c> handles are not created and item ids are only validated.</param> /// <returns>The handles containing any error information.</returns> public HdaItemHandle[] GetItemHandles(Session session, string[] itemIds, int[] clientHandles, bool validateOnly) { HdaItemHandle[] handles = new HdaItemHandle[itemIds.Length]; ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); for (int ii = 0; ii < itemIds.Length; ii++) { InternalHandle handle = new InternalHandle(); handles[ii] = handle; if (clientHandles != null) { handle.ClientHandle = clientHandles[ii]; } string itemId = itemIds[ii]; if (String.IsNullOrEmpty(itemId)) { handle.Error = ResultIds.E_INVALIDITEMID; continue; } // check if item has already been assigned. Item item = null; if (!validateOnly) { lock (m_lock) { if (m_items.TryGetValue(itemId, out item)) { handle.NodeId = item.NodeId; handle.ServerHandle = ++m_lastServerHandle; handle.Item = item; item.Refs++; m_handles[handle.ServerHandle] = handle; Utils.Trace("Created Handle: {0} {1}", handle.ServerHandle, handle.NodeId); continue; } } } // create a new item. handle.Item = item = new Item(); item.ItemId = itemId; handle.Error = ResultIds.S_OK; // assume valid for no - set to an error when detected. handle.NodeId = item.NodeId = m_mapper.GetRemoteNodeId(itemId); nodesToRead.Add(Construct(handle, Attributes.UserAccessLevel)); nodesToRead.Add(Construct(handle, Attributes.DisplayName)); nodesToRead.Add(Construct(handle, Attributes.Description)); nodesToRead.Add(Construct(handle, Attributes.DataType)); nodesToRead.Add(Construct(handle, Attributes.ValueRank)); nodesToRead.Add(Construct(handle, Attributes.Historizing)); } // check if nothing to do. if (nodesToRead.Count == 0) { return handles; } DataValueCollection values = null; DiagnosticInfoCollection diagnosticInfos = null; // read values from the UA server. session.Read( null, 0, TimestampsToReturn.Neither, nodesToRead, out values, out diagnosticInfos); // validate response from the UA server. ClientBase.ValidateResponse(values, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); // assign a local handle to all valid items. NodeIdCollection nodesToRegister = new NodeIdCollection(); List<InternalHandle> items = new List<InternalHandle>(); for (int ii = 0; ii < nodesToRead.Count; ii++) { InternalHandle handle = (InternalHandle)nodesToRead[ii].Handle; DataValue value = values[ii]; Item item = handle.Item; // check status codes. if (StatusCode.IsBad(value.StatusCode)) { // description is an optional attribute. if (nodesToRead[ii].AttributeId != Attributes.Description) { handle.Error = ResultIds.E_UNKNOWNITEMID; } continue; } // check access level. if (nodesToRead[ii].AttributeId == Attributes.UserAccessLevel) { byte accessLevel = value.GetValue<byte>(AccessLevels.None); if ((accessLevel & AccessLevels.HistoryRead) == 0) { handle.Error = ResultIds.E_UNKNOWNITEMID; continue; } } // save attribute. switch (nodesToRead[ii].AttributeId) { case Attributes.DisplayName: { item.DisplayName = value.GetValue<LocalizedText>(null); break; } case Attributes.Description: { item.Description = value.GetValue<LocalizedText>(null); break; } case Attributes.DataType: { item.DataType = value.GetValue<NodeId>(null); break; } case Attributes.ValueRank: { item.ValueRank = value.GetValue<int>(ValueRanks.Scalar); break; } case Attributes.Historizing: { item.Historizing = value.GetValue<bool>(false); break; } } // should have all item metadata when processing the historizing attribute result. if (nodesToRead[ii].AttributeId == Attributes.Historizing) { // check for a fatal error with one or more mandatory attributes. if (handle.Error != ResultIds.S_OK) { continue; } BuiltInType builtInType = DataTypes.GetBuiltInType(item.DataType, session.TypeTree); item.RemoteType = new TypeInfo(builtInType, item.ValueRank); if (!validateOnly) { nodesToRegister.Add(item.NodeId); items.Add(handle); lock (m_lock) { m_items[handle.Item.ItemId] = handle.Item; handle.ServerHandle = ++m_lastServerHandle; handle.NodeId = handle.Item.NodeId; handle.Item.Refs++; m_handles[handle.ServerHandle] = handle; Utils.Trace("Created Handle: {0} {1}", handle.ServerHandle, handle.NodeId); } } } } return handles; }
/// <summary> /// Finds the NodeIds for the components for an instance. /// </summary> public void FindComponentIds( NodeId instanceId, IList<string> componentPaths, out NodeIdCollection componentIds, out List<ServiceResult> errors) { componentIds = new NodeIdCollection(); errors = new List<ServiceResult>(); // build list of paths to translate. BrowsePathCollection pathsToTranslate = new BrowsePathCollection(); for (int ii = 0; ii < componentPaths.Count; ii++) { BrowsePath pathToTranslate = new BrowsePath(); pathToTranslate.StartingNode = instanceId; pathToTranslate.RelativePath = RelativePath.Parse(componentPaths[ii], TypeTree); pathsToTranslate.Add(pathToTranslate); } // translate the paths. BrowsePathResultCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; ResponseHeader responseHeader = TranslateBrowsePathsToNodeIds( null, pathsToTranslate, out results, out diagnosticInfos); // verify that the server returned the correct number of results. ClientBase.ValidateResponse(results, pathsToTranslate); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, pathsToTranslate); for (int ii = 0; ii < componentPaths.Count; ii++) { componentIds.Add(NodeId.Null); errors.Add(ServiceResult.Good); // process any diagnostics associated with any error. if (StatusCode.IsBad(results[ii].StatusCode)) { errors[ii] = new ServiceResult(results[ii].StatusCode, ii, diagnosticInfos, responseHeader.StringTable); continue; } // Expecting exact one NodeId for a local node. // Report an error if the server returns anything other than that. if (results[ii].Targets.Count == 0) { errors[ii] = ServiceResult.Create( StatusCodes.BadTargetNodeIdInvalid, "Could not find target for path: {0}.", componentPaths[ii]); continue; } if (results[ii].Targets.Count != 1) { errors[ii] = ServiceResult.Create( StatusCodes.BadTooManyMatches, "Too many matches found for path: {0}.", componentPaths[ii]); continue; } if (results[ii].Targets[0].RemainingPathIndex != UInt32.MaxValue) { errors[ii] = ServiceResult.Create( StatusCodes.BadTargetNodeIdInvalid, "Cannot follow path to external server: {0}.", componentPaths[ii]); continue; } if (NodeId.IsNull(results[ii].Targets[0].TargetId)) { errors[ii] = ServiceResult.Create( StatusCodes.BadUnexpectedError, "Server returned a null NodeId for path: {0}.", componentPaths[ii]); continue; } if (results[ii].Targets[0].TargetId.IsAbsolute) { errors[ii] = ServiceResult.Create( StatusCodes.BadUnexpectedError, "Server returned a remote node for path: {0}.", componentPaths[ii]); continue; } // suitable target found. componentIds[ii] = ExpandedNodeId.ToNodeId(results[ii].Targets[0].TargetId, m_namespaceUris); } }
/// <summary> /// Invokes the UnregisterNodes service. /// </summary> /// <param name="requestHeader">The request header.</param> /// <param name="nodesToUnregister">The list of NodeIds to unregister</param> /// <returns> /// Returns a <see cref="ResponseHeader"/> object /// </returns> public override ResponseHeader UnregisterNodes(RequestHeader requestHeader, NodeIdCollection nodesToUnregister) { OperationContext context = ValidateRequest(requestHeader, RequestType.UnregisterNodes); try { if (nodesToUnregister == null || nodesToUnregister.Count == 0) { throw new ServiceResultException(StatusCodes.BadNothingToDo); } m_serverInternal.NodeManager.UnregisterNodes( context, nodesToUnregister); return CreateResponse(requestHeader, context.StringTable); } catch (ServiceResultException e) { lock (ServerInternal.DiagnosticsLock) { ServerInternal.ServerDiagnostics.RejectedRequestsCount++; if (IsSecurityError(e.StatusCode)) { ServerInternal.ServerDiagnostics.SecurityRejectedRequestsCount++; } } throw TranslateException(context, e); } finally { OnRequestComplete(context); } }