Esempio n. 1
0
        /// <summary>
        /// 处理OPC UA服务器重连事件
        /// </summary>
        private void Server_ReconnectComplete(object sender, EventArgs e)
        {
            OpcUaDeviceOutParamEntity opcUaDeviceOutParamEntity = new OpcUaDeviceOutParamEntity();

            try
            {
                if (!ReferenceEquals(sender, reconnectHandler))
                {
                    return;
                }

                session = reconnectHandler.Session;
                reconnectHandler.Dispose();
                reconnectHandler = null;

                opcUaDeviceOutParamEntity.StatusCode = (uint)DeviceStatusCode.ReConnOk;
            }
            catch (Exception exception)
            {
                opcUaDeviceOutParamEntity.StatusCode = (uint)DeviceStatusCode.ReConnFault;
            }

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

            Notification?.Invoke(this, args);
        }
Esempio n. 2
0
        /// <summary>
        /// 与OPC服务器断开连接
        /// </summary>
        /// <typeparam name="Tin"></typeparam>
        /// <typeparam name="Tout"></typeparam>
        /// <param name="disConnectParam"></param>
        /// <returns></returns>
        public Task <Tout> DisConnect <Tin, Tout>(Tin disConnectParam) where Tin : IDeviceParam where Tout : IDeviceParam
        {
            return(Task <Tout> .Factory.StartNew(() =>
            {
                OpcUaDeviceOutParamEntity opcUaDeviceOutParamEntity = new OpcUaDeviceOutParamEntity();

                if (session != null)
                {
                    try
                    {
                        Disconnect();
                        opcUaDeviceOutParamEntity.StatusCode = (uint)DeviceStatusCode.DisConnOk;
                        opcUaDeviceOutParamEntity.Value = "DisConnect Success";
                    }
                    catch (ServiceResultException e)
                    {
                        opcUaDeviceOutParamEntity.Value = e.LocalizedText;
                        opcUaDeviceOutParamEntity.StatusCode = e.StatusCode;
                    }
                    catch (Exception ex)
                    {
                        opcUaDeviceOutParamEntity.StatusCode = (uint)DeviceStatusCode.DisConnFault;
                        opcUaDeviceOutParamEntity.Value = "DisConnect failed";
                    }
                }

                DeviceEventArgs <DeviceParamEntityBase> args = new DeviceEventArgs <DeviceParamEntityBase>(opcUaDeviceOutParamEntity);
                Notification?.Invoke(this, args);
                return (Tout)(opcUaDeviceOutParamEntity as object);
            }));
        }
Esempio n. 3
0
        /// <summary>
        /// 从OPC服务器读取数据
        /// </summary>
        /// <typeparam name="Tin"></typeparam>
        /// <typeparam name="Tout"></typeparam>
        /// <param name="readParam"></param>
        /// <returns></returns>
        public Task <Tout> Read <Tin, Tout>(Tin readParam) where Tin : IDeviceParam where Tout : IDeviceParam
        {
            return(Task <Tout> .Factory.StartNew(() =>
            {
                var readNode = readParam as OpcUaDeviceInParamEntity;
                OpcUaDeviceOutParamEntity opcUaDeviceOutParamEntity = new OpcUaDeviceOutParamEntity();

                ReadValueId nodeToRead = new ReadValueId()
                {
                    NodeId = new NodeId(readNode.NodeId),
                    AttributeId = Attributes.Value
                };
                ReadValueIdCollection nodesToRead = new ReadValueIdCollection
                {
                    nodeToRead
                };
                try
                {
                    // read the current value
                    session.Read(
                        null,
                        0,
                        TimestampsToReturn.Neither,
                        nodesToRead,
                        out DataValueCollection results,
                        out DiagnosticInfoCollection diagnosticInfos);

                    ClientBase.ValidateResponse(results, nodesToRead);
                    ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);
                    //opcUaDeviceOutParamEntity.StatusCode = StatusCodes.Good;
                    opcUaDeviceOutParamEntity.StatusCode = (uint)DeviceStatusCode.ReadOk;
                    opcUaDeviceOutParamEntity.Value = results[0].Value;
                }
                catch (ServiceResultException e)
                {
                    opcUaDeviceOutParamEntity.Value = e.LocalizedText;
                    opcUaDeviceOutParamEntity.StatusCode = e.StatusCode;
                }
                catch (Exception ex)
                {
                    opcUaDeviceOutParamEntity.StatusCode = StatusCodes.Bad;
                    opcUaDeviceOutParamEntity.Value = null;
                    opcUaDeviceOutParamEntity.StatusCode = (uint)DeviceStatusCode.ReadFault;
                }

                DeviceEventArgs <DeviceParamEntityBase> args = new DeviceEventArgs <DeviceParamEntityBase>(opcUaDeviceOutParamEntity);
                Notification?.Invoke(this, args);

                return (Tout)(opcUaDeviceOutParamEntity as object);
            }));
        }
Esempio n. 4
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);
        }
Esempio n. 5
0
        /// <summary>
        /// 与OPC服务器建立连接
        /// </summary>
        /// <typeparam name="Tin"></typeparam>
        /// <typeparam name="Tout"></typeparam>
        /// <param name="connectParam"></param>
        /// <returns></returns>
        public Task <Tout> Connect <Tin, Tout>(Tin connectParam) where Tin : IDeviceParam where Tout : IDeviceParam
        {
            return(Task <Tout> .Factory.StartNew(() =>
            {
                OpcUaDeviceOutParamEntity opcUaDeviceOutParamEntity = new OpcUaDeviceOutParamEntity();

                try
                {
                    Task <bool> taskResult = Init();
                    if (taskResult.Result)
                    {
                        var param = connectParam as OpcUaDeviceConnectParamEntity;
                        Connect(param.DeviceUrl).Wait();
                        serverUrl = param.DeviceUrl;
                        if (Equals(session, null))
                        {
                            opcUaDeviceOutParamEntity.StatusCode = (uint)DeviceStatusCode.ConnFault;
                            opcUaDeviceOutParamEntity.Value = "Connect failed";
                        }
                        else
                        {
                            opcUaDeviceOutParamEntity.StatusCode = (uint)DeviceStatusCode.ConnOk;
                            opcUaDeviceOutParamEntity.Value = "Connect Success";
                        }
                    }
                    else
                    {
                        opcUaDeviceOutParamEntity.StatusCode = (uint)DeviceStatusCode.ConnFault;
                        opcUaDeviceOutParamEntity.Value = "Connect failed";
                    }
                }
                catch (ServiceResultException e)
                {
                    opcUaDeviceOutParamEntity.Value = e.LocalizedText;
                    opcUaDeviceOutParamEntity.StatusCode = e.StatusCode;
                }
                catch (Exception e)
                {
                    opcUaDeviceOutParamEntity.StatusCode = (uint)DeviceStatusCode.ConnFault;
                    opcUaDeviceOutParamEntity.Value = "Connect failed";
                }

                DeviceEventArgs <DeviceParamEntityBase> args = new DeviceEventArgs <DeviceParamEntityBase>(opcUaDeviceOutParamEntity);
                Notification?.Invoke(this, args);
                return (Tout)(opcUaDeviceOutParamEntity as object);
            }));
        }
Esempio n. 6
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);
        }
Esempio n. 7
0
        /// <summary>
        /// 处理心跳事件
        /// </summary>
        private void OnKeepAliveNotification(Session session, KeepAliveEventArgs e)
        {
            try
            {
                if (!ReferenceEquals(session, session))
                {
                    return;
                }

                OpcUaDeviceOutParamEntity opcUaDeviceOutParamEntity = new OpcUaDeviceOutParamEntity();

                if (ServiceResult.IsBad(e.Status))
                {
                    if (reconnectPeriod <= 0)
                    {
                        opcUaDeviceOutParamEntity.StatusCode = (uint)DeviceStatusCode.ReConnOk;
                        DeviceEventArgs <DeviceParamEntityBase> args = new DeviceEventArgs <DeviceParamEntityBase>(opcUaDeviceOutParamEntity);
                        Notification?.Invoke(this, args);
                        return;
                    }

                    if (reconnectHandler == null)
                    {
                        reconnectHandler = new SessionReconnectHandler();
                        reconnectHandler.BeginReconnect(session, reconnectPeriod * 1000, Server_ReconnectComplete);
                    }

                    return;
                }
                isConnected = true;
            }
            catch (Exception exception)
            {
                WriteLine(exception.ToString());
            }
        }
Esempio n. 8
0
        /// <summary>
        /// 创建订阅
        /// </summary>
        /// <param name="nodes"></param>
        /// <returns></returns>
        public Task <bool> CreateSubScriptions(List <NodeEntity> nodes)
        {
            return(Task.Run(() =>
            {
                if (session == null)
                {
                    return false;;
                }

                OpcUaDeviceOutParamEntity opcUaDeviceOutParamEntity = new OpcUaDeviceOutParamEntity();
                try
                {
                    List <int> intervals = nodes.Select(data => data.Interval).ToList <int>().Distinct().ToList <int>();
                    intervals.Sort();
                    foreach (int interval in intervals)
                    {
                        List <NodeEntity> subNodes = nodes.FindAll((s) => s.Interval == interval);

                        Subscription subscription;
                        if (!subscriptionDic.ContainsKey(interval))
                        {
                            subscription = new Subscription(session.DefaultSubscription);
                            session.AddSubscription(subscription);
                            subscription.Create();
                            subscriptionDic.Add(interval, subscription);
                        }
                        else
                        {
                            subscription = subscriptionDic[interval];
                        }

                        subscription.PublishingInterval = interval;
                        var monitoredItems = new List <MonitoredItem>();
                        foreach (NodeEntity entity in subNodes)
                        {
                            monitoredItems.Add(
                                new MonitoredItem(subscription.DefaultItem)
                            {
                                StartNodeId = entity.NodeId
                            }
                                );
                        }
                        ;
                        //monitoredItems.ForEach(i => i.Notification += OnMonitoredNotification);
                        if (subscription.MonitoredItemCount == 0)
                        {
                            subscription.AddItems(monitoredItems);
                            subscription.ApplyChanges();
                        }
                        else
                        {
                            subscription.RemoveItems(subscription.MonitoredItems);
                            subscription.AddItems(monitoredItems);
                            subscription.ApplyChanges();
                        }
                        subscription.FastDataChangeCallback += OnFastDataChange;
                        subscriptionDic[interval] = subscription;
                    }

                    //delete subscription
                    foreach (var data in subscriptionDic)
                    {
                        if (intervals.FindAll((s) => s == data.Key).Count() <= 0)
                        {
                            session.RemoveSubscription(subscriptionDic[data.Key]);
                        }
                    }
                }
                catch (ServiceResultException e)
                {
                    opcUaDeviceOutParamEntity.Value = e.LocalizedText;
                    opcUaDeviceOutParamEntity.StatusCode = e.StatusCode;
                    return false;
                }
                DeviceEventArgs <DeviceParamEntityBase> args = new DeviceEventArgs <DeviceParamEntityBase>(opcUaDeviceOutParamEntity);
                Notification?.Invoke(this, args);
                return true;
            }));
        }
Esempio n. 9
0
        /// <summary>
        /// 向OPC服务器写入数据
        /// </summary>
        /// <typeparam name="Tin"></typeparam>
        /// <typeparam name="Tout"></typeparam>
        /// <param name="writeParam"></param>
        /// <returns></returns>
        public Task <Tout> Write <Tin, Tout>(Tin writeParam) where Tin : IDeviceParam where Tout : IDeviceParam
        {
            return(Task <Tout> .Factory.StartNew(() =>
            {
                var writeNode = writeParam as OpcUaDeviceInParamEntity;
                OpcUaDeviceOutParamEntity opcUaDeviceOutParamEntity = new OpcUaDeviceOutParamEntity();
                WriteValue valueToWrite = new WriteValue()
                {
                    NodeId = new NodeId(writeNode.NodeId),
                    AttributeId = Attributes.Value
                };
                valueToWrite.Value.Value = Convert.ChangeType(writeNode.Value, writeNode.ValueType);
                //Type type = valueToWrite.Value.Value.GetType();
                //valueToWrite.Value.Value = Convert.ToInt16(writeNode.Value);
                valueToWrite.Value.StatusCode = StatusCodes.Good;
                valueToWrite.Value.ServerTimestamp = DateTime.MinValue;
                valueToWrite.Value.SourceTimestamp = DateTime.MinValue;

                WriteValueCollection valuesToWrite = new WriteValueCollection
                {
                    valueToWrite
                };

                try
                {
                    session.Write(
                        null,
                        valuesToWrite,
                        out StatusCodeCollection results,
                        out DiagnosticInfoCollection diagnosticInfos);

                    ClientBase.ValidateResponse(results, valuesToWrite);
                    ClientBase.ValidateDiagnosticInfos(diagnosticInfos, valuesToWrite);
                    //opcUaDeviceOutParamEntity.StatusCode = StatusCodes.Good;
                    opcUaDeviceOutParamEntity.Value = !StatusCode.IsBad(results[0]);
                    if (!StatusCode.IsBad(results[0]))
                    {
                        opcUaDeviceOutParamEntity.StatusCode = (uint)DeviceStatusCode.WriteOk;
                    }
                    else
                    {
                        opcUaDeviceOutParamEntity.StatusCode = (uint)DeviceStatusCode.WriteFault;
                    }
                }
                catch (ServiceResultException e)
                {
                    opcUaDeviceOutParamEntity.Value = e.LocalizedText;
                    opcUaDeviceOutParamEntity.StatusCode = e.StatusCode;
                }
                catch (Exception ex)
                {
                    opcUaDeviceOutParamEntity.StatusCode = StatusCodes.Bad;
                    opcUaDeviceOutParamEntity.Value = null;
                    opcUaDeviceOutParamEntity.StatusCode = (uint)DeviceStatusCode.WriteFault;
                }
                DeviceEventArgs <DeviceParamEntityBase> args = new DeviceEventArgs <DeviceParamEntityBase>(opcUaDeviceOutParamEntity);
                Notification?.Invoke(this, args);

                return (Tout)(opcUaDeviceOutParamEntity as object);
            }));
        }