From 9f540eb32cbbd9d58f6020940d5d8b0afa0e7c5c Mon Sep 17 00:00:00 2001 From: Samuele Locatelli Date: Tue, 14 Dec 2021 14:50:46 +0100 Subject: [PATCH] Update metodi OpcUa x loggare eventi su NLog --- IOB-WIN-NEXT/IobGeneric.cs | 7 +- IOB-WIN-NEXT/IobOpcUa.cs | 101 ++++++++--------------- IOB-WIN-NEXT/UAClient.cs | 160 ++++++++++++++++++++++--------------- 3 files changed, 132 insertions(+), 136 deletions(-) diff --git a/IOB-WIN-NEXT/IobGeneric.cs b/IOB-WIN-NEXT/IobGeneric.cs index d67cc024..737693e3 100644 --- a/IOB-WIN-NEXT/IobGeneric.cs +++ b/IOB-WIN-NEXT/IobGeneric.cs @@ -296,10 +296,15 @@ namespace IOB_WIN_NEXT public DateTime lastSim; /// - /// dataOra ultimo segnale inviato... + /// dataOra ultimo segnale inviato al SERVER... /// public DateTime lastWatchDog; + /// + /// dataOra ultimo segnale inviato a macchina/PLC... + /// + public DateTime lastWatchDogPLC = DateTime.Now; + /// /// Massimo numero di px da inviare in blocco /// diff --git a/IOB-WIN-NEXT/IobOpcUa.cs b/IOB-WIN-NEXT/IobOpcUa.cs index 2b99086e..df9dab5e 100644 --- a/IOB-WIN-NEXT/IobOpcUa.cs +++ b/IOB-WIN-NEXT/IobOpcUa.cs @@ -303,7 +303,6 @@ namespace IOB_WIN_NEXT /// private async Task doConnect() { - IOutput console = new ConsoleOutput(); short esitoLink = 0; // reset memoria dataItem.. dataItemMem = new Dictionary(); @@ -326,7 +325,7 @@ namespace IOB_WIN_NEXT await application.CheckApplicationInstanceCertificate(silent: false, minimumKeySize: 0).ConfigureAwait(false); lgInfo($"Chiamata UAClient con configurazione standard: {application.ApplicationConfiguration.ApplicationName}"); - UA_ref = new UAClient(application.ApplicationConfiguration, console, ClientBase.ValidateResponse); + UA_ref = new UAClient(application.ApplicationConfiguration, cIobConf.codIOB, ClientBase.ValidateResponse); lgInfo($"Chiamata apertura OpcUa Client: {cIobConf.cncIpAddr}:{port}"); UA_ref.ServerUrl = $"opc.tcp://{cIobConf.cncIpAddr}:{port}"; @@ -501,33 +500,7 @@ namespace IOB_WIN_NEXT private void UA_ref_eh_MonItChange(object sender, opcUaMonitItemChange e) { checkAndSend(e.CurrMonitoredItem, $"{e.CurrNotify.Value}", false); - // se abilitato watchdog... - if (opcUaParams.WatchDog.IsEnabled) - { - // se fosse watchdog --> processo il mio... - if (e.CurrMonitoredItem.DisplayName == opcUaParams.WatchDog.MemConfRead) - { - try - { - WatchDog++; - WatchDog = WatchDog > opcUaParams.WatchDog.MaxVal ? 0 : WatchDog; - WriteValue commWriteVal = new WriteValue(); - commWriteVal.NodeId = new NodeId(opcUaParams.WatchDog.MemConfWrite); - commWriteVal.AttributeId = Attributes.Value; - commWriteVal.Value = new DataValue(); - commWriteVal.Value.Value = WatchDog; - - List nodes2Write = new List(); - nodes2Write.Add(commWriteVal); - UA_ref.WriteNodes(nodes2Write); - } - catch (Exception exc) - { - lgError($"Eccezione in gestione WatchDog, valore attuale {WatchDog}{Environment.NewLine}{exc}"); - } - } - } lastCurrent = DateTime.Now; } @@ -745,47 +718,6 @@ namespace IOB_WIN_NEXT // bit 0 (poweron) imposto a 1 SE pingo + PowerOn=="ON"... bool powerOnOk = checkPing && hasPowerOn; - // lascio attivo sulla abse solo il poweron (da verificare il resto -#if false - // procedo SOLO SE mi da ping OK... - if (checkPing) - { - B_input = powerOnOk ? 1 : 0; - - // variabili RUN... - currRun = getDataItemValue(opcUaParams.keyRunMode); - - // salvo running come = working... - isRunning = isWorking; - - // se ho emergenza premuta --> emergenza! - if (hasEStopArmed) - { - B_input += (1 << 7); - } - // se ho emergenza premuta --> emergenza! - if (isWarmUpCoolDown) - { - B_input += (1 << 6); - } - // se ho almeno 1 allarme E NON SONO IN AUTO --> ALARM! - if (hasError) - { - B_input += (1 << 3); - } - if (isWorking) - { - // RUN = LAVORA! - B_input += (1 << 1); - } - else if (powerOnOk && (!isReady || isManual)) - { - // se NON ready --> manual - B_input += (1 << 4); - } - } -#endif - // controllo se sono poweroff e se non ho dati buoni da > 2 minuti --> disconnetto if (adesso.Subtract(lastCurrent).TotalMinutes > 2) { @@ -801,6 +733,37 @@ namespace IOB_WIN_NEXT vetoCheckStatus = adesso.AddSeconds(vetoSeconds * vFactor); } + // se abilitato watchdog... + if (opcUaParams.WatchDog.IsEnabled) + { + if (adesso.Subtract(lastWatchDogPLC).TotalSeconds > 2) + { + lastWatchDogPLC = adesso; + WatchDog++; + WatchDog = WatchDog > opcUaParams.WatchDog.MaxVal ? 0 : WatchDog; + + lgInfo($"WatchDog val: {WatchDog}"); + try + { + + WriteValue commWriteVal = new WriteValue(); + commWriteVal.NodeId = new NodeId(opcUaParams.WatchDog.MemConfWrite); + commWriteVal.AttributeId = Attributes.Value; + commWriteVal.Value = new DataValue(); + commWriteVal.Value.Value = WatchDog; + + List nodes2Write = new List(); + nodes2Write.Add(commWriteVal); + UA_ref.WriteNodes(nodes2Write); + lgInfo("Effettuata scrittura WatchDog"); + } + catch (Exception exc) + { + lgError($"Eccezione in gestione WatchDog, valore attuale {WatchDog}{Environment.NewLine}{exc}"); + } + } + } + // log opzionale! if (verboseLog) { diff --git a/IOB-WIN-NEXT/UAClient.cs b/IOB-WIN-NEXT/UAClient.cs index dc99903e..fb1b58df 100644 --- a/IOB-WIN-NEXT/UAClient.cs +++ b/IOB-WIN-NEXT/UAClient.cs @@ -71,25 +71,28 @@ namespace IOB_WIN_NEXT { #region Private Fields - private readonly IOutput m_output; - + private readonly string currIob; private readonly Action m_validateResponse; - private ApplicationConfiguration m_configuration; - private Session m_session; #endregion Private Fields + #region Protected Fields + + protected static Logger lg; + + #endregion Protected Fields + #region Public Constructors /// /// Initializes a new instance of the UAClient class. /// - public UAClient(ApplicationConfiguration configuration, IOutput output, Action validateResponse) + public UAClient(ApplicationConfiguration configuration, string codIOB, Action validateResponse) { m_validateResponse = validateResponse; - m_output = output; + currIob = codIOB; m_configuration = configuration; m_configuration.CertificateValidator.CertificateValidation += CertificateValidation; } @@ -138,13 +141,13 @@ namespace IOB_WIN_NEXT ServiceResult error = e.Error; while (error != null) { - m_output.WriteLine(error); + lgError($"{error.StatusCode} | {error.Code} | {error.LocalizedText}"); error = error.InnerResult; } if (certificateAccepted) { - m_output.WriteLine("Untrusted Certificate accepted. SubjectName = {0}", e.Certificate.SubjectName); + lgInfo($"Untrusted Certificate accepted. SubjectName = {e.Certificate.SubjectName}"); } e.AcceptAll = certificateAccepted; @@ -165,16 +168,40 @@ namespace IOB_WIN_NEXT { eh_MonItChange(this, new opcUaMonitItemChange(monitoredItem, notification)); } - m_output.WriteLine("Notification Received for Variable \"{0}\" and Value = {1}.", monitoredItem.DisplayName, notification.Value); + lgInfo($"Notification Received | Variable: {monitoredItem.DisplayName} | Value: {notification.Value}"); } catch (Exception ex) { - m_output.WriteLine("OnMonitoredItemNotification error: {0}", ex.Message); + lgError($"OnMonitoredItemNotification error: {ex.Message}"); } } #endregion Private Methods + #region Protected Methods + + /// + /// Effettua logging ERROR corretto impostanto anche la variabile IOB prima di scrivere... + /// + /// + protected void lgError(string message) + { + lg.Factory.Configuration.Variables["codIOB"] = currIob; + lg.Error(message); + } + + /// + /// Effettua logging INFO corretto impostanto anche la variabile IOB prima di scrivere... + /// + /// + protected void lgInfo(string message) + { + lg.Factory.Configuration.Variables["codIOB"] = currIob; + lg.Info(message); + } + + #endregion Protected Methods + #region Public Methods /// @@ -185,7 +212,7 @@ namespace IOB_WIN_NEXT bool fatto = false; if (m_session == null || m_session.Connected == false) { - m_output.WriteLine("Session not connected!"); + lgInfo("Session not connected!"); return false; } @@ -204,15 +231,15 @@ namespace IOB_WIN_NEXT NodeId nodeToBrowse = new NodeId(startNodeVal, startNodeNS); // Call Browse service - m_output.WriteLine("Browsing {0} node...", nodeToBrowse); + lgInfo($"Browsing {nodeToBrowse} node..."); ReferenceDescriptionCollection browseResults = browser.Browse(nodeToBrowse); // Display the results - m_output.WriteLine("Browse returned {0} results:", browseResults.Count); + lgInfo($"Browse returned {browseResults.Count} results:"); foreach (ReferenceDescription result in browseResults) { - m_output.WriteLine($" NodeId = {result.NodeId}, DisplayName = {result.DisplayName.Text}, NodeClass = {result.NodeClass}, Others: {result.BinaryEncodingId} | {result.BrowseName}"); + lgInfo($" NodeId = {result.NodeId}, DisplayName = {result.DisplayName.Text}, NodeClass = {result.NodeClass}, Others: {result.BinaryEncodingId} | {result.BrowseName}"); // se NON fa parte dell'elenco dei VETO di filterItems... if (!vetoBrowse.Contains($"{result.NodeId}")) { @@ -228,7 +255,7 @@ namespace IOB_WIN_NEXT catch (Exception ex) { // Log Error - m_output.WriteLine($"Browse Error : {ex.Message}."); + lgError($"Browse Error : {ex.Message}"); } return fatto; @@ -242,7 +269,7 @@ namespace IOB_WIN_NEXT bool fatto = false; if (m_session == null || m_session.Connected == false) { - m_output.WriteLine("Session not connected!"); + lgInfo("Session not connected!"); return false; } @@ -261,22 +288,23 @@ namespace IOB_WIN_NEXT NodeId nodeToBrowse = new NodeId(browsePath); // Call Browse service - m_output.WriteLine("Browsing {0} node...", nodeToBrowse); + lgInfo($"Browsing {nodeToBrowse} node..."); ReferenceDescriptionCollection browseResults = browser.Browse(nodeToBrowse); // Display the results - m_output.WriteLine("Browse returned {0} results:", browseResults.Count); + lgInfo($"Browse returned {browseResults.Count} results:"); foreach (ReferenceDescription result in browseResults) { // se veto --> loggo veto if (vetoBrowse.Contains($"{result.NodeId}")) { - m_output.WriteLine($"| FILTERED --> NodeId = {result.NodeId}, DisplayName = {result.DisplayName.Text}, NodeClass = {result.NodeClass}, Others: {result.BinaryEncodingId} | {result.BrowseName}"); + lgInfo($"| FILTERED --> NodeId = {result.NodeId}, DisplayName = {result.DisplayName.Text}, NodeClass = {result.NodeClass}, Others: {result.BinaryEncodingId} | {result.BrowseName}"); } // se NON fa parte dell'elenco dei VETO di filterItems... - else { - m_output.WriteLine($" NodeId = {result.NodeId}, DisplayName = {result.DisplayName.Text}, NodeClass = {result.NodeClass}, Others: {result.BinaryEncodingId} | {result.BrowseName}"); + else + { + lgInfo($" NodeId = {result.NodeId}, DisplayName = {result.DisplayName.Text}, NodeClass = {result.NodeClass}, Others: {result.BinaryEncodingId} | {result.BrowseName}"); // se mancasse aggiungo... if (!nodeIdNameList.ContainsKey($"{result.NodeId}")) { @@ -284,7 +312,7 @@ namespace IOB_WIN_NEXT // se รจ un nodo object --> faccio sub browse! if (result.NodeClass != NodeClass.Variable) { - this.Browse($"{result.NodeId}",vetoBrowse, ref nodeIdNameList); + this.Browse($"{result.NodeId}", vetoBrowse, ref nodeIdNameList); } } } @@ -294,7 +322,7 @@ namespace IOB_WIN_NEXT catch (Exception ex) { // Log Error - m_output.WriteLine($"Browse Error : {ex.Message}."); + lgError($"Browse Error : {ex.Message}"); } return fatto; @@ -307,7 +335,7 @@ namespace IOB_WIN_NEXT { if (m_session == null || m_session.Connected == false) { - m_output.WriteLine("Session not connected!"); + lgInfo("Session not connected!"); return; } @@ -325,20 +353,20 @@ namespace IOB_WIN_NEXT IList outputArguments = null; // Invoke Call service - m_output.WriteLine("Calling UAMethod for node {0} ...", methodId); + lgInfo($"Calling UAMethod for node {methodId} ..."); outputArguments = m_session.Call(objectId, methodId, inputArguments); // Display results - m_output.WriteLine("Method call returned {0} output argument(s):", outputArguments.Count); + lgInfo($"Method call returned {outputArguments.Count} output argument(s):"); foreach (var outputArgument in outputArguments) { - m_output.WriteLine(" OutputValue = {0}", outputArgument.ToString()); + lgInfo($" OutputValue = {outputArgument}"); } } catch (Exception ex) { - m_output.WriteLine("Method call error: {0}", ex.Message); + lgInfo($"Method call error: {ex.Message}"); } } @@ -351,11 +379,11 @@ namespace IOB_WIN_NEXT { if (m_session != null && m_session.Connected == true) { - m_output.WriteLine("Session already connected!"); + lgInfo("Session already connected!"); } else { - m_output.WriteLine("Connecting..."); + lgInfo("Connecting..."); // Get the endpoint by connecting to server's discovery endpoint. // Try to find the first endopint without security. @@ -383,7 +411,7 @@ namespace IOB_WIN_NEXT } // Session created successfully. - m_output.WriteLine($"New Session Created with SessionName = {m_session.SessionName}"); + lgInfo($"New Session Created with SessionName = {m_session.SessionName}"); } return true; @@ -391,7 +419,7 @@ namespace IOB_WIN_NEXT catch (Exception ex) { // Log Error - m_output.WriteLine($"Create Session Error : {ex.Message}"); + lgInfo($"Create Session Error : {ex.Message}"); return false; } } @@ -405,24 +433,24 @@ namespace IOB_WIN_NEXT { if (m_session != null) { - m_output.WriteLine("Disconnecting..."); + lgInfo("Disconnecting..."); m_session.Close(); m_session.Dispose(); m_session = null; // Log Session Disconnected event - m_output.WriteLine("Session Disconnected."); + lgInfo("Session Disconnected."); } else { - m_output.WriteLine("Session not created!"); + lgInfo("Session not created!"); } } catch (Exception ex) { // Log Error - m_output.WriteLine($"Disconnect Error : {ex.Message}"); + lgInfo($"Disconnect Error : {ex.Message}"); } } @@ -436,7 +464,7 @@ namespace IOB_WIN_NEXT string answ = ""; if (m_session == null || m_session.Connected == false) { - m_output.WriteLine("Session not connected!"); + lgInfo("Session not connected!"); return answ; } @@ -456,7 +484,7 @@ namespace IOB_WIN_NEXT //}; //// Read the node attributes - //m_output.WriteLine("Reading nodes..."); + //lgInfo("Reading nodes..."); //// Call Read Service //m_session.Read( @@ -473,7 +501,7 @@ namespace IOB_WIN_NEXT //// Display the results. //foreach (DataValue result in resultsValues) //{ - // m_output.WriteLine("Read Value = {0} , StatusCode = {1}", result.Value, result.StatusCode); + // lgInfo("Read Value = {0} , StatusCode = {1}", result.Value, result.StatusCode); //} //#endregion Read a node by calling the Read Service @@ -488,7 +516,7 @@ namespace IOB_WIN_NEXT catch (Exception exc) { // Log Error - m_output.WriteLine($"ReadValue Error : {Environment.NewLine}{exc}"); + lgInfo($"ReadValue Error : {Environment.NewLine}{exc}"); } #endregion Read the Value attribute of a node by calling the Session.ReadValue method @@ -496,7 +524,7 @@ namespace IOB_WIN_NEXT catch (Exception ex) { // Log Error - m_output.WriteLine($"Read Nodes Error : {ex.Message}."); + lgInfo($"Read Nodes Error : {ex.Message}."); } return answ; } @@ -508,7 +536,7 @@ namespace IOB_WIN_NEXT { if (m_session == null || m_session.Connected == false) { - m_output.WriteLine("Session not connected!"); + lgInfo("Session not connected!"); return; } @@ -528,7 +556,7 @@ namespace IOB_WIN_NEXT }; // Read the node attributes - m_output.WriteLine("Reading nodes..."); + lgInfo("Reading nodes..."); // Call Read Service m_session.Read( @@ -545,7 +573,7 @@ namespace IOB_WIN_NEXT // Display the results. foreach (DataValue result in resultsValues) { - m_output.WriteLine("Read Value = {0} , StatusCode = {1}", result.Value, result.StatusCode); + lgInfo($"Read Value = {result.Value} , StatusCode = {result.StatusCode}"); } #endregion Read a node by calling the Read Service @@ -553,17 +581,17 @@ namespace IOB_WIN_NEXT #region Read the Value attribute of a node by calling the Session.ReadValue method // Read Server NamespaceArray - m_output.WriteLine("Reading Value of NamespaceArray node..."); + lgInfo("Reading Value of NamespaceArray node..."); DataValue namespaceArray = m_session.ReadValue(Variables.Server_NamespaceArray); // Display the result - m_output.WriteLine($"NamespaceArray Value = {namespaceArray}"); + lgInfo($"NamespaceArray Value = {namespaceArray}"); #endregion Read the Value attribute of a node by calling the Session.ReadValue method } catch (Exception ex) { // Log Error - m_output.WriteLine($"Read Nodes Error : {ex.Message}."); + lgInfo($"Read Nodes Error : {ex.Message}."); } } @@ -575,7 +603,7 @@ namespace IOB_WIN_NEXT List monItList = new List(); if (m_session == null || m_session.Connected == false) { - m_output.WriteLine("Session not connected!"); + lgInfo("Session not connected!"); return monItList; } @@ -594,7 +622,7 @@ namespace IOB_WIN_NEXT // Create the subscription on Server side subscription.Create(); - m_output.WriteLine("New Subscription created with SubscriptionId = {0}.", subscription.Id); + lgInfo($"New Subscription created with SubscriptionId = {subscription.Id}"); // Create MonitoredItems for data changes foreach (var item in DataList) @@ -689,11 +717,11 @@ namespace IOB_WIN_NEXT // Create the monitored items on Server side subscription.ApplyChanges(); - m_output.WriteLine("MonitoredItems created for SubscriptionId = {0}.", subscription.Id); + lgInfo($"MonitoredItems created for SubscriptionId = {subscription.Id}"); } catch (Exception ex) { - m_output.WriteLine("Subscribe error: {0}", ex.Message); + lgInfo($"Subscribe error: {ex.Message}"); } return monItList; } @@ -704,7 +732,7 @@ namespace IOB_WIN_NEXT { if (m_session == null || m_session.Connected == false) { - m_output.WriteLine("Session not connected!"); + lgInfo("Session not connected!"); return; } @@ -717,7 +745,7 @@ namespace IOB_WIN_NEXT // Write the node attributes StatusCodeCollection results = null; DiagnosticInfoCollection diagnosticInfos; - m_output.WriteLine("Writing nodes..."); + lgInfo("Writing nodes..."); // Call Write Service m_session.Write(null, @@ -729,17 +757,17 @@ namespace IOB_WIN_NEXT m_validateResponse(results, nodesToWrite); // Display the results. - m_output.WriteLine("Write Results :"); + lgInfo("Write Results :"); foreach (StatusCode writeResult in results) { - m_output.WriteLine(" {0}", writeResult); + lgInfo($" {writeResult}"); } } catch (Exception ex) { // Log Error - m_output.WriteLine($"Write Nodes Error : {ex.Message}."); + lgInfo($"Write Nodes Error : {ex.Message}"); } } @@ -750,7 +778,7 @@ namespace IOB_WIN_NEXT { if (m_session == null || m_session.Connected == false) { - m_output.WriteLine("Session not connected!"); + lgInfo("Session not connected!"); return; } @@ -764,7 +792,7 @@ namespace IOB_WIN_NEXT // Write the node attributes StatusCodeCollection results = null; DiagnosticInfoCollection diagnosticInfos; - m_output.WriteLine("Writing nodes..."); + lgInfo("Writing nodes..."); // Call Write Service m_session.Write(null, @@ -776,17 +804,17 @@ namespace IOB_WIN_NEXT m_validateResponse(results, nodesToWrite); // Display the results. - m_output.WriteLine("Write Results :"); + lgInfo("Write Results :"); foreach (StatusCode writeResult in results) { - m_output.WriteLine(" {0}", writeResult); + lgInfo(" {writeResult}"); } } catch (Exception ex) { // Log Error - m_output.WriteLine($"Write Nodes Error : {ex.Message}."); + lgInfo($"Write Nodes Error : {ex.Message}"); } } @@ -797,7 +825,7 @@ namespace IOB_WIN_NEXT { if (m_session == null || m_session.Connected == false) { - m_output.WriteLine("Session not connected!"); + lgInfo("Session not connected!"); return; } @@ -860,7 +888,7 @@ namespace IOB_WIN_NEXT // Write the node attributes StatusCodeCollection results = null; DiagnosticInfoCollection diagnosticInfos; - m_output.WriteLine("Writing nodes..."); + lgInfo("Writing nodes..."); // Call Write Service m_session.Write(null, @@ -872,17 +900,17 @@ namespace IOB_WIN_NEXT m_validateResponse(results, nodesToWrite); // Display the results. - m_output.WriteLine("Write Results :"); + lgInfo("Write Results :"); foreach (StatusCode writeResult in results) { - m_output.WriteLine(" {0}", writeResult); + lgInfo($" {writeResult}"); } } catch (Exception ex) { // Log Error - m_output.WriteLine($"Write Nodes Error : {ex.Message}."); + lgInfo($"Write Nodes Error : {ex.Message}."); } }