/// <summary> /// Callback to receive data changes from an UA server. /// </summary> /// <param name="clientHandle">The source of the event.</param> /// <param name="value">The instance containing the changed data.</param> private void ClientApi_ValueChanged(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) { // We have to call an invoke method. if (this.InvokeRequired) { // Asynchronous execution of the valueChanged delegate. this.BeginInvoke(new MonitoredItemNotificationEventHandler(ClientApi_ValueChanged), monitoredItem, e); return; } // Extract notification from event MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification; if (notification == null) { return; } Object value = notification.Value.WrappedValue.Value; // Get the according item. ListViewItem item = (ListViewItem)monitoredItem.Handle; // Set current value, status code and timestamp. item.SubItems[2].Text = Utils.Format("{0}", notification.Value.Value); item.SubItems[3].Text = Utils.Format("{0}", notification.Value.StatusCode); item.SubItems[4].Text = Utils.Format("{0:HH:mm:ss.fff}", notification.Value.SourceTimestamp.ToLocalTime()); }
/// <summary> /// Tag点变化回调事件 /// </summary> /// <param name="key"></param> /// <param name="monitoredItem"></param> /// <param name="eventArgs"></param> private void SubCallBack(string groupName, MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs eventArgs) { MonitoredItemNotification notification = eventArgs.NotificationValue as MonitoredItemNotification; if (this.groupDictionary.Count() == 0) { return; } var nodeId = Convert.ToString(monitoredItem.StartNodeId); //Linq:切勿使用 Count() > 0 来判断集合非空,存在性能问题,应改用Any var tag = this.groupDictionary[groupName].GetTags().Where(p => p.OpcTagName.Equals(nodeId)).FirstOrDefault(); //var tag = this.groupDictionary[groupName].GetTags().Where(p => p.OpcTagName.Equals(nodeId)).FirstOrDefault(); if (tag != null) { //标签时间戳 tag.TimeStamps = Convert.ToDateTime(DateTime.Now); tag.Qualities = "Good"; //标签值,必须写在最后,值变化会触发事件处理,其它值必须在此之前完成赋值 tag.Value = notification.Value.WrappedValue.Value; //tag.DataType = typeof(Int32); tag.DataType = TypeInfo.GetSystemType(notification.Value.WrappedValue.TypeInfo.BuiltInType, notification.Value.WrappedValue.TypeInfo.ValueRank); //tag.DataTypeName = notification.Value.WrappedValue.TypeInfo.ToString(); } else { //不处理 } }
/// <summary> /// Processes a Publish repsonse from the server. /// </summary> void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) { if (InvokeRequired) { BeginInvoke(m_MonitoredItemNotification, monitoredItem, e); return; } else if (!IsHandleCreated) { return; } try { // ignore notifications for other monitored items. if (!Object.ReferenceEquals(m_monitoredItem, monitoredItem)) { return; } // notify controls of the change. EventsCTRL.NotificationReceived(e); DataChangesCTRL.NotificationReceived(e); LatestValueCTRL.ShowValue(monitoredItem, true); // update item status. UpdateStatus(); } catch (Exception exception) { GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } }
private void OnNewValueFromChannel(MonitoredItem item, MonitoredItemNotificationEventArgs e) { foreach (var value in item.DequeueValues()) { NewValueFromChannel?.Invoke(this, new TagExchangeWithChannelArgs(value.Value, value.SourceTimestamp)); } }
public void SubCallback1(string key, MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs args) { if (InvokeRequired) { Invoke(new Action <string, MonitoredItem, MonitoredItemNotificationEventArgs>(SubCallback1), key, monitoredItem, args); return; } if (key == "A") { // 如果有多个的订阅值都关联了当前的方法,可以通过key和monitoredItem来区分 MonitoredItemNotification notification = args.NotificationValue as MonitoredItemNotification; if (notification != null) { try { textBox1.Text = notification.Value.WrappedValue.Value.ToString(); } catch (Exception ex) { Debug.WriteLine(ex.Message); } } } }
/// <summary> /// Hier werden die Werte der Variablen bei Änderung in die Datenbank geschrieben /// </summary> /// <param name="item"></param> /// <param name="e"></param> private void WriteDataOnNotificationAsync(MonitoredItem item, MonitoredItemNotificationEventArgs e) { foreach (var value in item.DequeueValues()) { addData.SaveValueAsync(sqlOpcUaServerId, item.StartNodeId.ToString(), item.DisplayName, value.Value.ToString(), value.StatusCode.ToString(), value.SourceTimestamp); } }
// HANDLERS PLC /// <summary> /// Handler for Telemetry data changes. /// </summary> /// <param name="item"></param> /// <param name="e"></param> private static void OnNotification(MonitoredItem item, MonitoredItemNotificationEventArgs e) { string symbol = ""; if (item.DisplayName == TemperatureDisplayName) { symbol = "°C"; } foreach (var value in item.DequeueValues()) { Console.WriteLine("{0} ({1}): {2} - {3}{4}", value.SourceTimestamp, value.StatusCode, item.DisplayName, value.Value, symbol); if (item.DisplayName == "ServerStatusCurrentTime") { // Only send the status to IoT Central when it changes. if (value.StatusCode != prevStatusCode) { eventInfoText = "OPC UA Server status" + " - " + value.StatusCode; SendEventTelemetryAsync(); } prevStatusCode = value.StatusCode; } } }
void monitoredItem_Notification(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) { if (this.InvokeRequired) { this.BeginInvoke(new MonitoredItemNotificationEventHandler(monitoredItem_Notification), monitoredItem, e); return; } try { MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification; if (notification == null) { return; } Console.WriteLine(monitoredItem.DisplayName + ": " + notification.Value.WrappedValue.ToString()); outputWindow.label1.Text = monitoredItem.DisplayName + " value: " + Utils.Format("{0}", notification.Value.WrappedValue.ToString()) + ";\nStatusCode: " + Utils.Format("{0}", notification.Value.StatusCode.ToString()) + ";\nSource timestamp: " + notification.Value.SourceTimestamp.ToString() + ";\nServer timestamp: " + notification.Value.ServerTimestamp.ToString(); } catch (Exception exception) { ClientUtils.HandleException(this.Text, exception); } }
private static void OnNotification(MonitoredItem item, MonitoredItemNotificationEventArgs e) { foreach (var value in item.DequeueValues()) { Console.WriteLine("{0}: {1}, {2}, {3}, {4}, {5}, {6}", item.DisplayName, item.LastMessage, value.WrappedValue, value.StatusCode, item.Status, item.AttributeId, item.StartNodeId); } }
/// <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 { if (!Object.ReferenceEquals(monitoredItem.Subscription, m_subscription)) { return; } MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification; if (notification == null) { return; } AddValue(notification.Value, null); m_dataset.AcceptChanges(); ResultsDV.FirstDisplayedCell = ResultsDV.Rows[ResultsDV.Rows.Count - 1].Cells[0]; } catch (Exception exception) { MessageBox.Show(exception.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } }
void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) { if (InvokeRequired) { BeginInvoke(new MonitoredItemNotificationEventHandler(MonitoredItem_Notification), monitoredItem, e); return; } try { Control control = monitoredItem.Handle as Control; if (control == null) { return; } MonitoredItemNotification datachange = e.NotificationValue as MonitoredItemNotification; if (datachange == null) { return; } control.Text = datachange.Value.WrappedValue.ToString(); } catch (Exception exception) { ClientUtils.HandleException(this.Text, exception); } }
private void SubCallback(string key, MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs args) { if (InvokeRequired) { Invoke(new Action <string, MonitoredItem, MonitoredItemNotificationEventArgs>(SubCallback), key, monitoredItem, args); return; } if (key == "A") { // 如果有多个的订阅值都关联了当前的方法,可以通过key和monitoredItem来区分 MonitoredItemNotification notification = args.NotificationValue as MonitoredItemNotification; if (notification != null) { textBox3.Text = notification.Value.WrappedValue.Value.ToString( ); } } else if (key == "B") { // 需要区分出来每个不同的节点信息 MonitoredItemNotification notification = args.NotificationValue as MonitoredItemNotification; if (monitoredItem.StartNodeId.ToString( ) == MonitorNodeTags[0]) { textBox5.Text = notification.Value.WrappedValue.Value.ToString( ); } else if (monitoredItem.StartNodeId.ToString( ) == MonitorNodeTags[1]) { textBox9.Text = notification.Value.WrappedValue.Value.ToString( ); } else if (monitoredItem.StartNodeId.ToString( ) == MonitorNodeTags[2]) { textBox10.Text = notification.Value.WrappedValue.Value.ToString( ); } } }
private void OnNotification(MonitoredItem item, MonitoredItemNotificationEventArgs e) { foreach (var value in item.DequeueValues()) { Tag tag = new Tag() { NodeId = item.ResolvedNodeId, Name = item.DisplayName, Value = value.Value, LastSync = value.SourceTimestamp, StatusCode = value.StatusCode, Type = value.WrappedValue.TypeInfo }; if (ListOfTags.Tags.Exists(t => t.Name == tag.Name)) { int index = ListOfTags.Tags.FindIndex(t => t.Name == tag.Name); ListOfTags.Tags[index] = tag; } else { tag.FirstRead = true; ListOfTags.Tags.Add(tag); } OnTagChange?.Invoke(this, tag); } }
/// <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 { if (m_session == null) { return; } MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification; if (notification == null) { return; } ListViewItem.ListViewSubItem item = (ListViewItem.ListViewSubItem)monitoredItem.Handle; item.Text = Utils.Format("{0}", notification.Value.WrappedValue); } catch (Exception exception) { MessageBox.Show(exception.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void OnNotification(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) { try { if (m_session == null) { return; } MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification; if (notification == null) { return; } foreach (var value in monitoredItem.DequeueValues()) { foreach (var itemUA in ItemsOPCUA) { if (itemUA.nodeId == monitoredItem.StartNodeId) { SetCurData(itemUA.signal, Convert.ToDouble(Opc.Ua.Utils.Format("{0}", notification.Value.WrappedValue)), Scada.Data.Configuration.BaseValues.CnlStatuses.Defined); break; } } } } catch (Exception ex) { WriteToLog(KPNumStr + (Localization.UseRussian ? "Ошибка при обработке изменения текущих данных: " : "Error handling current data changing: ") + ex.Message); lastCommSucc = false; } }
/// <summary> /// Event fired when an iem is modified /// </summary> /// <param name="monitoredItem"></param> /// <param name="e"></param> private void Item_Notification(MonitoredItem item, MonitoredItemNotificationEventArgs e) { foreach (var value in item.DequeueValues()) { SetValeForTag(item.StartNodeId.ToString(), value.Value, (int)value.StatusCode.CodeBits, value.ServerTimestamp, true); } }
void monitoredItem_Notification(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) { //if (this.InvokeRequired) //{ // this.BeginInvoke(new MonitoredItemNotificationEventHandler(monitoredItem_Notification), monitoredItem, e); // return; //} try { MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification; if (notification == null) { return; } Console.WriteLine(monitoredItem.DisplayName + ": " + notification.Value.WrappedValue.ToString()); WriteToFile(monitoredItem.DisplayName + ": " + notification.Value.WrappedValue.ToString()); //using (EventLog eventLog = new EventLog("Monitored Item")) //{ // eventLog.Source = "OPC_Service Monitored Item"; // eventLog.WriteEntry(monitoredItem.DisplayName + ": " + notification.Value.WrappedValue.ToString(), EventLogEntryType.Information, 101, 1); //} } catch (Exception exception) { Console.WriteLine(exception); } }
private void ItemChanged(MonitoredItem monitoreditem, MonitoredItemNotificationEventArgs e) { MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification; if (notification != null) { string nodeid = monitoreditem.StartNodeId.Identifier.ToString(); if (!_SubscriptionTags.ContainsKey(nodeid)) { throw (new Exception(string.Format("订阅回调触发,但是_SubscriptionTags不包含键;key:{0}", nodeid))); } TagItem item = _SubscriptionTags[nodeid]; if (item == null) { throw (new Exception(string.Format("订阅回调触发,但是未找到键对应TagItem对象;key:{0},value:null", nodeid))); } if (item.CallBack == null) { return; } item.CBType = TagItem.CallBackType.Subscription; item.Value = notification.Value.Value; item.Timestamp = notification.Value.SourceTimestamp; item.Quality = notification.Value.StatusCode.ToString(); item.CallBack(item); } }
private void OnValueChange(MonitoredItem opcItem, MonitoredItemNotificationEventArgs e) { List <IMeasurement> measurements = new List <IMeasurement>(); foreach (var value in opcItem.DequeueValues()) { var key = opcItem.StartNodeId.ToString().ToUpper(); if (items.ContainsKey(key)) { var item = items[key]; if (item != null) { var measurement = Measurement.Clone(item, Convert.ToDouble(value.Value), value.SourceTimestamp.ToUniversalTime().Ticks); measurement.StateFlags = MeasurementStateFlags.Normal; measurements.Add(measurement); } } else { OnStatusMessage(MessageLevel.Warning, $"OPC key {key} not found."); } } OnNewMeasurements(measurements); m_measurementsReceived += measurements.Count; //OnStatusMessage(MessageLevel.Info, $"Updating OPC values."); }
private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) { try { if (e.NotificationValue == null || monitoredItem.Subscription.Session == null) { return; } JsonEncoder encoder = new JsonEncoder( monitoredItem.Subscription.Session.MessageContext, false); encoder.WriteNodeId("MonitoredItem", monitoredItem.ResolvedNodeId); e.NotificationValue.Encode(encoder); var json = encoder.Close(); var bytes = new UTF8Encoding(false).GetBytes(json); foreach (var publisher in m_publishers) { try { publisher.Publish(new ArraySegment <byte>(bytes)); } catch (Exception ex) { Utils.Trace(ex, "Failed to publish message, dropping...."); } } } catch (Exception exception) { Utils.Trace(exception, "Error processing monitored item notification."); } }
/// <summary> /// Callback method for updating values of subscibed nodes /// </summary> /// <param name="monitoredItem"></param> /// <param name="e"></param> private void Notification_MonitoredItem(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) { if (!(e.NotificationValue is MonitoredItemNotification notification)) { return; } var value = notification.Value; var variable = Notifications.FirstOrDefault(x => x.Name == monitoredItem.DisplayName); if (variable == null) { return; } var message = ""; if (variable.IsDigital && (bool)value.Value) { message = variable.IsOneDescription; } else if (variable.IsDigital && !(bool)value.Value) { message = variable.IsZeroDescription; } else if (!variable.IsDigital) { message = $"Hodnota premennej sa zmenila o {variable.FilterValue} [{variable.DeadbandType.ToString()}] na {notification.Value.Value}. "; } _messenger.Send(new SendNotificationAdd(variable.Name, variable.NodeId, message, value.SourceTimestamp)); }
// Notification Event Handler (Method to write a value from OPC UA notifications to a local variable) private static void OnNotification(MonitoredItem item, MonitoredItemNotificationEventArgs e, ref int variable) { foreach (var value in item.DequeueValues()) { variable = value.GetValue <UInt16>(0); // assigns the referenced 'variable' (e.g. valueCoffeeLevel) the value of the Monitored Item. } }
private static void OnNotification(MonitoredItem item, MonitoredItemNotificationEventArgs e) { foreach (var value in item.DequeueValues()) { Console.WriteLine("{0}: {1}, {2}, {3}", item.DisplayName, value.Value, value.SourceTimestamp, value.StatusCode); } }
/// <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 { if (m_session == null) { return; } MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification; if (notification == null) { return; } ListViewItem item = (ListViewItem)monitoredItem.Handle; item.SubItems[5].Text = Utils.Format("{0}", notification.Value.WrappedValue); item.SubItems[6].Text = Utils.Format("{0}", notification.Value.StatusCode); item.SubItems[7].Text = Utils.Format("{0:HH:mm:ss.fff}", notification.Value.SourceTimestamp.ToLocalTime()); } catch (Exception exception) { ClientUtils.HandleException(this.Text, exception); } }
private void ClientApi_ValueChanged(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) { try { if (this.InvokeRequired) { this.BeginInvoke(new MonitoredItemNotificationEventHandler(ClientApi_ValueChanged), monitoredItem, e); return; } MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification; if (notification == null) { return; } if (monitoredItem.DisplayName == "item8") { // Get the according item textBox5.Text = notification.Value.WrappedValue.ToString(); // this.GatherData_save_to_databse(notification.Value.WrappedValue.ToString()); } else if (monitoredItem.DisplayName == "item2") { // Get the according item textBox1.Text = notification.Value.WrappedValue.ToString(); } } catch (Exception ex) { MessageBox.Show("Unexpected error in the data change callback:\n\n" + ex.Message); } }
private static void MonitoredItem_TestStation(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) { try { lock (m_mesStatusLock) { MonitoredItemNotification change = e.NotificationValue as MonitoredItemNotification; m_statusTest = (StationStatus)change.Value.Value; Trace("--TestStation: {0}", m_statusTest); switch (m_statusTest) { case StationStatus.Ready: // nothing to do break; case StationStatus.WorkInProgress: // nothing to do break; case StationStatus.Done: Trace("#{0} Tested, Passed", m_serialNumber[c_Test]); m_doneTest = true; break; case StationStatus.Discarded: Trace("#{0} Tested, not Passed, Discarded", m_serialNumber[c_Test]); m_sessionTest.Call(m_station.RootMethodNode, m_station.ResetMethodNode, null); break; case StationStatus.Fault: { m_faultTest = true; Task.Run(async() => { Trace("<<TestStation: Fault>>"); await Task.Delay(c_waitTime); Trace("<<TestStation: Restart from Fault>>"); m_faultTest = false; m_sessionTest.Call(m_station.RootMethodNode, m_station.ResetMethodNode, null); }); } break; default: { Trace("Argument error: Invalid station status type received!"); return; } } } } catch (Exception exception) { Trace("Exception: Error processing monitored item notification: " + exception.Message); } }
private async void WriteDataOnNotificationAsync(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) { var tag = _tags.Where(t => monitoredItem.DisplayName == t.TagName).FirstOrDefault(); var value = (MonitoredItemNotification)monitoredItem.LastValue; tag.Value = value.Value.WrappedValue.Value.ToString(); await _eventSender.SendAsync(nameof(GQLSubscription.OnTagUpdated), tag); }
private void OnNotification(MonitoredItem item, MonitoredItemNotificationEventArgs e) { foreach (var value in item.DequeueValues()) { DataValues = $"{item.ResolvedNodeId}:{value.SourceTimestamp}:{value.StatusCode}:{value.Value}"; Console.WriteLine("{0}: {1}, {2}, {3}", item.DisplayName, value.Value, value.SourceTimestamp, value.StatusCode); } }
private void OnChange(MonitoredItem item, MonitoredItemNotificationEventArgs e) { foreach (DataValue value in item.DequeueValues()) { var v = value.Value; NodeValueChanged(this, new NodeValueChangedNotification(item.StartNodeId.ToString(), v)); } }
private void Notification_MonitoredItem(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) { MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification; if (notification == null) { return; } }