/// <summary>
 /// Convert to monitored item notifications
 /// </summary>
 /// <param name="eventFieldList"></param>
 /// <param name="monitoredItem"></param>
 /// <returns></returns>
 public static MonitoredItemNotificationModel ToMonitoredItemNotification(
     this EventFieldList eventFieldList, MonitoredItem monitoredItem)
 {
     if (eventFieldList == null || monitoredItem == null)
     {
         return(null);
     }
     return(new MonitoredItemNotificationModel {
         Id = monitoredItem.DisplayName,
         DisplayName = monitoredItem.DisplayName,
         NodeId = monitoredItem.StartNodeId,
         AttributeId = monitoredItem.AttributeId,
         ClientHandle = eventFieldList.ClientHandle,
         Value = ToDataValue(eventFieldList, monitoredItem),
         NotificationData = eventFieldList.Message == null ||
                            eventFieldList.Message.IsEmpty ? null :
                            eventFieldList.Message.NotificationData.ToList(),
         PublishTime = eventFieldList.Message == null ||
                       eventFieldList.Message.IsEmpty ? (DateTime?)null :
                       eventFieldList.Message.PublishTime,
         SequenceNumber = eventFieldList.Message == null ||
                          eventFieldList.Message.IsEmpty ? (uint?)null :
                          eventFieldList.Message.SequenceNumber,
         StringTable = eventFieldList.Message == null ||
                       eventFieldList.Message.IsEmpty ? null :
                       eventFieldList.Message.StringTable
     });
 }
 /// <summary>
 /// Convert to Datavalue
 /// </summary>
 /// <param name="eventFields"></param>
 /// <param name="monitoredItem"></param>
 /// <returns></returns>
 public static DataValue ToDataValue(this EventFieldList eventFields,
                                     MonitoredItem monitoredItem)
 {
     if (eventFields == null)
     {
         return(new DataValue(StatusCodes.BadNoData));
     }
     return(new DataValue {
         ServerPicoseconds = 0,
         ServerTimestamp = eventFields.GetEventValue <DateTime>(
             BrowseNames.Time, monitoredItem),
         SourcePicoseconds = 0,
         SourceTimestamp = eventFields.GetEventValue <DateTime>(
             BrowseNames.ReceiveTime, monitoredItem),
         StatusCode = eventFields.GetEventValue <StatusCode>(
             BrowseNames.StatusCode, monitoredItem),
         Value = new EncodeableDictionary {
             Fields = new KeyValuePairCollection(eventFields.EventFields
                                                 .Select((value, i) => new Opc.Ua.KeyValuePair {
                 Key = monitoredItem.GetFieldName(i),
                 Value = value
             }))
         }
     });
 }
Example #3
0
        /// <summary>
        /// The service result for a field in an notification (the field must contain a Status object).
        /// </summary>
        public static ServiceResult GetServiceResult(IEncodeable notification, int index)
        {
            EventFieldList eventFields = notification as EventFieldList;

            if (eventFields == null)
            {
                return(null);
            }

            NotificationMessage message = eventFields.Message;

            if (message != null)
            {
                return(null);
            }

            if (index < 0 || index >= eventFields.EventFields.Count)
            {
                return(null);
            }

            StatusResult status =
                ExtensionObject.ToEncodeable(eventFields.EventFields[index].Value as ExtensionObject) as StatusResult;

            if (status == null)
            {
                return(null);
            }

            return(new ServiceResult(status.StatusCode, status.DiagnosticInfo, message.StringTable));
        }
Example #4
0
 /// <summary>
 /// Displays the event.
 /// </summary>
 public void DisplayEvent(EventFieldList e)
 {
     if (e != null)
     {
         DisplayEvent(e.EventFields);
     }
 }
        /// <summary>
        /// Shows an event in the control.
        /// </summary>
        private void ShowValue(ref int index, ref bool overwrite, EventFieldList value, int fieldIndex)
        {
            // ignore children that are not elements.
            object field = value.EventFields[fieldIndex].Value;

            if (field == null)
            {
                return;
            }

            // get the name of the element.
            string name = null;

            if (m_monitoredItem != null)
            {
                name = m_monitoredItem.GetFieldName(fieldIndex);
            }

            // get the type name.
            string type = value.GetType().Name;

            // update the list view.
            UpdateList(
                ref index,
                ref overwrite,
                value,
                field,
                fieldIndex,
                name,
                type);
        }
        /// <summary>
        /// Convert to monitored item notifications
        /// </summary>
        /// <param name="eventFieldList"></param>
        /// <param name="monitoredItem"></param>
        /// <returns></returns>
        public static MonitoredItemNotificationModel ToMonitoredItemNotification(
            this EventFieldList eventFieldList, MonitoredItem monitoredItem)
        {
            if (eventFieldList == null || monitoredItem == null)
            {
                return(null);
            }

            var handleId = monitoredItem.Handle as SubscriptionServices.MonitoredItemWrapper;

            return(new MonitoredItemNotificationModel {
                Id = handleId?.Template?.Id,
                DisplayName = monitoredItem.DisplayName,
                NodeId = handleId?.Template?.StartNodeId,
                AttributeId = monitoredItem.AttributeId,
                ClientHandle = eventFieldList.ClientHandle,
                Value = ToDataValue(eventFieldList, monitoredItem),
                NotificationData = eventFieldList.Message == null || eventFieldList.Message.IsEmpty
                    ? null
                    : eventFieldList.Message.NotificationData.ToList(),
                PublishTime = eventFieldList.Message == null || eventFieldList.Message.IsEmpty
                    ? (DateTime?)null
                    : eventFieldList.Message.PublishTime,
                SequenceNumber = eventFieldList.Message == null || eventFieldList.Message.IsEmpty
                    ? (uint?)null
                    : eventFieldList.Message.SequenceNumber,
                StringTable = eventFieldList.Message == null || eventFieldList.Message.IsEmpty
                    ? null
                    : eventFieldList.Message.StringTable,
                IsHeartbeat = false
            });
        }
Example #7
0
        /// <summary>
        /// Processes a change to the subscription.
        /// </summary>
        public void SubscriptionChanged(SubscriptionStateChangedEventArgs e)
        {
            if ((e.Status & SubscriptionChangeMask.ItemsDeleted) != 0)
            {
                // collect events for items that have been deleted.
                List <ListViewItem> itemsToRemove = new List <ListViewItem>();

                foreach (ListViewItem listItem in ItemsLV.Items)
                {
                    EventFieldList eventFields = listItem.Tag as EventFieldList;

                    if (eventFields != null)
                    {
                        if (m_subscription.FindItemByClientHandle(eventFields.ClientHandle) == null)
                        {
                            itemsToRemove.Add(listItem);
                        }
                    }
                }

                // remove events for items that have been deleted.
                foreach (ListViewItem listItem in itemsToRemove)
                {
                    listItem.Remove();
                }
            }
        }
Example #8
0
        /// <summary>
        /// Saves a data change or event in the cache.
        /// </summary>
        public void SaveValueInCache(IEncodeable newValue)
        {
            lock (m_cache) {
                m_lastNotification = newValue;

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

                    if (datachange != null)
                    {
                        // validate the ServerTimestamp of the notification.
                        if (datachange.Value != null && datachange.Value.ServerTimestamp > DateTime.UtcNow)
                        {
                            Utils.Trace("Received ServerTimestamp {0} is in the future for MonitoredItemId {1}",
                                        datachange.Value.ServerTimestamp.ToLocalTime(), ClientHandle);
                        }

                        // validate SourceTimestamp of the notification.
                        if (datachange.Value != null && datachange.Value.SourceTimestamp > DateTime.UtcNow)
                        {
                            Utils.Trace("Received SourceTimestamp {0} is in the future for MonitoredItemId {1}",
                                        datachange.Value.ServerTimestamp.ToLocalTime(), ClientHandle);
                        }

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

                        //Utils.Trace(
                        //     "SaveValueInCache: ServerHandle={0}, Value={1}, StatusCode={2}",
                        //     this.ClientHandle,
                        //     datachange.Value.WrappedValue,
                        //     datachange.Value.StatusCode);

                        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));
                }
            }
        }
Example #9
0
 /// <summary>
 /// Returns value of the field name containing the event type.
 /// </summary>
 public object GetFieldValue(
     EventFieldList eventFields, 
     NodeId         eventTypeId, 
     string         browsePath, 
     uint           attributeId)
 {
     QualifiedNameCollection browseNames = SimpleAttributeOperand.Parse(browsePath);
     return GetFieldValue(eventFields, eventTypeId, browseNames, attributeId);
 }
 /// <summary>
 /// Utility method to combine the retrieved field names (from the monitored item filter select clause)
 /// and the retrieved field values (from a received event) into a name/value dictionary.
 /// </summary>
 /// <param name="arg">A field list from a received event.</param>
 /// <returns>A dictionary of field name to field value.</returns>
 protected Dictionary <string, object> EventFieldListToDictionary(EventFieldList arg)
 {
     return
         (((EventFilter)MonitoredItem.Filter).SelectClauses           // all retrieved fields for event
          .Zip(arg.EventFields)                                       // values of retrieved fields
          .ToDictionary(
              p => SimpleAttributeOperand.Format(p.First.BrowsePath), // e.g. "/EventId"
              p => p.Second.Value));
 }
Example #11
0
 /// <summary>
 /// Returns value of the field name containing the event type.
 /// </summary>
 public object GetFieldValue(
     EventFieldList eventFields, 
     NodeId         eventTypeId, 
     QualifiedName  browseName)
 {
     QualifiedNameCollection browsePath = new QualifiedNameCollection();
     browsePath.Add(browseName);
     return GetFieldValue(eventFields, eventTypeId, browsePath, Attributes.Value);
 }
Example #12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="monitoredItem"></param>
        /// <param name="e"></param>
        protected virtual void ItemNotificationHandler(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e)
        {
            try
            {
                if (monitoredItem != null)
                {
                    Opc.Ua.MonitoredItemNotification change = e.NotificationValue as Opc.Ua.MonitoredItemNotification;
                    if (change != null)
                    {
                        DataValue dv = change.Value;
                        if (dv != null)
                        {
                            ListViewItem[] lvis = ItemsLV.Items.Find(monitoredItem.ClientHandle.ToString(), false);
                            if (lvis.Length > 0)
                            {
                                DiagnosticListViewItem dlvi = lvis[0].Tag as DiagnosticListViewItem;
                                dlvi.UpdateInListView(lvis[0], dv, m_Session);
                            }
                        }
                        else
                        {
                            Utils.Trace("dv is null: {0}", MethodBase.GetCurrentMethod());
                        }
                    }
                    else
                    {
                        EventFieldList eventFields = e.NotificationValue as EventFieldList;
                        if (eventFields != null)
                        {
                            // get the event fields.
                            NodeId        eventType  = monitoredItem.GetFieldValue(eventFields, ObjectTypes.BaseEventType, BrowseNames.EventType) as NodeId;
                            string        sourceName = monitoredItem.GetFieldValue(eventFields, ObjectTypes.BaseEventType, BrowseNames.SourceName) as string;
                            DateTime?     time       = monitoredItem.GetFieldValue(eventFields, ObjectTypes.BaseEventType, BrowseNames.Time) as DateTime?;
                            ushort?       severity   = monitoredItem.GetFieldValue(eventFields, ObjectTypes.BaseEventType, BrowseNames.Severity) as ushort?;
                            LocalizedText message    = monitoredItem.GetFieldValue(eventFields, ObjectTypes.BaseEventType, BrowseNames.Message) as LocalizedText;
                            NodeId        sourceNode = monitoredItem.GetFieldValue(eventFields, ObjectTypes.BaseEventType, BrowseNames.SourceNode) as NodeId;

                            if (eventType == new NodeId(ObjectTypes.AuditAddNodesEventType))
                            {
                            }
                            else
                            {
                            }
                        }
                        else
                        {
                            Utils.Trace("eventFields is null " + MethodBase.GetCurrentMethod());
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception);
            }
        }
Example #13
0
        /// <summary>
        /// Saves a notification in the cache.
        /// </summary>
        public void OnNotification(EventFieldList notification)
        {
            m_events.Enqueue(notification);
            m_lastEvent = notification;

            while (m_events.Count > m_queueSize)
            {
                m_events.Dequeue();
            }
        }
Example #14
0
        /// <summary>
        /// Returns all events in the queue.
        /// </summary>
        public IList <EventFieldList> Publish()
        {
            EventFieldList[] events = new EventFieldList[m_events.Count];

            for (int ii = 0; ii < events.Length; ii++)
            {
                events[ii] = m_events.Dequeue();
            }

            return(events);
        }
        /// <summary>
        /// Returns value of the field name containing the event type.
        /// </summary>
        public static T GetEventValue <T>(this EventFieldList eventFields, string name,
                                          MonitoredItem monitoredItem, T defaultValue = default)
        {
            // get value
            var value = monitoredItem.GetFieldValue(eventFields, ObjectTypes.BaseEventType, name);

            if (value != null)
            {
                return(value.As <T>());
            }
            return(defaultValue);
        }
Example #16
0
        /// <summary>
        /// Returns value of the field name containing the event type.
        /// </summary>
        public INode GetEventType(EventFieldList eventFields)
        {
            // get event type.
            NodeId eventTypeId = GetFieldValue(eventFields, ObjectTypes.BaseEventType, Opc.Ua.BrowseNames.EventType) as NodeId;

            if (eventTypeId != null && m_subscription != null && m_subscription.Session != null)
            {
                return(m_subscription.Session.NodeCache.Find(eventTypeId));
            }

            // no event type in event field list.
            return(null);
        }
Example #17
0
        /// <summary>
        /// Returns value of the field name containing the event type.
        /// </summary>
        public DateTime GetEventTime(EventFieldList eventFields)
        {
            // get event time.
            DateTime?eventTime = GetFieldValue(eventFields, ObjectTypes.BaseEventType, Opc.Ua.BrowseNames.Time) as DateTime?;

            if (eventTime != null)
            {
                return(eventTime.Value);
            }

            // no event time in event field list.
            return(DateTime.MinValue);
        }
Example #18
0
 private void DetailsMI_Click(object sender, EventArgs e)
 {
     try {
         foreach (DataGridViewRow row in EventsDV.SelectedRows)
         {
             DataRowView    source = row.DataBoundItem as DataRowView;
             EventFieldList e2     = (EventFieldList)source.Row[0];
             new ViewEventDetailsDlg().ShowDialog(m_filter, e2.EventFields);
             break;
         }
     } catch (Exception exception) {
         ClientUtils.HandleException(this.Text, exception);
     }
 }
Example #19
0
        /// <summary>
        /// Processes a new notification.
        /// </summary>
        public void NotificationReceived(MonitoredItemNotificationEventArgs e)
        {
            EventFieldList eventFields = e.NotificationValue as EventFieldList;

            if (eventFields == null)
            {
                return;
            }

            if (m_monitoredItem != null)
            {
                if (m_monitoredItem.ClientHandle != eventFields.ClientHandle)
                {
                    return;
                }
            }

            // get the events.
            List <EventFieldList> events = new List <EventFieldList>();

            events.Add(eventFields);

            // fill in earlier events.
            foreach (ListViewItem listItem in ItemsLV.Items)
            {
                eventFields = listItem.Tag as EventFieldList;

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

                if (eventFields != null)
                {
                    events.Add(eventFields);
                }

                if (events.Count >= MaxEventCount)
                {
                    break;
                }
            }

            UpdateEvents(events, 1);
            AdjustColumns();
        }
Example #20
0
        /// <see cref="BaseListCtrl.UpdateItem" />
        protected override void UpdateItem(ListViewItem listItem, object item)
        {
            MonitoredItem monitoredItem = item as MonitoredItem;

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

            listItem.SubItems[0].Text = String.Format("{0}", monitoredItem.Status.Id);
            listItem.SubItems[1].Text = String.Format("{0}", monitoredItem.DisplayName);
            listItem.SubItems[2].Text = String.Format("{0}", monitoredItem.NodeClass);
            listItem.SubItems[3].Text = String.Format("{0}", monitoredItem.Status.SamplingInterval);
            listItem.SubItems[4].Text = String.Format("{0}", monitoredItem.Status.QueueSize);
            listItem.SubItems[5].Text = String.Empty;
            listItem.SubItems[6].Text = String.Format("{0}", monitoredItem.Status.Error);
            listItem.SubItems[7].Text = String.Empty;

            IEncodeable value = monitoredItem.LastValue;

            if (value != null)
            {
                MonitoredItemNotification datachange = value as MonitoredItemNotification;

                if (datachange != null)
                {
                    listItem.SubItems[5].Text = String.Format("{0}", datachange.Value);

                    if (datachange.Value.SourceTimestamp != DateTime.MinValue)
                    {
                        listItem.SubItems[7].Text = String.Format("{0:HH:mm:ss.fff}",
                                                                  datachange.Value.SourceTimestamp.ToLocalTime());
                    }
                }

                EventFieldList eventFields = value as EventFieldList;

                if (eventFields != null)
                {
                    listItem.SubItems[5].Text = String.Format("{0}", monitoredItem.GetEventType(eventFields));
                    listItem.SubItems[7].Text = String.Format("{0:HH:mm:ss.fff}",
                                                              monitoredItem.GetEventTime(eventFields).ToLocalTime());
                }
            }

            listItem.Tag = item;
        }
Example #21
0
        private void ViewMI_Click(object sender, EventArgs e)
        {
            try {
                EventFieldList fieldList = SelectedTag as EventFieldList;

                if (fieldList == null)
                {
                    return;
                }

                new ComplexValueEditDlg().ShowDialog(fieldList,
                                                     m_subscription.FindItemByClientHandle(fieldList.ClientHandle));
            } catch (Exception exception) {
                GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception);
            }
        }
Example #22
0
        /// <summary>
        /// Extracts a field value from an incoming event.
        /// </summary>
        private T ExtractField <T>(EventFieldList e, int index, T defaultValue)
        {
            if (e == null || index >= e.EventFields.Count || index < 0)
            {
                return(defaultValue);
            }

            Variant value = e.EventFields[index];

            if (!typeof(T).IsInstanceOfType(value.Value))
            {
                return(defaultValue);
            }

            return((T)value.Value);
        }
Example #23
0
        /// <summary>
        /// Updates the display with a new value for a monitored variable.
        /// </summary>
        private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new MonitoredItemNotificationEventHandler(MonitoredItem_Notification), monitoredItem, e);
                return;
            }

            try
            {
                // check for valid notification.
                EventFieldList notification = e.NotificationValue as EventFieldList;

                if (notification == null)
                {
                    return;
                }

                // check if monitored item has changed.
                if (!Object.ReferenceEquals(m_monitoredItem, monitoredItem))
                {
                    return;
                }

                // check if the filter has changed.
                if (notification.EventFields.Count != m_filter.Fields.Count + 1)
                {
                    return;
                }

                // create an item and add to top of list.
                ListViewItem item = CreateListItem(m_filter, notification.EventFields);
                EventsLV.Items.Insert(0, item);

                // adjust the width of the columns.
                for (int ii = 0; ii < EventsLV.Columns.Count; ii++)
                {
                    EventsLV.Columns[ii].Width = -2;
                }
            }
            catch (Exception exception)
            {
                ClientUtils.HandleException(this.Text, exception);
            }
        }
Example #24
0
        /// <summary>
        /// Finds the type of the event for the notification.
        /// </summary>
        /// <param name="monitoredItem">The monitored item.</param>
        /// <param name="notification">The notification.</param>
        /// <returns>The NodeId of the EventType.</returns>
        public static NodeId FindEventType(MonitoredItem monitoredItem, EventFieldList notification)
        {
            EventFilter filter = monitoredItem.Status.Filter as EventFilter;

            if (filter != null)
            {
                for (int ii = 0; ii < filter.SelectClauses.Count; ii++)
                {
                    SimpleAttributeOperand clause = filter.SelectClauses[ii];

                    if (clause.BrowsePath.Count == 1 && clause.BrowsePath[0] == BrowseNames.EventType)
                    {
                        return(notification.EventFields[ii].Value as NodeId);
                    }
                }
            }

            return(null);
        }
Example #25
0
        private void MonitorItem_Notification(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e)
        {
            try
            {
                EventFieldList notification = e.NotificationValue as EventFieldList;

                if (notification == null)
                {
                    return;
                }
                var filter = monitoredItem.Filter as Opc.Ua.EventFilter;

                if (filter != null)
                {
                    var values = GetEventFilterValues(monitoredItem.StartNodeId, filter);
                    if (values != null)
                    {
                        var eventType  = (NodeId)notification.EventFields[notification.EventFields.Count - 1].Value;
                        var sourceNode = (NodeId)notification.EventFields[notification.EventFields.Count - 2].Value;
                        var key        = new SourceAndEventTypeKey(sourceNode, eventType);
                        lock (_eventData)
                        {
                            List <EventFilterValues> eventFilterValuesList;
                            if (_eventData.TryGetValue(monitoredItem.StartNodeId, out eventFilterValuesList))
                            {
                                var eventFilterValues = eventFilterValuesList.FirstOrDefault(a => a.Filter.IsEqual(filter));
                                if (eventFilterValues != null)
                                {
                                    eventFilterValues.Values[key] = notification.EventFields;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                _log.LogError(exception, "Error in monitor notification");
            }
        }
        /// <summary>
        /// Saves a data change or event in the cache.
        /// </summary>
        public void SaveValueInCache(IEncodeable newValue)
        {
            lock (m_cache)
            {
                m_lastNotification = newValue;

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

                    if (datachange != null)
                    {
                        Utils.Trace(
                            "SaveValueInCache: ServerHandle={0}, Value={1}, StatusCode={2}",
                            this.ClientHandle,
                            datachange.Value.WrappedValue,
                            datachange.Value.StatusCode);

                        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));
                }
            }
        }
 /// <summary>
 /// Returns value of the field name containing the event type.
 /// </summary>
 public object GetFieldValue(
     EventFieldList eventFields, 
     NodeId         eventTypeId, 
     QualifiedName  browseName)
 {
     QualifiedNameCollection browsePath = new QualifiedNameCollection();
     browsePath.Add(browseName);
     return GetFieldValue(eventFields, eventTypeId, browsePath, Attributes.Value);
 }
Example #28
0
        /// <summary>
        /// Returns value of the field name containing the event type.
        /// </summary>
        public object GetFieldValue(
            EventFieldList eventFields,
            NodeId eventTypeId,
            IList <QualifiedName> browsePath,
            uint attributeId)
        {
            if (eventFields == null)
            {
                return(null);
            }

            EventFilter filter = m_filter as EventFilter;

            if (filter == null)
            {
                return(null);
            }

            for (int ii = 0; ii < filter.SelectClauses.Count; ii++)
            {
                if (ii >= eventFields.EventFields.Count)
                {
                    return(null);
                }

                // check for match.
                SimpleAttributeOperand clause = filter.SelectClauses[ii];

                // attribute id
                if (clause.AttributeId != attributeId)
                {
                    continue;
                }

                // match null browse path.
                if (browsePath == null || browsePath.Count == 0)
                {
                    if (clause.BrowsePath != null && clause.BrowsePath.Count > 0)
                    {
                        continue;
                    }

                    // ignore event type id when matching null browse paths.
                    return(eventFields.EventFields[ii].Value);
                }

                // match browse path.

                // event type id.
                if (clause.TypeDefinitionId != eventTypeId)
                {
                    continue;
                }

                // match element count.
                if (clause.BrowsePath.Count != browsePath.Count)
                {
                    continue;
                }

                // check each element.
                bool match = true;

                for (int jj = 0; jj < clause.BrowsePath.Count; jj++)
                {
                    if (clause.BrowsePath[jj] != browsePath[jj])
                    {
                        match = false;
                        break;
                    }
                }

                // check of no match.
                if (!match)
                {
                    continue;
                }

                // return value.
                return(eventFields.EventFields[ii].Value);
            }

            // no event type in event field list.
            return(null);
        }
Example #29
0
        /// <summary>
        /// Shows an event in the control.
        /// </summary>
        private void ShowValue(ref int index, ref bool overwrite, EventFieldList value, int fieldIndex)
        {        
            // ignore children that are not elements.
            object field = value.EventFields[fieldIndex].Value;

            if (field == null)
            {
                return;
            }
            
            // get the name of the element.
            string name = null;

            if (m_monitoredItem != null)
            {                
                name = m_monitoredItem.GetFieldName(fieldIndex);
            }
            
            // get the type name.
            string type = value.GetType().Name;
                        
            // update the list view.
            UpdateList(
                ref index,
                ref overwrite,
                value,
                field,
                fieldIndex,
                name,
                type);
        }        
Example #30
0
        /// <summary>
        /// Additional new event processing when the received event maps to a (COM AE) condition event type.  We need to extract
        /// the condition name, subcondition name, changeMask, newState, Quality, AckRequired, ActiveTime and cookie.
        /// </summary>
        /// <param name="monitoredItem"></param>
        /// <param name="eventFields"></param>
        /// <param name="ev"></param>
        /// <param name="cat"></param>
        void SetConditionEventFields(MonitoredItem monitoredItem, EventFieldList eventFields, EventNotification ev, EventCategory cat)
        {
            LocalizedText localText;
            String ConditionName;
            StatusCode? Status;
            DateTime? TimeOfLastTransition;

            try
            {
                NodeId eventType = monitoredItem.GetFieldValue(eventFields, Opc.Ua.ObjectTypes.BaseEventType, Opc.Ua.BrowseNames.EventType) as NodeId;

                // UA events are categorized into three subsets.  The first of these subsets consists of types and subtypes of ConditionType
                // which yields the event condition name, quality and enable/disable status.
                if (m_session.TypeTree.IsTypeOf(eventType, Opc.Ua.ObjectTypes.ConditionType))
                {
                    ConditionName = monitoredItem.GetFieldValue(eventFields, Opc.Ua.ObjectTypes.ConditionType, Opc.Ua.BrowseNames.ConditionName) as String;
                    if (ConditionName != null)
                        ev.ConditionName = ConditionName;
                    else
                        ev.ConditionName = cat.BrowseName;

                    // Set the subcondition name as conditionname for now.  If the event of of type AlarmconditionType and a subcondition (UA substate)
                    // exists then this field will be set accordingly.
                    ev.SubConditionName = ev.ConditionName;

                    bool? enabled = monitoredItem.GetFieldValue(eventFields, Opc.Ua.ObjectTypes.ConditionType,
                        "/EnabledState/Id", Attributes.Value) as bool?;

                    Status = monitoredItem.GetFieldValue(eventFields, Opc.Ua.ObjectTypes.ConditionType,
                        "/Quality", Attributes.Value) as StatusCode?;

                    ev.Quality = MapStatusToQuality(Status);

                    if (enabled == true)
                        ev.NewState |= OpcRcw.Ae.Constants.CONDITION_ENABLED;
                    else
                        ev.NewState &= ~OpcRcw.Ae.Constants.CONDITION_ENABLED;
                }

                // The second of the three UA event subsets consists of types and subtypes of AcknowledgeableconditionType.
                // This categorization yields events which support acknowledgement in addition to enable/disable state
                if (m_session.TypeTree.IsTypeOf(eventType, Opc.Ua.ObjectTypes.AcknowledgeableConditionType))
                {
                    bool? acked = monitoredItem.GetFieldValue(eventFields, Opc.Ua.ObjectTypes.AcknowledgeableConditionType,
                        "/AckedState/Id", Attributes.Value) as bool?;

                    // Extract the "ConditionId" (nodeId of the condition instance)
                    ev.ConditionId = monitoredItem.GetFieldValue(eventFields, Opc.Ua.ObjectTypes.AcknowledgeableConditionType,
                        "", Attributes.NodeId) as NodeId;

                    ev.AcknowledgeMethod = Opc.Ua.Methods.AcknowledgeableConditionType_Acknowledge;
                    
                    if (acked == true)
                    {
                        ev.NewState |= OpcRcw.Ae.Constants.CONDITION_ACKED;
                        ev.AckRequired = false;
                    }
                    else
                    {
                        ev.NewState &= ~OpcRcw.Ae.Constants.CONDITION_ACKED;
                        ev.AckRequired = true;
                    }

                }

                // the third of the three UA event subsets consists of types and subtypes of AlarmConditionType.  This
                // categorization yields events which support the notion of Active/Inactive and also may support substates
                // (subconditions).
                if (m_session.TypeTree.IsTypeOf(eventType, Opc.Ua.ObjectTypes.AlarmConditionType))
                {
                    bool? active = monitoredItem.GetFieldValue(eventFields, Opc.Ua.ObjectTypes.AlarmConditionType,
                        "/ActiveState/Id", Attributes.Value) as bool?;

                    TimeOfLastTransition = monitoredItem.GetFieldValue(eventFields, Opc.Ua.ObjectTypes.AlarmConditionType,
                        "/ActiveState/TransitionTime", Attributes.Value) as DateTime?;

                    if (active == true)
                    {
                        ev.NewState |= OpcRcw.Ae.Constants.CONDITION_ACTIVE;
                        ev.ActiveTime = TimeOfLastTransition ?? DateTime.MinValue;
                    }

                    // Active subconditon. 
                    localText = monitoredItem.GetFieldValue(eventFields, Opc.Ua.ObjectTypes.AlarmConditionType,
                        "/ActiveState/EffectiveDisplayName", Attributes.Value) as LocalizedText;
                    if (localText != null && localText.ToString() != "")
                        ev.SubConditionName = localText.ToString();
                }
                else // If this is not an AlarmConditionType (thus no UA active/inactive states apply) default to Active
                    ev.NewState |= OpcRcw.Ae.Constants.CONDITION_ACTIVE;
            }
            catch (Exception e)
            {
                Utils.Trace(e, "Unexpected error in SetConditionEventFields");
            }
        }
        /// <summary>
		/// Adds an event to the queue.
		/// </summary>
        public virtual void QueueEvent(EventFieldList fields)
        {
            lock (m_lock)
            {
                // make space in the queue.
                if (m_events.Count >= m_queueSize)
                {
                    m_overflow = true;

                    if (m_discardOldest)
                    {
                        m_events.RemoveAt(0);
                    }
                }

                // queue the event.
                m_events.Add(fields);
                m_readyToPublish = true;
                m_readyToTrigger = true;
            }
        }
        /// <summary>
        /// Fetches the event fields from the event.
        /// </summary>
        private EventFieldList GetEventFields(FilterContext context, EventFilter filter, IFilterTarget instance)
        {
            // fetch the event fields.
            EventFieldList fields = new EventFieldList();

            fields.ClientHandle = m_clientHandle;
            fields.Handle = instance;

            foreach (SimpleAttributeOperand clause in filter.SelectClauses)
            {
                // get the value of the attribute (apply localization).
                object value = instance.GetAttributeValue(
                    context, 
                    clause.TypeDefinitionId, 
                    clause.BrowsePath, 
                    clause.AttributeId, 
                    clause.ParsedIndexRange);

                // add the value to the list of event fields.
                if (value != null)
                {
                    // translate any localized text.
                    LocalizedText text = value as LocalizedText;

                    if (text != null)
                    {
                        value = m_server.ResourceManager.Translate(m_session.PreferredLocales, text);
                    }

                    // add value.
                    fields.EventFields.Add(new Variant(value));
                }

                // add a dummy entry for missing values.
                else
                {
                    fields.EventFields.Add(Variant.Null);
                }
            }

            return fields;
        }
        /// <summary>
        /// Saves a notification in the cache.
        /// </summary>
        public void OnNotification(EventFieldList notification)
        {
            m_events.Enqueue(notification);
            m_lastEvent = notification;

            while (m_events.Count > m_queueSize)
            {
                m_events.Dequeue();
            }
        }
        /// <summary>
        /// Returns all events in the queue.
        /// </summary>
        public IList<EventFieldList> Publish()
        {
            EventFieldList[] events = new EventFieldList[m_events.Count];

            for (int ii = 0; ii < events.Length; ii++)
            {
                events[ii] = m_events.Dequeue();
            }

            return events;
        }
        /// <summary>
        /// Formats a value for display in the control.
        /// </summary>
        private string GetValueText(object value)
        {
            // check for null.
            if (value == null)
            {
                return("(null)");
            }

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

            if (bytes != null)
            {
                StringBuilder buffer = new StringBuilder();

                for (int ii = 0; ii < bytes.Length; ii++)
                {
                    if (ii != 0 && ii % 16 == 0)
                    {
                        buffer.Append(" ");
                    }

                    buffer.AppendFormat("{0:X2} ", bytes[ii]);
                }

                return(buffer.ToString());
            }

            // format xml element.
            XmlElement xml = value as XmlElement;

            if (xml != null)
            {
                // return the entire element if not expandable.
                if (!IsExpandableType(xml))
                {
                    return(xml.OuterXml);
                }

                // show only the start tag.
                string text = xml.OuterXml;

                int index = text.IndexOf('>');

                if (index != -1)
                {
                    text = text.Substring(0, index);
                }

                return(text);
            }

            // format array.
            Array array = value as Array;

            if (array != null)
            {
                return(Utils.Format("{1}[{0}]", array.Length, value.GetType().GetElementType().Name));
            }

            // format list.
            IList list = value as IList;

            if (list != null)
            {
                string type = value.GetType().Name;

                if (type.EndsWith("Collection"))
                {
                    type = type.Substring(0, type.Length - "Collection".Length);
                }
                else
                {
                    type = "Object";
                }

                return(Utils.Format("{1}[{0}]", list.Count, type));
            }

            // format encodeable object.
            IEncodeable encodeable = value as IEncodeable;

            if (encodeable != null)
            {
                return(encodeable.GetType().Name);
            }

            // format extension object.
            ExtensionObject extension = value as ExtensionObject;

            if (extension != null)
            {
                return(GetValueText(extension.Body));
            }

            // check for event value.
            EventFieldList eventFields = value as EventFieldList;

            if (eventFields != null)
            {
                if (m_monitoredItem != null)
                {
                    return(String.Format("{0}", m_monitoredItem.GetEventType(eventFields)));
                }

                return(eventFields.GetType().Name);
            }

            // check for data value.
            DataValue dataValue = value as DataValue;

            if (dataValue != null)
            {
                if (StatusCode.IsBad(dataValue.StatusCode))
                {
                    return(String.Format("{0}", dataValue.StatusCode));
                }

                return(String.Format("{0}", dataValue.Value));
            }

            // use default formatting.
            return(Utils.Format("{0}", value));
        }
 /// <summary>
 /// Returns value of the field name containing the event type.
 /// </summary>
 public object GetFieldValue(
     EventFieldList eventFields, 
     NodeId         eventTypeId, 
     string         browsePath, 
     uint           attributeId)
 {
     QualifiedNameCollection browseNames = SimpleAttributeOperand.Parse(browsePath);
     return GetFieldValue(eventFields, eventTypeId, browseNames, attributeId);
 }
        /// <summary>
        /// Returns true if the type can be expanded.
        /// </summary>
        private bool IsExpandableType(object value)
        {
            // check for null.
            if (value == null)
            {
                return(false);
            }

            // check for Variant.
            if (value is Variant)
            {
                return(IsExpandableType(((Variant)value).Value));
            }

            // check for bytes.
            byte[] bytes = value as byte[];

            if (bytes != null)
            {
                return(false);
            }

            // check for xml element.
            XmlElement xml = value as XmlElement;

            if (xml != null)
            {
                if (xml.ChildNodes.Count == 1 && xml.ChildNodes[0] is XmlText)
                {
                    return(false);
                }

                return(xml.HasChildNodes);
            }

            // check for array.
            Array array = value as Array;

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

            // check for list.
            IList list = value as IList;

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

            // check for encodeable object.
            IEncodeable encodeable = value as IEncodeable;

            if (encodeable != null)
            {
                return(true);
            }

            // check for extension object.
            ExtensionObject extension = value as ExtensionObject;

            if (extension != null)
            {
                return(IsExpandableType(extension.Body));
            }

            // check for data value.
            DataValue datavalue = value as DataValue;

            if (datavalue != null)
            {
                return(true);
            }

            // check for event value.
            EventFieldList eventFields = value as EventFieldList;

            if (eventFields != null)
            {
                return(true);
            }

            // must be a simple value.
            return(false);
        }
        /// <summary>
        /// Shows a value in control.
        /// </summary>
        private async Task ShowValue(int index, 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.ToString());
                return;
            }

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

            if (datachange != null)
            {
                ShowValue(ref index, ref overwrite, datachange.Value.ToString());
                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.ToString());
                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)
            {
                bool result = await PromptOnLongList(bytes.Length / 16);

                if (!result)
                {
                    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)
            {
                bool result = await PromptOnLongList(array.Length);

                if (!result)
                {
                    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)
            {
                bool result = await PromptOnLongList(list.Count);

                if (!result)
                {
                    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)
            {
                bool result = await PromptOnLongList(xml.ChildNodes.Count);

                if (!result)
                {
                    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.ToString());
                return;
            }

            // show unknown types as strings.
            ShowValue(ref index, ref overwrite, String.Format("{0}", value));
        }
        /// <summary>
        /// Returns value of the field name containing the event type.
        /// </summary>
        public object GetFieldValue(
            EventFieldList       eventFields, 
            NodeId               eventTypeId, 
            IList<QualifiedName> browsePath, 
            uint                 attributeId)
        {
            if (eventFields == null)
            {
                return null;
            }
            
            EventFilter filter = m_filter as EventFilter;

            if (filter == null)
            {
                return null;
            }
            
            for (int ii = 0; ii < filter.SelectClauses.Count; ii++)
            {
                if (ii >= eventFields.EventFields.Count)
                {
                    return null;
                }
                
                // check for match.
                SimpleAttributeOperand clause = filter.SelectClauses[ii];

                // attribute id
                if (clause.AttributeId != attributeId)
                {
                    continue;
                }
                
                // match null browse path.
                if (browsePath == null || browsePath.Count == 0)
                {
                    if (clause.BrowsePath != null && clause.BrowsePath.Count > 0)
                    {
                        continue;
                    }
                    
                    // ignore event type id when matching null browse paths.
                    return eventFields.EventFields[ii].Value;
                }

                // match browse path.

                // event type id.
                if (clause.TypeDefinitionId != eventTypeId)
                {
                    continue;
                }

                // match element count.
                if (clause.BrowsePath.Count != browsePath.Count)
                {
                    continue;
                }
            
                // check each element.
                bool match = true;

                for (int jj = 0; jj < clause.BrowsePath.Count; jj++)
                {                    
                    if (clause.BrowsePath[jj] !=  browsePath[jj])
                    {
                        match = false;
                        break;
                    }
                }

                // check of no match.
                if (!match)
                {
                    continue;
                }
            
                // return value.
                return eventFields.EventFields[ii].Value;
            }

            // no event type in event field list.
            return null;
        }
        /// <summary>
        /// Returns value of the field name containing the event type.
        /// </summary>
        public INode GetEventType(EventFieldList eventFields)
        {
            // get event type.
            NodeId eventTypeId = GetFieldValue(eventFields, ObjectTypes.BaseEventType, Opc.Ua.BrowseNames.EventType) as NodeId;

            if (eventTypeId != null && m_subscription != null && m_subscription.Session != null)
            {
                return m_subscription.Session.NodeCache.Find(eventTypeId);
            }

            // no event type in event field list.
            return null;
        }
        /// <summary>
        /// Returns value of the field name containing the event type.
        /// </summary>
        public DateTime GetEventTime(EventFieldList eventFields)
        {
            // get event time.
            DateTime? eventTime = GetFieldValue(eventFields, ObjectTypes.BaseEventType, Opc.Ua.BrowseNames.Time) as DateTime?;

            if (eventTime != null)
            {
                return eventTime.Value;
            }

            // no event time in event field list.
            return DateTime.MinValue;
        }