// 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.
     }
 }
Example #2
0
        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 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);
     }
 }
        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);
            }
        }
Example #5
0
        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;
            }
        }
 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);
     }
 }
Example #7
0
 private void OnNewValueFromChannel(MonitoredItem item, MonitoredItemNotificationEventArgs e)
 {
     foreach (var value in item.DequeueValues())
     {
         NewValueFromChannel?.Invoke(this, new TagExchangeWithChannelArgs(value.Value, value.SourceTimestamp));
     }
 }
Example #8
0
 /// <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);
     }
 }
Example #9
0
        // 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;
                }
            }
        }
Example #10
0
 /// <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);
     }
 }
Example #11
0
        private void dataReturned(object sender, EventArgs e)
        {
            MonitoredItem monitoredItem = (MonitoredItem)sender;

            foreach (var value in monitoredItem.DequeueValues())
            {
                string message = string.Format("{0}={1}\t[Source Time: {2}, Status: {3}]", monitoredItem.DisplayName, value.Value, value.SourceTimestamp.ToString("yyyy-MM-dd HH:mm:ss.fff"), value.StatusCode);
                log.Info(message);
                tagDB.UpdateTagValue(monitoredItem.DisplayName, value.Value.ToString());

                if (monitoredItem.DisplayName.EndsWith("Trigger")) // == "Camera01Trigger")
                {
                    if ((bool)value.Value == true)
                    {
                        // Reset trigger
                        opcuaClient.WriteValueToPath(string.Format("{0}/{1}", TagPath, monitoredItem.DisplayName), false);

                        string tagRoot      = monitoredItem.DisplayName.Substring(0, monitoredItem.DisplayName.Length - "Trigger".Length);
                        string CameraUriTag = tagRoot + "CameraURI";

                        // If the tag exists and has a valid value, attempt a callup
                        if (tagDB.Tags.Exists(x => x.name == CameraUriTag))
                        {
                            var tagValue = tagDB.Tags.Find(item => item.name == CameraUriTag).value;
                            if (tagValue != null && tagValue != "")
                            {
                                int viewerNum = int.Parse(tagRoot.Substring(tagRoot.Length - 2, 2)) - 1;
                                callupDelegate(new Uri(tagValue), viewerNum);
                            }
                        }
                        else
                        {
                            // Tag not yet assigned
                            log.Warn(string.Format("Tag not found [{0}].  Callup cannot be performed.", CameraUriTag));
                        }
                    }
                }
                else if (monitoredItem.DisplayName.EndsWith("CameraURI"))
                {
                    string tagRoot = monitoredItem.DisplayName.Substring(0, monitoredItem.DisplayName.Length - "CameraURI".Length);

                    // If the tag exists and has a valid value, attempt a callup
                    if (tagDB.Tags.Exists(x => x.name == monitoredItem.DisplayName))
                    {
                        var tagValue = tagDB.Tags.Find(item => item.name == monitoredItem.DisplayName).value;
                        if (tagValue != null && tagValue != "")
                        {
                            int viewerNum = int.Parse(tagRoot.Substring(tagRoot.Length - 2, 2)) - 1;
                            callupDelegate(new Uri(tagValue), viewerNum);
                        }
                    }
                    else
                    {
                        // Tag not yet assigned
                        log.Warn(string.Format("Tag not found [{0}].  Callup cannot be performed.", monitoredItem.DisplayName));
                    }
                }
            }
        }
Example #12
0
 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);
     }
 }
Example #13
0
        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));
            }
        }
Example #14
0
 private static void OnNotification(MonitoredItem item, MonitoredItemNotificationEventArgs e)
 {
     foreach (DataValue value in item.DequeueValues())
     {
         if (value.Value != null && Data.tags.ContainsKey(item.DisplayName))
         {
             Data.tags[item.DisplayName].Value = value.Value.ToString();
             value.GetValue(true);
             value.Value = true;
         }
     }
 }
        private static void OnNotification(MonitoredItem item, MonitoredItemNotificationEventArgs e)
        {
            string logPrefix = $"{_logClassPrefix}:SingleNodeIdTest:";

            foreach (var value in item.DequeueValues())
            {
                if (_lastTimestamp != new DateTime(0) && value.ServerTimestamp - _lastTimestamp > TimeSpan.FromSeconds(_publishingIntervalSec * 1.3))
                {
                    Logger.Warning($"{logPrefix}{item.DisplayName} publishing is too late: diff: {value.ServerTimestamp - _lastTimestamp}, max: {_publishingIntervalSec * 1.3}, serverTimestamp: {value.ServerTimestamp}, lastTimestamp: {_lastTimestamp}");
                }
                _lastTimestamp = value.ServerTimestamp;
            }
        }
Example #16
0
        /// <summary>
        /// Обработчик обновления тега по подписке
        /// </summary>
        private void OnNotification(MonitoredItem item, MonitoredItemNotificationEventArgs e)
        {
            LastPoll = DateTime.Now;
            foreach (var value in item.DequeueValues())
            {
                TagId tag = new TagId();
                tag.TagName  = item.DisplayName;
                tag.PollerId = PollerId;

                DateTime timestamp = DateTime.SpecifyKind(value.SourceTimestamp, DateTimeKind.Utc);
                timestamp = timestamp.ToLocalTime();
                if (value.Value != null)
                {
                    string signal = value.Value.ToString();
                    OnUpdate(tag, signal, timestamp, (int)value.StatusCode.Code);
                }
                else
                {
                    OnUpdate(tag, null, timestamp, (int)value.StatusCode.Code);
                }
                // проверка на то, что качество у нас Good или его производные
                // if ((value.StatusCode.Code & 0xFF000000) == 0)
                // {
                //     if (LoggerUtils.IsDiscreteType(value.Value))
                //     {
                //         bool signal = value.Value.ToString() == "True";
                //          OnUpdateDiscrete(tag, signal, timestamp, (int) value.StatusCode.Code);
                //     }
                //     else
                //         if (LoggerUtils.IsAnalogType(value.Value))
                //         {
                //             // я дичайше извиняюсь за этот и вышестоящий костыли, но более приличного способа кастануть ЭТО я не нашел
                //             float signal = float.Parse(value.Value.ToString());
                //             OnUpdateAnalog(tag, signal, timestamp, (int) value.StatusCode.Code);
                //         }
                //         else
                //             if (LoggerUtils.IsStringType(value.Value))
                //             {
                //                 // я дичайше извиняюсь за этот и вышестоящий костыли, но более приличного способа кастануть ЭТО я не нашел
                //                 string signal = value.Value.ToString();
                //                 OnUpdateString(tag, signal, timestamp, (int)value.StatusCode.Code);
                //             }
                // }
                // else
                //     {
                //         // я дичайше извиняюсь за этот и вышестоящий костыли, но более приличного способа кастануть ЭТО я не нашел
                //         float signal = float.Parse(value.Value.ToString());
                //         OnUpdateEmpty(tag,   timestamp, (int) value.StatusCode.Code);
                //     }
            }
        }
Example #17
0
        /// <summary>
        /// 处理订阅事件
        /// </summary>
        /// <param name="item"></param>
        /// <param name="e"></param>
        private void OnMonitoredNotification(MonitoredItem item, MonitoredItemNotificationEventArgs e)
        {
            OpcUaDeviceOutParamEntity opcUaDeviceOutParamEntity = new OpcUaDeviceOutParamEntity();

            opcUaDeviceOutParamEntity.StatusCode            = (uint)DeviceStatusCode.SubscriptionOK;
            opcUaDeviceOutParamEntity.SubScriptionValueList = new List <Tuple <string, object> >();
            foreach (var value in item.DequeueValues())
            {
                opcUaDeviceOutParamEntity.SubScriptionValueList.Add(Tuple.Create(item.ResolvedNodeId.ToString(), value.Value));
            }
            DeviceEventArgs <DeviceParamEntityBase> args = new DeviceEventArgs <DeviceParamEntityBase>(opcUaDeviceOutParamEntity);

            Notification.Invoke(this, args);
        }
Example #18
0
 private void OnComplexTypeNotification(MonitoredItem item, MonitoredItemNotificationEventArgs e)
 {
     foreach (var value in item.DequeueValues())
     {
         Console.WriteLine("{0}: {1}, {2}", item.DisplayName, value.SourceTimestamp, value.StatusCode);
         if (Verbose)
         {
             Console.WriteLine(value);
         }
         else if (PrintAsJson)
         {
             PrintValueAsJson(item.DisplayName, value);
         }
     }
 }
Example #19
0
        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);

                //Build up object
                dynamic telemetry = new System.Dynamic.ExpandoObject();
                telemetry.DisplayName     = item.DisplayName;
                telemetry.Value           = value.Value;
                telemetry.SourceTimeStamp = value.SourceTimestamp;
                telemetry.StatusCode      = value.StatusCode;

                //Send async to IoT Hub
                SendD2CMessageAsync(telemetry);
            }
        }
Example #20
0
        private static void OnNotification(MonitoredItem item, MonitoredItemNotificationEventArgs e)
        {
            Interlocked.Increment(ref ntCount);
            foreach (var value in item.DequeueValues())
            {
                Console.WriteLine("{0}: {1}, {2}", item.DisplayName, value.Value, value.StatusCode);
                byte[] bytes = (byte[])value.Value;
                Console.WriteLine(bytes[3]);
            }
            var evts = item.LastValue as EventFieldList;

            if (evts != null)
            {
                var fields = evts.EventFields;
                foreach (var field in fields)
                {
                    Console.WriteLine("事件信息:" + field.Value.ToString());
                }
            }
        }
Example #21
0
        private static void OnSensorData(MonitoredItem item, MonitoredItemNotificationEventArgs e)
        {
            Mapping mapping = Mapping.Instance;

            foreach (var data in item.DequeueValues())
            {
                var key      = item.DisplayName;
                var assetId  = Mapping.Instance.GetAssetByOpc(key);
                var value    = data.Value;
                var dateTime = DateTime.Now;

                if (!Global.OPCUA.Exists(x => x.Name == key))
                {
                    Global.OPCUA.Add(new Records_OPCUA(key, "", "", 0, ""));
                }

                Global.OPCUA.Find(x => x.Name == key).Value = value.ToString();
                BufferSender.Instance.Add(assetId, value, dateTime);
            }
        }
Example #22
0
 public void OnTagValueChange(MonitoredItem item, MonitoredItemNotificationEventArgs e)
 {
     foreach (var value in item.DequeueValues())
     {
         if (item.DisplayName == "ServerStatusCurrentTime")
         {
             LastTimeOPCServerFoundAlive = value.SourceTimestamp.ToLocalTime();
         }
         else
         {
             if (value.Value != null)
             {
                 Console.WriteLine("{0}: {1}, {2}, {3}", item.DisplayName, value.Value.ToString(), value.SourceTimestamp.ToLocalTime(), value.StatusCode);
             }
             else
             {
                 Console.WriteLine("{0}: {1}, {2}, {3}", item.DisplayName, "Null Value", value.SourceTimestamp, value.StatusCode);
             }
             if (TagList.ContainsKey(item.DisplayName))
             {
                 if (value.Value != null)
                 {
                     TagList[item.DisplayName].LastGoodValue       = value.Value.ToString();
                     TagList[item.DisplayName].CurrentValue        = value.Value.ToString();
                     TagList[item.DisplayName].LastUpdatedTime     = DateTime.Now;
                     TagList[item.DisplayName].LastSourceTimeStamp = value.SourceTimestamp.ToLocalTime();
                     TagList[item.DisplayName].StatusCode          = value.StatusCode.ToString();
                 }
                 else
                 {
                     TagList[item.DisplayName].StatusCode   = value.StatusCode.ToString();
                     TagList[item.DisplayName].CurrentValue = null;
                 }
             }
         }
     }
     InitialisationCompleted = true;
 }
Example #23
0
        //private bool SetTagAddress(string address)
        //{
        //    //get Namespace
        //    string[] TagAddress = address.Split(';');
        //    if (TagAddress.Length < 2 || (address.Count(f => f == '=')!=2))
        //    {
        //        //WRONG ADDRESS TYPE
        //        IsAvailable = false;
        //        _Address = address;
        //        ClientBound.Logger?.LogException($"OPC - Tag creation error on: {this.Name} @ {this.Address}. Address must be in the format: ns=x, s=xxx");
        //        return false;
        //    }
        //    else
        //    {
        //        string[] NamespacePart = TagAddress[0].Split('=');
        //        if (NamespacePart.Length >= 2)
        //        {
        //            int NS = 0;
        //            if (Int32.TryParse(NamespacePart[1], out NS))
        //            {
        //                _NameSpaceIndex = (ushort)NS;
        //            }
        //        }
        //        string[] AddressPart = TagAddress[1].Split('=');
        //        if (AddressPart.Length >= 2)
        //        {
        //            _Address = AddressPart[1];
        //        }
        //        return true;
        //    }
        //}

        #endregion

        #region Tag Subscription

        internal void OnSubscriptionNotification(MonitoredItem item, MonitoredItemNotificationEventArgs e)
        {
            try
            {
                foreach (var value in item.DequeueValues())
                {
                    //Update tag
                    if (StatusCode.IsGood(value.StatusCode))
                    {
                        Value      = value.Value;
                        LastUpdate = value.SourceTimestamp;
                        Quality    = TagQuality.GOOD;
                        //Execute external event
                        _OnTagValueChange?.Invoke(this);
                    }
                    else
                    {
                        if (StatusCode.IsUncertain(value.StatusCode))
                        {
                            Quality = TagQuality.UNKNOWN;
                        }
                        else if (StatusCode.IsBad(value.StatusCode))
                        {
                            Quality = TagQuality.ERROR;
                        }
                        else
                        {
                            Quality = TagQuality.UNKNOWN;
                        }
                        ClientBound.Logger?.LogWarning($"OPCTag {this.Name} quality's {this.Quality}");
                    }
                }
            }
            catch (Exception ex)
            {
                ClientBound.Logger?.LogException($"OPC - Tag Subscription Error. Address: {this.Address}. Ex: {ex.Message}");
            }
        }
        /// <summary>
        /// OPC Item callback
        /// </summary>
        /// <param name="item"></param>
        /// <param name="e"></param>
        private void OnNotification(MonitoredItem item, MonitoredItemNotificationEventArgs e)
        {
            //Initialize NotificationEventArgs OPCItemDTO with MonitoredItem data
            foreach (var value in item.DequeueValues())
            {
                OPC.Helpers.NotificationEventArgs notificationEventArgs = new OPC.Helpers.NotificationEventArgs(new NotificationEvent
                {
                    Tag = item.ResolvedNodeId.ToString()
                });

                //Create list of exception
                List <Exception> exceptions = new List <Exception>();

                //Invoke OnChange Action by iterating on all subscribers event handlers
                foreach (Delegate handler in OnNotificationEventHandler.GetInvocationList())
                {
                    try
                    {
                        //pass sender object and eventArgs while
                        handler.DynamicInvoke(this, notificationEventArgs);
                    }
                    catch (Exception ex)
                    {
                        //Add exception in exception list if occured any
                        exceptions.Add(ex);
                    }
                }

                //Check if any exception occured while
                //invoking the subscribers event handlers
                if (exceptions.Any())
                {
                    //Throw aggregate exception of all exceptions
                    //occured while invoking subscribers event handlers
                    throw new AggregateException(exceptions);
                }
            }
        }
Example #25
0
        private void OnNotificationItem(MonitoredItem item, MonitoredItemNotificationEventArgs e)
        {
            DataChangeView view = new DataChangeView();

            Console.WriteLine("Sono l'item" + item.ClientHandle);


            string message = ("update: " + item.ClientHandle);

            foreach (var value in item.DequeueValues())
            {
                Console.WriteLine("{0}: {1}, {2}, {3}", item.DisplayName, value.Value, value.SourceTimestamp, value.StatusCode);
                view.ClientHandle    = item.ClientHandle;
                view.DisplayName     = item.DisplayName;
                view.Value           = value.Value.ToString();
                view.SourceTimestamp = value.SourceTimestamp.ToString();
                view.ServerTimestamp = value.ServerTimestamp.ToString();
                view.StatusCode      = value.StatusCode.ToString();


                MessagingCenter.Send <ClientOPC, DataChangeView>(this, message, view);
            }
        }
Example #26
0
        private void OnFastDataChange(Subscription subscription, DataChangeNotification notification, IList <string> stringTable)
        {
            OpcUaDeviceOutParamEntity opcUaDeviceOutParamEntity = new OpcUaDeviceOutParamEntity();

            opcUaDeviceOutParamEntity.StatusCode            = (uint)DeviceStatusCode.SubscriptionOK;
            opcUaDeviceOutParamEntity.SubScriptionValueList = new List <Tuple <string, object> >();

            foreach (MonitoredItemNotification itemNotification in notification.MonitoredItems)
            {
                MonitoredItem item = subscription.FindItemByClientHandle(itemNotification.ClientHandle);
                if (item == null)
                {
                    continue;
                }
                foreach (var value in item.DequeueValues())
                {
                    opcUaDeviceOutParamEntity.SubScriptionValueList.Add(Tuple.Create(item.ResolvedNodeId.ToString(), value.Value));
                }
            }

            DeviceEventArgs <DeviceParamEntityBase> args = new DeviceEventArgs <DeviceParamEntityBase>(opcUaDeviceOutParamEntity);

            Notification.Invoke(this, args);
        }
        private void OnMonitorNotification(MonitoredItem monitoreditem, MonitoredItemNotificationEventArgs e)
        {
            VariableNode varNode = (VariableNode)monitoreditem.Subscription.Session.ReadNode(monitoreditem.StartNodeId);

            foreach (var value in monitoreditem.DequeueValues())
            {
                Console.WriteLine("Got a value");
                var     typeManager = new DataTypeManager(monitoreditem.Subscription.Session);
                UaValue opcvalue    = typeManager.GetUaValue(varNode, value, false);

                dynamic monitorInfoPair;

                lock (_monitorPublishInfo)
                {
                    monitorInfoPair = _monitorPublishInfo
                                      .SelectMany(pair => pair.Value, (parent, child) => new { ServerUrl = parent.Key, Info = child })
                                      .First(couple => couple.Info.Subscription == monitoreditem.Subscription);
                }

                var message = $"[TOPIC: {monitorInfoPair.Info.Topic}]  \t ({monitoreditem.DisplayName}): {opcvalue.Value}";
                monitorInfoPair.Info.Forward(message);
                Console.WriteLine(message);
            }
        }
        private void OnNotification(MonitoredItem item, MonitoredItemNotificationEventArgs e)
        {
            var value = item.DequeueValues();

            TagNotification(item.DisplayName, value.First().Value);
        }
Example #29
0
            private async void OnNotification(MonitoredItem item, MonitoredItemNotificationEventArgs e)
            {
                //MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification;
                //Console.WriteLine("Notification Received for Variable \"{0}\" and Value = {1} type {2}.", item.DisplayName, notification.Value, notification.TypeId);

                foreach (var value in item.DequeueValues())
                {
                    if (value != null)
                    {
                        string tp = "unknown";

                        try
                        {
                            if (value.WrappedValue.TypeInfo != null)
                            {
                                tp = value.WrappedValue.TypeInfo.BuiltInType.ToString();
                                // Log(conn_name + " - " + item.ResolvedNodeId + "TYPE: " + tp, LogLevelDetailed);
                            }
                            else
                            {
                                Log(conn_name + " - " + item.ResolvedNodeId + " TYPE: ?????", LogLevelDetailed);
                            }

                            Log(conn_name + " - " + item.ResolvedNodeId + " " + item.DisplayName + " " + value.Value + " " + value.SourceTimestamp + " " + value.StatusCode, LogLevelDetailed);

                            if (value.Value != null)
                            {
                                Double dblValue = 0.0;
                                string strValue = "";

                                try
                                {
                                    if (tp == "Variant")
                                    {
                                        try
                                        {
                                            dblValue = System.Convert.ToDouble(value.Value);
                                        }
                                        catch
                                        {
                                            try
                                            {
                                                dblValue = System.Convert.ToInt64(value.Value);
                                            }
                                            catch
                                            {
                                                try
                                                {
                                                    dblValue = System.Convert.ToInt32(value.Value);
                                                }
                                                catch
                                                {
                                                    dblValue = 0;
                                                    try
                                                    {
                                                        var opt = new JsonSerializerOptions
                                                        {
                                                            NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.WriteAsString
                                                        };
                                                        strValue = JsonSerializer.Serialize(value.Value, opt);
                                                    }
                                                    catch
                                                    {
                                                        strValue = value.Value.ToString();
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    else
                                    if (tp == "DateTime")
                                    {
                                        dblValue = ((DateTimeOffset)System.Convert.ToDateTime(value.Value)).ToUnixTimeMilliseconds();
                                        strValue = System.Convert.ToDateTime(value.Value).ToString("o");
                                    }
                                    else
                                    {
                                        dblValue = System.Convert.ToDouble(value.Value);
                                        strValue = value.Value.ToString();
                                    }
                                }
                                catch (Exception excpt)
                                {
                                    strValue = value.Value.ToString();
                                }

                                var options = new JsonSerializerOptions
                                {
                                    NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.WriteAsString
                                };

                                OPC_Value iv =
                                    new OPC_Value()
                                {
                                    valueJson          = JsonSerializer.Serialize(value, options),
                                    selfPublish        = true,
                                    address            = item.ResolvedNodeId.ToString(),
                                    asdu               = tp,
                                    isDigital          = true,
                                    value              = dblValue,
                                    valueString        = strValue,
                                    hasSourceTimestamp = value.SourceTimestamp != DateTime.MinValue,
                                    sourceTimestamp    = value.SourceTimestamp,
                                    serverTimestamp    = DateTime.Now,
                                    quality            = StatusCode.IsGood(value.StatusCode),
                                    cot            = 3,
                                    conn_number    = conn_number,
                                    conn_name      = conn_name,
                                    common_address = "",
                                    display_name   = item.DisplayName
                                };
                                OPCDataQueue.Enqueue(iv);
                            }
                        }
                        catch (Exception excpt)
                        {
                            Log(conn_name + " - " + excpt.Message);
                            Log(conn_name + " - " + "TYPE:" + tp);
                            Log(conn_name + " - " + item.ResolvedNodeId + " " + item.DisplayName + " " + value.Value + " " + value.SourceTimestamp + " " + value.StatusCode);
                        }
                    }
                    else
                    {
                        Log(conn_name + " - " + item.ResolvedNodeId + " " + item.DisplayName + " NULL VALUE!", LogLevelDetailed);
                    }

                    Thread.Yield();
                    Thread.Sleep(1);
                    //if ((OPCDataQueue.Count % 50) == 0)
                    //{
                    //    await Task.Delay(200);
                    //}
                }
            }
Example #30
0
        private static async void OnNotification(MonitoredItem item, MonitoredItemNotificationEventArgs e)
        {
            try
            {
                foreach (var value in item.DequeueValues())
                {
                    _logger.Info("{0}: {1}, {2}, {3}, {4}", item.DisplayName, item.ResolvedNodeId, value.Value, value.SourceTimestamp, value.StatusCode);
                    Console.WriteLine("{0}: {1}, {2}, {3}, {4}", item.DisplayName, item.ResolvedNodeId, value.Value, value.SourceTimestamp, value.StatusCode);
                    if (value.WrappedValue.TypeInfo.BuiltInType == BuiltInType.Boolean)
                    {
                        if ((bool)value.Value == true)
                        {
                            var _currentoperationData = _operationTriggers.FirstOrDefault(x => x.Value.nodeId == item.ResolvedNodeId);
                            if (_currentoperationData.Key is null)
                            {
                                break;
                            }
                            var _id = _session.ReadValue(_currentoperationData.Value.nodeIdNumSet);

                            var _operation   = _currentoperationData.Key;
                            var _operationId = Int32.Parse(_id.ToString());
                            if (_operationId < 1)
                            {
                                _logger.Info("Operation: {0}; Id: {1}", _operation, _id);
                                _logger.Info("Id was less than 1");
                                return;
                            }

                            var _operationService = new OperationService(_connectionString);
                            var _schema           = new InformationSchemaDA(_connectionString);
                            var _fields           = await _schema.GetAllFieldFromTableAsync(_operation, new CancellationToken(), false);

                            var _result = await _operationService.GetDataByOpertaionTableNameAndId(_operation, _operationId, _fields.ToList(), _databaseName);

                            if (_result == null)
                            {
                                return;
                            }

                            _logger.Info("======================================//--//======================================");
                            Console.WriteLine("{0}: {1}, {2}, {3}, {4}", item.DisplayName, item.ResolvedNodeId, value.Value, value.SourceTimestamp, value.StatusCode);
                            _logger.Info("Operation: {0}; Id: {1}", _operation, _id);
                            _logger.Info("{0}: {1}, {2}, {3}, {4}", item.DisplayName, item.ResolvedNodeId, value.Value, value.SourceTimestamp, value.StatusCode);

                            var _selectedOperation = _operationTriggers.FirstOrDefault(x => 0 == string.Compare(x.Key, _operation, true));

                            foreach (var s in _selectedOperation.Value.items)
                            {
                                if (s.nodeId == null || s.nodeId == 0)
                                {
                                    continue;
                                }

                                var _node = _result.FirstOrDefault(x => 0 == string.Compare("recipe_" + _operation + "_" + x.Key, s.item, true));
                                if (_node.Key != null)
                                {
                                    var _value = OpcConverter.Convert(s.typeInfo.ToString(), _node.Value);
                                    Console.WriteLine("{0}: was updated, value:{1}", _node.Key, _value);

                                    OpcWriter.SetExpectedType(_session, s.nodeId);
                                    OpcWriter.WriteValue(_session, s.nodeId, TypeConverter.Convert(s.typeInfo.ToString(), _node.Value), TypeConverter.Convert(s.typeInfo.ToString()));
                                    _logger.Info("{0}: was updated, value:{1}", _node.Key, _value);
                                }
                            }

                            OpcWriter.SetExpectedType(_session, (_currentoperationData.Value.nodeIdNumGet));
                            OpcWriter.WriteValue(_session, _currentoperationData.Value.nodeIdNumGet, OpcConverter.Convert("long", _id.ToString()), OpcConverter.Convert("long"));
                            Console.WriteLine("Id InumGet: was updated on {0}.", _id);
                            _logger.Info("Id InumGet: was updated on {0}.", _id);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Error OnNotification method: {0}", ex.Message);
            }
        }