예제 #1
0
        /// <summary>
        /// Checks if the subscription is ready to publish and returns a notification message.
        /// </summary>
        public NotificationMessage Publish()
        {
            lock (m_lock)
            {
                long currentTime = DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond;

                // check of it is time for a publish.
                if (m_lastPublishTime + m_publishingInterval < currentTime)
                {
                    ListOfMonitoredItemNotification notifications = new ListOfMonitoredItemNotification();
                    ListOfDiagnosticInfo diagnosticInfos = new ListOfDiagnosticInfo();

                    // check each monitored item for data changes to send.
                    foreach (MonitoredItem monitoredItem in m_monitoredItems.Values)
                    {
                        while (monitoredItem.Values.Count > 0)
                        {
                            MonitoredItemNotification notification = new MonitoredItemNotification();

                            notification.ClientHandle = monitoredItem.Parameters.ClientHandle;
                            notification.Value = monitoredItem.Values.Dequeue();

                            notifications.Add(notification);
                            diagnosticInfos.Add(monitoredItem.DiagnosticInfos.Dequeue());
                        }
                    }

                    // check if any notifications were found.
                    if (notifications.Count > 0)
                    {
                        // subscriptions can produce different types of notifications so the notification parameter 
                        // is an extensible parameter. This means the object must be manually serialized and wrapped in
                        // an ExtensionObject which specifies the type of data contained in the Body. The complete
                        // UA SDK takes care this housekeeping and will serialize extensible parameters automatically.

                        DataChangeNotification body = new DataChangeNotification();

                        body.MonitoredItems = notifications;
                        body.DiagnosticInfos = diagnosticInfos;
                        
                        ExtensionObject extension = new ExtensionObject(
                            new ExpandedNodeId(Objects.DataChangeNotification_Encoding_DefaultXml),
                            body);

                        // construct the message and assign a new sequence number.
                        NotificationMessage message = new NotificationMessage();

                        message.SequenceNumber = ++m_nextSequenceNumber;
                        message.PublishTime = DateTime.UtcNow;
                        message.NotificationData = new ListOfExtensionObject();

                        message.NotificationData.Add(extension);

                        m_lastPublishTime = currentTime;
                        m_nextKeepAliveTime = (long)(currentTime + m_publishingInterval * m_keepAliveCount);

                        return message;
                    }
                }

                // check if it is time for a keep alive.
                if (m_nextKeepAliveTime < currentTime)
                {
                    NotificationMessage message = new NotificationMessage();

                    message.SequenceNumber = m_nextSequenceNumber;
                    message.PublishTime = DateTime.UtcNow;
                    message.NotificationData = new ListOfExtensionObject();

                    m_nextKeepAliveTime = (long)(currentTime + m_publishingInterval * m_keepAliveCount);

                    return message;
                }

                return null;
            }
        }
예제 #2
0
        /// <summary>
        /// Publishes a value.
        /// </summary>
        private void Publish(
            OperationContext context,
            DataValue value,
            ServiceResult error,
            Queue <MonitoredItemNotification> notifications,
            Queue <DiagnosticInfo> diagnostics)
        {
            // set semantics changed bit.
            if (m_semanticsChanged)
            {
                if (value != null)
                {
                    value.StatusCode = value.StatusCode.SetSemanticsChanged(true);
                }

                if (error != null)
                {
                    error = new ServiceResult(
                        error.StatusCode.SetSemanticsChanged(true),
                        error.SymbolicId,
                        error.NamespaceUri,
                        error.LocalizedText,
                        error.AdditionalInfo,
                        error.InnerResult);
                }

                m_semanticsChanged = false;
            }

            // set structure changed bit.
            if (m_structureChanged)
            {
                if (value != null)
                {
                    value.StatusCode = value.StatusCode.SetStructureChanged(true);
                }

                if (error != null)
                {
                    error = new ServiceResult(
                        error.StatusCode.SetStructureChanged(true),
                        error.SymbolicId,
                        error.NamespaceUri,
                        error.LocalizedText,
                        error.AdditionalInfo,
                        error.InnerResult);
                }

                m_structureChanged = false;
            }

            // copy data value.
            MonitoredItemNotification item = new MonitoredItemNotification();

            item.ClientHandle = m_clientHandle;
            item.Value        = value;

            // apply timestamp filter.
            if (m_timestampsToReturn != TimestampsToReturn.Server && m_timestampsToReturn != TimestampsToReturn.Both)
            {
                item.Value.ServerTimestamp = DateTime.MinValue;
            }

            if (m_timestampsToReturn != TimestampsToReturn.Source && m_timestampsToReturn != TimestampsToReturn.Both)
            {
                item.Value.SourceTimestamp = DateTime.MinValue;
            }

            notifications.Enqueue(item);

            // update diagnostic info.
            DiagnosticInfo diagnosticInfo = null;

            if (m_lastError != null)
            {
                if ((m_diagnosticsMasks & DiagnosticsMasks.OperationAll) != 0)
                {
                    diagnosticInfo = ServerUtils.CreateDiagnosticInfo(m_source.Server, context, m_lastError);
                }
            }

            diagnostics.Enqueue(diagnosticInfo);
        }
예제 #3
0
        /// <summary>
        /// Shows a value in control.
        /// </summary>
        private void ShowValue(ref int index, ref bool overwrite, object value)
        {
            if (value == null)
            {
                return;
            }

            // show monitored items.
            MonitoredItem monitoredItem = value as MonitoredItem;

            if (monitoredItem != null)
            {
                m_monitoredItem = monitoredItem;
                ShowValue(ref index, ref overwrite, monitoredItem.LastValue);
                return;
            }

            // show data changes
            MonitoredItemNotification datachange = value as MonitoredItemNotification;

            if (datachange != null)
            {
                ShowValue(ref index, ref overwrite, datachange.Value);
                return;
            }

            // show write value with IndexRange
            WriteValue writevalue = value as WriteValue;

            if (writevalue != null)
            {
                // check if the value is an array
                Array arrayvalue = writevalue.Value.Value as Array;

                if (arrayvalue != null)
                {
                    NumericRange  indexRange;
                    ServiceResult result = NumericRange.Validate(writevalue.IndexRange, out indexRange);

                    if (ServiceResult.IsGood(result) && indexRange != NumericRange.Empty)
                    {
                        for (int ii = 0; ii < arrayvalue.Length; ii++)
                        {
                            bool enabled = ((indexRange.Begin <= ii && indexRange.End >= ii) ||
                                            (indexRange.End < 0 && indexRange.Begin == ii));

                            ShowValue(ref index, ref overwrite, arrayvalue, ii, enabled);
                        }

                        return;
                    }
                }
            }

            // show events
            EventFieldList eventFields = value as EventFieldList;

            if (eventFields != null)
            {
                for (int ii = 0; ii < eventFields.EventFields.Count; ii++)
                {
                    ShowValue(ref index, ref overwrite, eventFields, ii);
                }

                return;
            }

            // show extension bodies.
            ExtensionObject extension = value as ExtensionObject;

            if (extension != null)
            {
                ShowValue(ref index, ref overwrite, extension.Body);
                return;
            }

            // show encodeables.
            IEncodeable encodeable = value as IEncodeable;

            if (encodeable != null)
            {
                PropertyInfo[] properties = encodeable.GetType().GetProperties();

                foreach (PropertyInfo property in properties)
                {
                    ShowValue(ref index, ref overwrite, encodeable, property);
                }

                return;
            }

            // show bytes.
            byte[] bytes = value as byte[];

            if (bytes != null)
            {
                if (!PromptOnLongList(bytes.Length / 16))
                {
                    return;
                }

                for (int ii = 0; ii < bytes.Length; ii += 16)
                {
                    ShowValue(ref index, ref overwrite, bytes, ii);
                }

                return;
            }

            // show arrays
            Array array = value as Array;

            if (array == null)
            {
                Matrix matrix = value as Matrix;

                if (matrix != null)
                {
                    array = matrix.ToArray();
                }
            }

            if (array != null)
            {
                if (!PromptOnLongList(array.GetLength(0)))
                {
                    return;
                }

                for (int ii = 0; ii < array.GetLength(0); ii++)
                {
                    ShowValue(ref index, ref overwrite, array, ii);
                }

                return;
            }

            // show lists
            IList list = value as IList;

            if (list != null)
            {
                if (!PromptOnLongList(list.Count))
                {
                    return;
                }

                for (int ii = 0; ii < list.Count; ii++)
                {
                    ShowValue(ref index, ref overwrite, list, ii);
                }

                return;
            }

            // show xml elements
            XmlElement xml = value as XmlElement;

            if (xml != null)
            {
                if (!PromptOnLongList(xml.ChildNodes.Count))
                {
                    return;
                }

                for (int ii = 0; ii < xml.ChildNodes.Count; ii++)
                {
                    ShowValue(ref index, ref overwrite, xml, ii);
                }

                return;
            }

            // show data value.
            DataValue datavalue = value as DataValue;

            if (datavalue != null)
            {
                ShowValue(ref index, ref overwrite, datavalue, 0);
                ShowValue(ref index, ref overwrite, datavalue, 1);
                ShowValue(ref index, ref overwrite, datavalue, 2);
                ShowValue(ref index, ref overwrite, datavalue, 3);
                return;
            }

            // show node id value.
            NodeId nodeId = value as NodeId;

            if (nodeId != null)
            {
                ShowValue(ref index, ref overwrite, nodeId, 0);
                ShowValue(ref index, ref overwrite, nodeId, 1);
                ShowValue(ref index, ref overwrite, nodeId, 2);
                return;
            }

            // show expanded node id value.
            ExpandedNodeId expandedNodeId = value as ExpandedNodeId;

            if (expandedNodeId != null)
            {
                ShowValue(ref index, ref overwrite, expandedNodeId, 0);
                ShowValue(ref index, ref overwrite, expandedNodeId, 1);
                ShowValue(ref index, ref overwrite, expandedNodeId, 2);
                ShowValue(ref index, ref overwrite, expandedNodeId, 3);
                return;
            }

            // show qualified name value.
            QualifiedName qualifiedName = value as QualifiedName;

            if (qualifiedName != null)
            {
                ShowValue(ref index, ref overwrite, qualifiedName, 0);
                ShowValue(ref index, ref overwrite, qualifiedName, 1);
                return;
            }

            // show qualified name value.
            LocalizedText localizedText = value as LocalizedText;

            if (localizedText != null)
            {
                ShowValue(ref index, ref overwrite, localizedText, 0);
                ShowValue(ref index, ref overwrite, localizedText, 1);
                return;
            }

            // show variant.
            Variant?variant = value as Variant?;

            if (variant != null)
            {
                ShowValue(ref index, ref overwrite, variant.Value.Value);
                return;
            }

            // show unknown types as strings.
            ShowValue(ref index, ref overwrite, String.Format("{0}", value));
        }
예제 #4
0
        /// <summary>
        /// Shows a value in control.
        /// </summary>
        private void ShowValue(ref int index, ref bool overwrite, object value)
        {
            if (value == null)
            {
                return;
            }

            // show monitored items.
            MonitoredItem monitoredItem = value as MonitoredItem;

            if (monitoredItem != null)
            {
                m_monitoredItem = monitoredItem;
                ShowValue(ref index, ref overwrite, monitoredItem.LastValue);
                return;
            }            
            
            // show data changes
            MonitoredItemNotification datachange = value as MonitoredItemNotification;

            if (datachange != null)
            {
                ShowValue(ref index, ref overwrite, datachange.Value);
                return;
            }            
            
            // show events
            EventFieldList eventFields = value as EventFieldList;

            if (eventFields != null)
            {                
                for (int ii = 0; ii < eventFields.EventFields.Count; ii++)
                {
                    ShowValue(ref index, ref overwrite, eventFields, ii);
                }

                return;
            }

            // show extension bodies.
            ExtensionObject extension = value as ExtensionObject;

            if (extension != null)
            {
                ShowValue(ref index, ref overwrite, extension.Body);
                return;
            }

            // show encodeables.
            IEncodeable encodeable = value as IEncodeable;

            if (encodeable != null)
            {
                PropertyInfo[] properties = encodeable.GetType().GetProperties();

                foreach (PropertyInfo property in properties)
                {
                    ShowValue(ref index, ref overwrite, encodeable, property);
                }

                return;
            }
                        
            // show bytes.
            byte[] bytes = value as byte[];

            if (bytes != null)
            {
                if (!PromptOnLongList(bytes.Length/16))
                {
                    return;
                }

                for (int ii = 0; ii < bytes.Length; ii+=16)
                {
                    ShowValue(ref index, ref overwrite, bytes, ii);
                }
                
                return;
            }

            // show arrays
            Array array = value as Array;

            if (array != null)
            {
                if (!PromptOnLongList(array.Length))
                {
                    return;
                }

                for (int ii = 0; ii < array.Length; ii++)
                {
                    ShowValue(ref index, ref overwrite, array, ii);
                }

                return;
            }
            
            // show lists
            IList list = value as IList;

            if (list != null)
            {
                if (!PromptOnLongList(list.Count))
                {
                    return;
                }

                for (int ii = 0; ii < list.Count; ii++)
                {
                    ShowValue(ref index, ref overwrite, list, ii);
                }

                return;
            }
            
            // show xml elements
            XmlElement xml = value as XmlElement;
            
            if (xml != null)
            {
                if (!PromptOnLongList(xml.ChildNodes.Count))
                {
                    return;
                }

                for (int ii = 0; ii < xml.ChildNodes.Count; ii++)
                {
                    ShowValue(ref index, ref overwrite, xml, ii);
                }

                return;
            }
            
            // show data value.
            DataValue datavalue = value as DataValue;

            if (datavalue != null)
            {
                ShowValue(ref index, ref overwrite, datavalue, 0);
                ShowValue(ref index, ref overwrite, datavalue, 1);
                ShowValue(ref index, ref overwrite, datavalue, 2);
                ShowValue(ref index, ref overwrite, datavalue, 3);
                return;
            }

            // show node id value.
            NodeId nodeId = value as NodeId;

            if (nodeId != null)
            {
                ShowValue(ref index, ref overwrite, nodeId, 0);
                ShowValue(ref index, ref overwrite, nodeId, 1);
                ShowValue(ref index, ref overwrite, nodeId, 2);
                return;
            }

            // show expanded node id value.
            ExpandedNodeId expandedNodeId = value as ExpandedNodeId;

            if (expandedNodeId != null)
            {
                ShowValue(ref index, ref overwrite, expandedNodeId, 0);
                ShowValue(ref index, ref overwrite, expandedNodeId, 1);
                ShowValue(ref index, ref overwrite, expandedNodeId, 2);
                ShowValue(ref index, ref overwrite, expandedNodeId, 3);
                return;
            }            

            // show qualified name value.
            QualifiedName qualifiedName = value as QualifiedName;

            if (qualifiedName != null)
            {
                ShowValue(ref index, ref overwrite, qualifiedName, 0);
                ShowValue(ref index, ref overwrite, qualifiedName, 1);
                return;
            }

            // show qualified name value.
            LocalizedText localizedText = value as LocalizedText;

            if (localizedText != null)
            {
                ShowValue(ref index, ref overwrite, localizedText, 0);
                ShowValue(ref index, ref overwrite, localizedText, 1);
                return;
            }
            
            // show variant.
            Variant? variant = value as Variant?;

            if (variant != null)
            {
                ShowValue(ref index, ref overwrite, variant.Value.Value);
                return;
            }

            // show unknown types as strings.
            ShowValue(ref index, ref overwrite, String.Format("{0}", value));
        }
        private static void MonitoredItem_AssemblyStation(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e)
        {
            try
            {
                lock (m_mesStatusLock)
                {
                    MonitoredItemNotification change = e.NotificationValue as MonitoredItemNotification;
                    m_statusAssembly = (StationStatus)change.Value.Value;

                    Trace("-AssemblyStation: {0}", m_statusAssembly);

                    // now check what the status is
                    switch (m_statusAssembly)
                    {
                    case StationStatus.Ready:
                        if ((!m_faultTest) || (!m_faultPackaging))
                        {
                            // build the next product by calling execute with new serial number
                            m_serialNumber[c_Assembly]++;
                            Trace("#{0} Assemble ", m_serialNumber[c_Assembly]);
                            m_sessionAssembly.Session.Call(m_station.RootMethodNode, m_station.ExecuteMethodNode, m_serialNumber[c_Assembly]);
                        }
                        break;

                    case StationStatus.WorkInProgress:
                        // nothing to do
                        break;

                    case StationStatus.Done:
                        m_doneAssembly = true;
                        break;

                    case StationStatus.Discarded:
                        // product was automatically discarded by the station, reset
                        Trace("#{0} Discarded in Assembly", m_serialNumber[c_Assembly]);
                        m_sessionAssembly.Session.Call(m_station.RootMethodNode, m_station.ResetMethodNode, null);
                        break;

                    case StationStatus.Fault:
                        Task.Run(async() =>
                        {
                            // station is at fault state, wait some time to simulate manual intervention before reseting
                            Trace("<<AssemblyStation: Fault>>");
                            await Task.Delay(c_waitTime);
                            Trace("<<AssemblyStation: Restart from Fault>>");

                            m_sessionAssembly.Session.Call(m_station.RootMethodNode, m_station.ResetMethodNode, null);
                        });
                        break;

                    default:
                        Trace("Argument error: Invalid station status type received!");
                        break;
                    }
                }
            }
            catch (Exception exception)
            {
                Trace("Exception: Error processing monitored item notification: " + exception.Message);
            }
        }
예제 #6
0
        private void WriteMI_Click(object sender, EventArgs e)
        {
            try
            {
                // get the current session.
                Session session = Get <Session>(NodesTV.SelectedItem);

                if (session == null || !session.Connected)
                {
                    return;
                }

                // build list of nodes to read.
                WriteValueCollection values = new WriteValueCollection();

                MonitoredItem monitoredItem = Get <MonitoredItem>(NodesTV.SelectedItem);

                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.SelectedItem);

                    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(String.Empty, GuiUtils.CallerName(), exception);
            }
        }
예제 #7
0
        /// <see cref="BaseListCtrl.UpdateItem" />
        protected override void UpdateItem(ListViewItem listItem, object item)
        {
            MonitoredItemNotification change = item as MonitoredItemNotification;

            if (change == null)
            {
                base.UpdateItem(listItem, item);
                return;
            }

            // fill in the columns.
            listItem.SubItems[0].Text = String.Format("[{0}]", change.ClientHandle);

            MonitoredItem monitoredItem = null;

            if (m_subscription != null)
            {
                monitoredItem = m_subscription.FindItemByClientHandle(change.ClientHandle);
            }

            if (monitoredItem != null)
            {
                listItem.SubItems[1].Text = String.Format("{0}", monitoredItem.DisplayName);
            }
            else
            {
                listItem.SubItems[1].Text = "(unknown)";
            }

            listItem.SubItems[2].Text = String.Format("{0}", change.Value.WrappedValue);

            // check of publishing has stopped for some reason.
            if (m_subscription.PublishingStopped)
            {
                listItem.SubItems[3].Text = String.Format("{0}", (StatusCode)StatusCodes.UncertainNoCommunicationLastUsableValue);
            }
            else
            {
                listItem.SubItems[3].Text = change.Value.StatusCode.ToString();
            }

            DateTime time = change.Value.SourceTimestamp;

            if (time != null && time != DateTime.MinValue)
            {
                listItem.SubItems[4].Text = String.Format("{0:HH:mm:ss.fff}", time.ToLocalTime());
            }
            else
            {
                listItem.SubItems[4].Text = String.Empty;
            }

            time = change.Value.ServerTimestamp;

            if (time != null && time != DateTime.MinValue)
            {
                listItem.SubItems[5].Text = String.Format("{0:HH:mm:ss.fff}", time.ToLocalTime());
            }
            else
            {
                listItem.SubItems[5].Text = String.Empty;
            }

            listItem.Tag       = change;
            listItem.ForeColor = (m_subscription.PublishingStopped)?Color.Red:Color.Empty;
        }
        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;
                }
            }
        }
예제 #9
0
        /// <summary>
        /// Processes a new notification.
        /// </summary>
        public void NotificationReceived(NotificationEventArgs e)
        {
            // get the changes.
            List <MonitoredItemNotification> changes = new List <MonitoredItemNotification>();

            foreach (MonitoredItemNotification change in e.NotificationMessage.GetDataChanges(false))
            {
                if (m_monitoredItem != null)
                {
                    if (m_monitoredItem.ClientHandle != change.ClientHandle)
                    {
                        continue;
                    }
                }
                else
                {
                    if (m_subscription.FindItemByClientHandle(change.ClientHandle) == null)
                    {
                        continue;
                    }
                }

                changes.Add(change);
            }

            // check if nothing more to do.
            if (changes.Count == 0)
            {
                return;
            }

            int offset = changes.Count;

            if (m_showHistory)
            {
                // fill in earlier changes.
                foreach (ListViewItem listItem in ItemsLV.Items)
                {
                    MonitoredItemNotification change = listItem.Tag as MonitoredItemNotification;

                    if (change == null)
                    {
                        continue;
                    }

                    if (m_monitoredItem != null)
                    {
                        if (m_monitoredItem.ClientHandle != change.ClientHandle)
                        {
                            continue;
                        }
                    }

                    changes.Add(change);

                    if (changes.Count >= MaxChangeCount)
                    {
                        break;
                    }
                }

                // ensure the newest changes appear first.
                changes.Reverse();
            }

            UpdateChanges(changes, offset);
            AdjustColumns();
        }
예제 #10
0
        /// <summary>
        /// Updates the events displayed in the control.
        /// </summary>
        private void UpdateChanges(IList <MonitoredItemNotification> changes, int offset)
        {
            // save selected indexes.
            List <int> indexes = new List <int>(ItemsLV.SelectedIndices.Count);

            foreach (int index in ItemsLV.SelectedIndices)
            {
                indexes.Add(index);
            }

            // add all new values.
            if (m_showHistory)
            {
                BeginUpdate();

                foreach (MonitoredItemNotification change in changes)
                {
                    AddItem(change);
                }

                EndUpdate();
            }

            // only update changed values.
            else
            {
                foreach (ListViewItem listItem in ItemsLV.Items)
                {
                    listItem.ForeColor = Color.Gray;
                }

                for (int ii = changes.Count - 1; ii >= 0; ii--)
                {
                    bool found = false;

                    foreach (ListViewItem listItem in ItemsLV.Items)
                    {
                        MonitoredItemNotification change = listItem.Tag as MonitoredItemNotification;

                        if (change != null && change.ClientHandle == changes[ii].ClientHandle)
                        {
                            UpdateItem(listItem, changes[ii]);
                            found = true;
                            listItem.ForeColor = Color.Empty;
                            break;
                        }
                    }

                    if (!found)
                    {
                        AddItem(changes[ii]);
                    }
                }
            }

            // preserve selection.
            foreach (int index in indexes)
            {
                ItemsLV.Items[index].Selected = false;

                if (index + offset < ItemsLV.Items.Count)
                {
                    ItemsLV.Items[index + offset].Selected = true;
                }
            }
        }
예제 #11
0
        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;
            }
            //PROJECT

            //updating the Mould used (to structure the Database)
            //is call because of Mould_Type?
            if (monitoredItem.ClientHandle == Mould_Type_handle)
            {
                int value = (int)notification.Value.WrappedValue.Value;
                Mould_Type = value;
                //update screen
                label5.Text = "value: " + Utils.Format("{0}", Mould_Type.ToString()) +
                              ";\nStatusCode: " + Utils.Format("{0}", notification.Value.StatusCode.ToString()) +
                              ";\nSource timestamp: " + notification.Value.SourceTimestamp.ToString() +
                              ";\nServer timestamp: " + notification.Value.ServerTimestamp.ToString();
            }

            //is call because of Pressure_Array?
            DataValueCollection read2 = Read_Value("ns=3;s=Start_Piece");

            if (monitoredItem.ClientHandle == Pressure_Array_handle && (bool)read2[0].Value)
            {
                double[] value = (double[])notification.Value.WrappedValue.Value;
                Pressure_Array = value;
                for (int i = 0; i < 28; i++)
                {
                    Pressure_1[i] = Pressure_Array[i];
                    Pressure_2[i] = Pressure_Array[i + 28];
                }
                label1.Text = Pressure_1[1].ToString();

                DataValueCollection read  = Read_Value("ns=3;s=Actual_Mould");
                DataValueCollection read1 = Read_Value("ns=3;s=Piece_SN");

                if ((int)read[0].Value == 1)
                {
                    var payload = new LineProtocolPayload();
                    //when new value of Pressure_1 then update DB
                    for (int j = 0; j < 28; j++)
                    {
                        DateTime t        = DateTime.UtcNow.Subtract(TimeSpan.FromMilliseconds((27 - j) * 285));
                        var      DBMould1 = new LineProtocolPoint(
                            "Mould_1__MLQC_DB",
                            new Dictionary <string, object>
                        {
                            { "Pressure 1", Pressure_1[j] },
                            { "Pressure 2", Pressure_2[j] },
                            { "Piece Serial Number", (int)read1[0].Value }
                        },
                            null,
                            t
                            );
                        payload.Add(DBMould1);
                    }

                    var client = new LineProtocolClient(new Uri(DB_server), DB_database);
                    //send data to DB
                    var influxResult = client.WriteAsync(payload);
                }

                if ((int)read[0].Value == 2)
                {
                    var payload = new LineProtocolPayload();
                    //when new value of Pressure_1 then update DB
                    for (int j = 0; j < 28; j++)
                    {
                        DateTime t        = DateTime.UtcNow.Subtract(TimeSpan.FromMilliseconds((27 - j) * 50));
                        var      DBMould1 = new LineProtocolPoint(
                            "Mould_2__MLQC_DB",
                            new Dictionary <string, object>
                        {
                            { "Pressure 1 =", Pressure_1[j] },
                            { "Pressure 2 =", Pressure_2[j] }
                        },
                            null,
                            t
                            );
                        payload.Add(DBMould1);
                    }

                    var client = new LineProtocolClient(new Uri(DB_server), DB_database);
                    //send data to DB
                    var influxResult = client.WriteAsync(payload);
                }
            }
        }
예제 #12
0
        /// <summary>
        /// The notification that the data for a monitored item has changed on an OPC UA server
        /// </summary>
        public static void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e)
        {
            try
            {
                if (e.NotificationValue == null || monitoredItem.Subscription.Session == null)
                {
                    return;
                }

                MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification;
                if (notification == null)
                {
                    return;
                }

                DataValue value = notification.Value as DataValue;
                if (value == null)
                {
                    return;
                }

                JsonEncoder encoder        = new JsonEncoder(monitoredItem.Subscription.Session.MessageContext, false);
                string      applicationURI = monitoredItem.Subscription.Session.Endpoint.Server.ApplicationUri;
                encoder.WriteString("ApplicationUri", applicationURI);
                encoder.WriteString("DisplayName", monitoredItem.DisplayName);

                // write NodeId as ns=x;i=y
                NodeId nodeId = monitoredItem.ResolvedNodeId;
                encoder.WriteString("NodeId", new NodeId(nodeId.Identifier, nodeId.NamespaceIndex).ToString());

                // suppress output of server timestamp in json by setting it to minvalue
                value.ServerTimestamp = DateTime.MinValue;
                encoder.WriteDataValue("Value", value);

                string json  = encoder.CloseAndReturnText();
                byte[] bytes = new UTF8Encoding(false).GetBytes(json);

                // publish
                var properties = new Dictionary <string, string>();
                properties.Add("content-type", "application/opcua+uajson");
                properties.Add("deviceName", m_deviceName);

                if (m_accessKey != null)
                {
                    properties.Add("source", "mapping");
                    properties.Add("deviceKey", m_accessKey);
                }

                try
                {
                    Publish(new Message(json, properties));
                    Trace("Opc.Ua.Publisher.Module: Published: " + json + " from " + m_deviceName);
                }
                catch (Exception ex)
                {
                    Trace("Opc.Ua.Publisher.Module: Failed to publish message, dropping...");
                    Trace(ex.ToString());
                }
            }
            catch (Exception exception)
            {
                Trace("Opc.Ua.Publisher.Module: Error processing monitored item notification: " + exception.ToString());
            }
        }
예제 #13
0
        private void Notification_MonitoredItem(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new MonitoredItemNotificationEventHandler(Notification_MonitoredItem), monitoredItem, e);
                return;
            }

            MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification;

            if (notification == null)
            {
                return;
            }

            if (monitoredItem.DisplayName.Contains("heating-"))
            {
                if (monitoredItem.DisplayName.Contains("state"))
                {
                    if (notification.Value.WrappedValue.ToString() == "true")
                    {
                        heatingMotorStatus.Text      = "Running";
                        heatingMotorStatus.BackColor = Color.Lime;
                    }

                    else if (notification.Value.WrappedValue.ToString() == "false")
                    {
                        heatingMotorStatus.Text      = "Off";
                        heatingMotorStatus.BackColor = Color.Red;
                    }
                }
                else if (monitoredItem.DisplayName.Contains("speed"))
                {
                    heatingMotorSpeed.Text = notification.Value.WrappedValue.ToString();
                }
                else
                {
                    if (notification.Value.WrappedValue.ToString() == "true")
                    {
                        startHeatingAnyway.Text      = "Stop";
                        startHeatingAnyway.BackColor = Color.Lime;
                        startHeatingAnywayCB.Checked = true;
                    }
                    else
                    {
                        startHeatingAnyway.Text      = "Start Anyway";
                        startHeatingAnyway.BackColor = Color.Red;
                        startHeatingAnywayCB.Checked = false;
                    }
                }
            }
            else if (monitoredItem.DisplayName.Contains("cooling-"))
            {
                if (monitoredItem.DisplayName.Contains("state"))
                {
                    if (notification.Value.WrappedValue.ToString() == "true")
                    {
                        coolingMotorStatus.Text      = "Running";
                        coolingMotorStatus.BackColor = Color.Lime;
                    }

                    else if (notification.Value.WrappedValue.ToString() == "false")
                    {
                        coolingMotorStatus.Text      = "Off";
                        coolingMotorStatus.BackColor = Color.Red;
                    }
                }
                else if (monitoredItem.DisplayName.Contains("speed"))
                {
                    coolingMotorSpeed.Text = notification.Value.WrappedValue.ToString();
                }
                else
                {
                    if (notification.Value.WrappedValue.ToString() == "true")
                    {
                        startCoolingAnyway.Text      = "Stop";
                        startCoolingAnyway.BackColor = Color.Lime;
                        startCoolingAnywayCB.Checked = true;
                    }
                    else
                    {
                        startCoolingAnyway.Text      = "Start Anyway";
                        startCoolingAnyway.BackColor = Color.Red;
                        startCoolingAnywayCB.Checked = false;
                    }
                }
            }
            else
            {
                temperatureValue.Text = notification.Value.WrappedValue.ToString();
                sourceTimestamp.Text  = notification.Value.SourceTimestamp.ToString();
                serverTimestamp.Text  = notification.Value.ServerTimestamp.ToString();
                this.updateChart(notification.Value.WrappedValue.ToString());
            }
        }
        /// <summary>
        /// Saves a notification in the cache.
        /// </summary>
        public void OnNotification(MonitoredItemNotification notification)
        {
            m_values.Enqueue(notification.Value);
            m_lastValue = notification.Value;
            
            Utils.Trace(
                "NotificationReceived: ClientHandle={0}, Value={1}", 
                notification.ClientHandle,
                m_lastValue.Value);

            while (m_values.Count > m_queueSize)
            {
                m_values.Dequeue();
            }
        }
예제 #15
0
        /// <summary>
        /// Checks if the subscription is ready to publish and returns a notification message.
        /// </summary>
        public NotificationMessage Publish()
        {
            lock (m_lock)
            {
                long currentTime = DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond;

                // check of it is time for a publish.
                if (m_lastPublishTime + m_publishingInterval < currentTime)
                {
                    ListOfMonitoredItemNotification notifications   = new ListOfMonitoredItemNotification();
                    ListOfDiagnosticInfo            diagnosticInfos = new ListOfDiagnosticInfo();

                    // check each monitored item for data changes to send.
                    foreach (MonitoredItem monitoredItem in m_monitoredItems.Values)
                    {
                        while (monitoredItem.Values.Count > 0)
                        {
                            MonitoredItemNotification notification = new MonitoredItemNotification();

                            notification.ClientHandle = monitoredItem.Parameters.ClientHandle;
                            notification.Value        = monitoredItem.Values.Dequeue();

                            notifications.Add(notification);
                            diagnosticInfos.Add(monitoredItem.DiagnosticInfos.Dequeue());
                        }
                    }

                    // check if any notifications were found.
                    if (notifications.Count > 0)
                    {
                        // subscriptions can produce different types of notifications so the notification parameter
                        // is an extensible parameter. This means the object must be manually serialized and wrapped in
                        // an ExtensionObject which specifies the type of data contained in the Body. The complete
                        // UA SDK takes care this housekeeping and will serialize extensible parameters automatically.

                        DataChangeNotification body = new DataChangeNotification();

                        body.MonitoredItems  = notifications;
                        body.DiagnosticInfos = diagnosticInfos;

                        ExtensionObject extension = new ExtensionObject(
                            new ExpandedNodeId(Objects.DataChangeNotification_Encoding_DefaultXml),
                            body);

                        // construct the message and assign a new sequence number.
                        NotificationMessage message = new NotificationMessage();

                        message.SequenceNumber   = ++m_nextSequenceNumber;
                        message.PublishTime      = DateTime.UtcNow;
                        message.NotificationData = new ListOfExtensionObject();

                        message.NotificationData.Add(extension);

                        m_lastPublishTime   = currentTime;
                        m_nextKeepAliveTime = (long)(currentTime + m_publishingInterval * m_keepAliveCount);

                        return(message);
                    }
                }

                // check if it is time for a keep alive.
                if (m_nextKeepAliveTime < currentTime)
                {
                    NotificationMessage message = new NotificationMessage();

                    message.SequenceNumber   = m_nextSequenceNumber;
                    message.PublishTime      = DateTime.UtcNow;
                    message.NotificationData = new ListOfExtensionObject();

                    m_nextKeepAliveTime = (long)(currentTime + m_publishingInterval * m_keepAliveCount);

                    return(message);
                }

                return(null);
            }
        }
		/// <summary>
		/// Publishes a single data change notifications.
		/// </summary>
        protected virtual bool Publish(
            OperationContext                 context,
            Queue<MonitoredItemNotification> notifications,
            Queue<DiagnosticInfo>            diagnostics,
            DataValue                        value, 
            ServiceResult                    error)
        {            
            // set semantics changed bit.
            if (m_semanticsChanged)
            {
                if (value != null)
                {
                    value.StatusCode = value.StatusCode.SetSemanticsChanged(true);
                }

                if (error != null)
                {
                    error = new ServiceResult(
                        error.StatusCode.SetSemanticsChanged(true), 
                        error.SymbolicId,
                        error.NamespaceUri,
                        error.LocalizedText,
                        error.AdditionalInfo,
                        error.InnerResult);
                }

                m_semanticsChanged = false;
            }
            
            // set structure changed bit.
            if (m_structureChanged)
            {
                if (value != null)
                {
                    value.StatusCode = value.StatusCode.SetStructureChanged(true);
                }

                if (error != null)
                {
                    error = new ServiceResult(
                        error.StatusCode.SetStructureChanged(true), 
                        error.SymbolicId,
                        error.NamespaceUri,
                        error.LocalizedText,
                        error.AdditionalInfo,
                        error.InnerResult);
                }

                m_structureChanged = false;
            }

            // copy data value.
            MonitoredItemNotification item = new MonitoredItemNotification();

            item.ClientHandle = m_clientHandle;
            item.Value        = value;
            
            // apply timestamp filter.
            if (m_timestampsToReturn != TimestampsToReturn.Server && m_timestampsToReturn != TimestampsToReturn.Both)
            {
                item.Value.ServerTimestamp = DateTime.MinValue;
            }

            if (m_timestampsToReturn != TimestampsToReturn.Source && m_timestampsToReturn != TimestampsToReturn.Both)
            {
                item.Value.SourceTimestamp = DateTime.MinValue;
            }

            ServerUtils.ReportPublishValue(m_nodeId, m_id, item.Value);
            notifications.Enqueue(item);

            // update diagnostic info.
            DiagnosticInfo diagnosticInfo = null;
            
            if ((m_diagnosticsMasks & DiagnosticsMasks.OperationAll) != 0)
            {
                diagnosticInfo = ServerUtils.CreateDiagnosticInfo(m_server, context, error);
            }

            diagnostics.Enqueue(diagnosticInfo);

            return false;
        }
예제 #17
0
        /// <summary>
        /// Saves a data change or event in the cache.
        /// </summary>
        public void SaveValueInCache(IEncodeable newValue)
        {
            lock (m_cache)
            {
                // only validate timestamp on first sample
                bool validateTimestamp = m_lastNotification == null;

                m_lastNotification = newValue;

                if (m_dataCache != null)
                {
                    MonitoredItemNotification datachange = newValue as MonitoredItemNotification;

                    if (datachange != null)
                    {
                        if (datachange.Value != null)
                        {
                            if (validateTimestamp)
                            {
                                var now = DateTime.UtcNow;

                                // validate the ServerTimestamp of the notification.
                                if (datachange.Value.ServerTimestamp > now)
                                {
                                    Utils.LogWarning("Received ServerTimestamp {0} is in the future for MonitoredItemId {1}",
                                                     datachange.Value.ServerTimestamp.ToLocalTime(), ClientHandle);
                                }

                                // validate SourceTimestamp of the notification.
                                if (datachange.Value.SourceTimestamp > now)
                                {
                                    Utils.LogWarning("Received SourceTimestamp {0} is in the future for MonitoredItemId {1}",
                                                     datachange.Value.SourceTimestamp.ToLocalTime(), ClientHandle);
                                }
                            }

                            if (datachange.Value.StatusCode.Overflow)
                            {
                                Utils.LogWarning("Overflow bit set for data change with ServerTimestamp {0} and value {1} for MonitoredItemId {2}",
                                                 datachange.Value.ServerTimestamp.ToLocalTime(), datachange.Value.Value, ClientHandle);
                            }
                        }

                        m_dataCache.OnNotification(datachange);
                    }
                }

                if (m_eventCache != null)
                {
                    EventFieldList eventchange = newValue as EventFieldList;

                    if (m_eventCache != null)
                    {
                        m_eventCache.OnNotification(eventchange);
                    }
                }

                if (m_Notification != null)
                {
                    m_Notification(this, new MonitoredItemNotificationEventArgs(newValue));
                }
            }
        }