Exemplo n.º 1
0
        /// <inheritdoc />
        public override void Execute(OpcSession session)
        {
            LogExecutionStart(session);
            NormalizeNodeId(session);
            // read the node info
            Node node = session.OpcUaClientSession.ReadNode(OpcUaNodeId);

            // report the node info
            Logger.Debug($"Action ({Description}) Node DisplayName is '{node.DisplayName}'");
            Logger.Debug($"Action ({Description}) Node Description is '{node.Description}'");

            // read the value
            DataValue dataValue = session.OpcUaClientSession.ReadValue(OpcUaNodeId);

            try
            {
                Value = dataValue.Value;
            }
            catch (Exception e)
            {
                Logger.Warning(e, $"Cannot convert type of read value.");
                Value = "Cannot convert type of read value.";
            }

            // report the node value
            Logger.Debug($"Action ({Description}) Node data value is '{dataValue.Value}'");
        }
Exemplo n.º 2
0
        /// <inheritdoc />
        public override void Execute(OpcSession session)
        {
            LogExecutionStart(session);
            NormalizeNodeId(session);
            // read the node info
            Node node = session.OpcUaClientSession.ReadNode(OpcUaNodeId);

            // report the node info
            Logger.Information($"Node Displayname is '{node.DisplayName}'");
            Logger.Information($"Node Description is '{node.Description}'");

            Logger.Debug($"Node id: «{node.NodeId}»; browse name: «{node.BrowseName}»; xml encoding id: «{node.XmlEncodingId}».");

            // read the value
            dataValue1 = session.OpcUaClientSession.ReadValue(node.NodeId);

            // report the node value
            Logger.Information($"Node Value is '{dataValue1.Value}'");
            Logger.Information($"Node Value is '{dataValue1}'");

            if (Program.HaveToWriteCsv)
            {
                WriteToCsvFile();
            }
        }
Exemplo n.º 3
0
        public override void Execute(OpcSession session)
        {
            LogExecutionStart(session);
            NormalizeNodeId(session);
            HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection
            {
                new HistoryReadValueId {
                    NodeId = OpcUaNodeId
                }
            };

            Opc.Ua.Client.Session uaSession = session.OpcUaClientSession;
            Logger.Debug("About to perform a HistoryRead:");
            Logger.Debug("Details:");
            Logger.Debug($"  Start time:  {details.StartTime}");
            Logger.Debug($"  End time:  {details.EndTime}");
            Logger.Debug($"  Read modified:  {details.IsReadModified}");
            Logger.Debug($"  Values per node:  {details.NumValuesPerNode}");
            Logger.Debug($"  Return bounds:  {details.ReturnBounds}");
            Logger.Debug("Nodes to read:");
            nodesToRead.ForEach(n => Logger.Debug($"  {n}({n.NodeId})"));
            uaSession.HistoryRead(
                null,
                new ExtensionObject(details),
                TimestampsToReturn.Both,
                false,
                nodesToRead,
                out HistoryReadResultCollection results,
                out DiagnosticInfoCollection diagnostics
                );
            Logger.Debug($"HistoryRead got {results.Count} results, {diagnostics.Count} diagnostics.");
            HistoryReadResult hrr      = results[0];
            HistoryData       histData = (HistoryData)ExtensionObject.ToEncodeable(hrr.HistoryData);

            if (StatusCode.IsBad(hrr.StatusCode))
            {
                Logger.Information($"Bad result ({hrr.StatusCode}) reading {OpcNodeId}");
            }
            else
            {
                if (StatusCode.IsGood(hrr.StatusCode))
                {
                    Logger.Debug($"Good result: {histData}, {histData.DataValues.Count} values.");
                }
                if (StatusCode.IsUncertain(hrr.StatusCode))
                {
                    Logger.Information($"Uncertain result: {hrr}");
                }
            }
            foreach (DataValue dv in histData.DataValues)
            {
                Logger.Debug($"  {dv} ({dv.SourceTimestamp})");
                dataValue1 = new DataValue();                 // Acá debería asignarse algo que viene desde «results».
                if (Program.HaveToWriteCsv)
                {
                    WriteDataValueToCsvFile(dv);
                }
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Shutdown all sessions.
        /// </summary>
        public async static Task SessionShutdownAsync()
        {
            if (HaveToWriteCsv)
            {
                csvWriter.Flush();
                csvWriter.Dispose();
            }

            try
            {
                while (OpcSessions.Count > 0)
                {
                    OpcSession opcSession = null;
                    try
                    {
                        await OpcSessionsListSemaphore.WaitAsync();

                        opcSession = OpcSessions.ElementAt(0);
                        OpcSessions.RemoveAt(0);
                    }
                    finally
                    {
                        OpcSessionsListSemaphore.Release();
                    }
                    await opcSession?.ShutdownAsync();
                }
            }
            catch (Exception e)
            {
                Logger.Fatal(e, "Failed to shutdown all sessions.");
            }

            // wait and continue after a while
            uint maxTries = ShutdownRetryCount;

            while (true)
            {
                int sessionCount = OpcSessions.Count;
                if (sessionCount == 0)
                {
                    return;
                }
                if (maxTries-- == 0)
                {
                    Logger.Information($"There are still {sessionCount} sessions alive. Ignore and continue shutdown.");
                    return;
                }
                Logger.Information($"{ProgramName} is shutting down. Wait {SessionConnectWait} seconds, since there are stil {sessionCount} sessions alive...");
                await Task.Delay(SessionConnectWait * 1000);
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Create the data structures to manage actions.
        /// </summary>
        public static async Task <bool> CreateOpcActionDataAsync()
        {
            try
            {
                await OpcActionListSemaphore.WaitAsync();

                await OpcSessionsListSemaphore.WaitAsync();

                // create actions out of the configuration
                var uniqueSessionInfo = _actionConfiguration.Select(n => new Tuple <Uri, bool>(n.EndpointUrl, n.UseSecurity)).Distinct();
                foreach (var sessionInfo in uniqueSessionInfo)
                {
                    // create new session info.
                    OpcSession opcSession = new OpcSession(sessionInfo.Item1, sessionInfo.Item2, OpcSessionCreationTimeout);

                    // add all actions to the session
                    List <OpcAction> actionsOnEndpoint = new List <OpcAction>();
                    var endpointConfigs = _actionConfiguration.Where(c => c.EndpointUrl == sessionInfo.Item1 && c.UseSecurity == sessionInfo.Item2);
                    foreach (var config in endpointConfigs)
                    {
                        config?.Read.ForEach(a => opcSession.OpcActions.Add(new OpcReadAction(config.EndpointUrl, a)));
                        config?.Test.ForEach(a => opcSession.OpcActions.Add(new OpcTestAction(config.EndpointUrl, a)));
                        config?.HistoryRead.ForEach(a => opcSession.OpcActions.Add(new OpcHistoryReadAction(config.EndpointUrl, a)));
                    }

                    // report actions
                    Logger.Information($"Actions on '{opcSession.EndpointUrl.AbsoluteUri}' {(opcSession.UseSecurity ? "with" : "without")} security.");
                    foreach (var action in opcSession.OpcActions)
                    {
                        Logger.Information($"{action.Description}, recurring each: {action.Interval} sec");
                    }

                    // add session
                    OpcSessions.Add(opcSession);
                }
            }
            catch (Exception e)
            {
                Logger.Fatal(e, "Error: creation of the internal OPC management structures failed. Exiting...");
                Environment.ExitCode = 1;
                return(false);
            }
            finally
            {
                OpcSessionsListSemaphore.Release();
                OpcActionListSemaphore.Release();
            }
            return(true);
        }
Exemplo n.º 6
0
 /// <summary>
 /// Execute function needs to be overloaded.
 /// </summary>
 public virtual void Execute(OpcSession session)
 {
     Logger.Error($"No Execute method for action ({Description}) defined.");
     Environment.ExitCode = 1;
     throw new Exception($"No Execute method for action ({ Description}) defined.");
 }
Exemplo n.º 7
0
 /// <summary>
 /// Generate receiver's opcUaNodeId from its opcNodeId.
 /// </summary>
 protected virtual void NormalizeNodeId(OpcSession session)
 {
     OpcUaNodeId = session.GetNodeIdFromId(OpcNodeId);
     Logger.Debug($"NodeId to query: «{OpcUaNodeId}».");
 }
Exemplo n.º 8
0
 protected virtual void LogExecutionStart(OpcSession session)
 {
     Logger.Information($"Start action {Description} on '{session.EndpointUrl}'");
     Logger.Debug($"NodeId to query: «{OpcUaNodeId}».");
 }