/// <summary> /// Writes the value /// </summary> private Variant WriteValue(Session session, NodeId nodeId) { // cast the value to a string. object value = TypeInfo.Cast(ValueTB.Text, TypeInfo.Scalars.String, m_sourceType.BuiltInType); // build list of attributes to read. WriteValueCollection nodesToWrite = new WriteValueCollection(); WriteValue nodeToWrite = new WriteValue(); nodeToWrite.NodeId = nodeId; nodeToWrite.AttributeId = Attributes.Value; // using the WrappedValue instead of the Value property because we know the TypeInfo. // this makes the assignment more efficient by avoiding reflection to determine type. nodeToWrite.Value.WrappedValue = new Variant(value, m_sourceType); nodesToWrite.Add(nodeToWrite); // override the diagnostic masks (other parameters are set to defaults). RequestHeader requestHeader = new RequestHeader(); requestHeader.ReturnDiagnostics = (uint)DiagnosticsMasks.All; // read the attributes. StatusCodeCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; ResponseHeader responseHeader = session.Write( requestHeader, nodesToWrite, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, nodesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToWrite); // check status. if (StatusCode.IsBad(results[0])) { // embed the diagnostic information in a exception. throw ServiceResultException.Create(results[0], 0, diagnosticInfos, responseHeader.StringTable); } // return valid value. return nodeToWrite.Value.WrappedValue; }
private void ChangeLogFileBTN_Click(object sender, EventArgs e) { if (m_session == null) { return; } try { // want to get error text for this call. m_session.ReturnDiagnostics = DiagnosticsMasks.All; WriteValue value = new WriteValue(); value.NodeId = m_logFileNodeId; value.AttributeId = Attributes.Value; value.Value.Value = LogFilePathTB.Text; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(value); StatusCodeCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; ResponseHeader responseHeader = m_session.Write( null, valuesToWrite, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, valuesToWrite); if (StatusCode.IsBad(results[0])) { throw ServiceResultException.Create(results[0], 0, diagnosticInfos, responseHeader.StringTable); } } catch (Exception exception) { ClientUtils.HandleException(this.Text, exception); } finally { m_session.ReturnDiagnostics = DiagnosticsMasks.None; } }
/// <summary> /// Write a list of nodes to the Server /// </summary> public void WriteNodes() { if (m_session == null || m_session.Connected == false) { Console.WriteLine("Session not connected!"); return; } try { // Write the configured nodes WriteValueCollection nodesToWrite = new WriteValueCollection(); // Int32 Node - Objects\CTT\Scalar\Scalar_Static\Int32 WriteValue intWriteVal = new WriteValue(); intWriteVal.NodeId = new NodeId("ns=2;s=Scalar_Static_Int32"); intWriteVal.AttributeId = Attributes.Value; intWriteVal.Value = new DataValue(); intWriteVal.Value.Value = (int)100; nodesToWrite.Add(intWriteVal); // Float Node - Objects\CTT\Scalar\Scalar_Static\Float WriteValue floatWriteVal = new WriteValue(); floatWriteVal.NodeId = new NodeId("ns=2;s=Scalar_Static_Float"); floatWriteVal.AttributeId = Attributes.Value; floatWriteVal.Value = new DataValue(); floatWriteVal.Value.Value = (float)100.5; nodesToWrite.Add(floatWriteVal); // String Node - Objects\CTT\Scalar\Scalar_Static\String WriteValue stringWriteVal = new WriteValue(); stringWriteVal.NodeId = new NodeId("ns=2;s=Scalar_Static_String"); stringWriteVal.AttributeId = Attributes.Value; stringWriteVal.Value = new DataValue(); stringWriteVal.Value.Value = "String Test"; nodesToWrite.Add(stringWriteVal); // Write the node attributes StatusCodeCollection results = null; DiagnosticInfoCollection diagnosticInfos; Console.WriteLine("Writing nodes..."); // Call Write Service m_session.Write(null, nodesToWrite, out results, out diagnosticInfos); // Validate the response ClientBase.ValidateResponse(results, nodesToWrite); // Display the results. Console.WriteLine("Write Results :"); foreach (StatusCode writeResult in results) { Console.WriteLine(" {0}", writeResult); } } catch (Exception ex) { // Log Error string logMessage = String.Format("Write Nodes Error : {0}.", ex.Message); Console.WriteLine(logMessage); } }
private void UpdateBTN_Click(object sender, EventArgs e) { try { WriteValue nodeToWrite = new WriteValue(); nodeToWrite.NodeId = m_variableId; nodeToWrite.AttributeId = Attributes.Value; nodeToWrite.Value = new DataValue(); nodeToWrite.Value.WrappedValue = GetValue(); WriteValueCollection nodesToWrite = new WriteValueCollection(); nodesToWrite.Add(nodeToWrite); // read the attributes. StatusCodeCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; ResponseHeader responseHeader = m_session.Write( null, nodesToWrite, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, nodesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToWrite); // check for error. if (StatusCode.IsBad(results[0])) { throw ServiceResultException.Create(results[0], 0, diagnosticInfos, responseHeader.StringTable); } } catch (Exception exception) { ClientUtils.HandleException(this.Text, exception); } }
/// <summary> /// Handles a write operation. /// </summary> protected override void Write( ServerSystemContext context, IList<WriteValue> nodesToWrite, IList<ServiceResult> errors, List<NodeHandle> nodesToValidate, IDictionary<NodeId, NodeState> cache) { WriteValueCollection requests = new WriteValueCollection(); List<int> indexes = new List<int>(); // validates the nodes and constructs requests for external nodes. for (int ii = 0; ii < nodesToValidate.Count; ii++) { WriteValue nodeToWrite = nodesToWrite[ii]; NodeHandle handle = nodesToValidate[ii]; lock (Lock) { // validate node. NodeState source = ValidateNode(context, handle, cache); if (source == null) { continue; } // determine if a local node. if (PredefinedNodes.ContainsKey(source.NodeId)) { // write the attribute value. errors[handle.Index] = source.WriteAttribute( context, nodeToWrite.AttributeId, nodeToWrite.ParsedIndexRange, nodeToWrite.Value); // updates to source finished - report changes to monitored items. source.ClearChangeMasks(context, false); } WriteValue request = (WriteValue)nodeToWrite.Clone(); request.NodeId = m_mapper.ToRemoteId(nodeToWrite.NodeId); request.Value.WrappedValue = m_mapper.ToRemoteVariant(nodeToWrite.Value.WrappedValue); requests.Add(request); indexes.Add(ii); } } // send request to external system. try { Opc.Ua.Client.Session client = GetClientSession(context); StatusCodeCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; ResponseHeader responseHeader = client.Write( null, requests, out results, out diagnosticInfos); // these do sanity checks on the result - make sure response matched the request. ClientBase.ValidateResponse(results, requests); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, requests); // set results. for (int ii = 0; ii < requests.Count; ii++) { errors[indexes[ii]] = ServiceResult.Good; if (results[ii] != StatusCodes.Good) { errors[indexes[ii]] = new ServiceResult(results[ii], ii, diagnosticInfos, responseHeader.StringTable); } } } catch (Exception e) { // handle unexpected communication error. ServiceResult error = ServiceResult.Create(e, StatusCodes.BadUnexpectedError, "Could not access external system."); for (int ii = 0; ii < requests.Count; ii++) { errors[indexes[ii]] = error; } } }
/// <summary> /// Parses the value and writes it to server. Closes the dialog if successful. /// </summary> private void OkBTN_Click(object sender, EventArgs e) { try { WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = m_nodeId; valueToWrite.AttributeId = m_attributeId; valueToWrite.Value.Value = ChangeType(); valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. StatusCodeCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; m_session.Write( null, valuesToWrite, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, valuesToWrite); if (StatusCode.IsBad(results[0])) { throw new ServiceResultException(results[0]); } DialogResult = DialogResult.OK; } catch (Exception exception) { ClientUtils.HandleException("Error Writing Value", exception); } }
/// <summary> /// Removes nodes that are not actually writeable. /// </summary> private void InitialWrite() { WriteValueCollection nodesToWrite = new WriteValueCollection(); lock (m_variables) { for (int ii = 0; ii < m_variables.Count; ii++) { TestVariable variable = m_variables[ii]; WriteValue nodeToWrite = new WriteValue(); nodeToWrite.NodeId = variable.Variable.NodeId; nodeToWrite.AttributeId = Attributes.Value; DataValue value = new DataValue(); if (!m_useDeadbandValues) { bool different = false; do { value.Value = m_generator.GetRandom( variable.Variable.DataType, variable.Variable.ValueRank, variable.Variable.ArrayDimensions, Session.TypeTree); if (variable.EURange != null) { value.Value = EnsureInRange(value.Value, variable.Variable, variable.EURange); } different = true; for (int jj = variable.Values.Count - 1; jj >= 0; jj--) { if (m_comparer.CompareVariant(value.WrappedValue, variable.Values[jj].WrappedValue)) { different = false; break; } if (variable.DataType == BuiltInType.Boolean) { break; } } } while (!different); } else { value.Value = IncrementValue(variable, m_deadbandCounter); } value.StatusCode = StatusCodes.Good; value.ServerTimestamp = DateTime.MinValue; value.SourceTimestamp = DateTime.MinValue; nodeToWrite.Value = value; nodeToWrite.Handle = variable.Values.Count; nodesToWrite.Add(nodeToWrite); variable.Values.Add(value); variable.Timestamps.Add(DateTime.MinValue); } } StatusCodeCollection results; DiagnosticInfoCollection diagnosticInfos; DateTime now = DateTime.UtcNow; RequestHeader requestHeader = new RequestHeader(); requestHeader.ReturnDiagnostics = 0; // need to check if the test completes and the next one starts while the write is in progress. ResponseHeader responseHeader = Session.Write( requestHeader, nodesToWrite, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, nodesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToWrite); // check diagnostics. if (diagnosticInfos != null && diagnosticInfos.Count > 0) { Log("Returned non-empty DiagnosticInfos array during Write."); return; } // check results. lock (m_variables) { List<TestVariable> writeableVariables = new List<TestVariable>(); for (int ii = 0; ii < nodesToWrite.Count; ii++) { if (StatusCode.IsGood(results[ii])) { m_variables[ii].WriteError = false; writeableVariables.Add(m_variables[ii]); } } m_variables.Clear(); m_variables.AddRange(writeableVariables); } }
/// <summary> /// Adds random values to write. /// </summary> private void AddWriteValues( TestVariable variable, WriteValueCollection nodesToWrite) { WriteValue nodeToWrite = new WriteValue(); nodeToWrite.NodeId = variable.Variable.NodeId; nodeToWrite.AttributeId = Attributes.Value; DataValue value = new DataValue(); value.Value = m_generator.GetRandom( variable.Variable.DataType, variable.Variable.ValueRank, variable.Variable.ArrayDimensions, Session.TypeTree); value.StatusCode = StatusCodes.Good; value.ServerTimestamp = DateTime.MinValue; value.SourceTimestamp = DateTime.MinValue; variable.Values.Add(value); nodeToWrite.Value = value; nodeToWrite.Handle = variable; nodesToWrite.Add(nodeToWrite); }
/// <summary> /// IOPCSyncIO::Write - Writes values to one or more items in a group. /// </summary> public void Write( int dwCount, int[] phServer, object[] pItemValues, out System.IntPtr ppErrors) { // validate arguments. if (dwCount == 0 || phServer == null || pItemValues == null || dwCount != phServer.Length || dwCount != pItemValues.Length) { throw ComUtils.CreateComException(ResultIds.E_INVALIDARG); } try { int[] errors = new int[dwCount]; // build list of values to write. WriteValueCollection valuesToWrite = new WriteValueCollection(); lock (m_lock) { if (m_subscription == null) throw ComUtils.CreateComException(ResultIds.E_FAIL); for (int ii = 0; ii < dwCount; ii++) { Item itemToWrite = null; if (!m_items.TryGetValue(phServer[ii], out itemToWrite)) { errors[ii] = ResultIds.E_INVALIDHANDLE; continue; } VariableNode variable = itemToWrite.Variable; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = variable.NodeId; valueToWrite.IndexRange = null; valueToWrite.AttributeId = Attributes.Value; DataValue value = new DataValue(); int error = 0; value.Value = m_server.VariantValueToValue(variable, pItemValues[ii], out error); if (error != ResultIds.S_OK) { errors[ii] = error; continue; } valueToWrite.Value = value; // needed to correlate results to input. valueToWrite.Handle = ii; valuesToWrite.Add(valueToWrite); } } // write values from server. StatusCodeCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; if (valuesToWrite.Count > 0) { m_session.Write( null, valuesToWrite, out results, out diagnosticInfos); // validate response from the UA server. ClientBase.ValidateResponse(results, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, valuesToWrite); //Utils.Trace( // "SyncWrite: GroupHandle={0}, ServerHandle={1}, Value={2}", // m_clientHandle, // phServer[0], // valuesToWrite[0].Value.WrappedValue); } for (int ii = 0; ii < valuesToWrite.Count; ii++) { // get index in original array. int index = (int)valuesToWrite[ii].Handle; // map UA code to DA code. errors[index] = Server.MapWriteStatusToErrorCode(results[ii]); } // marshal error codes. ppErrors = ComUtils.GetInt32s(errors); } catch (Exception e) { Utils.Trace(e, "Error writing items."); throw ComUtils.CreateComException(e); } }
/// <summary> /// Writes the values for the specified item ids. /// </summary> /// <param name="itemIds">The item ids.</param> /// <param name="values">The values.</param> /// <returns>The results.</returns> public int[] Write(string[] itemIds, DaValue[] values) { int[] results = new int[itemIds.Length]; WriteValueCollection valuesToWrite = new WriteValueCollection(); ComDaReadPropertiesRequest[] requests = new ComDaReadPropertiesRequest[values.Length]; // prepare request. for (int ii = 0; ii < itemIds.Length; ii++) { ComDaReadPropertiesRequest request = requests[ii] = new ComDaReadPropertiesRequest(); request.ItemId = itemIds[ii]; } // need to get the data type of the remote node. m_browseManager.GetPropertyValues(Session, requests, PropertyIds.UaBuiltInType, PropertyIds.UaValueRank); // validate items. for (int ii = 0; ii < requests.Length; ii++) { ComDaReadPropertiesRequest request = requests[ii]; if (request.Error < 0) { results[ii] = request.Error; continue; } int?builtInType = request.Values[0].Value as int?; int?valueRank = request.Values[1].Value as int?; if (builtInType == null || valueRank == null) { results[ii] = ResultIds.E_UNKNOWNITEMID; continue; } // convert value to UA data type. WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = m_mapper.GetRemoteNodeId(itemIds[ii]); valueToWrite.AttributeId = Attributes.Value; valueToWrite.Handle = ii; // convert value to UA data type. try { TypeInfo remoteType = new TypeInfo((BuiltInType)builtInType.Value, valueRank.Value); valueToWrite.Value = m_mapper.GetRemoteDataValue(values[ii], remoteType); } catch (Exception e) { results[ii] = ComUtils.GetErrorCode(e, ResultIds.E_BADTYPE); continue; } valuesToWrite.Add(valueToWrite); } // check if nothing to do. if (valuesToWrite.Count == 0) { return(results); } // write the values to the server. int[] remoteResults = m_groupManager.Write(valuesToWrite); // copy results. for (int ii = 0; ii < valuesToWrite.Count; ii++) { results[(int)valuesToWrite[ii].Handle] = remoteResults[ii]; } return(results); }
private void button1_Click(object sender, EventArgs e) { try { int[] arr = { 1, 2 }; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = "ns=3;s=Actual_Mould"; valueToWrite.AttributeId = Attributes.Value; if (comboBox1.SelectedIndex == 0) { valueToWrite.Value.Value = arr[0]; } else if (comboBox1.SelectedIndex == 1) { valueToWrite.Value.Value = arr[1]; } valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. StatusCodeCollection results2 = null; DiagnosticInfoCollection diagnosticInfos2 = null; m_session.Write( null, valuesToWrite, out results2, out diagnosticInfos2); ClientBase.ValidateResponse(results2, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos2, valuesToWrite); if (StatusCode.IsBad(results2[0])) { throw new ServiceResultException(results2[0]); } } catch (Exception exception) { ClientUtils.HandleException("Error Writing Value", exception); } //Start the production of the piece DataValueCollection results = Read_Value("ns=3;s=Start_Piece"); bool Start_PieceValue = (bool)results[0].Value; try { bool[] arr = { true, false }; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = "ns=3;s=Start_Piece"; valueToWrite.AttributeId = Attributes.Value; if (Start_PieceValue) { valueToWrite.Value.Value = arr[1]; } else { valueToWrite.Value.Value = arr[0]; } valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. StatusCodeCollection results2 = null; DiagnosticInfoCollection diagnosticInfos2 = null; m_session.Write( null, valuesToWrite, out results2, out diagnosticInfos2); ClientBase.ValidateResponse(results2, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos2, valuesToWrite); if (StatusCode.IsBad(results2[0])) { throw new ServiceResultException(results2[0]); } } catch (Exception exception) { ClientUtils.HandleException("Error Writing Value", exception); } //Disable Start Piece button until piece is made button1.Enabled = false; //Assign a Serial Number to the pieces if (comboBox1.SelectedIndex == 0) { try { int arr = Piece_SN_Value + 1; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = "ns=3;s=Piece_SN"; valueToWrite.AttributeId = Attributes.Value; valueToWrite.Value.Value = arr; valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. StatusCodeCollection results2 = null; DiagnosticInfoCollection diagnosticInfos2 = null; m_session.Write( null, valuesToWrite, out results2, out diagnosticInfos2); ClientBase.ValidateResponse(results2, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos2, valuesToWrite); if (StatusCode.IsBad(results2[0])) { throw new ServiceResultException(results2[0]); } } catch (Exception exception) { ClientUtils.HandleException("Error Writing Value", exception); } DataValueCollection results1 = Read_Value("ns=3;s=Piece_SN"); Piece_SN_Value = (int)results1[0].Value; } else if (comboBox1.SelectedIndex == 1) { try { int arr = Piece_SN_Value + 1; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = "ns=3;s=Piece_SN"; valueToWrite.AttributeId = Attributes.Value; valueToWrite.Value.Value = arr; valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. StatusCodeCollection results2 = null; DiagnosticInfoCollection diagnosticInfos2 = null; m_session.Write( null, valuesToWrite, out results2, out diagnosticInfos2); ClientBase.ValidateResponse(results2, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos2, valuesToWrite); if (StatusCode.IsBad(results2[0])) { throw new ServiceResultException(results2[0]); } } catch (Exception exception) { ClientUtils.HandleException("Error Writing Value", exception); } DataValueCollection results1 = Read_Value("ns=3;s=Piece_SN"); Piece_SN_Value = (int)results1[0].Value; } label6.Text = Piece_SN_Value.ToString(); //Read the value of the Serial Number of the Machine DataValueCollection results4 = Read_Value("ns=3;s=Machine_SN"); string Machine_SN_Value = (string)results4[0].Value; //Read the value of the Serial Number of the Mould if (comboBox1.SelectedIndex == 0) { results3 = Read_Value("ns=3;s=Mould_1_SN"); try { int arr = 1; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = "ns=3;s=Actual_Mould"; valueToWrite.AttributeId = Attributes.Value; valueToWrite.Value.Value = arr; valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. StatusCodeCollection results2 = null; DiagnosticInfoCollection diagnosticInfos2 = null; m_session.Write( null, valuesToWrite, out results2, out diagnosticInfos2); ClientBase.ValidateResponse(results2, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos2, valuesToWrite); if (StatusCode.IsBad(results2[0])) { throw new ServiceResultException(results2[0]); } } catch (Exception exception) { ClientUtils.HandleException("Error Writing Value", exception); } } else if (comboBox1.SelectedIndex == 1) { results3 = Read_Value("ns=3;s=Mould_2_SN"); try { int arr = 2; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = "ns=3;s=Actual_Mould"; valueToWrite.AttributeId = Attributes.Value; valueToWrite.Value.Value = arr; valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. StatusCodeCollection results2 = null; DiagnosticInfoCollection diagnosticInfos2 = null; m_session.Write( null, valuesToWrite, out results2, out diagnosticInfos2); ClientBase.ValidateResponse(results2, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos2, valuesToWrite); if (StatusCode.IsBad(results2[0])) { throw new ServiceResultException(results2[0]); } } catch (Exception exception) { ClientUtils.HandleException("Error Writing Value", exception); } } string Mould_SN_Value = (string)results3[0].Value; DataValueCollection read = Read_Value("ns=3;s=Operator_ID"); int Operator_ID_Value = (int)read[0].Value; //when new piece is made then update DB //format of convertion from real number to string NumberFormatInfo nfi = new NumberFormatInfo(); nfi.NumberDecimalSeparator = "."; nfi.NumberGroupSeparator = ""; nfi.NumberDecimalDigits = 2; //Execute command string query = Utils.Format("INSERT INTO db_project.table1 (Piece_SN, Machine_SN, Mould_SN, Operator_ID) VALUES({0},{1},{2},{3});", Piece_SN_Value.ToString("N", nfi), Machine_SN_Value, Mould_SN_Value, Operator_ID_Value.ToString("N", nfi)); MySqlCommand cmd = new MySqlCommand(query, DB_connection); cmd.ExecuteNonQuery(); }
private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e) { //Change Mould string message = "Do you want to select this Mould?"; var result = MessageBox.Show(message, (string)"Change Mould", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { //Show the Serial Number of the selected Mould if (comboBox1.SelectedIndex == 0) { //Change the values of Change_Mould and Mould_Changed try { bool arr = true; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = "ns=3;s=Change_Mould"; valueToWrite.AttributeId = Attributes.Value; valueToWrite.Value.Value = arr; valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. StatusCodeCollection results2 = null; DiagnosticInfoCollection diagnosticInfos2 = null; m_session.Write( null, valuesToWrite, out results2, out diagnosticInfos2); ClientBase.ValidateResponse(results2, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos2, valuesToWrite); if (StatusCode.IsBad(results2[0])) { throw new ServiceResultException(results2[0]); } } catch (Exception exception) { ClientUtils.HandleException("Error Writing Value", exception); } try { bool arr = false; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = "ns=3;s=Mould_Changed"; valueToWrite.AttributeId = Attributes.Value; valueToWrite.Value.Value = arr; valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. StatusCodeCollection results2 = null; DiagnosticInfoCollection diagnosticInfos2 = null; m_session.Write( null, valuesToWrite, out results2, out diagnosticInfos2); ClientBase.ValidateResponse(results2, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos2, valuesToWrite); if (StatusCode.IsBad(results2[0])) { throw new ServiceResultException(results2[0]); } } catch (Exception exception) { ClientUtils.HandleException("Error Writing Value", exception); } DataValueCollection values = Read_Value("ns=3;s=Mould_1_SN"); label8.Text = (string)values[0].Value; //Update the value of Mould_tobeused try { string arr = "1"; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = "ns=3;s=Mould_tobeused"; valueToWrite.AttributeId = Attributes.Value; valueToWrite.Value.Value = arr; valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. StatusCodeCollection results2 = null; DiagnosticInfoCollection diagnosticInfos2 = null; m_session.Write( null, valuesToWrite, out results2, out diagnosticInfos2); ClientBase.ValidateResponse(results2, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos2, valuesToWrite); if (StatusCode.IsBad(results2[0])) { throw new ServiceResultException(results2[0]); } } catch (Exception exception) { ClientUtils.HandleException("Error Writing Value", exception); } //Update the value of Actual_Mould try { int arr = 1; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = "ns=3;s=Actual_Mould"; valueToWrite.AttributeId = Attributes.Value; valueToWrite.Value.Value = arr; valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. StatusCodeCollection results2 = null; DiagnosticInfoCollection diagnosticInfos2 = null; m_session.Write( null, valuesToWrite, out results2, out diagnosticInfos2); ClientBase.ValidateResponse(results2, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos2, valuesToWrite); if (StatusCode.IsBad(results2[0])) { throw new ServiceResultException(results2[0]); } } catch (Exception exception) { ClientUtils.HandleException("Error Writing Value", exception); } } else if (comboBox1.SelectedIndex == 1) { //Change the values of Change_Mould and Mould_Changed try { bool arr = true; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = "ns=3;s=Change_Mould"; valueToWrite.AttributeId = Attributes.Value; valueToWrite.Value.Value = arr; valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. StatusCodeCollection results2 = null; DiagnosticInfoCollection diagnosticInfos2 = null; m_session.Write( null, valuesToWrite, out results2, out diagnosticInfos2); ClientBase.ValidateResponse(results2, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos2, valuesToWrite); if (StatusCode.IsBad(results2[0])) { throw new ServiceResultException(results2[0]); } } catch (Exception exception) { ClientUtils.HandleException("Error Writing Value", exception); } try { bool arr = false; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = "ns=3;s=Mould_Changed"; valueToWrite.AttributeId = Attributes.Value; valueToWrite.Value.Value = arr; valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. StatusCodeCollection results2 = null; DiagnosticInfoCollection diagnosticInfos2 = null; m_session.Write( null, valuesToWrite, out results2, out diagnosticInfos2); ClientBase.ValidateResponse(results2, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos2, valuesToWrite); if (StatusCode.IsBad(results2[0])) { throw new ServiceResultException(results2[0]); } } catch (Exception exception) { ClientUtils.HandleException("Error Writing Value", exception); } DataValueCollection values = Read_Value("ns=3;s=Mould_2_SN"); label8.Text = (string)values[0].Value; //Update the value of Mould_tobeused try { string arr = "2"; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = "ns=3;s=Mould_tobeused"; valueToWrite.AttributeId = Attributes.Value; valueToWrite.Value.Value = arr; valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. StatusCodeCollection results2 = null; DiagnosticInfoCollection diagnosticInfos2 = null; m_session.Write( null, valuesToWrite, out results2, out diagnosticInfos2); ClientBase.ValidateResponse(results2, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos2, valuesToWrite); if (StatusCode.IsBad(results2[0])) { throw new ServiceResultException(results2[0]); } } catch (Exception exception) { ClientUtils.HandleException("Error Writing Value", exception); } //Update the value of Actual_Mould try { int arr = 2; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = "ns=3;s=Actual_Mould"; valueToWrite.AttributeId = Attributes.Value; valueToWrite.Value.Value = arr; valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. StatusCodeCollection results2 = null; DiagnosticInfoCollection diagnosticInfos2 = null; m_session.Write( null, valuesToWrite, out results2, out diagnosticInfos2); ClientBase.ValidateResponse(results2, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos2, valuesToWrite); if (StatusCode.IsBad(results2[0])) { throw new ServiceResultException(results2[0]); } } catch (Exception exception) { ClientUtils.HandleException("Error Writing Value", exception); } } button1.Enabled = false; } else if (result == DialogResult.No) { comboBox1.SelectedIndexChanged -= comboBox1_SelectedIndexChanged_1; comboBox1.SelectedText = _comboBoxIndex; comboBox1.Text = _comboBoxIndex; comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged_1; } }
void monitoredItem_Notification(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) { //This part of the code is needed to manage issues related to windows forms if (this.InvokeRequired) { this.BeginInvoke(new MonitoredItemNotificationEventHandler(monitoredItem_Notification), monitoredItem, e); return; } MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification; if (notification == null) { return; } //is call because of atual_state? if (monitoredItem.ClientHandle == Actual_State_handle) { double value = (double)notification.Value.WrappedValue.Value; Actual_State = value; //update screen label4.Text = Actual_State.ToString(); if (Actual_State > 1) { try { bool arr = false; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = "ns=3;s=Start_Piece"; valueToWrite.AttributeId = Attributes.Value; valueToWrite.Value.Value = arr; valueToWrite.Value.StatusCode = StatusCodes.Good; valueToWrite.Value.ServerTimestamp = DateTime.MinValue; valueToWrite.Value.SourceTimestamp = DateTime.MinValue; WriteValueCollection valuesToWrite = new WriteValueCollection(); valuesToWrite.Add(valueToWrite); // write current value. StatusCodeCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; m_session.Write( null, valuesToWrite, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, valuesToWrite); if (StatusCode.IsBad(results[0])) { throw new ServiceResultException(results[0]); } } catch (Exception exception) { ClientUtils.HandleException("Error Writing Value", exception); } } if (Actual_State == 8) { button1.Enabled = true; } } //is call because of Change_Mould? if (monitoredItem.ClientHandle == Change_Mould_handle) { bool value = (bool)notification.Value.WrappedValue.Value; //update screen if (value == false) { button1.Enabled = true; } } }
private void WriteMI_Click(object sender, EventArgs e) { try { // get the current session. Session session = Get <Session>(NodesTV.SelectedNode); if (session == null || !session.Connected) { return; } // build list of nodes to read. WriteValueCollection values = new WriteValueCollection(); MonitoredItem monitoredItem = Get <MonitoredItem>(NodesTV.SelectedNode); if (monitoredItem != null) { WriteValue value = new WriteValue(); value.NodeId = monitoredItem.ResolvedNodeId; value.AttributeId = monitoredItem.AttributeId; value.IndexRange = monitoredItem.IndexRange; MonitoredItemNotification datachange = monitoredItem.LastValue as MonitoredItemNotification; if (datachange != null) { value.Value = (DataValue)Utils.Clone(datachange.Value); } values.Add(value); } else { Subscription subscription = Get <Subscription>(NodesTV.SelectedNode); if (subscription != null) { foreach (MonitoredItem item in subscription.MonitoredItems) { WriteValue value = new WriteValue(); value.NodeId = item.ResolvedNodeId; value.AttributeId = item.AttributeId; value.IndexRange = item.IndexRange; MonitoredItemNotification datachange = item.LastValue as MonitoredItemNotification; if (datachange != null) { value.Value = (DataValue)Utils.Clone(datachange.Value); } values.Add(value); } } } // show form. new WriteDlg().Show(session, values); } catch (Exception exception) { GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } }
/// <summary> /// Handles a write request. /// </summary> public List<ServiceResult> Write(List<WriteRequest> requests) { if (m_session == null) { throw new ServiceResultException(StatusCodes.BadCommunicationError); } WriteValueCollection valuesToWrite = new WriteValueCollection(); for (int ii = 0; ii < requests.Count; ii++) { WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = ExpandedNodeId.ToNodeId(requests[ii].RemoteId, m_session.NamespaceUris); valueToWrite.AttributeId = requests[ii].WriteValue.AttributeId; valueToWrite.IndexRange = requests[ii].WriteValue.IndexRange; valueToWrite.Value = requests[ii].WriteValue.Value; valuesToWrite.Add(valueToWrite); } StatusCodeCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; ResponseHeader responseHeader = m_session.Write( null, valuesToWrite, out results, out diagnosticInfos); Session.ValidateResponse(results, valuesToWrite); Session.ValidateDiagnosticInfos(diagnosticInfos, valuesToWrite); List<ServiceResult> errors = new List<ServiceResult>(); for (int ii = 0; ii < requests.Count; ii++) { if (results[ii] != StatusCodes.Good) { errors.Add(new ServiceResult(results[ii], ii, diagnosticInfos, responseHeader.StringTable)); } else { errors.Add(null); } } return errors; }
/// <summary> /// IOPCAsyncIO3::WriteVQT - Writes one or more values, qualities and timestamps for the items specified. /// The results are returned via the client�s IOPCDataCallback connection established /// through the server�s IConnectionPointContainer. /// </summary> public void WriteVQT( int dwCount, int[] phServer, OPCITEMVQT[] pItemVQT, int dwTransactionID, out int pdwCancelID, out System.IntPtr ppErrors) { pdwCancelID = 0; // validate arguments. if (dwCount == 0 || phServer == null || pItemVQT == null || dwCount != phServer.Length || dwCount != pItemVQT.Length) { throw ComUtils.CreateComException(ResultIds.E_INVALIDARG); } // get callback object - nothing more to do if missing. IOPCDataCallback callback = (IOPCDataCallback)GetCallback(typeof(IOPCDataCallback).GUID); if (callback == null) { throw ComUtils.CreateComException(ResultIds.CONNECT_E_NOCONNECTION); } try { int[] errors = new int[dwCount]; // build list of values to write. WriteValueCollection valuesToWrite = new WriteValueCollection(); lock (m_lock) { if (m_subscription == null) throw ComUtils.CreateComException(ResultIds.E_FAIL); CallbackValue[] conversionErrors = null; for (int ii = 0; ii < dwCount; ii++) { Item itemToWrite = null; if (!m_items.TryGetValue(phServer[ii], out itemToWrite)) { errors[ii] = ResultIds.E_INVALIDHANDLE; continue; } VariableNode variable = itemToWrite.Variable; WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = variable.NodeId; valueToWrite.IndexRange = null; valueToWrite.AttributeId = Attributes.Value; DataValue value = new DataValue(); int error = 0; value.Value = m_server.VariantValueToValue(variable, pItemVQT[ii].vDataValue, out error); if (error != ResultIds.S_OK) { // only allocate this array when it is needed. if (conversionErrors == null) { conversionErrors = new CallbackValue[dwCount]; } // create the callback item. CallbackValue conversionError = new CallbackValue(); conversionError.ClientHandle = itemToWrite.ClientHandle; conversionError.Error = error; conversionErrors[ii] = conversionError; errors[ii] = error; continue; } valueToWrite.Value = value; if (pItemVQT[ii].bQualitySpecified != 0) { value.StatusCode = ComUtils.GetQualityCode(pItemVQT[ii].wQuality); } if (pItemVQT[ii].bTimeStampSpecified != 0) { value.SourceTimestamp = ComUtils.GetDateTime(pItemVQT[ii].ftTimeStamp); } // needed to correlate results to input. valueToWrite.Handle = itemToWrite; valuesToWrite.Add(valueToWrite); } // create transaction. if (valuesToWrite.Count > 0 || conversionErrors != null) { pdwCancelID = Utils.IncrementIdentifier(ref m_nextHandle); m_transactions[pdwCancelID] = new AsyncWriteTransaction(dwTransactionID, valuesToWrite); } // send conversion errors in the callback if no valid items available (CTT bug workaround). if (valuesToWrite.Count == 0 && conversionErrors != null) { // must return S_OK from this function if sending the errors in the callback. List<CallbackValue> errorsToSend = new List<CallbackValue>(); for (int ii = 0; ii < conversionErrors.Length; ii++) { if (conversionErrors[ii] != null) { errors[ii] = ResultIds.S_OK; errorsToSend.Add(conversionErrors[ii]); } } // queue the request. CallbackRequest request = new CallbackRequest(); request.CallbackType = CallbackType.Write; request.Callback = callback; request.TransactionId = dwTransactionID; request.GroupHandle = m_clientHandle; request.ServerHandle = m_serverHandle; request.Values = errorsToSend; QueueCallbackRequest(request); } } // write values from server. if (valuesToWrite.Count > 0) { m_session.BeginWrite( null, valuesToWrite, new AsyncCallback(OnWriteComplete), pdwCancelID); } // marshal error codes. ppErrors = ComUtils.GetInt32s(errors); } catch (Exception e) { Utils.Trace(e, "Error writing items."); throw ComUtils.CreateComException(e); } }
/// <summary> /// Write a given OPC node with the given value. /// </summary> public string WriteOpcNode(string nodeID, string newValue, Session session) { if (string.IsNullOrEmpty(nodeID) || string.IsNullOrEmpty(newValue) || (session == null)) { return(null); } string[] delimiter = { "__$__" }; string[] nodeIDSplit = nodeID.Split(delimiter, 3, StringSplitOptions.None); string node; if (nodeIDSplit.Length == 1) { node = nodeIDSplit[0]; } else { node = nodeIDSplit[1]; } // Read the variable DataValueCollection values = null; DiagnosticInfoCollection readDiagnosticInfos = null; ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); foreach (uint attributeId in Attributes.GetIdentifiers()) { ReadValueId valueId = new ReadValueId(); valueId.NodeId = new NodeId(node); valueId.AttributeId = attributeId; valueId.IndexRange = null; valueId.DataEncoding = null; nodesToRead.Add(valueId); } ResponseHeader responseHeader = session.Read(null, 0, TimestampsToReturn.Neither, nodesToRead, out values, out readDiagnosticInfos); // get DataType of the node Node dataTypeIdNode = null; NodeId dataTypeId = null; int valueRank = 0; for (int ii = 0; ii < nodesToRead.Count; ii++) { // check if node supports attribute if (values[ii].StatusCode == StatusCodes.BadAttributeIdInvalid) { continue; } switch (nodesToRead[ii].AttributeId) { case Attributes.DataType: dataTypeId = values[ii].Value as NodeId; if (dataTypeId != null) { dataTypeIdNode = session.ReadNode(dataTypeId); } break; case Attributes.ValueRank: valueRank = (int)values[ii].Value; break; default: break; } } var nodesToWrite = new WriteValueCollection(); WriteValue writeValue = new WriteValue(); writeValue.NodeId = new NodeId(node); writeValue.AttributeId = Attributes.Value; writeValue.IndexRange = null; Variant value = new Variant(); BuildDataValue(ref session, ref value, dataTypeId, valueRank, newValue); writeValue.Value.Value = value; nodesToWrite.Add(writeValue); StatusCodeCollection results; DiagnosticInfoCollection writeDiagnosticInfos; session.Write(null, nodesToWrite, out results, out writeDiagnosticInfos); return(results[0].ToString()); }
/////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// #region IOPCItemIO Members /// <summary> /// IOPCItemIO::WriteVQT - Writes one or more values, qualities and timestamps for the items specified. /// This is functionally similar to the IOPCSyncIO2::WriteVQT except that there is no associated group. /// </summary> public void WriteVQT( int dwCount, string[] pszItemIDs, OPCITEMVQT[] pItemVQT, out System.IntPtr ppErrors) { lock (m_lock) { if (m_session == null) throw ComUtils.CreateComException(ResultIds.E_FAIL); // validate arguments. if (dwCount == 0 || pszItemIDs == null || pItemVQT == null || dwCount != pszItemIDs.Length || dwCount != pItemVQT.Length) { throw ComUtils.CreateComException(ResultIds.E_INVALIDARG); } try { int[] errors = new int[dwCount]; // build list of values to write. WriteValueCollection valuesToWrite = new WriteValueCollection(); for (int ii = 0; ii < dwCount; ii++) { NodeId nodeId = ItemIdToNodeId(pszItemIDs[ii]); if (nodeId == null) { errors[ii] = ResultIds.E_INVALIDITEMID; continue; } VariableNode variable = m_session.NodeCache.Find(nodeId) as VariableNode; if (variable == null) { errors[ii] = ResultIds.E_UNKNOWNITEMID; continue; } WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = nodeId; valueToWrite.IndexRange = null; valueToWrite.AttributeId = Attributes.Value; DataValue value = new DataValue(); int error = 0; value.Value = VariantValueToValue(variable, pItemVQT[ii].vDataValue, out error); if (error != ResultIds.S_OK) { errors[ii] = error; continue; } if (pItemVQT[ii].bQualitySpecified != 0) { value.StatusCode = ComUtils.GetQualityCode(pItemVQT[ii].wQuality); } if (pItemVQT[ii].bTimeStampSpecified != 0) { value.SourceTimestamp = ComUtils.GetDateTime(pItemVQT[ii].ftTimeStamp); } valueToWrite.Value = value; // needed to correlate results to input. valueToWrite.Handle = ii; valuesToWrite.Add(valueToWrite); } // write values from server. StatusCodeCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; if (valuesToWrite.Count > 0) { m_session.Write( null, valuesToWrite, out results, out diagnosticInfos); // validate response from the UA server. ClientBase.ValidateResponse(results, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, valuesToWrite); } for (int ii = 0; ii < valuesToWrite.Count; ii++) { // get index in original array. int index = (int)valuesToWrite[ii].Handle; // map UA code to DA code. errors[index] = MapWriteStatusToErrorCode(results[ii]); } // marshal error codes. ppErrors = ComUtils.GetInt32s(errors); } catch (Exception e) { throw ComUtils.CreateComException(e); } } }
private bool WriteToKEPServer(Session AMSession, SenderJobProps job) { // Step 2 -- Read the value of a node representing a PI Point data under the hood NodeId nodeToRead = new NodeId(job.Command /*Element*/, 2); Node node = AMSession.NodeCache.Find(nodeToRead) as Node; if (node != null) { DataValue value = AMSession.ReadValue(nodeToRead); WriteValue Wvalue = new WriteValue(); Wvalue.NodeId = nodeToRead; Wvalue.AttributeId = Attributes.Value; if ((node.NodeClass & (NodeClass.Variable | NodeClass.VariableType)) == 0) { Wvalue.AttributeId = Attributes.DisplayName; } Wvalue.IndexRange = null; Wvalue.Value = value; Wvalue.Value.Value = ConvertToObject(job.CommandRule); if (Wvalue.Value.Value != null) { WriteValueCollection nodesToWrite = new WriteValueCollection(); nodesToWrite.Add(Wvalue); StatusCodeCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; ResponseHeader responseHeader = AMSession.Write( null, nodesToWrite, out results, out diagnosticInfos); Session.ValidateResponse(results, nodesToWrite); //Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToWrite); if (results[0].Code == 0) { return(true); } else { SenderMonitorEvent.sendMonitorEvent(vpEventLog, String.Format("Can not send command to KEP Server. ErrorCode: {0}. ErrorText: {1}. Job order ID: {2}", results[0].Code, results[0].ToString(), job.JobOrderID), EventLogEntryType.Error); return(false); } } else { SenderMonitorEvent.sendMonitorEvent(vpEventLog, String.Format("Can not convert command value: {0}. Job order ID: {1}", job.CommandRule, job.JobOrderID), EventLogEntryType.Error); return(false); } } else { SenderMonitorEvent.sendMonitorEvent(vpEventLog, String.Format("Item not found: {0}. Job order ID: ", job.Command, job.JobOrderID), EventLogEntryType.Error); return(false); } }
/// <summary> /// Adds random values to write. /// </summary> private void AddWriteBadValues( TestVariable variable, WriteValueCollection nodesToWrite) { for (BuiltInType ii = BuiltInType.Null; ii < BuiltInType.DataValue; ii++) { if (variable.DataType != ii || variable.Variable.ValueRank >= 0) { // add random scalar. WriteValue nodeToWrite = new WriteValue(); nodeToWrite.NodeId = variable.Variable.NodeId; nodeToWrite.AttributeId = Attributes.Value; DataValue value = new DataValue(); value.Value = m_generator.GetRandom(ii); value.StatusCode = StatusCodes.Good; value.ServerTimestamp = DateTime.MinValue; value.SourceTimestamp = DateTime.MinValue; variable.Values.Add(value); nodeToWrite.Value = value; nodeToWrite.Handle = variable; nodesToWrite.Add(nodeToWrite); } if (variable.DataType != ii || variable.Variable.ValueRank == ValueRanks.Scalar) { // add random array. WriteValue nodeToWrite = new WriteValue(); nodeToWrite.NodeId = variable.Variable.NodeId; nodeToWrite.AttributeId = Attributes.Value; DataValue value = new DataValue(); value.Value = m_generator.GetRandomArray(ii, true, 100, false); value.StatusCode = StatusCodes.Good; value.ServerTimestamp = DateTime.MinValue; value.SourceTimestamp = DateTime.MinValue; variable.Values.Add(value); nodeToWrite.Value = value; nodeToWrite.Handle = variable; nodesToWrite.Add(nodeToWrite); } } }
private async Task HandleSettingChanged(TwinCollection desiredProperties, object userContext) { var reportedProperties = new TwinCollection(); var opcSessions = Program.NodeConfiguration.OpcSessions; foreach (var opcSession in opcSessions) { foreach (var opcSubscription in opcSession.OpcSubscriptions) { foreach (var opcMonitoredItem in opcSubscription.OpcMonitoredItems) { var key = opcMonitoredItem.Key; try { if (!desiredProperties.Contains(key)) { continue; } //Handle OPC UA Property overwrite and acknowledge setting change //Get JSON Value of desired property which is reported by setting change from IoT Central var jsonValue = new Newtonsoft.Json.Linq.JObject(desiredProperties[key]) .GetValue("value").ToString(); var session = opcSession.OpcUaClientSession.GetSession(); var nodesToRead = new ReadValueIdCollection { new ReadValueId() { NodeId = opcMonitoredItem.ConfigNodeId, AttributeId = Attributes.DataType } }; session.Read( null, 0, TimestampsToReturn.Neither, nodesToRead, out DataValueCollection attributeResults, out DiagnosticInfoCollection attributeDiagnostics); ClientBase.ValidateResponse(attributeResults, nodesToRead); ClientBase.ValidateDiagnosticInfos(attributeDiagnostics, nodesToRead); var dataType = (uint)((NodeId)attributeResults.First().Value).Identifier; var namespaceIndex = ((NodeId)attributeResults.First().Value).NamespaceIndex; object value = null; try { if (namespaceIndex == 0) { switch (dataType) { case DataTypes.Boolean: value = Convert.ToBoolean(jsonValue); break; case DataTypes.Byte: value = Convert.ToByte(jsonValue); break; case DataTypes.DateTime: value = Convert.ToDateTime(jsonValue); break; case DataTypes.Double: value = Convert.ToDouble(jsonValue); break; case DataTypes.Float: value = float.Parse(jsonValue); break; case DataTypes.Guid: value = new Guid(jsonValue); break; case DataTypes.Int16: value = Convert.ToInt16(jsonValue); break; case DataTypes.Int32: value = Convert.ToInt32(jsonValue); break; case DataTypes.Int64: value = Convert.ToInt64(jsonValue); break; case DataTypes.Integer: value = Convert.ToInt32(jsonValue); break; case DataTypes.Number: value = Convert.ToInt32(jsonValue); break; case DataTypes.SByte: value = Convert.ToSByte(jsonValue); break; case DataTypes.String: value = Convert.ToString(jsonValue); break; case DataTypes.UInt16: value = Convert.ToUInt16(jsonValue); break; case DataTypes.UInt32: value = Convert.ToUInt32(jsonValue); break; case DataTypes.UInt64: value = Convert.ToUInt64(jsonValue); break; case DataTypes.UInteger: value = Convert.ToUInt32(jsonValue); break; default: throw new NotSupportedException("Data type is not supported."); } } else { // custom data type - hope for the best value = Convert.ToInt32(jsonValue); _logger.Warning("Conversion into a custom data type ({DataType}). Int32 assumed.", dataType); } } catch (Exception ex) { var dataTypeName = GetDataTypeName(dataType) ?? dataType.ToString(); string errorMessage = "Update of reported properties failed."; if (ex is NotSupportedException) { errorMessage = $"Data type '{dataTypeName}' is not supported."; } else if (ex is FormatException || ex is OverflowException) { errorMessage = $"Conversion can not be executed. '{jsonValue}' is not of data type '{dataTypeName}'."; } _logger.Error(ex, $"{nameof(HandleSettingChanged)}: {errorMessage}"); reportedProperties[key] = new { value = desiredProperties[key]["value"], desiredVersion = desiredProperties["$version"], message = errorMessage, status = "failed" }; await UpdateReportedPropertiesAsync(reportedProperties); continue; } //Create a new WriteValueCollection to write the new information to OPC UA Server var valuesToWrite = new WriteValueCollection(); var newValueToWrite = new WriteValue { NodeId = opcMonitoredItem.ConfigNodeId, AttributeId = opcMonitoredItem.AttributeId, Value = new DataValue { Value = value, ServerTimestamp = DateTime.MinValue, SourceTimestamp = DateTime.MinValue } }; valuesToWrite.Add(newValueToWrite); opcSubscription.OpcUaClientSubscription.Subscription.Session.Write( null, valuesToWrite, out var results, out var diagnosticInfos); ClientBase.ValidateResponse(results, valuesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, valuesToWrite); string status, message; if (StatusCode.IsBad(results[0])) { _logger.Error($"[{results[0].ToString()}]: Cannot write Setting value of Monitored Item with NodeId {opcMonitoredItem.Id} and Key {opcMonitoredItem.Key}"); status = IoTCentral_ReportedPropertyStatusFailed; message = $"Failure during synchronizing OPC UA Values, Reason: {results[0].ToString()}"; } else { status = IoTCentral_ReportedPropertyStatusCompleted; message = string.Empty; } reportedProperties[key] = new { value = desiredProperties[key]["value"], status, desiredVersion = desiredProperties["$version"], message }; await UpdateReportedPropertiesAsync(reportedProperties); } catch (Exception e) { _logger.Error(e, "Error while updating reported Setting."); reportedProperties[key] = new { value = desiredProperties[key]["value"], desiredVersion = desiredProperties["$version"], status = IoTCentral_ReportedPropertyStatusFailed, message = $"Failure during synchronizing OPC UA Values, Reason: {e.Message}" }; await UpdateReportedPropertiesAsync(reportedProperties); } } } } }
/// <summary> /// Reads the attributes, verifies the results and updates the nodes. /// </summary> private bool Write(int counter) { bool success = true; m_deadbandCounter++; WriteValueCollection nodesToWrite = new WriteValueCollection(); lock (m_variables) { if (m_stopped != 0 || counter != m_writeTimerCounter) { return true; } for (int ii = 0; ii < m_variables.Count; ii++) { TestVariable variable = m_variables[ii]; WriteValue nodeToWrite = new WriteValue(); nodeToWrite.NodeId = variable.Variable.NodeId; nodeToWrite.AttributeId = Attributes.Value; DataValue value = new DataValue(); if (!m_useDeadbandValues) { bool different = false; do { value.Value = m_generator.GetRandom( variable.Variable.DataType, variable.Variable.ValueRank, variable.Variable.ArrayDimensions, Session.TypeTree); if (variable.EURange != null) { value.Value = EnsureInRange(value.Value, variable.Variable, variable.EURange); } different = true; for (int jj = variable.Values.Count-1; jj >= 0; jj--) { if (m_comparer.CompareVariant(value.WrappedValue, variable.Values[jj].WrappedValue)) { different = false; break; } if (variable.DataType == BuiltInType.Boolean) { break; } } } while (!different); } else { value.Value = IncrementValue(variable, m_deadbandCounter); } value.StatusCode = StatusCodes.Good; value.ServerTimestamp = DateTime.MinValue; value.SourceTimestamp = DateTime.MinValue; nodeToWrite.Value = value; nodeToWrite.Handle = variable.Values.Count; nodesToWrite.Add(nodeToWrite); variable.Values.Add(value); variable.Timestamps.Add(DateTime.MinValue); } m_lastWriteTime = DateTime.UtcNow; } StatusCodeCollection results; DiagnosticInfoCollection diagnosticInfos; DateTime now = DateTime.UtcNow; RequestHeader requestHeader = new RequestHeader(); requestHeader.ReturnDiagnostics = 0; // need to check if the test completes and the next one starts while the write is in progress. ResponseHeader responseHeader = Session.Write( requestHeader, nodesToWrite, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, nodesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToWrite); // check diagnostics. if (diagnosticInfos != null && diagnosticInfos.Count > 0) { Log("Returned non-empty DiagnosticInfos array during Write."); return false; } // check results. lock (m_variables) { if (m_lastWriteTime > DateTime.MinValue && (DateTime.UtcNow - m_lastWriteTime).TotalMilliseconds > 300) { m_writeDelayed = true; Log("WARNING: A Write operation took {0}s. Test results may not be meaningful.", (DateTime.UtcNow - m_lastWriteTime).TotalSeconds); } m_lastWriteTime = DateTime.UtcNow; if (m_stopped != 0 || counter != m_writeTimerCounter) { return true; } for (int ii = 0; ii < nodesToWrite.Count; ii++) { TestVariable variable = m_variables[ii]; if (StatusCode.IsBad(results[ii])) { if (results[ii] == StatusCodes.BadTypeMismatch || results[ii] == StatusCodes.BadOutOfRange) { variable.WriteError = true; continue; } Log("Unexpected error during Write."); return false; } WriteValue request = nodesToWrite[ii]; variable.Timestamps[(int)request.Handle] = responseHeader.Timestamp; } m_writeCount++; } return success; }
/// <summary> /// Returns the items in the control. /// </summary> public WriteValueCollection GetValues() { WriteValueCollection values = new WriteValueCollection(); foreach (ListViewItem item in ItemsLV.Items) { WriteValue value = item.Tag as WriteValue; if (value != null) { value.Value.StatusCode = StatusCodes.Good; value.Value.ServerTimestamp = DateTime.MinValue; value.Value.SourceTimestamp = DateTime.MinValue; values.Add(value); } } return values; }
private void WriteMI_Click(object sender, EventArgs e) { try { if (NodesTV.SelectedNode == null) { return; } ReferenceDescription reference = NodesTV.SelectedNode.Tag as ReferenceDescription; if (reference == null || (reference.NodeClass & (NodeClass.Variable | NodeClass.VariableType)) == 0) { return; } Session session = m_browser.Session; // build list of nodes to read. WriteValueCollection values = new WriteValueCollection(); WriteValue value = new WriteValue(); value.NodeId = (NodeId)reference.NodeId; value.AttributeId = Attributes.Value; value.IndexRange = null; value.Value = null; values.Add(value); // show form. new WriteDlg().Show(session, values); } catch (Exception exception) { GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } }
/// <summary> /// Adds index ranges to the collection. /// </summary> private void AddWriteValues( Node node, WriteValueCollection nodesToWrite, params uint[] attributeIds) { if (attributeIds != null) { for (int ii = 0; ii < attributeIds.Length; ii++) { WriteValue nodeToWrite = new WriteValue(); nodeToWrite.NodeId = node.NodeId; nodeToWrite.AttributeId = attributeIds[ii]; DataValue value = new DataValue(); ServiceResult result = node.Read( null, attributeIds[ii], value); value.StatusCode = StatusCodes.Good; value.ServerTimestamp = DateTime.MinValue; value.SourceTimestamp = DateTime.MinValue; if (ServiceResult.IsBad(result)) { value.Value = null; } nodeToWrite.Value = value; nodeToWrite.Handle = node; nodesToWrite.Add(nodeToWrite); Array array = value.Value as Array; if (array != null) { NumericRange range = new NumericRange(0, 1); object subarray = array; range.ApplyRange(ref subarray); nodeToWrite = new WriteValue(); nodeToWrite.Value = new DataValue(); nodeToWrite.Value.Value = subarray; nodeToWrite.Value.StatusCode = StatusCodes.Good; nodeToWrite.Value.ServerTimestamp = DateTime.MinValue; nodeToWrite.Value.SourceTimestamp = DateTime.MinValue; nodeToWrite.NodeId = node.NodeId; nodeToWrite.AttributeId = attributeIds[ii]; nodeToWrite.IndexRange = "0"; nodeToWrite.Handle = node; nodesToWrite.Add(nodeToWrite); } nodeToWrite = new WriteValue(); nodeToWrite.Value = new DataValue(); nodeToWrite.Value.Value = value.Value; nodeToWrite.Value.StatusCode = StatusCodes.Uncertain; nodeToWrite.Value.ServerTimestamp = DateTime.MinValue; nodeToWrite.Value.SourceTimestamp = DateTime.MinValue; nodeToWrite.NodeId = node.NodeId; nodeToWrite.AttributeId = attributeIds[ii]; nodeToWrite.Handle = node; nodesToWrite.Add(nodeToWrite); nodeToWrite = new WriteValue(); nodeToWrite.Value = new DataValue(); nodeToWrite.Value.Value = value.Value; nodeToWrite.Value.StatusCode = StatusCodes.Good; nodeToWrite.Value.ServerTimestamp = DateTime.UtcNow; nodeToWrite.Value.SourceTimestamp = DateTime.MinValue; nodeToWrite.NodeId = node.NodeId; nodeToWrite.AttributeId = attributeIds[ii]; nodeToWrite.Handle = node; nodesToWrite.Add(nodeToWrite); nodeToWrite = new WriteValue(); nodeToWrite.Value = new DataValue(); nodeToWrite.Value.Value = value.Value; nodeToWrite.Value.StatusCode = StatusCodes.Good; nodeToWrite.Value.ServerTimestamp = DateTime.MinValue; nodeToWrite.Value.SourceTimestamp = DateTime.UtcNow; nodeToWrite.NodeId = node.NodeId; nodeToWrite.AttributeId = attributeIds[ii]; nodeToWrite.Handle = node; nodesToWrite.Add(nodeToWrite); } } }
/// <summary> /// Performs n synchronous write operation. /// </summary> /// <param name="serverHandles">The server handles.</param> /// <param name="values">The values.</param> /// <returns>Any errors.</returns> public int[] SyncWrite(int[] serverHandles, DaValue[] values) { TraceState("SyncWrite", serverHandles.Length); ThrowIfDisposed(); int[] results = new int[serverHandles.Length]; WriteValueCollection valuesToWrite = new WriteValueCollection(); lock (m_lock) { // validate items. DaValue convertedValue = new DaValue(); for (int ii = 0; ii < serverHandles.Length; ii++) { ComDaGroupItem item = null; if (!m_itemsByHandle.TryGetValue(serverHandles[ii], out item)) { results[ii] = ResultIds.E_INVALIDHANDLE; continue; } // apply the COM type conversion. DaValue requestedValue = values[ii]; if (requestedValue.Value == null) { results[ii] = ResultIds.E_BADTYPE; continue; } if (item.CanonicalDataType != (short)VarEnum.VT_EMPTY) { object value = null; int error = ComUtils.ChangeTypeForCOM(requestedValue.Value, (VarEnum)item.CanonicalDataType, out value); if (error < 0) { results[ii] = error; continue; } // could happen if there is a problem reading the datatype from the server. if (requestedValue.Value == null) { results[ii] = ResultIds.E_BADTYPE; continue; } // copy all of the attributes into the converted value. convertedValue.Value = value; convertedValue.Quality = requestedValue.Quality; convertedValue.Timestamp = requestedValue.Timestamp; convertedValue.Error = requestedValue.Error; requestedValue = convertedValue; } WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = item.NodeId; valueToWrite.AttributeId = Attributes.Value; valueToWrite.Handle = ii; // convert value to UA data type. try { valueToWrite.Value = m_manager.Mapper.GetRemoteDataValue(requestedValue, item.RemoteDataType); } catch (Exception e) { results[ii] = ComUtils.GetErrorCode(e, ResultIds.E_BADTYPE); continue; } valuesToWrite.Add(valueToWrite); } } // check if nothing to do. if (valuesToWrite.Count == 0) { return results; } // write the values to the server. int[] remoteResults = m_manager.Write(valuesToWrite); // copy results. for (int ii = 0; ii < valuesToWrite.Count; ii++) { results[(int)valuesToWrite[ii].Handle] = remoteResults[ii]; } return results; }
/// <summary> /// Reads the values displayed in the control and moves to the display results state. /// </summary> public void Write() { if (m_session == null) { throw new ServiceResultException(StatusCodes.BadNotConnected); } // build list of values to write. WriteValueCollection nodesToWrite = new WriteValueCollection(); foreach (DataGridViewRow row in ResultsDV.Rows) { DataRowView source = row.DataBoundItem as DataRowView; WriteValue value = (WriteValue)source.Row[0]; row.Selected = false; nodesToWrite.Add(value); } // read the values. StatusCodeCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; m_session.Write( null, nodesToWrite, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, nodesToWrite); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToWrite); IndexRangeCH.Visible = false; DataTypeCH.Visible = false; ValueCH.Visible = false; StatusCodeCH.Visible = false; ResultCH.Visible = true; // add the results to the display. for (int ii = 0; ii < results.Count; ii++) { DataRowView source = ResultsDV.Rows[ii].DataBoundItem as DataRowView; UpdateRow(source.Row, results[ii]); } }
/// <summary> /// Writes the values for the specified item ids. /// </summary> /// <param name="itemIds">The item ids.</param> /// <param name="values">The values.</param> /// <returns>The results.</returns> public int[] Write(string[] itemIds, DaValue[] values) { int[] results = new int[itemIds.Length]; WriteValueCollection valuesToWrite = new WriteValueCollection(); ComDaReadPropertiesRequest[] requests = new ComDaReadPropertiesRequest[values.Length]; // prepare request. for (int ii = 0; ii < itemIds.Length; ii++) { ComDaReadPropertiesRequest request = requests[ii] = new ComDaReadPropertiesRequest(); request.ItemId = itemIds[ii]; } // need to get the data type of the remote node. m_browseManager.GetPropertyValues(Session, requests, PropertyIds.UaBuiltInType, PropertyIds.UaValueRank); // validate items. for (int ii = 0; ii < requests.Length; ii++) { ComDaReadPropertiesRequest request = requests[ii]; if (request.Error < 0) { results[ii] = request.Error; continue; } int? builtInType = request.Values[0].Value as int?; int? valueRank = request.Values[1].Value as int?; if (builtInType == null || valueRank == null) { results[ii] = ResultIds.E_UNKNOWNITEMID; continue; } // convert value to UA data type. WriteValue valueToWrite = new WriteValue(); valueToWrite.NodeId = m_mapper.GetRemoteNodeId(itemIds[ii]); valueToWrite.AttributeId = Attributes.Value; valueToWrite.Handle = ii; // convert value to UA data type. try { TypeInfo remoteType = new TypeInfo((BuiltInType)builtInType.Value, valueRank.Value); valueToWrite.Value = m_mapper.GetRemoteDataValue(values[ii], remoteType); } catch (Exception e) { results[ii] = ComUtils.GetErrorCode(e, ResultIds.E_BADTYPE); continue; } valuesToWrite.Add(valueToWrite); } // check if nothing to do. if (valuesToWrite.Count == 0) { return results; } // write the values to the server. int[] remoteResults = m_groupManager.Write(valuesToWrite); // copy results. for (int ii = 0; ii < valuesToWrite.Count; ii++) { results[(int)valuesToWrite[ii].Handle] = remoteResults[ii]; } return results; }