/// <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); } }
/// <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); } }
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> /// 发送上线完成信号 /// </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); } }
/// <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"); } }
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> /// 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)); } }
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; } }
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> /// 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); } }
/// <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 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 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)); }
/// <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> /// 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; } }
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); }
private NodeIdCollection InitMonitorItem(ushort nameSpaceIndex) { my_MonitorNodes = new NodeIdCollection(); string comDB = MyStationModel.DataReadDB; //握手信号交互DB块 my_MonitorNodes.Add(new NodeId(comDB + MyStnBaseProtocol.PLC_MES_Heart, nameSpaceIndex)); //心跳 my_MonitorNodes.Add(new NodeId(comDB + MyStnBaseProtocol.PLC_MES_CellNG, nameSpaceIndex)); //电芯NG剔料 my_MonitorNodes.Add(new NodeId(comDB + MyStnBaseProtocol.PLC_MES_DataRequest, nameSpaceIndex)); //上线请求 my_MonitorNodes.Add(new NodeId(comDB + MyStnBaseProtocol.PLC_MES_DataSave, nameSpaceIndex)); //下线请求 my_MonitorNodes.Add(new NodeId(comDB + MyStnBaseProtocol.PLC_MES_ReadBom, nameSpaceIndex)); //读BOM my_MonitorNodes.Add(new NodeId(comDB + MyStnBaseProtocol.PLC_MES_RepairRequest, nameSpaceIndex)); //返修上线 my_MonitorNodes.Add(new NodeId(comDB + MyStnBaseProtocol.PLC_MES_RepairSave, nameSpaceIndex)); //返修下线 my_MonitorNodes.Add(new NodeId(comDB + MyStnBaseProtocol.PLC_MES_MaterialAndonRequest, nameSpaceIndex)); //PLC安东物料拉动 my_MonitorNodes.Add(new NodeId(comDB + MyStnBaseProtocol.PLC_MES_OCV_Test, nameSpaceIndex)); //OCV测试 monitorClientHandl = new int[9]; for (int i = 0; i < 9; i++) { monitorClientHandl[i] = i; } return(my_MonitorNodes); }
/// <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 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); } }
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"; }
/// <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"); } }
public void SendRepairWriteDown() { try { NodeIdCollection readdownNode = new NodeIdCollection(); // string comDB = MyStationModel.CommunicationDB;//握手信号交互DB块 string comDB = MyStationModel.DataWriteDB; //握手信号交互DB块 readdownNode.Add(new NodeId(comDB + MyBaseProtocol.MES_PLC_RepairWriteDown, 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"); } }
private void btnRead_Click(object sender, EventArgs e) { string nodeID = txtNodeID.Text.Trim(); string writevalue = txtWriteValue.Text.Trim(); NodeIdCollection nic = new NodeIdCollection(); NodeId nodeid = new NodeId(nodeID); nic.Add(nodeid); DataValueCollection valueC; server.ReadValues( nic, out valueC); txtReadValue.Text = valueC[0].Value.ToString(); txtResult.Text = "read success:" + valueC[0].Value.ToString(); }
/// <summary> /// 发送错误代码 /// </summary> public void SendErrorsCode(byte errorcode) { try { NodeIdCollection writingNode = new NodeIdCollection(); //string comDB = MyStationModel.CommunicationDB;//握手信号交互DB块 string comDB = MyStationModel.DataWriteDB; //握手信号交互DB块 writingNode.Add(new NodeId(comDB + MyBaseProtocol.MES_PLC_ErrorCode, ServerIndex)); //错误代码 DataValueCollection values = new DataValueCollection(); byte [] buff = { errorcode }; DataValue v = new DataValue(); v.Value = errorcode; values.Add(new DataValue(v)); StatusCodeCollection codes; MyServer.WriteValues(writingNode, values, out codes); } catch (Exception ex) { LogHelper.Write(ex, "system"); } }
/// <summary> /// Writes and displays the new values. /// </summary> private void UpdateCurrentValues() { try { // Prepare call to ClientAPI. NodeIdCollection nodesToRead = new NodeIdCollection(this.listView.Items.Count); foreach (ListViewItem item in this.listView.Items) { // NodeIds. String sNodeId = item.SubItems[1].Text; NodeId nodeId = new NodeId(sNodeId); nodesToRead.Add(nodeId); } // Call to ClientAPI. m_Server.ReadValues( nodesToRead, out m_currentValues); int i = 0; foreach (ListViewItem item in this.listView.Items) { // Update current value. item.SubItems[2].Text = m_currentValues[i].Value.ToString(); i++; } // Update status label. toolStripStatusLabel.Text = "Updating current values succeeded."; } catch (Exception e) { // Update status label. toolStripStatusLabel.Text = "An exception occured while updating current values: " + e.Message; } }
/// <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> /// 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; }
private void ReadFromOPC() { NodeIdCollection nodes = new NodeIdCollection(); List <Type> types = new List <Type>(); List <object> result = new List <object>(); List <ServiceResult> errors = new List <ServiceResult>(); // Make a list of all the OPC item that we want to read foreach (var item in config.HistoryMeasurements.Item) { if (!item.Output) { nodes.Add(item.Tag); types.Add(typeof(object)); } } foreach (var item in config.AsgardMeasurements.Item) { if (!item.Output) { nodes.Add(item.Tag); types.Add(typeof(object)); } } foreach (var item in config.StatpipeMeasurements.Item) { if (!item.Output) { nodes.Add(item.Tag); types.Add(typeof(object)); } } foreach (var item in config.Validation.Item) { if (!item.Output) { nodes.Add(item.Tag); types.Add(typeof(object)); } } foreach (var item in nodes) { logger.Debug(CultureInfo.InvariantCulture, "Item to read: \"{0}\"", item.ToString()); } // Read all of the items try { opcClient.OpcSession.ReadValues(nodes, types, out result, out errors); } catch (Exception e) { Status = 1.0; logger.Error(e, "Error reading values from OPC."); } for (int n = 0; n < result.Count; n++) { logger.Debug(CultureInfo.InvariantCulture, "Item: \"{0}\" Value: \"{1}\" Status: \"{2}\"", nodes[n].ToString(), result[n], errors[n].StatusCode.ToString()); } int it = 0; foreach (var meas in config.HistoryMeasurements.Item) { if (!meas.Output) { meas.Value = Convert.ToDouble(result[it++], CultureInfo.InvariantCulture); meas.TimeStamp = DateTime.Now; logger.Debug(CultureInfo.InvariantCulture, "Measurement: \"{0}\" Value: {1} TimeStamp: {2} Tag: \"{3}\"", meas.Name, meas.Value, meas.TimeStamp.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture), meas.Tag); } } foreach (var meas in config.AsgardMeasurements.Item) { meas.Value = Convert.ToDouble(result[it++], CultureInfo.InvariantCulture); meas.TimeStamp = DateTime.Now; logger.Debug(CultureInfo.InvariantCulture, "Measurement: \"{0}\" Value: {1} TimeStamp: {2} Tag: \"{3}\"", meas.Name, meas.Value, meas.TimeStamp.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture), meas.Tag); } foreach (var meas in config.StatpipeMeasurements.Item) { meas.Value = Convert.ToDouble(result[it++], CultureInfo.InvariantCulture); meas.TimeStamp = DateTime.Now; logger.Debug(CultureInfo.InvariantCulture, "Measurement: \"{0}\" Value: {1} TimeStamp: {2} Tag: \"{3}\"", meas.Name, meas.Value, meas.TimeStamp.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture), meas.Tag); } foreach (var meas in config.Validation.Item) { if (!meas.Output) { meas.Value = Convert.ToDouble(result[it++], CultureInfo.InvariantCulture); meas.TimeStamp = DateTime.Now; logger.Debug(CultureInfo.InvariantCulture, "Measurement: \"{0}\" Value: {1} TimeStamp: {2} Tag: \"{3}\"", meas.Name, meas.Value, meas.TimeStamp.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture), meas.Tag); } } }
/// <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> /// 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> /// Registers a set of node ids. /// </summary> public virtual void RegisterNodes( OperationContext context, NodeIdCollection nodesToRegister, out NodeIdCollection registeredNodeIds) { if (nodesToRegister == null) throw new ArgumentNullException("nodesToRegister"); // return the node id provided. registeredNodeIds = new NodeIdCollection(nodesToRegister.Count); for (int ii = 0; ii < nodesToRegister.Count; ii++) { registeredNodeIds.Add(nodesToRegister[ii]); } Utils.Trace( (int)Utils.TraceMasks.ServiceDetail, "MasterNodeManager.RegisterNodes - Count={0}", nodesToRegister.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, nodesToRegister, registeredNodeIds, processedNodes); } */ }
/// <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> /// 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> /// 给PLC写数据 /// </summary> /// <param name="ordrNum">订单号</param> /// <param name="sncode">packid</param> /// <param name="ptcode">成品物料号</param> /// <param name="mozuCode"></param> /// <param name="mozusnnum"></param> /// <param name="keyValues">配方(key:Item value:配方值)</param> /// <returns></returns> public bool InitRequestData(string ordrNum, string sncode, string ptcode, string mozuCode, string mozusnnum, int canwork, int notwork, int ngmodel, int normalwork, int workfinish, int agluefinish, int bgluefinish, int planqty, Dictionary <string, byte[]> keyValues) { try { string ordnum = ".60,b,40"; //工单号地址 string prdcode = ".100,b,20"; //pack总成物料号 string snnum = ".120,b,70"; //产品sn号 string mzcode = ".190,b,20"; // 模组物料号 string mzsn = ".210,b,70"; //模组序列号--已经不写了 string canWorkItem = ".1,x4"; //可加工 string notWorkItem = ".1,x5"; //不可加工 string ngModelItem = ".2,x6"; //NG排出 string normalWorkItem = ".2,x7"; //正常加工 string workFinishItem = ".1,x7"; //当前工位加工完成 string aGlueFinishItem = ".3,x0"; //A扫码完成 string bGlueFinishItem = ".3,x1"; //B扫码完成 string formulaItem = keyValues.Keys.ToList()[0]; //配方的地址 string orderQtyItem = ".280,i"; //订单数量 string dbnum = MyStationModel.DataWriteDB; //写数据的DB块 NodeIdCollection writeNodecoll = new NodeIdCollection(); writeNodecoll.Add(new NodeId(dbnum + ordnum, ServerIndex)); //工单号 writeNodecoll.Add(new NodeId(dbnum + prdcode, ServerIndex)); //物料号 writeNodecoll.Add(new NodeId(dbnum + snnum, ServerIndex)); //packid writeNodecoll.Add(new NodeId(dbnum + mzcode, ServerIndex)); //模组物料号 writeNodecoll.Add(new NodeId(dbnum + mzsn, ServerIndex)); //模组物料号 writeNodecoll.Add(new NodeId(dbnum + canWorkItem, ServerIndex)); //可加工 writeNodecoll.Add(new NodeId(dbnum + notWorkItem, ServerIndex)); //不可加工 writeNodecoll.Add(new NodeId(dbnum + ngModelItem, ServerIndex)); //ng排料 writeNodecoll.Add(new NodeId(dbnum + normalWorkItem, ServerIndex)); //正常加工 writeNodecoll.Add(new NodeId(dbnum + workFinishItem, ServerIndex)); //本工位加工完成 writeNodecoll.Add(new NodeId(dbnum + aGlueFinishItem, ServerIndex)); //A扫码完成 writeNodecoll.Add(new NodeId(dbnum + bGlueFinishItem, ServerIndex)); //B扫码完成 writeNodecoll.Add(new NodeId(dbnum + formulaItem, ServerIndex)); //配方 writeNodecoll.Add(new NodeId(dbnum + orderQtyItem, ServerIndex)); //订单数量 DataValueCollection values = new DataValueCollection(); byte[] ordnumbuff = ConvertHelper.StringToByteArray(ordrNum, 40); byte[] ptcocebuff = ConvertHelper.StringToByteArray(ptcode, 20); byte[] sncodebuff = ConvertHelper.StringToByteArray(sncode, 70); byte[] mzcodebuff = ConvertHelper.StringToByteArray(mozuCode, 20); byte[] mzsnnumbuff = ConvertHelper.StringToByteArray(mozusnnum, 70); bool canworkValue = Convert.ToBoolean(canwork); bool notworkValue = Convert.ToBoolean(notwork); bool ngmodelValue = Convert.ToBoolean(ngmodel); bool normalVlue = Convert.ToBoolean(normalwork); bool workFinishValue = Convert.ToBoolean(workfinish); bool aGlueFinishValue = Convert.ToBoolean(agluefinish); bool bGlueFinishValue = Convert.ToBoolean(bgluefinish); byte[] formulaValue = keyValues[formulaItem];//配方值 short qty = (short)planqty; values.Add(new DataValue(ordnumbuff)); values.Add(new DataValue(ptcocebuff)); values.Add(new DataValue(sncodebuff)); values.Add(new DataValue(mzcodebuff)); values.Add(new DataValue(mzsnnumbuff)); values.Add(new DataValue(canworkValue)); values.Add(new DataValue(notworkValue)); values.Add(new DataValue(ngmodelValue)); values.Add(new DataValue(normalVlue)); values.Add(new DataValue(workFinishValue)); values.Add(new DataValue(aGlueFinishValue)); values.Add(new DataValue(bGlueFinishValue)); values.Add(new DataValue(formulaValue)); values.Add(new DataValue(qty));//数量 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(ex, "system"); return(false); } }