Esempio n. 1
0
 /// <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");
     }
 }
Esempio n. 2
0
 /// <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);
     }
 }
Esempio n. 3
0
        /// <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);
            }
        }
Esempio n. 4
0
        /// <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);
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Gets the history for the attribute.
        /// </summary>
        public void GetHistoryResults(
            ISystemContext context,
            HistoryReadValueId nodeToRead,
            DataValueCollection values)
        {
            DataValue value = null;

            do
            {
                value = NextValue(
                    context,
                    nodeToRead.ParsedIndexRange,
                    nodeToRead.DataEncoding);

                if (value != null)
                {
                    values.Add(value);

                    if (MaxReturnValues > 0 && values.Count == MaxReturnValues)
                    {
                        break;
                    }
                }
            }while (value != null);

            Completed = value == null;
        }
Esempio n. 6
0
        /// <summary>
        /// Gets the history for the attribute.
        /// </summary>
        public void GetHistoryResults(
            ISystemContext context,
            HistoryReadValueId nodeToRead,
            DataValueCollection values)
        {
            DataValue value = null;

            do
            {
                if (m_annotations == null || m_position >= m_annotations.Count)
                {
                    break;
                }

                value = m_annotations[m_position++];
                ApplyIndexRangeAndDataEncoding(context, nodeToRead.ParsedIndexRange, nodeToRead.DataEncoding, value);
                values.Add(value);

                if (values.Count == MaxReturnValues)
                {
                    break;
                }
            }while (value != null);

            Completed = m_annotations == null || m_position >= m_annotations.Count;

            if (m_annotations != null && m_position > 0)
            {
                m_annotations.RemoveRange(0, m_position);
                m_position = 0;
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Used by the performance test.
        /// </summary>
        public override ResponseHeader Read(
            RequestHeader requestHeader,
            double maxAge,
            TimestampsToReturn timestampsToReturn,
            ReadValueIdCollection nodesToRead,
            out DataValueCollection values,
            out DiagnosticInfoCollection diagnosticInfos)
        {
            if (requestHeader.ReturnDiagnostics != 5000)
            {
                return(base.Read(requestHeader, maxAge, timestampsToReturn, nodesToRead, out values, out diagnosticInfos));
            }

            diagnosticInfos = null;

            DataValue value = new DataValue();

            value.WrappedValue    = new Variant((int)1);
            value.SourceTimestamp = DateTime.UtcNow;

            values = new DataValueCollection(nodesToRead.Count);

            foreach (ReadValueId valueId in nodesToRead)
            {
                values.Add(value);
            }

            return(new ResponseHeader());
        }
Esempio n. 8
0
 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);
     }
 }
        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);
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Adds a DataValue to a list of values to return.
        /// </summary>
        private void AddValue(
            TimestampsToReturn timestampsToReturn,
            NumericRange indexRange,
            QualifiedName dataEncoding,
            DataValueCollection values,
            DataValue value)
        {
            // ignore invalid case.
            if (value == null)
            {
                return;
            }

            // save the last timestamp returned.
            m_lastTime = value.ServerTimestamp;

            // check if the index range or data encoding can be applied.
            if (StatusCode.IsGood(value.StatusCode))
            {
                object valueToReturn = value.Value;

                // apply the index range.
                if (indexRange != NumericRange.Empty)
                {
                    StatusCode error = indexRange.ApplyRange(ref valueToReturn);

                    if (StatusCode.IsBad(error))
                    {
                        value.Value      = null;
                        value.StatusCode = error;
                    }
                    else
                    {
                        value.Value = valueToReturn;
                    }
                }

                // apply the data encoding.
                if (!QualifiedName.IsNull(dataEncoding))
                {
                    value.Value      = null;
                    value.StatusCode = StatusCodes.BadDataEncodingUnsupported;
                }
            }

            // apply the timestamps filter.
            if (timestampsToReturn == TimestampsToReturn.Neither || timestampsToReturn == TimestampsToReturn.Server)
            {
                value.SourceTimestamp = DateTime.MinValue;
            }

            if (timestampsToReturn == TimestampsToReturn.Neither || timestampsToReturn == TimestampsToReturn.Source)
            {
                value.ServerTimestamp = DateTime.MinValue;
            }

            // add result.
            values.Add(value);
        }
Esempio n. 11
0
        public ResponseHeader Read(ReadValueIdCollection itemsToRead, out DataValueCollection values, out DiagnosticInfoCollection diagnosticInfos)
        {
            values          = new DataValueCollection();
            diagnosticInfos = new DiagnosticInfoCollection();

            foreach (var item in itemsToRead)
            {
                values.Add(new DataValue(12345, new StatusCode(0)));
            }

            return(new ResponseHeader());
        }
Esempio n. 12
0
        /// <summary>
        /// Read Values of NodeIds, determine types, write back new random values.
        /// </summary>
        /// <param name="testSet">The nodeIds to modify.</param>
        private void UpdateValues(NodeId[] testSet)
        {
            // Read values
            var requestHeader = m_requestHeader;
            var nodesToRead   = new ReadValueIdCollection();

            foreach (NodeId nodeId in testSet)
            {
                nodesToRead.Add(new ReadValueId()
                {
                    NodeId = nodeId, AttributeId = Attributes.Value
                });
            }
            var response = m_server.Read(requestHeader, kMaxAge, TimestampsToReturn.Neither, nodesToRead,
                                         out var readDataValues, out var diagnosticInfos);

            ServerFixtureUtils.ValidateResponse(response);
            ServerFixtureUtils.ValidateDiagnosticInfos(diagnosticInfos, readDataValues);
            Assert.AreEqual(testSet.Length, readDataValues.Count);

            var modifiedValues = new DataValueCollection();

            foreach (var dataValue in readDataValues)
            {
                var typeInfo = TypeInfo.Construct(dataValue.Value);
                Assert.IsNotNull(typeInfo);
                var value = m_generator.GetRandom(typeInfo.BuiltInType);
                modifiedValues.Add(new DataValue()
                {
                    WrappedValue = new Variant(value)
                });
            }

            int ii           = 0;
            var nodesToWrite = new WriteValueCollection();

            foreach (NodeId nodeId in testSet)
            {
                nodesToWrite.Add(new WriteValue()
                {
                    NodeId = nodeId, AttributeId = Attributes.Value, Value = modifiedValues[ii]
                });
                ii++;
            }

            // Write Nodes
            requestHeader.Timestamp = DateTime.UtcNow;
            response = m_server.Write(requestHeader, nodesToWrite,
                                      out var writeDataValues, out diagnosticInfos);
            ServerFixtureUtils.ValidateResponse(response);
            ServerFixtureUtils.ValidateDiagnosticInfos(diagnosticInfos, writeDataValues);
        }
Esempio n. 13
0
        /// <summary>
        /// Samples the values of the items.
        /// </summary>
        private void DoSample(object state)
        {
            try
            {
                List <ISampledDataChangeMonitoredItem> items = state as List <ISampledDataChangeMonitoredItem>;

                // read values for all enabled items.
                if (items != null && items.Count > 0)
                {
                    ReadValueIdCollection itemsToRead = new ReadValueIdCollection(items.Count);
                    DataValueCollection   values      = new DataValueCollection(items.Count);
                    List <ServiceResult>  errors      = new List <ServiceResult>(items.Count);

                    // allocate space for results.
                    for (int ii = 0; ii < items.Count; ii++)
                    {
                        ReadValueId readValueId = items[ii].GetReadValueId();
                        readValueId.Processed = false;
                        itemsToRead.Add(readValueId);

                        values.Add(null);
                        errors.Add(null);
                    }

                    OperationContext context = new OperationContext(m_session, m_diagnosticsMask);

                    // read values.
                    m_nodeManager.Read(
                        context,
                        0,
                        itemsToRead,
                        values,
                        errors);

                    // update monitored items.
                    for (int ii = 0; ii < items.Count; ii++)
                    {
                        if (values[ii] == null)
                        {
                            values[ii] = new DataValue(StatusCodes.BadInternalError, DateTime.UtcNow);
                        }

                        items[ii].QueueValue(values[ii], errors[ii]);
                    }
                }
            }
            catch (Exception e)
            {
                Utils.Trace(e, "Server: Unexpected error sampling values.");
            }
        }
Esempio n. 14
0
        /// <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;
            }
        }
Esempio n. 15
0
        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";
        }
Esempio n. 16
0
        /// <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");
            }
        }
Esempio n. 17
0
        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");
            }
        }
Esempio n. 18
0
 /// <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");
     }
 }
Esempio n. 19
0
        /// <summary>
        /// Updates the history.
        /// </summary>
        private void InsertReplace(PerformUpdateType updateType)
        {
            DataValueCollection values = new DataValueCollection();

            foreach (DataRowView row in m_dataset.Tables[0].DefaultView)
            {
                DataValue value = (DataValue)row.Row[9];
                values.Add(value);
            }
            
            bool isStructured = false;

            PropertyWithHistory property = PropertyCB.SelectedItem as PropertyWithHistory;

            if (property != null && property.BrowseName == Opc.Ua.BrowseNames.Annotations)
            {
                isStructured = true;
            }

            HistoryUpdateResultCollection results = InsertReplace(GetSelectedNode(), updateType, isStructured, values);

            ResultsDV.Columns[ResultsDV.Columns.Count - 1].Visible = true;

            for (int ii = 0; ii < m_dataset.Tables[0].DefaultView.Count; ii++)
            {
                m_dataset.Tables[0].DefaultView[ii].Row[10] = results[0].OperationResults[ii];
            }

            m_dataset.AcceptChanges();
        }
Esempio n. 20
0
        /// <summary>
        /// Sends the read request to the server.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <param name="nodesToRead">The nodes to read.</param>
        /// <returns></returns>
        private DataValueCollection Read(Session session, ReadValueIdCollection nodesToRead)
        {
            // read attribute values from the server.
            DataValueCollection results = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            try
            {
                session.Read(
                    null,
                    0,
                    TimestampsToReturn.Source,
                    nodesToRead,
                    out results,
                    out diagnosticInfos);

                ClientBase.ValidateResponse(results, nodesToRead);
                ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);
            }
            catch (Exception e)
            {
                // convert to item level errors.
                ServiceResult error = new ServiceResult(e, StatusCodes.BadUnexpectedError);

                results = new DataValueCollection();

                for (int ii = 0; ii < nodesToRead.Count; ii++)
                {
                    results.Add(new DataValue(error.StatusCode));
                }
            }

            return results;
        }
Esempio n. 21
0
        /// <summary>
        /// Reads an DataValue array from the stream.
        /// </summary>
        public DataValueCollection ReadDataValueArray(string fieldName)
        {
            bool isNil = false;

            DataValueCollection values = new DataValueCollection();
                                    
            if (BeginField(fieldName, true, out isNil))
            {                                
                PushNamespace(Namespaces.OpcUaXsd);
                
                while (MoveToElement("DataValue"))
                {
                    values.Add(ReadDataValue("DataValue"));
                }

                // check the length.
                if (m_context.MaxArrayLength > 0 && m_context.MaxArrayLength < values.Count)
                {
                    throw new ServiceResultException(StatusCodes.BadEncodingLimitsExceeded);
                }

                PopNamespace();

                EndField(fieldName);
                return values;
            }

            if (isNil)
            {
                return null;
            }

            return values;
        }
        /// <summary>
        /// Reads an DataValue array from the stream.
        /// </summary>
        public DataValueCollection ReadDataValueArray(string fieldName)
        {
            var values = new DataValueCollection();

            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 = ReadDataValue(null);
                    values.Add(element);
                }
                finally
                {
                    m_stack.Pop();
                }
            }

            return values;
        }
Esempio n. 23
0
        /// <summary>
        /// Used by the performance test.
        /// </summary>
        public override ResponseHeader Read(
            RequestHeader                requestHeader, 
            double                       maxAge, 
            TimestampsToReturn           timestampsToReturn, 
            ReadValueIdCollection        nodesToRead, 
            out DataValueCollection      values, 
            out DiagnosticInfoCollection diagnosticInfos)
        {
            if (requestHeader.ReturnDiagnostics != 5000)
            {
                return base.Read(requestHeader, maxAge, timestampsToReturn, nodesToRead, out values, out diagnosticInfos);
            }

            diagnosticInfos = null;

            DataValue value = new DataValue();
            
            value.WrappedValue    = new Variant((int)1);
            value.SourceTimestamp = DateTime.UtcNow;

            values = new DataValueCollection(nodesToRead.Count);

            foreach (ReadValueId valueId in nodesToRead)
            {
                values.Add(value);
            }
            
            return new ResponseHeader();
        }                    
Esempio n. 24
0
        /// <summary>
        /// Adds a DataValue to a list of values to return.
        /// </summary>
        private void AddValue(
            TimestampsToReturn timestampsToReturn, 
            NumericRange indexRange,
            QualifiedName dataEncoding,
            DataValueCollection values, 
            DataValue value)
        {
            // ignore invalid case.
            if (value == null)
            {
                return;
            }

            // save the last timestamp returned.
            m_lastTime = value.ServerTimestamp;
            
            // check if the index range or data encoding can be applied.
            if (StatusCode.IsGood(value.StatusCode))
            {
                object valueToReturn = value.Value;
                
                // apply the index range.
                if (indexRange != NumericRange.Empty)
                {
                    StatusCode error = indexRange.ApplyRange(ref valueToReturn);

                    if (StatusCode.IsBad(error))
                    {
                        value.Value = null;
                        value.StatusCode = error;
                    }
                    else
                    {
                        value.Value = valueToReturn;
                    }
                }

                // apply the data encoding.
                if (!QualifiedName.IsNull(dataEncoding))
                {
                    value.Value = null;
                    value.StatusCode = StatusCodes.BadDataEncodingUnsupported;
                }
            }

            // apply the timestamps filter.
            if (timestampsToReturn == TimestampsToReturn.Neither || timestampsToReturn == TimestampsToReturn.Server)
            {
                value.SourceTimestamp = DateTime.MinValue;
            }

            if (timestampsToReturn == TimestampsToReturn.Neither || timestampsToReturn == TimestampsToReturn.Source)
            {
                value.ServerTimestamp = DateTime.MinValue;
            }

            // add result.
            values.Add(value);
        }
Esempio n. 25
0
        /// <summary>
        /// Samples the values of the items.
        /// </summary>
        private void DoSample(object state)
        {  
            try
            {
                List<ISampledDataChangeMonitoredItem> items = state as List<ISampledDataChangeMonitoredItem>;

                // read values for all enabled items.
                if (items != null && items.Count > 0)
                {
                    ReadValueIdCollection itemsToRead = new ReadValueIdCollection(items.Count);
                    DataValueCollection values = new DataValueCollection(items.Count);
                    List<ServiceResult> errors = new List<ServiceResult>(items.Count);

                    // allocate space for results.
                    for (int ii = 0; ii < items.Count; ii++)
                    {
                        ReadValueId readValueId = items[ii].GetReadValueId();
                        readValueId.Processed = false;
                        itemsToRead.Add(readValueId);

                        values.Add(null);
                        errors.Add(null);
                    }

                    OperationContext context = new OperationContext(m_session, m_diagnosticsMask);

                    // read values.
                    m_nodeManager.Read(
                        context,
                        0,
                        itemsToRead,
                        values,
                        errors);

                    // update monitored items.
                    for (int ii = 0; ii < items.Count; ii++)
                    {
                        if (values[ii] == null)
                        {
                            values[ii] = new DataValue(StatusCodes.BadInternalError, DateTime.UtcNow);
                        }

                        items[ii].QueueValue(values[ii], errors[ii]);
                    }
                }
            }
            catch (Exception e)
            {
                Utils.Trace(e, "Server: Unexpected error sampling values.");
            }
        }
Esempio n. 26
0
        /// <summary>
        /// Reads an DataValue array from the stream.
        /// </summary>
        public DataValueCollection ReadDataValueArray(string fieldName)
        {
            int length = ReadArrayLength();

            if (length == -1)
            {
                return null;
            }

            DataValueCollection values = new DataValueCollection(length);

            for (int ii = 0; ii < length; ii++)
            {
                values.Add(ReadDataValue(null));
            }

            return values;
        }
Esempio n. 27
0
        /// <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);
            }
        }
Esempio n. 28
0
        /// <summary>
        /// Reads a set of nodes
        /// </summary>
        public virtual void Read(
            OperationContext             context,
            double                       maxAge,
            TimestampsToReturn           timestampsToReturn,
            ReadValueIdCollection        nodesToRead,
            out DataValueCollection      values,
            out DiagnosticInfoCollection diagnosticInfos)
        {
            if (nodesToRead == null) throw new ArgumentNullException("nodesToRead");
            
            if (maxAge < 0)
            {
                throw new ServiceResultException(StatusCodes.BadMaxAgeInvalid);
            }

            if (timestampsToReturn < TimestampsToReturn.Source || timestampsToReturn > TimestampsToReturn.Neither)
            {
                throw new ServiceResultException(StatusCodes.BadTimestampsToReturnInvalid);
            }

            bool diagnosticsExist = false;
            values = new DataValueCollection(nodesToRead.Count);
            diagnosticInfos = new DiagnosticInfoCollection(nodesToRead.Count);

            // create empty list of errors.
            List<ServiceResult> errors = new List<ServiceResult>(values.Count);

            for (int ii = 0; ii < nodesToRead.Count; ii++)
            {
                errors.Add(null);
            }

            // add placeholder for each result.
            bool validItems = false;
        
            Utils.Trace(
                (int)Utils.TraceMasks.ServiceDetail, 
                "MasterNodeManager.Read - Count={0}", 
                nodesToRead.Count);

            for (int ii = 0; ii < nodesToRead.Count; ii++)
            {
                DataValue value = null;
                DiagnosticInfo diagnosticInfo = null;
                
                // pre-validate and pre-parse parameter.
                errors[ii] = ReadValueId.Validate(nodesToRead[ii]);
                
                // return error status.
                if (ServiceResult.IsBad(errors[ii]))
                {
                    nodesToRead[ii].Processed = true;
                }

                // found at least one valid item.
                else
                {
                    nodesToRead[ii].Processed = false;
                    validItems = true;
                }

                values.Add(value);
                diagnosticInfos.Add(diagnosticInfo);
            }

            // call each node manager.
            if (validItems)
            {                
                for (int ii = 0; ii < m_nodeManagers.Count; ii++)
                {
                    Utils.Trace(
                        (int)Utils.TraceMasks.ServiceDetail, 
                        "MasterNodeManager.Read - Calling NodeManager {0} of {1}", 
                        ii,
                        m_nodeManagers.Count);

                    m_nodeManagers[ii].Read(
                        context,
                        maxAge,
                        nodesToRead,
                        values,
                        errors);
                }
            }

            // process results.
            for (int ii = 0; ii < nodesToRead.Count; ii++)
            {
                DataValue value = values[ii];

                // set an error code for nodes that were not handled by any node manager.
                if (!nodesToRead[ii].Processed)
                {
                    value = values[ii] = new DataValue(StatusCodes.BadNodeIdUnknown, DateTime.UtcNow);
                    errors[ii] = new ServiceResult(values[ii].StatusCode);
                }

                // update the diagnostic info and ensure the status code in the data value is the same as the error code.
                if (errors[ii] != null && errors[ii].Code != StatusCodes.Good)
                {
                    if (value == null)
                    {
                        value = values[ii] = new DataValue(errors[ii].Code, DateTime.UtcNow);
                    }

                    value.StatusCode = errors[ii].Code;

                    if ((context.DiagnosticsMask & DiagnosticsMasks.OperationAll) != 0)
                    {
                        diagnosticInfos[ii] = ServerUtils.CreateDiagnosticInfo(m_server, context, errors[ii]);
                        diagnosticsExist = true;
                    }
                }

                // apply the timestamp filters.
                if (timestampsToReturn != TimestampsToReturn.Server && timestampsToReturn != TimestampsToReturn.Both)
                {
                    value.ServerTimestamp = DateTime.MinValue;
                }

                if (timestampsToReturn != TimestampsToReturn.Source && timestampsToReturn != TimestampsToReturn.Both)
                {
                    value.SourceTimestamp = DateTime.MinValue;
                }
            }

            // clear the diagnostics array if no diagnostics requested or no errors occurred.
            UpdateDiagnostics(context, diagnosticsExist, ref diagnosticInfos);
        }