From 9874bd5d0cc30d8e4c439c7ef7c4a5cfae8e68ac Mon Sep 17 00:00:00 2001 From: Samuele Locatelli Date: Thu, 4 Nov 2021 16:12:41 +0100 Subject: [PATCH] cleanup --- .../ConsoleReferenceClient/UAClient.cs.bak | 670 --- IOB-WIN/AdapterForm.cs.bak | 1760 ------ IOB-WIN/IobGeneric.cs.bak | 4724 ----------------- IOB-WIN/IobMTC.cs.bak | 1234 ----- IOB-WIN/Objects.cs.bak | 46 - 5 files changed, 8434 deletions(-) delete mode 100644 IOB-OPC-UA/Applications/ConsoleReferenceClient/UAClient.cs.bak delete mode 100644 IOB-WIN/AdapterForm.cs.bak delete mode 100644 IOB-WIN/IobGeneric.cs.bak delete mode 100644 IOB-WIN/IobMTC.cs.bak delete mode 100644 IOB-WIN/Objects.cs.bak diff --git a/IOB-OPC-UA/Applications/ConsoleReferenceClient/UAClient.cs.bak b/IOB-OPC-UA/Applications/ConsoleReferenceClient/UAClient.cs.bak deleted file mode 100644 index 11cd47d7..00000000 --- a/IOB-OPC-UA/Applications/ConsoleReferenceClient/UAClient.cs.bak +++ /dev/null @@ -1,670 +0,0 @@ -/* ======================================================================== - * Copyright (c) 2005-2020 The OPC Foundation, Inc. All rights reserved. - * - * OPC Foundation MIT License 1.00 - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, - * copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following - * conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - * - * The complete license agreement can be found here: - * http://opcfoundation.org/License/MIT/1.00/ - * ======================================================================*/ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Threading.Tasks; -using Opc.Ua; -using Opc.Ua.Client; - -namespace Quickstarts.ConsoleReferenceClient -{ - /// - /// Evento per incapsulare dati x refresh pagina - /// - public class opcUaMonitItemChange : EventArgs - { - #region Private Fields - - /// - /// Monitored Item da notificare - /// - private readonly MonitoredItem _monitoredItem; - - /// - /// Valore notifica - /// - private readonly MonitoredItemNotification _notification; - - #endregion Private Fields - - #region Public Constructors - - /// - /// salvataggio obj - /// - /// - public opcUaMonitItemChange(MonitoredItem monitoredItem, MonitoredItemNotification notification) - { - _monitoredItem = monitoredItem; - _notification = notification; - } - - #endregion Public Constructors - - #region Public Properties - - /// - /// Proprietà lettura del MonitoredItem - /// - public MonitoredItem CurrMonitoredItem - { - get { return _monitoredItem; } - } - - /// - /// Proprietà lettura della notifica - /// - public MonitoredItemNotification CurrNotify - { - get { return _notification; } - } - - #endregion Public Properties - } - - /// - /// OPC UA Client with examples of basic functionality. - /// - internal class UAClient - { - #region Private Fields - - private readonly IOutput m_output; - - private readonly Action m_validateResponse; - - private ApplicationConfiguration m_configuration; - - private Session m_session; - - #endregion Private Fields - - #region Public Constructors - - /// - /// Initializes a new instance of the UAClient class. - /// - public UAClient(ApplicationConfiguration configuration, IOutput output, Action validateResponse) - { - m_validateResponse = validateResponse; - m_output = output; - m_configuration = configuration; - m_configuration.CertificateValidator.CertificateValidation += CertificateValidation; - } - - #endregion Public Constructors - - #region Public Events - - /// - /// Evento notifica variazione MonitoredItem - /// - public event EventHandler eh_MonItChange; - - #endregion Public Events - - #region Public Properties - - /// - /// Gets or sets the server URL. - /// - public string ServerUrl { get; set; } = "opc.tcp://localhost:62541/Quickstarts/ReferenceServer"; - - /// - /// Gets the client session. - /// - public Session Session => m_session; - - #endregion Public Properties - - #region Private Methods - - /// - /// Handles the certificate validation event. - /// This event is triggered every time an untrusted certificate is received from the server. - /// - private void CertificateValidation(CertificateValidator sender, CertificateValidationEventArgs e) - { - bool certificateAccepted = true; - - // **** - // Implement a custom logic to decide if the certificate should be - // accepted or not and set certificateAccepted flag accordingly. - // The certificate can be retrieved from the e.Certificate field - // *** - - ServiceResult error = e.Error; - while (error != null) - { - m_output.WriteLine(error); - error = error.InnerResult; - } - - if (certificateAccepted) - { - m_output.WriteLine("Untrusted Certificate accepted. SubjectName = {0}", e.Certificate.SubjectName); - } - - e.AcceptAll = certificateAccepted; - } - - /// - /// Handle DataChange notifications from Server - /// - private void OnMonitoredItemNotification(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) - { - try - { - // Log MonitoredItem Notification event - MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification; - - // sollevo evento notifica vaziazione MonitoredItem - if (eh_MonItChange != null) - { - eh_MonItChange(this, new opcUaMonitItemChange(monitoredItem, notification)); - } - m_output.WriteLine("Notification Received for Variable \"{0}\" and Value = {1}.", monitoredItem.DisplayName, notification.Value); - } - catch (Exception ex) - { - m_output.WriteLine("OnMonitoredItemNotification error: {0}", ex.Message); - } - } - - #endregion Private Methods - - #region Public Methods - - /// - /// Browse Server nodes - /// - public Dictionary Browse(ushort startNodeNS, uint startNodeVal) - { - Dictionary nodeIdNameList = new Dictionary(); - if (m_session == null || m_session.Connected == false) - { - m_output.WriteLine("Session not connected!"); - return nodeIdNameList; - } - - try - { - // Create a Browser object - Browser browser = new Browser(m_session); - - // Set browse parameters - browser.BrowseDirection = BrowseDirection.Forward; - browser.NodeClassMask = (int)NodeClass.Object | (int)NodeClass.Variable; - browser.ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences; - - //NodeId nodeToBrowse = ObjectIds.Server; - //NodeId nodeToBrowse = new NodeId("ns=4,i=5001"); - NodeId nodeToBrowse = new NodeId(startNodeVal, startNodeNS); - - // Call Browse service - m_output.WriteLine("Browsing {0} node...", nodeToBrowse); - ReferenceDescriptionCollection browseResults = browser.Browse(nodeToBrowse); - - // Display the results - m_output.WriteLine("Browse returned {0} results:", browseResults.Count); - - foreach (ReferenceDescription result in browseResults) - { - m_output.WriteLine($" NodeId = {result.NodeId}, DisplayName = {result.DisplayName.Text}, NodeClass = {result.NodeClass}, Others: {result.BinaryEncodingId} | {result.BrowseName}"); - nodeIdNameList.Add(result.NodeId.ToString(), result.DisplayName.Text); - } - } - catch (Exception ex) - { - // Log Error - m_output.WriteLine($"Browse Error : {ex.Message}."); - } - - return nodeIdNameList; - } - - /// - /// Call UA method - /// - public void CallMethod() - { - if (m_session == null || m_session.Connected == false) - { - m_output.WriteLine("Session not connected!"); - return; - } - - try - { - // Define the UA Method to call - // Parent node - Objects\CTT\Methods - // Method node - Objects\CTT\Methods\Add - NodeId objectId = new NodeId("ns=2;s=Methods"); - NodeId methodId = new NodeId("ns=2;s=Methods_Add"); - - // Define the method parameters - // Input argument requires a Float and an UInt32 value - object[] inputArguments = new object[] { (float)10.5, (uint)10 }; - IList outputArguments = null; - - // Invoke Call service - m_output.WriteLine("Calling UAMethod for node {0} ...", methodId); - outputArguments = m_session.Call(objectId, methodId, inputArguments); - - // Display results - m_output.WriteLine("Method call returned {0} output argument(s):", outputArguments.Count); - - foreach (var outputArgument in outputArguments) - { - m_output.WriteLine(" OutputValue = {0}", outputArgument.ToString()); - } - } - catch (Exception ex) - { - m_output.WriteLine("Method call error: {0}", ex.Message); - } - } - - /// - /// Creates a session with the UA server - /// - public async Task ConnectAsync() - { - try - { - if (m_session != null && m_session.Connected == true) - { - m_output.WriteLine("Session already connected!"); - } - else - { - m_output.WriteLine("Connecting..."); - - // Get the endpoint by connecting to server's discovery endpoint. - // Try to find the first endopint without security. - EndpointDescription endpointDescription = CoreClientUtils.SelectEndpoint(ServerUrl, false); - - EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(m_configuration); - ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration); - - // Create the session - Session session = await Session.Create( - m_configuration, - endpoint, - false, - false, - m_configuration.ApplicationName, - 30 * 60 * 1000, - new UserIdentity(), - null - ); - - // Assign the created session - if (session != null && session.Connected) - { - m_session = session; - } - - // Session created successfully. - m_output.WriteLine($"New Session Created with SessionName = {m_session.SessionName}"); - } - - return true; - } - catch (Exception ex) - { - // Log Error - m_output.WriteLine($"Create Session Error : {ex.Message}"); - return false; - } - } - - /// - /// Disconnects the session. - /// - public void Disconnect() - { - try - { - if (m_session != null) - { - m_output.WriteLine("Disconnecting..."); - - m_session.Close(); - m_session.Dispose(); - m_session = null; - - // Log Session Disconnected event - m_output.WriteLine("Session Disconnected."); - } - else - { - m_output.WriteLine("Session not created!"); - } - } - catch (Exception ex) - { - // Log Error - m_output.WriteLine($"Disconnect Error : {ex.Message}"); - } - } - - /// - /// Read a list of nodes from Server - /// - public void ReadNodes() - { - if (m_session == null || m_session.Connected == false) - { - m_output.WriteLine("Session not connected!"); - return; - } - - try - { - #region Read a node by calling the Read Service - - // build a list of nodes to be read - ReadValueIdCollection nodesToRead = new ReadValueIdCollection() - { - // Value of ServerStatus - new ReadValueId() { NodeId = Variables.Server_ServerStatus, AttributeId = Attributes.Value }, - // BrowseName of ServerStatus_StartTime - new ReadValueId() { NodeId = Variables.Server_ServerStatus_StartTime, AttributeId = Attributes.BrowseName }, - // Value of ServerStatus_StartTime - new ReadValueId() { NodeId = Variables.Server_ServerStatus_StartTime, AttributeId = Attributes.Value } - }; - - // Read the node attributes - m_output.WriteLine("Reading nodes..."); - - // Call Read Service - m_session.Read( - null, - 0, - TimestampsToReturn.Both, - nodesToRead, - out DataValueCollection resultsValues, - out DiagnosticInfoCollection diagnosticInfos); - - // Validate the results - m_validateResponse(resultsValues, nodesToRead); - - // Display the results. - foreach (DataValue result in resultsValues) - { - m_output.WriteLine("Read Value = {0} , StatusCode = {1}", result.Value, result.StatusCode); - } - - #endregion Read a node by calling the Read Service - - #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..."); - DataValue namespaceArray = m_session.ReadValue(Variables.Server_NamespaceArray); - // Display the result - m_output.WriteLine($"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}."); - } - } - - /// - /// Create Subscription and MonitoredItems for DataChanges - /// - public List SubscribeToDataChanges(Dictionary DataList) - { - List monItList = new List(); - if (m_session == null || m_session.Connected == false) - { - m_output.WriteLine("Session not connected!"); - return monItList; - } - - try - { - // Create a subscription for receiving data change notifications - - // Define Subscription parameters - Subscription subscription = new Subscription(m_session.DefaultSubscription); - - subscription.DisplayName = "Steamware Console Subscription"; - subscription.PublishingEnabled = true; - subscription.PublishingInterval = 1000; - - m_session.AddSubscription(subscription); - - // Create the subscription on Server side - subscription.Create(); - m_output.WriteLine("New Subscription created with SubscriptionId = {0}.", subscription.Id); - - // Create MonitoredItems for data changes - foreach (var item in DataList) - { - MonitoredItem currMonIt = new MonitoredItem(subscription.DefaultItem); - // Int32 Node - Objects\CTT\Scalar\Simulation\Int32 - currMonIt.StartNodeId = new NodeId(item.Key); - currMonIt.AttributeId = Attributes.Value; - currMonIt.DisplayName = item.Value; - currMonIt.SamplingInterval = 1000; - currMonIt.Notification += OnMonitoredItemNotification; - subscription.AddItem(currMonIt); - monItList.Add(currMonIt); - } - -#if false - MonitoredItem IO_120_00_MonitoredItem = new MonitoredItem(subscription.DefaultItem); - // Int32 Node - Objects\CTT\Scalar\Simulation\Int32 - IO_120_00_MonitoredItem.StartNodeId = new NodeId("ns=4;s=IO_120.00"); - IO_120_00_MonitoredItem.AttributeId = Attributes.Value; - IO_120_00_MonitoredItem.DisplayName = "IO_120 Variable"; - IO_120_00_MonitoredItem.SamplingInterval = 1000; - IO_120_00_MonitoredItem.Notification += OnMonitoredItemNotification; - subscription.AddItem(IO_120_00_MonitoredItem); - - MonitoredItem IO_120_01_MonitoredItem = new MonitoredItem(subscription.DefaultItem); - // Int32 Node - Objects\CTT\Scalar\Simulation\Int32 - IO_120_01_MonitoredItem.StartNodeId = new NodeId("ns=4;s=IO_120.01"); - IO_120_01_MonitoredItem.AttributeId = Attributes.Value; - IO_120_01_MonitoredItem.DisplayName = "IO_120_01 Variable"; - IO_120_01_MonitoredItem.SamplingInterval = 1000; - IO_120_01_MonitoredItem.Notification += OnMonitoredItemNotification; - subscription.AddItem(IO_120_01_MonitoredItem); - - MonitoredItem IO_130_MonitoredItem = new MonitoredItem(subscription.DefaultItem); - // Int32 Node - Objects\CTT\Scalar\Simulation\Int32 - IO_130_MonitoredItem.StartNodeId = new NodeId("ns=4;s=IO_130"); - IO_130_MonitoredItem.AttributeId = Attributes.Value; - IO_130_MonitoredItem.DisplayName = "IO_130 Variable"; - IO_130_MonitoredItem.SamplingInterval = 1000; - IO_130_MonitoredItem.Notification += OnMonitoredItemNotification; - subscription.AddItem(IO_130_MonitoredItem); - - MonitoredItem IO_135_MonitoredItem = new MonitoredItem(subscription.DefaultItem); - // Int32 Node - Objects\CTT\Scalar\Simulation\Int32 - IO_135_MonitoredItem.StartNodeId = new NodeId("ns=4;s=IO_135"); - IO_135_MonitoredItem.AttributeId = Attributes.Value; - IO_135_MonitoredItem.DisplayName = "IO_135 Variable"; - IO_135_MonitoredItem.SamplingInterval = 1000; - IO_135_MonitoredItem.Notification += OnMonitoredItemNotification; - subscription.AddItem(IO_135_MonitoredItem); - - MonitoredItem IO_140_MonitoredItem = new MonitoredItem(subscription.DefaultItem); - // Int32 Node - Objects\CTT\Scalar\Simulation\Int32 - IO_140_MonitoredItem.StartNodeId = new NodeId("ns=4;s=IO_140"); - IO_140_MonitoredItem.AttributeId = Attributes.Value; - IO_140_MonitoredItem.DisplayName = "IO_140 Variable"; - IO_140_MonitoredItem.SamplingInterval = 1000; - IO_140_MonitoredItem.Notification += OnMonitoredItemNotification; - subscription.AddItem(IO_140_MonitoredItem); - - //MonitoredItem intMonitoredItem = new MonitoredItem(subscription.DefaultItem); - //// Int32 Node - Objects\CTT\Scalar\Simulation\Int32 - //intMonitoredItem.StartNodeId = new NodeId("ns=2;s=Scalar_Simulation_Int32"); - //intMonitoredItem.AttributeId = Attributes.Value; - //intMonitoredItem.DisplayName = "Int32 Variable"; - //intMonitoredItem.SamplingInterval = 1000; - //intMonitoredItem.Notification += OnMonitoredItemNotification; - - //subscription.AddItem(intMonitoredItem); - - //MonitoredItem floatMonitoredItem = new MonitoredItem(subscription.DefaultItem); - //// Float Node - Objects\CTT\Scalar\Simulation\Float - //floatMonitoredItem.StartNodeId = new NodeId("ns=2;s=Scalar_Simulation_Float"); - //floatMonitoredItem.AttributeId = Attributes.Value; - //floatMonitoredItem.DisplayName = "Float Variable"; - //floatMonitoredItem.SamplingInterval = 1000; - //floatMonitoredItem.Notification += OnMonitoredItemNotification; - - //subscription.AddItem(floatMonitoredItem); - - //MonitoredItem stringMonitoredItem = new MonitoredItem(subscription.DefaultItem); - //// String Node - Objects\CTT\Scalar\Simulation\String - //stringMonitoredItem.StartNodeId = new NodeId("ns=2;s=Scalar_Simulation_String"); - //stringMonitoredItem.AttributeId = Attributes.Value; - //stringMonitoredItem.DisplayName = "String Variable"; - //stringMonitoredItem.SamplingInterval = 1000; - //stringMonitoredItem.Notification += OnMonitoredItemNotification; - - //subscription.AddItem(stringMonitoredItem); -#endif - - // Create the monitored items on Server side - subscription.ApplyChanges(); - m_output.WriteLine("MonitoredItems created for SubscriptionId = {0}.", subscription.Id); - } - catch (Exception ex) - { - m_output.WriteLine("Subscribe error: {0}", ex.Message); - } - return monItList; - } - - /// - /// Write a list of nodes to the Server - /// - public void WriteNodes() - { - if (m_session == null || m_session.Connected == false) - { - m_output.WriteLine("Session not connected!"); - return; - } - - try - { - // Write the configured nodes - WriteValueCollection nodesToWrite = new WriteValueCollection(); - - // Int32 Node - Objects\CTT\Scalar\Scalar_Static\Int32 - WriteValue commWriteVal = new WriteValue(); - commWriteVal.NodeId = new NodeId("ns=4;s=IO_151"); - commWriteVal.AttributeId = Attributes.Value; - commWriteVal.Value = new DataValue(); - commWriteVal.Value.Value = (int)111; - nodesToWrite.Add(commWriteVal); - - WriteValue artWriteVal = new WriteValue(); - artWriteVal.NodeId = new NodeId("ns=4;s=IO_151"); - artWriteVal.AttributeId = Attributes.Value; - artWriteVal.Value = new DataValue(); - artWriteVal.Value.Value = (int)222; - nodesToWrite.Add(artWriteVal); - - WriteValue qtyWriteVal = new WriteValue(); - qtyWriteVal.NodeId = new NodeId("ns=4;s=IO_153"); - qtyWriteVal.AttributeId = Attributes.Value; - qtyWriteVal.Value = new DataValue(); - qtyWriteVal.Value.Value = (int)333; - nodesToWrite.Add(qtyWriteVal); - - //// Int32 Node - Objects\CTT\Scalar\Scalar_Static\Int32 - //WriteValue intWriteVal = new WriteValue(); - //intWriteVal.NodeId = new NodeId("ns=2;s=Scalar_Static_Int32"); - //intWriteVal.AttributeId = Attributes.Value; - //intWriteVal.Value = new DataValue(); - //intWriteVal.Value.Value = (int)100; - //nodesToWrite.Add(intWriteVal); - - //// Float Node - Objects\CTT\Scalar\Scalar_Static\Float - //WriteValue floatWriteVal = new WriteValue(); - //floatWriteVal.NodeId = new NodeId("ns=2;s=Scalar_Static_Float"); - //floatWriteVal.AttributeId = Attributes.Value; - //floatWriteVal.Value = new DataValue(); - //floatWriteVal.Value.Value = (float)100.5; - //nodesToWrite.Add(floatWriteVal); - - //// String Node - Objects\CTT\Scalar\Scalar_Static\String - //WriteValue stringWriteVal = new WriteValue(); - //stringWriteVal.NodeId = new NodeId("ns=2;s=Scalar_Static_String"); - //stringWriteVal.AttributeId = Attributes.Value; - //stringWriteVal.Value = new DataValue(); - //stringWriteVal.Value.Value = "String Test"; - //nodesToWrite.Add(stringWriteVal); - - // Write the node attributes - StatusCodeCollection results = null; - DiagnosticInfoCollection diagnosticInfos; - m_output.WriteLine("Writing nodes..."); - - // Call Write Service - m_session.Write(null, - nodesToWrite, - out results, - out diagnosticInfos); - - // Validate the response - m_validateResponse(results, nodesToWrite); - - // Display the results. - m_output.WriteLine("Write Results :"); - - foreach (StatusCode writeResult in results) - { - m_output.WriteLine(" {0}", writeResult); - } - } - catch (Exception ex) - { - // Log Error - m_output.WriteLine($"Write Nodes Error : {ex.Message}."); - } - } - - #endregion Public Methods - } -} diff --git a/IOB-WIN/AdapterForm.cs.bak b/IOB-WIN/AdapterForm.cs.bak deleted file mode 100644 index 58d9da9b..00000000 --- a/IOB-WIN/AdapterForm.cs.bak +++ /dev/null @@ -1,1760 +0,0 @@ -using IOB_UT; -using MapoSDK; -using Newtonsoft.Json; -using NLog; -using NLog.Config; -using NLog.Targets; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Drawing; -using System.IO; -using System.Threading; -using System.Windows.Forms; - -namespace IOB_WIN -{ - public partial class AdapterForm : Form - { - #region Protected Fields - - /// - /// contatore veloce - /// - protected int fastCount; - - /// - /// Data-Ora prima apertura FORM... - /// - protected DateTime firstStart; - - /// - /// Oggetto ultimo inviato stato IOB x REDIS - /// - protected IobWinStatus lastIobStatus = new IobWinStatus(); - - /// - /// Oggetto ultimo inviato stato MP-IO x REDIS - /// - protected ServerMpStatus lastSrvStatus = new ServerMpStatus(); - - /// - /// ultimo tentativo riavvio... - /// - protected DateTime lastStartTry; - - /// - /// contatore normale - /// - protected int normCount; - - /// - /// Contatore campionamento memoria - /// - protected int sampleMemCount; - - /// - /// contatore lento - /// - protected int slowCount; - - /// - /// contatore sync allarmi - /// - protected int verySlowCount; - - /// - /// Temnpo attesa std in MS - /// - protected int waitRecMSec = 30000; - - #endregion Protected Fields - - #region Public Fields - - /// - /// oggetto logging - /// - public static Logger lg; - - /// - /// Modello macchina - /// - public string curModel = ""; - - /// - /// Vendor macchina - /// - public string curVendor = ""; - - /// - /// configurazione caricata - /// - public IobConfiguration IOBConf; - - /// - /// Oggetto x gestione dell'adapter GENERICO (x poter usare metodi di ognuno...) - /// - public IobGeneric iobObj; - - /// - /// tipo di adapter prescelto... - /// - public tipoAdapter tipoScelto = tipoAdapter.SIMULA; - - #endregion Public Fields - - #region Public Constructors - - /// - /// Avvio MainForm - /// - /// - public AdapterForm(string codIOB) - { - CurrIOB = codIOB; - // continuo avvio... - InitializeComponent(); - myGraphInitForm(); - - checkEditMes2Plc(); - - // inizializzo orologi - firstStart = DateTime.Now; - lastStartTry = DateTime.Now; - - initDatamonitor(); - - waitRecMSec = utils.CRI("waitRecMSec"); - - LogManager.ReconfigExistingLoggers(); - - lg = LogManager.GetCurrentClassLogger(); - displayTaskAndLog("MainForm Starting"); - - // se abilitato autoload conf leggo file corretto... - if (utils.CRB("autoLoadConf")) - { - try - { - loadIniFile(defConfFilePath); - lgInfo("INI LOADED"); - } - catch (Exception exc) - { - displayTaskAndLog(string.Format("Eccezione in autoLoadConf: {0}", exc)); - } - } - else - { - // definisco e avvio tipo adapter generico - tipoScelto = tipoAdapter.ND; - curVendor = "ACME"; - curModel = "NONE"; - IOBConf = new IobConfiguration(); - loadIobType(); - displayTaskAndLog("Waiting for config file selection"); - } - - // cerco tra i parametri opzionali se ho il parametro di - int timerIntMs = utils.CRI("timerIntMs"); - if (IOBConf.optPar.ContainsKey("timerIntMs")) - { - // recupero - string rawVal = IOBConf.optPar["timerIntMs"]; - if (!string.IsNullOrEmpty(rawVal)) - { - int.TryParse(rawVal, out timerIntMs); - lgInfo($"Impostato timerIntMs da IOB.ini: {timerIntMs}"); - } - } - // Start timer periodico comunicazione - gather.Interval = timerIntMs; - gather.Enabled = true; - displayTaskAndLog(string.Format("Main timer set: {0}ms", gather.Interval)); - - // Start timer periodico interfaccia - displTimer.Interval = utils.CRI("timerIntMs"); - displTimer.Enabled = true; - - displayTaskAndLog("Program Running"); - - // check oggetto not null - if (iobObj != null) - { - try - { - // verifico server online... - if (iobObj.checkServerAlive) - { - // segnalo reboot (programma)... - IobGeneric.callUrl(iobObj.urlReboot, true); - } - else - { - displayTaskAndLog("AdapterForm: Server OFFLINE"); - } - } - catch (Exception exc) - { - lgError(string.Format("AdapterForm: EXCEPTION in fase di chiamata URL di reboot:{0}{1}{2}", iobObj.urlReboot, Environment.NewLine, exc)); - } - } - displayTaskAndLog("Main Form OK"); - } - - #endregion Public Constructors - - #region Private Delegates - - private delegate void SafeCallDelegate(string text); - - #endregion Private Delegates - - #region Protected Properties - - /// - /// Valore protected comunicazione PLC - /// - protected bool _commPlcActive { get; set; } = false; - - /// - /// Valore protetto stato comunicazione - /// - protected int _commSrvActive { get; set; } = 0; - - /// - /// Valore protected semaforo IN - /// - protected Semaforo _sIN { get; set; } = Semaforo.ND; - - /// - /// Valore protected semaforo OUT - /// - protected Semaforo _sOUT { get; set; } = Semaforo.ND; - - /// - /// Codice IOB della macchina cui connettersi (x scegliere corretto file di conf...) - /// - protected string CurrIOB { get; set; } - - protected int delayShowLogMs { get; set; } = utils.CRI("delayShowLogMs"); - - /// - /// Dictionary dei divieti del datamonitor - /// - protected Dictionary dMonDisplVetoVeto { get; set; } = new Dictionary(); - - /// - /// array degli oggetti datamonitor da mostrare - /// - protected Dictionary dMonValues { get; set; } = new Dictionary(); - - /// - /// Veto a NUOVE scritture in COUNTER... - /// - protected DateTime logCounterVeto { get; set; } = DateTime.Now; - - /// - /// Stringa corrente di log... - /// - protected string logWatchString { get; set; } = ""; - - /// - /// Veto a NUOVE scritture in logWatch... - /// - protected DateTime logWatchWriteVeto { get; set; } = DateTime.Now; - - protected int maxAlQueue { get; set; } - - protected int maxEvQueue { get; set; } - - protected int maxFlQueue { get; set; } - - protected int maxMsQueue { get; set; } - - protected int qAlLen { get; set; } - - protected int qEvLen { get; set; } - - protected int qFlLen { get; set; } - - protected int qMsLen { get; set; } - - protected int totQueue - { - get - { - return qEvLen + qFlLen + qAlLen + qMsLen; - } - } - - #endregion Protected Properties - - #region Public Properties - - public int alQueueLen - { - set - { - qAlLen = value; - lblQueueAlarmLen.Text = qAlLen.ToString(); - showQueueData(); - // se supero max precedente, ed è > 10... loggo! - if (qAlLen > maxAlQueue && qAlLen > 10) - { - maxAlQueue = qAlLen; - lgInfo($"[WARN] Coda FLog di {value} record"); - } - else - { - maxAlQueue--; - maxAlQueue = maxAlQueue < qAlLen ? qAlLen : maxAlQueue; - } - } - get - { - return qAlLen; - } - } - - /// - /// Visualizzazione stato di comunicazione attiva con PLC - /// - public bool commPlcActive - { - get - { - return _commPlcActive; - } - set - { - _commPlcActive = value; - // se true --> comunica/verde, altrimenti grigio - lblCNC.ForeColor = value ? Color.SeaGreen : Color.Black; - statusStrip1.Refresh(); - } - } - - /// - /// Visualizzazione stato di comunicazione attiva con PLC: - /// 0 = NO PING - /// 1 = PING OK - /// 2 = IOB enabled - /// - public int commSrvActive - { - get - { - return _commSrvActive; - } - set - { - _commSrvActive = value; - switch (value) - { - case 0: - lblSrvUrl.ForeColor = Color.Red; - break; - - case 1: - lblSrvUrl.ForeColor = Color.OrangeRed; - break; - - case 2: - lblSrvUrl.ForeColor = Color.SeaGreen; - break; - - default: - break; - } - statusStrip1.Refresh(); - } - } - - public string counterIob - { - get - { - return lblPzCountIob.Text; - } - set - { - lblPzCountIob.Text = value; - } - } - - public string counterMac - { - get - { - return lblPzCountMac.Text; - } - set - { - lblPzCountMac.Text = value; - } - } - - /// - /// Stringa dati monitoraggio mostrata (1 SX)... - /// - public string dataMonitor_0 - { - get - { - return dMonValues[0]; - } - set - { - DateTime adesso = DateTime.Now; - // salvo nell'array... - dMonValues[0] = value; - if (dMonDisplVetoVeto[0] < adesso) - { - // se scaduto veto --> display! - lblRawData.Text = value; - // update veto! - dMonDisplVetoVeto[0] = adesso.AddMilliseconds(delayShowLogMs); - } - } - } - - /// - /// Stringa dati monitoraggio mostrata (1 SX)... - /// - public string dataMonitor_1 - { - get - { - return dMonValues[1]; - } - set - { - DateTime adesso = DateTime.Now; - // salvo nell'array... - dMonValues[1] = value; - if (dMonDisplVetoVeto[1] < adesso) - { - // se scaduto veto --> display! - lblOutMessage.Text = value; - // update veto! - dMonDisplVetoVeto[1] = adesso.AddMilliseconds(delayShowLogMs); - } - } - } - - /// - /// Stringa dati monitoraggio mostrata (2 centro)... - /// - public string dataMonitor_2 - { - get - { - return dMonValues[2]; - } - set - { - DateTime adesso = DateTime.Now; - // salvo nell'array... - dMonValues[2] = value; - if (dMonDisplVetoVeto[2] < adesso) - { - // se scaduto veto --> display! - lblOutMessage2.Text = value; - // update veto! - dMonDisplVetoVeto[2] = adesso.AddMilliseconds(delayShowLogMs); - } - } - } - - /// - /// Stringa dati monitoraggio mostrata (3 dx)... - /// - public string dataMonitor_3 - { - get - { - return dMonValues[3]; - } - set - { - DateTime adesso = DateTime.Now; - // salvo nell'array... - dMonValues[3] = value; - if (dMonDisplVetoVeto[3] < adesso) - { - // se scaduto veto --> display! - lblOutMessage3.Text = value; - // update veto! - dMonDisplVetoVeto[3] = adesso.AddMilliseconds(delayShowLogMs); - } - } - } - - /// - /// label del numero di record processati (libera) - /// - public string dataProcLabel - { - get - { - return lblDataProc.Text; - } - set - { - lblDataProc.Text = value; - } - } - - /// - /// File configurazione default - /// - public string defConfFilePath - { - get - { - return string.Format(@"{0}\{1}.ini", utils.confDir, CurrIOB); - } - } - - public bool enableEditMes2Plc { get; set; } - - public int evQueueLen - { - set - { - qEvLen = value; - lblQueueLen.Text = qEvLen.ToString(); - showQueueData(); - // se supero max precedente, ed è > 10... loggo! - if (qEvLen > maxEvQueue && qEvLen > 10) - { - maxEvQueue = qEvLen; - lgInfo($"[WARN] Coda EV di {value} record"); - } - else - { - maxEvQueue--; - maxEvQueue = maxEvQueue < qEvLen ? qEvLen : maxEvQueue; - } - } - get - { - return qEvLen; - } - } - - public int flQueueLen - { - set - { - qFlLen = value; - lblQueueFLogLen.Text = qFlLen.ToString(); - showQueueData(); - // se supero max precedente, ed è > 10... loggo! - if (qFlLen > maxFlQueue && qFlLen > 10) - { - maxFlQueue = qFlLen; - lgInfo($"[WARN] Coda FLog di {value} record"); - } - else - { - maxFlQueue--; - maxFlQueue = maxFlQueue < qFlLen ? qFlLen : maxFlQueue; - } - } - get - { - return qFlLen; - } - } - - /// - /// Log verboso da configurazione (SOLO CHAIVE "verbose"... - /// - public bool isVerboseLog { get; set; } = utils.CRB("verbose"); - - /// - /// Logwatcher (in modalità "accodamento in testa" ultimi messaggi...) - /// - public string logWatcher - { - get - { - return lblLogfile.Text; - } - set - { - try - { - logWatchString = limitLine2show($"{value}{Environment.NewLine}{logWatchString}"); - DateTime adesso = DateTime.Now; - if (logWatchWriteVeto < adesso) - { - lblLogfile.Text = logWatchString; - lblLogfile.Refresh(); - logWatchWriteVeto = adesso.AddMilliseconds(delayShowLogMs); - } - } - catch (Exception exc) - { - lgError($"Errore in esecuzione logWatcher{Environment.NewLine}--> {value}"); - if (isVerboseLog) - { - lgError($"{exc}"); - } - } - } - } - - public int msQueueLen - { - set - { - qMsLen = value; - lblQueueMessLen.Text = qMsLen.ToString(); - showQueueData(); - // se supero max precedente, ed è > 10... loggo! - if (qMsLen > maxMsQueue && qMsLen > 10) - { - maxMsQueue = qMsLen; - lgInfo($"[WARN] Coda FLog di {value} record"); - } - else - { - maxMsQueue--; - maxMsQueue = maxMsQueue < qMsLen ? qMsLen : maxMsQueue; - } - } - get - { - return qMsLen; - } - } - - /// - /// Numero max linee da mostrare (da controllo)... - /// - public int nLine2show - { - get - { - int answ = 5; - try - { - Int32.TryParse(nLines.Text, out answ); - } - catch - { } - return answ; - } - set - { - nLines.Text = value.ToString(); - } - } - - /// - /// Imposta COLORE SFONDO x Semaforo IN - /// - public Semaforo sIN - { - get - { - return _sIN; - } - set - { - _sIN = value; - var newColor = decSemaforo(value); - if (newColor != bIN.BackColor) - { - bIN.BackColor = newColor; - bIN.Refresh(); - } - } - } - - /// - /// Imposta COLORE SFONDO x Semaforo OUT - /// - public Semaforo sOUT - { - get - { - return _sOUT; - } - set - { - _sOUT = value; - var newColor = decSemaforo(value); - if (newColor != bOUT.BackColor) - { - bOUT.BackColor = newColor; - bOUT.Refresh(); - } - } - } - - /// - /// Task watcher (in modalità "accodamento in testa" ultimi messaggi...) - /// - public string taskWatcher - { - get - { - return lblTaskLog.Text; - } - set - { - try - { - lblTaskLog.Text = limitLine2show($"{value}{Environment.NewLine}{lblTaskLog.Text}"); - lblTaskLog.Refresh(); - } - catch (Exception exc) - { - lgError($"Errore in esecuzione taskWatcher{Environment.NewLine}--> {value}"); - if (isVerboseLog) - { - lgError($"{exc}"); - } - } - } - } - - #endregion Public Properties - - #region Private Methods - - private void BtnOpenLog_Click(object sender, EventArgs e) - { - try - { - string logPath = $"{System.AppDomain.CurrentDomain.BaseDirectory}logs\\{CurrIOB}\\{DateTime.Today:yyyy-MM-dd}.log"; - Process.Start(logPath); - } - catch (Exception exc) - { - lgError($"Eccezione in show log (MAIN):{Environment.NewLine}{exc}"); - } - } - - private void BtnSendPLC_Click(object sender, EventArgs e) - { - // invia a MES il parametro selezionato (es ART / ODL / PRG NAME, come task2exe..) - Dictionary forcedTask = new Dictionary(); - // guardo i parametri... - if (!string.IsNullOrEmpty(txtValue.Text)) - { - forcedTask.Add(cmbParamValues.SelectedValue.ToString(), txtValue.Text); - } - // chiedo esecuzione task! - iobObj.processTask(forcedTask); - chkEdit.Checked = false; - toggleEditMes2Plc(); - } - - private void checkEditMes2Plc() - { - cmbParamValues.Enabled = enableEditMes2Plc; - txtValue.Enabled = enableEditMes2Plc; - if (enableEditMes2Plc) - { - // aggiorno (se possibile) i parametri selezionabili... - fixComboParameters(); - } - } - - private void checkFastTask() - { - // decremento... - fastCount--; - // se il counter è a zero eseguo... - if (fastCount <= 0) - { - fastCount = utils.CRI("fastCount"); - - // avvio fase raccolta dati e invio con adapter - iobObj.getAndSend(gatherCycle.HF); - } - } - - private void checkNormTask() - { - // decremento... - normCount--; - // se il counter è a zero eseguo... - if (normCount <= 0) - { - normCount = utils.CRI("normCount"); - - // avvio fase raccolta dati e invio con adapter - iobObj.getAndSend(gatherCycle.MF); - } - } - - private void checkSampleMem() - { - // decremento contatore... - sampleMemCount--; - if (sampleMemCount <= 0) - { - sampleMemCount = utils.CRI("sampleMemCount"); - // avvio fase raccolta dati e invio con adapter - iobObj.saveMemDump(dumpType.SAMPLE); - } - } - - private void checkSendTask() - { - // avvio fase invio con adapter (code MST) - iobObj.getAndSend(gatherCycle.VHF); - } - - private void checkSlowTask() - { - slowCount--; - if (slowCount <= 0) - { - slowCount = utils.CRI("slowCount"); - - // avvio fase raccolta dati e invio con adapter - iobObj.getAndSend(gatherCycle.LF); - } - } - - private void checkVerySlowData() - { - verySlowCount--; - if (verySlowCount <= 0) - { - verySlowCount = utils.CRI("verySlowCount"); - // avvio fase raccolta dati e invio con adapter - iobObj.getAndSend(gatherCycle.VLF); - } - } - - private void ChkEdit_CheckedChanged(object sender, EventArgs e) - { - toggleEditMes2Plc(); - } - - /// - /// Chiusura adapter - /// - private void closeAdapter() - { - fermaTutto(true, false, true, false); - } - - private void displTimer_Tick(object sender, EventArgs e) - { - } - - /// - /// Ferma tutti i componenti adapter + update buttons - /// - /// indica se fermare il timer (gather) principale (solo se non si chiude) - /// indica se tentare di riconnettersi - /// indica se sia richeisto di SVUOTARE le code delel info - /// indica se si debba aggiornare la form (no se si sta chiudendo...) - private void fermaTutto(bool stopTimer, bool tryRestart, bool forceDequeue, bool updateForm) - { - iobObj.stopAdapter(tryRestart, forceDequeue); - // salvo! - savePersistLayer(utils.defPersLayerFile); - savePersistLayer(utils.histPersLayerFile); - - stop.Enabled = false; - start.Enabled = true; - restart.Enabled = false; - - if (stopTimer) - { - gather.Enabled = false; - iobObj.tryDisconnect(); - } - - newDisplayData currDispData = new newDisplayData(); - currDispData.semIn = Semaforo.SS; - currDispData.semOut = Semaforo.SS; - if (updateForm) - { - updateFormDisplay(currDispData); - } - } - - private void fixComboParameters() - { - if (iobObj != null) - { - if (iobObj.memMap != null) - { - if (iobObj.memMap.mMapWrite != null) - { - if (iobObj.memMap.mMapWrite.Count > 0) - { - var oldParams = cmbParamValues.DataSource; - List parametri = new List(); - foreach (var item in iobObj.memMap.mMapWrite) - { - parametri.Add(item.Key); - } - // salvo selezione - int oldIdx = cmbParamValues.SelectedIndex; - // riassegno e ri-seleziono - cmbParamValues.DataSource = parametri; - cmbParamValues.SelectedIndex = oldIdx >= 0 ? oldIdx : 0; ; - } - } - } - } - } - - private void gather_Tick(object sender, EventArgs e) - { - bool doLog = false; - if (iobObj != null) - { - if (iobObj.periodicLog) - { - doLog = true; - } - try - { - refreshFormData(); - // check esecuzione SendTask (VHF) COMUNQUE... - checkSendTask(); - // eseguo cicli attivi SOLO se adapter è in EFFETTIVO running... - if (iobObj.adpRunning) - { - if (iobObj.connectionOk) - { - // se richiesto faccio memory DUMP INIZIALE! - if (iobObj.doStartMemDump) - { - lgInfo("Inizio dump memoria"); - iobObj.saveMemDump(dumpType.STARTUP); - // fatto! non ripeto... - iobObj.doStartMemDump = false; - lgInfo("Finito dump memoria"); - } - // controllo se sia abilitato sampleDump della meoria (periodico) - if (iobObj.doSampleMemory) - { - checkSampleMem(); - } - // check esecuzione FastTask - checkFastTask(); - // check esecuzione NormTask - checkNormTask(); - // check esecuzione SlowTask - checkSlowTask(); - // check esecuzione AlarmSync - checkVerySlowData(); - if (utils.CRI("waitEndCycle") > 0) - { - Thread.Sleep(utils.CRI("waitEndCycle")); - } - } - else - { - DateTime dtVeto = lastStartTry.AddMilliseconds(waitRecMSec); - if (iobObj.adpTryRestart && (DateTime.Now > dtVeto)) - { - if (doLog) - { - lgInfo($"Retry Time Elapsed ({waitRecMSec} ms)--> tryConnect"); - } - lastStartTry = DateTime.Now; - iobObj.tryConnect(); - } - } - } - else - { - if (doLog) - { - lgInfo("Adapter stopped"); - } - // verifico SE debba tentare il riavvio, ovvero NON running ma adpTryRestart e non ho riprovato x oltre waitRecMSec - DateTime dtVeto = lastStartTry.AddMilliseconds(waitRecMSec); - if (iobObj.adpTryRestart && (DateTime.Now > dtVeto)) - { - lastStartTry = DateTime.Now; - avviaAdapter(chkForceDequeue.Checked); - } - } - } - catch (Exception exc) - { - lgError(string.Format("Eccezione in fase di gatherTick: {0}{1}", Environment.NewLine, exc)); - } - } - } - - /// - /// Init oggetti datamonitor - /// - private void initDatamonitor() - { - for (int i = 0; i < 4; i++) - { - dMonDisplVetoVeto.Add(i, DateTime.Now); - dMonValues.Add(i, ""); - } - } - - /// - /// GEstione evento refresh - /// - /// - /// - private void IobObj_eh_refreshed(object sender, iobRefreshedEventArgs e) - { - // aggiorno! - updateFormDisplay(e.DisplayDataObject); - } - - /// - /// Carica file ini della configurazione richiesta - /// - /// - private void loadIniFile(string iniConfFile) - { - // out di cosa faccio... - displayTaskAndLog($"[STARTUP] Loading iniConfFile: {iniConfFile}"); - // leggo file - IniFile fIni = new IniFile(iniConfFile); - - // leggo vendor e modello... - curVendor = fIni.ReadString("MACHINE", "VENDOR", "ACME"); - curModel = fIni.ReadString("MACHINE", "MODEL", "NONE"); - // verifico tipo adapter - try - { - tipoScelto = (tipoAdapter)Enum.Parse(typeof(tipoAdapter), fIni.ReadString("IOB", "CNCTYPE", "DEMO")); - } - catch (Exception exc) - { - lgError($"Eccezione in conversione tipo adapter: richiesto un tipo non codificato...{Environment.NewLine}{exc}"); - tipoScelto = tipoAdapter.ND; - } - // carivo vettore parametri opzionai - Dictionary optParRead = new Dictionary(); - string[] optParRows = fIni.ReadSection("OPTPAR"); - if (optParRows.Length > 0) - { - try - { - string[] kvp; - foreach (var item in optParRows) - { - kvp = item.Split('='); - optParRead.Add(kvp[0], kvp[1]); - } - lgInfo($"Caricati {optParRead.Count} parametri opzionali da OPTPAR"); - } - catch (Exception exc) - { - lgError(string.Format("EXCEPTION in fase di lettura OPTPAR: {0}{1}", Environment.NewLine, exc)); - } - } - // inizializzio conf IOB - IOBConf = new IobConfiguration - { - pingMsTimeout = fIni.ReadInteger("IOB", "PING_MS_TIMEOUT", 500), - vendor = curVendor, - model = curModel, - tipoIob = tipoScelto, - optPar = optParRead, - versIOB = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(), - codIOB = CurrIOB, - cncIpAddr = fIni.ReadString("CNC", "IP", "::1"), - cncPort = fIni.ReadString("CNC", "PORT", "0"), - iniFileName = iniConfFile, - cpuType = fIni.ReadString("CNC", "CPUTYPE", ""), - rack = (short)fIni.ReadInteger("CNC", "RACK", 0), - slot = (short)fIni.ReadInteger("CNC", "SLOT", 0), - serverData = new serverMapo(fIni.ReadString("SERVER", "MPIP", "::1"), fIni.ReadString("SERVER", "MPURL", "/"), fIni.ReadString("SERVER", "CMDBASE", "/"), fIni.ReadString("SERVER", "CMDFLOG", "/"), fIni.ReadString("SERVER", "CMDALIVE", "/"), fIni.ReadString("SERVER", "CMDENABLED", "/"), fIni.ReadString("SERVER", "CMDREBO", "/"), fIni.ReadString("SERVER", "CMD_ODL_STARTED", "/IOB/getCurrOdlStart/"), fIni.ReadString("SERVER", "CLI_INST", "SW_CLI"), fIni.ReadString("SERVER", "CMD_FORCLE_SPLIT_ODL", "/IOB/forceSplitOdlFull/")), - MAX_COUNTER_BLINK = Convert.ToInt32(fIni.ReadString("BLINK", "MAX_COUNTER_BLINK", "1")), - BLINK_FILT = Convert.ToInt32(fIni.ReadString("BLINK", "BLINK_FILT", "0")), - TCMaxDelayFactor = Convert.ToDouble(fIni.ReadString("OPTPAR", "TC_MAX_TC_FACTOR", "1.2").Replace(".", ",")), - TCLambda = Convert.ToDouble(fIni.ReadString("OPTPAR", "TC_LAMBDA", "0.5").Replace(".", ",")), - TCMaxIncrPz = Convert.ToDouble(fIni.ReadString("OPTPAR", "TC_MAX_INCR", "5").Replace(".", ",")) - }; - lgInfo($"Creato IOBConf!"); - - // salvo serializzando json... nella folder x Cliente oppure Vendor_Model - string confJson = JsonConvert.SerializeObject(IOBConf, Formatting.Indented); - string path = fileMover.GetExecutingDirectoryName(); // Directory.GetCurrentDirectory(); - string fileName = Path.GetFileName(iniConfFile).Replace(".ini", ".iob"); - string dirPath = $"{path}\\DATA\\{IOBConf.serverData.ClientInstall}"; - string fullPath = $"{dirPath}\\{fileName}"; - // verifica directory - Directory.CreateDirectory(dirPath); - // salvataggio - File.WriteAllText(fullPath, confJson); - - loadIobType(); - // avvio macchina con adapter specificato... - if (utils.CRB("autoStartOnLoad")) - { - displayTaskAndLog("Auto Starting..."); - // avvio! - avviaAdapter(chkForceDequeue.Checked); - displayTaskAndLog("Auto Started!"); - } - try - { - // segnalo reboot (programma)... metto in coda invio... - //iobObj.sendToMoonPro(urlType.FLog, "IOB INI Loaded"); - //iobObj.QueueFLog.Enqueue(iobObj.qEncodeFLog("IOB-STATUS", "IOB INI Loaded")); - } - catch (Exception exc) - { - lgError(string.Format("EXCEPTION in fase di chiamata URL di segnalazione caricamento INI file:{0}{1}", Environment.NewLine, exc)); - } - } - - /// - /// carica IOB richiesto - /// - private void loadIobType() - { - switch (tipoScelto) - { - case tipoAdapter.SIMULA: - iobObj = new IobSimula(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.FILE_GEN: - iobObj = new IobFile(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.FILE_EUROM63: - iobObj = new IobFileEurom63(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.FANUC: - iobObj = new IobFanuc(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.KAWASAKI: - iobObj = new IobKawasaki(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.MTConnect: - iobObj = new IobMTC(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.OMRON: - iobObj = new IobOmron(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.OSAI_OPEN: - case tipoAdapter.OSAI_CNDEX: - case tipoAdapter.OSAI_VB6: - // versione CVCncLib - iobObj = new IobOSAI(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.SIEMENS: - iobObj = new IobSiemens(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.SIEMENS_APROCHIM: - iobObj = new IobSiemensAprochim(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.SIEMENS_AT2001: - iobObj = new IobSiemensAt2001(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.SIEMENS_COMUR: - iobObj = new IobSiemensComur(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.SIEMENS_FAPE: - iobObj = new IobSiemensFape(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.SIEMENS_INGENIA: - iobObj = new IobSiemensIngenia(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.SIEMENS_LASCO: - iobObj = new IobSiemensLasco(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.SIEMENS_PRESSOIL_CEI: - iobObj = new IobSiemensPressoilCei(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.SIEMENS_SAET: - iobObj = new IobSiemensSaet(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.SIEMENS_SIMEC: - iobObj = new IobSiemensSimec(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.SIEMENS_TORRI: - iobObj = new IobSiemensTorri(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.WPS: - iobObj = new IobWPS(this, IOBConf); - start.Enabled = true; - break; - - case tipoAdapter.ND: - default: - iobObj = new IobSimula(this, IOBConf); - start.Enabled = false; - break; - } - lblCNC.Text = $"CNC: {IOBConf.tipoIob} [{IOBConf.cncIpAddr}:{IOBConf.cncPort}]"; - lblSrvUrl.Text = $"SRV: {IOBConf.serverData.MPIP} | URL: {IOBConf.serverData.MPURL}{IOBConf.serverData.CMDBASE}"; - - // aggancio evento refresh - iobObj.eh_refreshed += IobObj_eh_refreshed; - - // carico i default values su interfaccia - setDefaults(); - - displayTaskAndLog(string.Format("Caricata conf per adapter {0}", tipoScelto)); - } - - /// - /// Fase chiusura Form - /// - /// - /// - private void MainForm_FormClosing(object sender, FormClosingEventArgs e) - { - closeAdapter(); - } - - /// - /// Completato resize form - /// - /// - /// - private void MainForm_Resize(object sender, EventArgs e) - { - } - - /// - /// Mostrata form - /// - /// - /// - private void MainForm_Shown(object sender, EventArgs e) - { - displayTaskAndLog("Main Form SHOWN (Adapter)"); - } - - private void mLoadConf_Click(object sender, EventArgs e) - { - // mostro selettore file x leggere adapter.. - OpenFileDialog openFileDial = new OpenFileDialog(); - - // directory iniziale - openFileDial.InitialDirectory = utils.confDir; // string.Format(@"{0}\{1}", Application.StartupPath, utils.CRS("dataConfPath")); - // Set filter options and filter index. - openFileDial.Filter = "INI Files (.ini)|*.ini|All Files (*.*)|*.*"; - openFileDial.FilterIndex = 1; - // altre opzioni - openFileDial.Multiselect = false; - - // Call the ShowDialog method to show the dialog box. - DialogResult userClickedOK = openFileDial.ShowDialog(); - - // Process input if the user clicked OK. - if (userClickedOK == DialogResult.OK) - { - string iniConfFile = openFileDial.FileName; - loadIniFile(iniConfFile); - lgInfo("INI LOADED"); - } - } - - private void refreshFormData() - { - // aggiorno visualizzazioni varie in form... - evQueueLen = iobObj.QueueIN.Count; - flQueueLen = iobObj.QueueFLog.Count; - alQueueLen = iobObj.QueueAlarm.Count; - msQueueLen = iobObj.QueueMessages.Count; - // aggiorno labels counters... - counterIob = $"pz IOB {iobObj.contapezziIOB}"; - counterMac = $"pz PLC {iobObj.contapezziPLC}"; - // verifico IOB status - IobWinStatus currIobStatus = new IobWinStatus() - { - CodIob = iobObj.cIobConf.codIOB, - queueEvLen = evQueueLen, - queueFlLen = flQueueLen, - queueAlLen = alQueueLen, - queueMsLen = msQueueLen, - counterIOB = iobObj.contapezziIOB, - counterMAC = iobObj.contapezziPLC, - lastUpdate = lastIobStatus.lastUpdate, - online = utils.IOB_Online, - lastDataIn = iobObj.lastReadPLC - }; - // se diverso SALVO! - if (lastIobStatus.online != currIobStatus.online || lastIobStatus.lastDataIn != currIobStatus.lastDataIn || lastIobStatus.counterIOB != currIobStatus.counterIOB || lastIobStatus.counterMAC != currIobStatus.counterMAC || lastIobStatus.queueEvLen != currIobStatus.queueEvLen || lastIobStatus.queueFlLen != currIobStatus.queueFlLen || lastIobStatus.queueAlLen != currIobStatus.queueAlLen || lastIobStatus.queueMsLen != currIobStatus.queueMsLen) - { - // aggiorno data - currIobStatus.lastUpdate = DateTime.Now; - // salvo su redis e in obj corrente - iobObj.redisMan.iobStatus = currIobStatus; - lastIobStatus = currIobStatus; - } - // se diverso SALVO MP IO status - if (lastSrvStatus.online != utils.MPIO_Online) - { - // aggiorno - ServerMpStatus currSrvStatus = iobObj.redisMan.servStatus; - currSrvStatus.online = utils.MPIO_Online; - currSrvStatus.lastUpdate = DateTime.Now; - // salvo su redis e in obj corrente - iobObj.redisMan.servStatus = currSrvStatus; - lastSrvStatus = currSrvStatus; - } - } - - /// - /// Button restart - /// - /// - /// - private void restart_Click(object sender, EventArgs e) - { - string message = "Attenzione: con l'operazione di reset veranno persi (e non inviati) i dati eventualmente accumulati (indipendentemente dalla selezione del checkbox 'svuota coda')."; - string caption = "Conferma Reset Dati IOB"; - MessageBoxButtons buttons = MessageBoxButtons.YesNo; - DialogResult result; - - // verifica con messagebox - result = MessageBox.Show(message, caption, buttons); - // solo se ho conferma da utente - if (result == DialogResult.Yes) - { - // faccio stop... SENZA inviare - fermaAdapter(false, false, true); - displayTaskAndLog("RESTARTING: Adapter Stopped"); - // rileggo INI - loadIniFile(defConfFilePath); - displayTaskAndLog("RESTARTING: Ini File Reloaded"); - // faccio start... CON RESET delel code - avviaAdapter(true); - displayTaskAndLog("RESTARTING: Adapter Started"); - // resetto i data monitor... - dataMonitor_0 = ""; - dataMonitor_1 = ""; - dataMonitor_2 = ""; - dataMonitor_3 = ""; - } - } - - /// - /// impostazione valori defaults - /// - private void setDefaults() - { - stop.Enabled = false; - - evQueueLen = 0; - flQueueLen = 0; - nLine2show = utils.CRI("numRowConsole"); - } - - private void splitContainer1_Panel1_Paint(object sender, PaintEventArgs e) - { - } - - /// - /// Avvio dell'adapter - /// - /// - /// - private void start_Click(object sender, EventArgs e) - { - avviaAdapter(chkForceDequeue.Checked); - // salvo che ho avviato adapter - lgInfo("Completato LOAD Adapter"); - } - - /// - /// fermata dell'adapter - /// - /// - /// - private void stop_Click(object sender, EventArgs e) - { - fermaAdapter(false, chkForceDequeue.Checked, true); - // salvo che ho fermato adapter - lgInfo("UNLOAD Adapter"); - } - - private void TabData_Selected(object sender, TabControlEventArgs e) - { - } - - private void toggleEditMes2Plc() - { - // abilita i campi --> PLC per editing - enableEditMes2Plc = !enableEditMes2Plc; - checkEditMes2Plc(); - } - - #endregion Private Methods - - #region Protected Methods - - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - /// - /// Effettua logging ERROR corretto impostanto anche la variabile IOB prima di scrivere... - /// - /// - protected void lgError(string txt2log) - { - if (!string.IsNullOrEmpty(txt2log)) - { - lg.Factory.Configuration.Variables["codIOB"] = this.CurrIOB; - lg.Error(txt2log); - // salvo anche in logwatcher... SE non si dimostra ricorsivo... - if (!txt2log.Contains("logWatcher")) - { - newDisplayData currDispData = new newDisplayData(); - currDispData.newLiveLogData = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} | ERROR | {txt2log}"; - updateFormDisplay(currDispData); - } - } - } - - /// - /// Effettua logging INFO corretto impostanto anche la variabile IOB prima di scrivere... - /// - /// - protected void lgInfo(string txt2log) - { - lg.Factory.Configuration.Variables["codIOB"] = this.CurrIOB; - lg.Info(txt2log); - // salvo anche in logwatcher... - newDisplayData currDispData = new newDisplayData(); - currDispData.newLiveLogData = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} | INFO | {txt2log}"; - updateFormDisplay(currDispData); - } - - /// - /// Init form (grafica) con helper x testi e varie - /// - protected void myGraphInitForm() - { - lblStatus.Text = "Loading"; - - // aggiunta tooltip x send forzato - ToolTip ttForceSend = new ToolTip(); - - // imposto delay. - ttForceSend.AutoPopDelay = 3000; - ttForceSend.InitialDelay = 500; - ttForceSend.ReshowDelay = 500; - // sempre visibile (che sia o meno attiva la form). - ttForceSend.ShowAlways = true; - - // imposto tooltip - ttForceSend.SetToolTip(this.chkForceDequeue, "Forza invio eventi allo stop"); - } - - /// - /// MOstra info su coda complessiva - /// - protected void showQueueData() - { - lblQueueLenTop.Text = totQueue == 0 ? "realtime" : $"ev: {qEvLen} | flog: {qFlLen} | tot: {totQueue}"; - } - - #endregion Protected Methods - - #region Public Methods - - /// - /// Decodifica colore da valore semaforico - /// - /// - /// - public static Color decSemaforo(Semaforo valore) - { - Color colore = Color.LightGray; - switch (valore) - { - case Semaforo.SV: - colore = Color.LightGreen; - break; - - case Semaforo.SG: - colore = Color.LightGoldenrodYellow; - break; - - case Semaforo.SR: - colore = Color.Red; - break; - - case Semaforo.SS: - colore = Color.DarkGray; - break; - - default: - colore = Color.LightGray; - break; - } - return colore; - } - - /// - /// Avvio l'adapter - /// - /// indica se sia richeisto di SVUOTARE le code delel info - public void avviaAdapter(bool resetQueue) - { - displayTaskAndLog("Adapter starting"); - // se NON sta girando... - if (!iobObj.adpRunning) - { - iobObj.startAdapter(resetQueue); - displayTaskAndLog("Adapter started!"); - - // fix buttons start/stop/dump - start.Enabled = false; - stop.Enabled = true; - restart.Enabled = true; - - displayTaskAndLog("Start Timers"); - // inizializzo contatori fast/mid/slow - fastCount = utils.CRI("fastCount"); - normCount = utils.CRI("normCount"); - slowCount = utils.CRI("slowCount"); - verySlowCount = utils.CRI("verySlowCount"); - displayTaskAndLog("Adapter Running..."); - // init max queue - maxEvQueue = 1; - maxFlQueue = 1; - - try - { - // segnalo reboot (programma)... - iobObj.QueueFLog.Enqueue(iobObj.qEncodeFLog("IOB-STATUS", "IOB Started")); - } - catch (Exception exc) - { - lgError(string.Format("EXCEPTION in fase di chiamata URL di segnalazione AVVIO IOB:{0}{1}", Environment.NewLine, exc)); - } - } - else - { - displayTaskAndLog("Adapter STILL Running..."); - } - } - - /// - /// mostra un testo sulla status bar + LOG - /// - /// - public void displayTaskAndLog(string txt2show) - { - lblStatus.Text = txt2show; - lblStatus.Invalidate(); - lgInfo(txt2show); - } - - /// - /// Ferma l'adapter - /// - /// determina se si debba tentare riavvio automatico (per caduta connessione) - /// indica se sia richeisto di SVUOTARE le code delel info - /// indica se aggiornare la form prima di fermare - public void fermaAdapter(bool tryRestart, bool forceDequeue, bool updateForm) - { - fermaTutto(false, tryRestart, forceDequeue, updateForm); - } - - /// - /// Effettua un trim della stringa al numero max di linee da mostrare a video - /// - /// - /// - public string limitLine2show(string newString) - { - if (!string.IsNullOrEmpty(newString)) - { - // se num righe superiore a limite trimmo... - if (newString.Split('\n').Length > nLine2show) - { - //int idx = newString.LastIndexOf('\r'); - int idx = newString.LastIndexOf(Environment.NewLine); - newString = newString.Substring(0, idx); - } - } - return newString; - } - - /// - /// Salva su file l'oggetto di persistenza dati - /// - /// - public void savePersistLayer(string filePath) - { - // in primis check semaforo salvataggio... - if (!iobObj.adpSaving) - { - // alzo semaforo salvataggio - iobObj.adpSaving = true; - // se HO dei dati... - if (iobObj.persistenceLayer != null) - { - try - { - utils.WritePlain(iobObj.persistenceLayer, filePath); - } - catch (Exception exc) - { - lgError(string.Format("Errore salvataggio file{0}{1}", Environment.NewLine, exc)); - } - } - else - { - lgInfo("persistenceLayer null, non salvato..."); - } - // abbasso semaforo salvataggio - iobObj.adpSaving = false; - } - } - - /// - /// Mostra update delle statistiche di comunicazione (numero chiamate, tempo medio...) - /// - /// - public void updateComStats(string txt2show) - { - lblComStats.Text = string.Format("{0} | ", txt2show); - } - - /// - /// Effettua update form una volta ricevuto OBJ che contiene le varie innovazioni... - /// - /// - public void updateFormDisplay(newDisplayData currDispData) - { - // ciclo x ogni oggetto x caricare le innovazioni... - if (currDispData != null && currDispData.hasData) - { - DateTime adesso = DateTime.Now; - // RealTime display - if (!string.IsNullOrWhiteSpace(currDispData.newInData)) - { - dataMonitor_0 = limitLine2show($"{currDispData.newInData}{Environment.NewLine}{dataMonitor_0}"); - } - if (!string.IsNullOrWhiteSpace(currDispData.newSignalData)) - { - dataMonitor_1 = limitLine2show($"{currDispData.newSignalData}{Environment.NewLine}{dataMonitor_1}"); - } - if (!string.IsNullOrWhiteSpace(currDispData.newFLogData)) - { - dataMonitor_3 = limitLine2show($"{currDispData.newFLogData}{Environment.NewLine}{dataMonitor_3}"); - } - if (!string.IsNullOrWhiteSpace(currDispData.newUrlCallData)) - { - dataMonitor_2 = limitLine2show($"{currDispData.newUrlCallData}{Environment.NewLine}{dataMonitor_2}"); - } - - // Bitmap lettura attuale - if (currDispData.counter >= 0) - { - if (logCounterVeto < adesso || lblCounter.Text != $"{currDispData.counter}") - { - lblCounter.Text = $"{currDispData.counter}"; - lblCounter.Refresh(); - logCounterVeto = adesso.AddMilliseconds(delayShowLogMs); - } - } - // Bitmap lettura attuale - if (!string.IsNullOrWhiteSpace(currDispData.currBitmap)) - { - lblBitmap.Text = currDispData.currBitmap; - lblBitmap.Refresh(); - } - // LiveLog - if (!string.IsNullOrWhiteSpace(currDispData.newLiveLogData)) - { - logWatcher = currDispData.newLiveLogData; - } - // semafori - if (currDispData.semOut != Semaforo.ND) - { - // aggiorno SE diverso - if (sOUT != currDispData.semOut) - { - sOUT = currDispData.semOut; - } - } - if (currDispData.semIn != Semaforo.ND) - { - //aggiorno SE diverso - if (sIN != currDispData.semIn) - { - sIN = currDispData.semIn; - } - } - } - } - - public void WriteTextSafe(string text) - { - if (lblOutMessage3.InvokeRequired) - { - var d = new SafeCallDelegate(WriteTextSafe); - lblOutMessage3.Invoke(d, new object[] { text }); - } - else - { - lblOutMessage3.Text = text; - } - } - - #endregion Public Methods - } -} \ No newline at end of file diff --git a/IOB-WIN/IobGeneric.cs.bak b/IOB-WIN/IobGeneric.cs.bak deleted file mode 100644 index 18735688..00000000 --- a/IOB-WIN/IobGeneric.cs.bak +++ /dev/null @@ -1,4724 +0,0 @@ -using IOB_UT; -using MapoSDK; -using Newtonsoft.Json; -using NLog; -using System; -using System.Collections; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Diagnostics; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Net; -using System.Net.NetworkInformation; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using System.Windows.Forms; - -namespace IOB_WIN -{ - public class IobGeneric - { - #region Protected Fields - - /// - /// wrapper di log - /// - protected static Logger lg; - - protected bool _connOk = false; - - /// - /// valore booleano di check se sia in fase di COMUNICAZIONE ATTIVA con il PLC/NC - /// - protected bool adpCommAct; - - /// - /// porta x adapter (x restart) - /// - protected int adpPortNum; - - /// - /// DataOra ultimo avvio adapter x watchdog - /// - protected DateTime adpStartRun; - - /// - /// Vettore 32 BIT valori in ingresso al filtro - /// - protected int B_input; - - /// - /// Vettore 32 BIT valori in uscita dal filtro - /// - protected int B_output; - - /// - /// Vettore 32 BIT valori precedenti - /// - protected int B_previous; - - /// - /// Dizionario valori impostati x produzione - /// - protected Dictionary currProdData = new Dictionary(); - - /// - /// Array dei contatori x segnali blinking - /// - protected int[] i_counters; - - /// - /// Indica impianto IN SETUP (fino a quando SMETTE di esserlo...) - /// - protected bool inSetup = false; - - /// - /// ultimo tentativo connessione... - /// - protected DateTime lastConnectTry; - - /// - /// Ultimo invio contapezzi (x invio delayed) - /// - protected DateTime lastPzCountSend; - - /// - /// Dizionario ultimi valori (double) delle TSVC - /// - protected Dictionary LastTSVC = new Dictionary(); - - /// - /// Ultima registrazione warning x ODL mancante (x scrivere solo ogni 15 secondi) - /// - protected DateTime lastWarnODL; - - /// - /// indica se serva refresh parametri e quindi PLC... - /// - protected bool needRefresh = true; - - /// - /// Form chiamante - /// - protected AdapterForm parentForm; - - /// - /// TImeout x ping al server - /// - protected int pingServerMsTimeout = utils.CRI("pingMsTimeout"); - - /// - /// Ritardo minimo x invio contapezzi - /// - protected int pzCountDelay; - - /// - /// Dizionario di VC da trattare come TimeSeries (con conf decodificata + processing successivo...) - /// - protected Dictionary TSVC_Data = new Dictionary(); - - /// - /// Dizionario di VARIABILI da trattare come eventi (da inviare quando cambiano oppure a scadenza periodo...) - /// - protected Dictionary VarArray = new Dictionary(); - - #endregion Protected Fields - - #region Public Fields - - /// - /// valore booleano di check se sia stato AVVIATO l'adapter (Running) - /// - public bool adpRunning = false; - - /// - /// valore booleano di check se l'adapter STIA SALVANDO - /// - public bool adpSaving = false; - - /// - /// valore booleano (richiesta di riavvio automatico) - /// - public bool adpTryRestart; - - /// - /// Conf adapter corrente - /// - public IobConfiguration cIobConf; - - /// - /// Conteggio ATTUALE ore macchina IN LAVORO - /// - public double contOreMaccLav; - - /// - /// Conteggio ATTUALE ore macchina ON - /// - public double contOreMaccOn; - - /// - /// contatore x simulazione valori input - /// - public int countSim = 0; - - /// - /// ODL attualmente sulla macchina - /// - public Int32 currIdxODL = 0; - - /// - /// Modo corrente (da classe ENUM) - /// - public CNC_MODE currMode; - - /// - /// ODL corrente caricato sulla macchina (stringa, da chiamata MP/IO) - /// - public string currODL = ""; - - /// - /// Indica se sia richiesto campionamento memoria PERIODICO - /// - public bool doSampleMemory; - - /// - /// Indica se si debba leggere e fare DUMP delle aree di memoria (1 volta solo all'avvio x debug...) - /// - public bool doStartMemDump; - - /// - /// Data/ora ultimo avvio adapter - /// - public DateTime dtAvvioAdp = DateTime.Now; - - /// - /// Data/ora ultimo spegnimento adapter - /// - public DateTime dtStopAdp = DateTime.Now; - - /// - /// Indicazione VETO check status IOB x evitare loop troppo stretti... - /// - public DateTime dtVetoCheckIOB = DateTime.Now.AddDays(-1); - - /// - /// Abilitazione lettura PrgName - /// - public bool enablePrgName = true; - - /// - /// Abilitazione invio pezzi "in blocco" per recupero contapezzi - /// - public bool enableSendPzCountBlock = false; - - /// - /// Determina se sia encessario convertire valori little/big endian (SIEMENS=true, OSAI=FALSE) - /// - public bool hasBigEndian = false; - - /// - /// dataOra ultima verifica CNC disconnesso... - /// - public DateTime lastDisconnCheck; - - /// - /// Data/ora ultima volta che IOB è stato dichairato online - /// - public DateTime lastIobOnline = DateTime.Now.AddHours(-1); - - /// - /// dataOra ultimo log periodico... - /// - public DateTime lastPeriodicLog; - - /// - /// dataOra ultimo PING inviato verso il PLC... - /// - public DateTime lastPING; - - /// - /// DataOra ultima lettura da PLC - /// - public DateTime lastReadPLC; - - /// - /// ULtimo valore inviato (in caso di disconnessione lo reinvia x garantire watchdog...) - /// - public string lastSignInVal = ""; - - /// - /// DateTime Ultimo valore simulazione generato - /// - public DateTime lastSim; - - /// - /// dataOra ultimo segnale inviato... - /// - public DateTime lastWatchDog; - - /// - /// Massimo numero di px da inviare in blocco - /// - public int maxSendPzCountBlock = 10; - - /// - /// Struttura memoria PLC x lettura/scrittura da JSON file - /// - public plcMemMap memMap; - - /// - /// Minimo numero di px da inviare in blocco - /// - public int minSendPzCountBlock = 5; - - /// - /// Variabile booleana che indica se sia necessario fare refresh del contapezzi - /// - public bool needRefreshPzCount = true; - - /// - /// Dizionario di persistenza per i valori da salvare da/su file - /// - public Dictionary persistenceLayer; - - /// - /// Determina se utilizzare blocchi di memoria IOT contigui (e quindi processing "monoblocco" semplificato"= - /// - public bool procIotMem = false; - - /// - /// Coda valori ALLARMI ove gestiti... - /// - public ConcurrentQueue QueueAlarm = new ConcurrentQueue(); - - /// - /// Oggetto della coda degli elementi letti di tipo FluxLog (e non ancora trasmessi) - /// - public ConcurrentQueue QueueFLog = new ConcurrentQueue(); - - /// - /// Oggetto della coda degli elementi letti (e non ancora trasmessi) - /// - public ConcurrentQueue QueueIN = new ConcurrentQueue(); - - /// - /// Coda valori MESSAGGI/EVENTI (da non sottocampionare come samples)... - /// - public ConcurrentQueue QueueMessages = new ConcurrentQueue(); - - /// - /// alias booleano false = R - /// - public bool R = false; - - /// - /// 32 byte input base (es strobe, 8 word da 32 bit di flags...) - /// - public byte[] RawInput = new byte[32]; - - /// - /// 32 byte output base (es ack, 8 word da 32 bit di flags...) - /// - public byte[] RawOutput = new byte[32]; - - /// - /// Oggetto connessione REDIS - /// - public RedisIobCache redisMan; - - /// - /// Oggetto cronometro x campionamento durate chiamate - /// - public Stopwatch stopwatch = new Stopwatch(); - - /// - /// Oggetto gestione TempiCiclo e contapezzi - /// - public TCMan tcMan = new TCMan(0.5, 1.3, 5); - - /// - /// Imposta veto chiamata split (durante chiamata, per 60 sec) - /// - public DateTime vetoSplit = DateTime.Now.AddMinutes(1); - - /// - /// alias booleano true = W - /// - public bool W = true; - - #endregion Public Fields - - #region Public Constructors - - /// - /// inizializzo l'oggetto sulla form SULLA BASE DEL FILE DI CONFIGURAZIONE letto - /// - /// - /// - public IobGeneric(AdapterForm caller, IobConfiguration IOBConf) - { - if (IOBConf != null) - { - // init oggetto redis... - redisMan = new RedisIobCache(IOBConf.serverData.MPIP, IOBConf.codIOB); - - // initi oggetto TCMan - tcMan = new TCMan(IOBConf.TCLambda, IOBConf.TCMaxDelayFactor, IOBConf.TCMaxIncrPz); - - // salvo il form chiamante - parentForm = caller; - // configurazione... - cIobConf = IOBConf; - - lastConnectTry = DateTime.Now; - - // aggiungo nel logger IDX Macchina - lg = LogManager.GetCurrentClassLogger(); - - lgInfo("Avvio preliminare AdapterGeneric"); - // aggiungo altri defaults - setDefaults(true); - - setParamPlc(); - - // checkLogDir x shrink! - checkShrinkDir(); - - // concluso! - lgInfo("Istanziata classe preliminare IOBGeneric"); - } - else - { - lgError("Error: IobCOnf is null!"); - } - } - - #endregion Public Constructors - - #region Public Events - - /// - /// Evento Iob ha subito un refresh - /// - public event EventHandler eh_refreshed; - - #endregion Public Events - - #region Private Properties - - /// - /// Verifica se la IOB sia ENABLED (da server o Demo) - /// - private bool checkIobEnabled - { - get - { - bool answ = false; - // controllo se ho veto al check... - if (dtVetoCheckIOB < DateTime.Now) - { - if (DemoOut) - { - answ = (QueueIN.Count + QueueFLog.Count >= nMaxSend); - } - else - { - try - { - // chiamo URL, se restituisce "OK" è enabled! - string callResp = callUrl(urlIobEnabled, true); - answ = (callResp == "OK"); - // attesa casuale se necessario - var rand = new Random(); - // primi 2 test - int maxTry = 2; - while (maxTry > 0 && !answ) - { - Thread.Sleep(rand.Next(250, 500)); - callResp = callUrl(urlIobEnabled, true); - answ = (callResp == "OK"); - maxTry--; - } - // se NON OK riprovo ANCORA 1 volta... - if (!answ) - { - resetWebClients(); - Thread.Sleep(rand.Next(250, 1000)); - callResp = callUrl(urlIobEnabled, false); - answ = (callResp == "OK"); - } - // altri 2 - maxTry = 2; - while (maxTry > 0 && !answ) - { - Thread.Sleep(rand.Next(250, 500)); - callResp = callUrl(urlIobEnabled, false); - answ = (callResp == "OK"); - maxTry--; - } - // salvo status... - IobOnline = answ; - // se online imposto veto check a 5 x tempo reinvio... - if (answ) - { - lastIobOnline = DateTime.Now; - } - dtVetoCheckIOB = DateTime.Now.AddMilliseconds(baseUtils.nextPauseSendMSec * 5); - } - catch - { } - } - // verifico SE è variato stato online/offline... - if (IobOnline != answ) - { - // se ORA sono online riporto... - if (answ) - { - lgInfo("IOB ONLINE for server MP/IO"); - } - else - { - lgInfo("IOB OFFLINE for server MP/IO"); - } - } - // fix colore - if (answ) - { - parentForm.commSrvActive = 2; - } - else - { - parentForm.commSrvActive = 1; - } - } - else - { - // altrimenti passo ultimo valore noto - answ = IobOnline; - } - return answ; - } - } - - /// - /// test ping all'indirizzo impostato nei parametri - /// - /// - private IPStatus testPingServer - { - get - { - IPStatus answ = IPStatus.Unknown; ; - IPAddress address; - PingReply reply; - using (Ping pingSender = new Ping()) - { - address = IPAddress.Loopback; - int maxRetry = maxPingRetry + 1; - int numRetry = 1; ; - string ipAdrr = cIobConf.serverData.MPIP.Replace("http://", "").Replace("https://", ""); - IPAddress.TryParse(ipAdrr, out address); - reply = pingSender.Send(address, pingServerMsTimeout); - // se ho timeout riprovo... - while (reply.Status != IPStatus.Success && numRetry < maxRetry) - { - lgInfo($"Ping KO | reply: {reply.Status} --> retry"); - reply = pingSender.Send(address, pingServerMsTimeout * numRetry / 2); - numRetry++; - if (reply.Status == IPStatus.Success) - { - lgInfo("PING OK!"); - break; - } - } - } - answ = reply.Status; - return answ; - } - } - - #endregion Private Properties - - #region Protected Properties - - /// - /// Valore del num max invii consecutivi da coda... - /// - protected static int nMaxSend - { - get - { - int answ = 5; - try - { - answ = utils.CRI("nMaxSend"); - } - catch - { } - return answ; - } - } - - /// - /// Variabile di appoggio GLOBALE x indicare macchina RUN (es x gestione su reset pezzi) - /// - protected bool isRunning { get; set; } = false; - - /// - /// Valore limite MASSIMO di invio di dati come array Json - /// - protected int maxJsonData { get; set; } = utils.CRI("maxJsonData"); - - /// - /// Valore limite MASSIMO di invio di dati come array Json x EVENTI - /// - protected int maxJsonDataEv { get; set; } = utils.CRI("maxJsonDataEv"); - - /// - /// Max tentativi ping permessi (default: 5) - /// - protected int maxPingRetry { get; set; } = 5; - - /// - /// Coda massima ammessa per FLog (se <=0 disattivata...) - /// - protected int maxQueueFLog { get; set; } = utils.CRI("maxQueueFLog"); - - /// - /// Valore MINIMO limite x decidere invio di dati come array Json - /// - protected int minJsonData { get; set; } = utils.CRI("minJsonData"); - - /// - /// Numero letture IN da avvio - /// - protected int nReadFilt { get; set; } - - /// - /// Numero letture IN da avvio - /// - protected int nReadIN { get; set; } - - /// - /// Numero invii OUT (svuotamento coda) - /// - protected int nSendOut { get; set; } - - /// - /// Numero simulazioni ammesse... - /// - protected int numSim { get; set; } - - /// - /// Indica se sia stato resettato un contapezzi - /// - protected bool pzCountResetted { get; set; } = false; - - /// - /// Fornisce il valore letto da BITMAP in formato valido x messa in coda nel formato dtEve#value#cont - /// - protected string qEncodeIN - { - get - { - string answ = ""; - try - { - answ = string.Format("{0:yyyyMMddHHmmssfff}#{1:X2}#{2}", DateTime.Now, B_output, counterSigIN); - } - catch - { } - return answ; - } - } - - /// - /// test ping all'indirizzo PLC/CNC impostato nei parametri - /// - /// - protected IPStatus testPingMachine - { - get - { - IPStatus answ = IPStatus.Unknown; - // se disabilitato salto... - if (pingDisabled) - { - answ = IPStatus.Success; - } - else - { - IPAddress address; - PingReply reply; - using (Ping pingSender = new Ping()) - { - address = IPAddress.Loopback; - IPAddress.TryParse(cIobConf.cncIpAddr, out address); - int pingMsTimeout = cIobConf.pingMsTimeout; - reply = pingSender.Send(address, pingMsTimeout); - answ = reply.Status; - } - } - return answ; - } - } - - /// - /// Secondi standard x veto check status e log - /// - protected int vetoSeconds { get; set; } = utils.CRI("vetoSeconds"); - - #endregion Protected Properties - - #region Public Properties - - /// - /// Verifica se sia in modalità DEMO avanzata (campionamento da set di valori ammessi...) - /// - public static bool DemoInSample - { - get - { - return baseUtils.CRB("DemoInSample"); - } - } - - /// - /// Verifica se sia in modalità DEMO x dati OUTPUT - /// - public static bool DemoOut - { - get - { - return utils.CRB("DemoOut"); - } - } - - /// - /// Indicazione VETO PING a server sino alla data-ora indicata - /// - public static DateTime dtVetoPing - { - get - { - return utils.dtVetoPing; - } - set - { - utils.dtVetoPing = value; - } - } - - /// - /// Indicazione VETO invio a server sino alla data-ora indicata - /// - public static DateTime dtVetoSend - { - get - { - return utils.dtVetoSend; - } - set - { - utils.dtVetoSend = value; - } - } - - /// - /// stato Online/Offline del server MP IO (su REDIS) - /// - public static bool MPOnline - { - get - { - return utils.MPIO_Online; - } - set - { - utils.MPIO_Online = value; - } - } - - /// - /// Verifica se il server sia ALIVE (tramite PING) - /// - public bool checkServerAlive - { - get - { - bool answ = false; - // controllo se ho un VETO all'invio... - if (dtVetoPing < DateTime.Now) - { - if (DemoOut) - { - answ = false; - } - else - { - IPStatus pingStatus = testPingServer; - // se passa il ping faccio il resto... - if (pingStatus == IPStatus.Success) - { - string callResp = ""; - try - { - // chiamo URL, se restituisce "OK" è alive! - callResp = callUrl(urlAlive, false); - answ = (callResp == "OK"); - } - catch (Exception exc) - { - lgError("Errore in checkServerAlive:{0}{1}", Environment.NewLine, exc); - } - // attesa casuale se necessario - var rand = new Random(); - // primi 3 test - int maxTry = 3; - while (maxTry > 0 && !answ) - { - try - { - Thread.Sleep(rand.Next(150, 500)); - callResp = callUrl(urlAlive, false); - answ = (callResp == "OK"); - maxTry--; - } - catch - { } - } - // se NON OK riprovo ANCORA 1 volta... - if (!answ) - { - resetWebClients(); - Thread.Sleep(rand.Next(500, 1000)); - callResp = callUrl(urlAlive, false); - answ = (callResp == "OK"); - } - // altri 3 - maxTry = 3; - while (maxTry > 0 && !answ) - { - try - { - Thread.Sleep(rand.Next(150, 500)); - callResp = callUrl(urlAlive, false); - answ = (callResp == "OK"); - maxTry--; - } - catch - { } - } - // verifico SE è variato stato online/offline... - if (MPOnline != answ) - { - // se ORA sono online riporto... - if (answ) - { - lgInfo("SERVER ONLINE in checkServerAlive"); - parentForm.commSrvActive = 1; - dtVetoPing = DateTime.Now.AddMilliseconds(baseUtils.nextPauseSendMSec); - } - else - { - lgInfo("SERVER OFFLINE in checkServerAlive"); - parentForm.commSrvActive = 0; - } - // salvo nuovo status... - MPOnline = answ; - } - else - { - // allungo periodo controllo... - dtVetoPing = DateTime.Now.AddMilliseconds(baseUtils.nextPauseSendMSec * 3); - } - } - else - { - lgInfo($"SERVER NOT RESPONDING (PING at {cIobConf.serverData.MPIP})"); - MPOnline = false; - // imposto veto a 10 volte reinvio dati standard... - dtVetoPing = DateTime.Now.AddMilliseconds(baseUtils.nextPauseSendMSec * 3); - utils.dtVetoSend = dtVetoPing; - } - } - } - else - { - // altrimenti passo ultimo valore noto... - answ = MPOnline; - } - return answ; - } - } - - /// - /// Salva verifica stato connessione OK - /// - /// - public virtual bool connectionOk - { - get - { - return _connOk || DemoIn; - } - set - { - _connOk = value; - } - } - - /// - /// Contapezzi attuale - /// - public Int32 contapezziIOB - { - get - { - return tcMan.pzCountIOB; - } - set - { - tcMan.pzCountIOB = value; - } - } - - /// - /// Ultima lettura variabile contapezzi da CNC - /// - public Int32 contapezziPLC - { - get - { - return tcMan.pzCountPLC; - } - set - { - tcMan.pzCountPLC = value; - } - } - - /// - /// Contatore x invio dati FluxLog - /// - public int counterFLog { get; set; } - - /// - /// Contatore x invio dati SignalIN - /// - public int counterSigIN { get; set; } - - /// - /// Verifica se sia in modalità DEMO --> da tipo IOB SIMULA... - /// - public bool DemoIn - { - get - { - return (cIobConf.tipoIob == tipoAdapter.SIMULA);// baseUtils.CRB("DemoIn"); - } - } - - /// - /// Indica lo stato Online/Offline della IOB - /// - public bool IobOnline - { - get - { - return utils.IOB_Online; - } - set - { - utils.IOB_Online = value; - } - } - - /// - /// Verifica se sia macchina multi = DoppioPallet da CONF - /// - public bool isMulti - { - get - { - bool answ = false; - if (cIobConf.optPar.Count > 0) - { - // cerco con chiave reale IS_MULTI - string keyName = "IS_MULTI"; - if (!cIobConf.optPar.ContainsKey(keyName)) - { - // legacy: accetto anche SIM_MULTI... - keyName = "SIM_MULTI"; - } - // vera verifica su chaive... - if (cIobConf.optPar.ContainsKey(keyName)) - { - string SIM_MULTI = getOptPar(keyName); - answ = SIM_MULTI == "1"; - } - } - return answ; - } - } - - /// - /// Log verboso da configurazione (SOLO CHAIVE "verbose"... - /// - public bool isVerboseLog { get; set; } = utils.CRB("verbose"); - - /// - /// Ultimo Alarm letto - /// - public string lastAlarm { get; set; } - - /// - /// Ultimo ARRAY DynData letto - /// - public Dictionary lastDynData { get; set; } = new Dictionary(); - - /// - /// Ultimo DynData (sunto) letto - /// - public string lastDynDataCtrlVal { get; set; } - - /// - /// Ultimo Override set letto - /// - public string lastOverrideFS { get; set; } - - /// - /// Ultimo Override set letto - /// - public string lastOverrideRapid { get; set; } - - /// - /// Ultimo programma letto - /// - public string lastPrgName { get; set; } - - /// - /// Ultimo SysInfo letto - /// - public string lastSysInfo { get; set; } - - /// - /// Ultimo URL - /// - public string lastUrl { get; set; } - - /// - /// Valore massimo accettato x incremento pezzi letti dal PLC (valore moltiplicato per 100... 200% --> 200) - /// - public int maxPzDeltaPerc - { - get - { - int answ = 250; - if (cIobConf.optPar.Count > 0) - { - // cerco con chiave MAX_PZ_INCR_PERC - string keyName = "MAX_PZ_INCR_PERC"; - // vera verifica su chaive... - if (cIobConf.optPar.ContainsKey(keyName)) - { - string MAX_PZ_INCR_PERC = getOptPar(keyName); - if (!int.TryParse(MAX_PZ_INCR_PERC, out answ)) - { - answ = 300; - } - } - } - return answ; - } - } - - /// - /// Verifica SE si debba fare log periodico (ogni "verboseLogTOut" sec...) - /// - public bool periodicLog - { - get - { - bool answ = false; - answ = (DateTime.Now.Subtract(lastPeriodicLog).TotalSeconds > utils.CRI("verboseLogTOut")); - if (answ) - { - lastPeriodicLog = DateTime.Now; - } - - return answ; - } - } - - /// - /// indica se ping disabilitato da optPar - /// - public bool pingDisabled - { - get - { - bool answ = false; - bool.TryParse(getOptPar("NO_PING"), out answ); - return answ; - } - } - - /// - /// DataOra dell'ultima lettura variabile contapezzi da CNC in secondi - /// - public double plcAvgTc - { - get - { - double answ = tcMan.avgTC > 0 ? tcMan.avgTC : 1; - return answ; - } - } - - /// - /// DataOra dell'ultima lettura variabile contapezzi da CNC - /// - public DateTime plcLastPzRead - { - get - { - return tcMan.lastObservedData; - } - } - - /// - /// URL per INVIO IN BLOCCO di un INCREMENTO x contapezzi (quelli della macchina: PLC/CNC)... - /// - public string urlAddPzCount - { - get - { - string answ = ""; - try - { - answ = string.Format(@"http://{0}{1}{2}/savePzCountInc/{3}?qty=", cIobConf.serverData.MPIP, cIobConf.serverData.MPURL, cIobConf.serverData.CMDALIVE, cIobConf.codIOB); - } - catch (Exception exc) - { - lgError(exc, "Errore in composizione urlAddPzCount"); - } - return answ; - } - } - - /// - /// URL per check alive... - /// - public string urlAlive - { - get - { - return string.Format(@"http://{0}{1}{2}", cIobConf.serverData.MPIP, cIobConf.serverData.MPURL, cIobConf.serverData.CMDALIVE); - } - } - - /// - /// URL per forzare split ODL... - /// - public string urlForceSplit - { - get - { - return string.Format(@"http://{0}{1}{2}{3}?doConfirm=true&qtyFromLast=true&roundStep=500", cIobConf.serverData.MPIP, cIobConf.serverData.MPURL, cIobConf.serverData.CMD_FORCLE_SPLIT_ODL, cIobConf.codIOB); - } - } - - /// - /// URL per salvataggio contapezzi... - /// - public string urlGetCurrODL - { - get - { - string answ = ""; - try - { - answ = string.Format(@"http://{0}{1}{2}/getCurrODL/{3}", cIobConf.serverData.MPIP, cIobConf.serverData.MPURL, cIobConf.serverData.CMDALIVE, cIobConf.codIOB); - } - catch (Exception exc) - { - lgError(exc, "Errore in composizione urlGetCurrODL"); - } - return answ; - } - } - - /// - /// URL per richiamo parametri da scrivere... - /// - public string urlGetParams2Write - { - get - { - string answ = ""; - try - { - answ = string.Format(@"http://{0}{1}{2}/getObjItems2Write/{3}", cIobConf.serverData.MPIP, cIobConf.serverData.MPURL, cIobConf.serverData.CMDALIVE, cIobConf.codIOB); - } - catch (Exception exc) - { - lgError(exc, "Errore in composizione urlGetParams2Write"); - } - return answ; - } - } - - /// - /// URL per recupero contapezzi... - /// - public string urlGetPzCount - { - get - { - string answ = ""; - try - { - answ = $@"http://{cIobConf.serverData.MPIP}{cIobConf.serverData.MPURL}{cIobConf.serverData.CMDALIVE}/getCounter/{cIobConf.codIOB}"; - } - catch (Exception exc) - { - lgError(exc, "Errore in composizione urlGetPzCount"); - } - return answ; - } - } - - /// - /// URL per recupero contapezzi REGISTRATI da TC... - /// - public string urlGetPzCountRec - { - get - { - string answ = ""; - try - { - answ = $@"http://{cIobConf.serverData.MPIP}{cIobConf.serverData.MPURL}{cIobConf.serverData.CMDALIVE}/getCounterTCRec/{cIobConf.codIOB}"; - } - catch (Exception exc) - { - lgError(exc, "Errore in composizione urlGetPzCountRec"); - } - return answ; - } - } - - /// - /// URL per richiamo task da eseguire... - /// - public string urlGetTask2Exe - { - get - { - string answ = ""; - try - { - answ = string.Format(@"http://{0}{1}{2}/getTask2Exe/{3}", cIobConf.serverData.MPIP, cIobConf.serverData.MPURL, cIobConf.serverData.CMDALIVE, cIobConf.codIOB); - } - catch (Exception exc) - { - lgError(exc, "Errore in composizione urlGetTask2Exe"); - } - return answ; - } - } - - /// - /// URL per recupero idle time IOB... - /// - public string urlIdleTime - { - get - { - return string.Format(@"http://{0}{1}{2}{3}", cIobConf.serverData.MPIP, cIobConf.serverData.MPURL, cIobConf.serverData.CMD_IDLE_TIME, cIobConf.codIOB); - } - } - - /// - /// URL per recupero inizio ODL... - /// - public string urlInizioOdlIob - { - get - { - return string.Format(@"http://{0}{1}{2}{3}", cIobConf.serverData.MPIP, cIobConf.serverData.MPURL, cIobConf.serverData.CMD_ODL_STARTED, cIobConf.codIOB); - } - } - - /// - /// URL per check se abilitato... - /// - public string urlIobEnabled - { - get - { - return string.Format(@"http://{0}{1}{2}{3}", cIobConf.serverData.MPIP, cIobConf.serverData.MPURL, cIobConf.serverData.CMDENABLED, cIobConf.codIOB); - } - } - - /// - /// URL per segnalazione reboot... - /// - public string urlReboot - { - get - { - string answ = ""; - try - { - answ = string.Format(@"http://{0}{1}{2}{3}&mac={4}", cIobConf.serverData.MPIP, cIobConf.serverData.MPURL, cIobConf.serverData.CMDREBO, cIobConf.codIOB, GetMACAddress()); - } - catch - { - answ = string.Format(@"http://{0}{1}{2}{3}", cIobConf.serverData.MPIP, cIobConf.serverData.MPURL, cIobConf.serverData.CMDREBO, cIobConf.codIOB); - } - return answ; - } - } - - /// - /// URL per richiamo task da eseguire... - /// - public string urlRemTask2Exe - { - get - { - string answ = ""; - try - { - answ = string.Format(@"http://{0}{1}{2}/remTask2Exe/{3}?taskName=", cIobConf.serverData.MPIP, cIobConf.serverData.MPURL, cIobConf.serverData.CMDALIVE, cIobConf.codIOB); - } - catch (Exception exc) - { - lgError(exc, "Errore in composizione urlRemTask2Exe"); - } - return answ; - } - } - - /// - /// URL per salvataggio dati PARAMETRI IOB... - /// - public string urlSaveAllParams - { - get - { - string answ = ""; - try - { - string machineName = Environment.MachineName; - string apiCall = "setObjItems"; - answ = string.Format(@"http://{0}{1}{2}/{3}/{4}", cIobConf.serverData.MPIP, cIobConf.serverData.MPURL, cIobConf.serverData.CMDALIVE, apiCall, cIobConf.codIOB); - } - catch (Exception exc) - { - lgError(exc, "Errore in composizione urlSaveMemConf"); - } - return answ; - } - } - - /// - /// URL per salvataggio dati conf memoria IOB... - /// - public string urlSaveMemMap - { - get - { - string answ = ""; - try - { - string machineName = Environment.MachineName; - answ = string.Format(@"http://{0}{1}{2}/saveConf/{3}", cIobConf.serverData.MPIP, cIobConf.serverData.MPURL, cIobConf.serverData.CMDALIVE, cIobConf.codIOB); - } - catch (Exception exc) - { - lgError(exc, "Errore in composizione urlSaveMemConf"); - } - return answ; - } - } - - /// - /// URL per salvataggio dati associazione Machine 2 IOB... - /// - public string urlSetM2IOB - { - get - { - string answ = ""; - try - { - string machineName = Environment.MachineName; - answ = string.Format(@"http://{0}{1}{2}/setM2IOB/{3}?IOB_name={4}", cIobConf.serverData.MPIP, cIobConf.serverData.MPURL, cIobConf.serverData.CMDALIVE, cIobConf.codIOB, machineName); - } - catch (Exception exc) - { - lgError(exc, "Errore in composizione urlSetM2IOB"); - } - return answ; - } - } - - /// - /// URL per salvataggio VALORI opzionali... - /// - public string urlSetOptVal - { - get - { - string answ = ""; - try - { - answ = string.Format(@"http://{0}{1}{2}/addOptPar/{3}?", cIobConf.serverData.MPIP, cIobConf.serverData.MPURL, cIobConf.serverData.CMDALIVE, cIobConf.codIOB); - } - catch (Exception exc) - { - lgError(exc, "Errore in composizione urlSetOptVal"); - } - return answ; - } - } - - /// - /// URL per salvataggio contapezzi... - /// - public string urlSetPzCount - { - get - { - string answ = ""; - try - { - answ = $@"http://{cIobConf.serverData.MPIP}{cIobConf.serverData.MPURL}{cIobConf.serverData.CMDALIVE}/setCounter/{cIobConf.codIOB}?counter="; - } - catch (Exception exc) - { - lgError(exc, "Errore in composizione urlSetPzCount"); - } - return answ; - } - } - - /// - /// URL per salvataggio contapezzi (quelli della macchina: PLC/CNC)... - /// - public string urlSetPzCountMAC - { - get - { - string answ = ""; - try - { - answ = $@"http://{cIobConf.serverData.MPIP}{cIobConf.serverData.MPURL}{cIobConf.serverData.CMDALIVE}/setCounter/MAC_{cIobConf.codIOB}?counter="; - } - catch (Exception exc) - { - lgError(exc, "Errore in composizione urlSetPzCountMAC"); - } - return answ; - } - } - - /// - /// URL per salvataggio in UPSERT dei PARAMETRI IOB scritti... - /// - public string urlUpdateWriteParams - { - get - { - string answ = ""; - try - { - string machineName = Environment.MachineName; - string apiCall = "upsertObjItems"; - answ = string.Format(@"http://{0}{1}{2}/{3}/{4}", cIobConf.serverData.MPIP, cIobConf.serverData.MPURL, cIobConf.serverData.CMDALIVE, apiCall, cIobConf.codIOB); - } - catch (Exception exc) - { - lgError(exc, "Errore in composizione urlSaveMemConf"); - } - return answ; - } - } - - /// - /// Verifica SE si debba fare log verboso (verboso + ogni tot letture IN) - /// - public bool verboseLog - { - get - { - bool answ = false; - int logEvery = utils.CRI("logEvery"); - if (logEvery < 1) - { - logEvery = 10; - } - - answ = utils.CRB("verbose") && (nReadIN % logEvery == 0); - return answ; - } - } - - #endregion Public Properties - - #region Private Methods - - /// - /// Verifica e se necessario comprime directory log... - /// - private void checkShrinkDir() - { - string path = string.Format("{0}logs\\{1}", AppDomain.CurrentDomain.BaseDirectory, cIobConf.codIOB); - baseUtils.shrinkDir(path); - } - - /// - /// Mostra i dati grezzi letti in esadecimale - /// Parametri da aggiornare x display in form - /// - private void displayRawData(ref newDisplayData currDispData) - { - // mostro update... - string newString = string.Format("{0:X}", B_input); - currDispData.newInData = newString; -#if false - // salvo coda debug... - QueueDebug.Enqueue(B_input); -#endif - } - - /// - /// Esegue filtraggio dati x bit blinking!!! - /// - private void filterData() - { - // effettuo filtraggio dei valori letti... inizializzo OUT! - B_output = 0; - // in primis verifico SE ci siano bit blinkng... se non ci sono OUT=IN... - if (cIobConf.BLINK_FILT == 0) - { - B_output = B_input; - } - else - { - // incomincio con i valori NON blinking: questi "passano invariati", inizio a sommare nel valore OUT... - B_output = B_input & ~cIobConf.BLINK_FILT; - // calcolo il valore dei BIT che "passano la maschera" - int iBlink = B_input & cIobConf.BLINK_FILT; - // ...aggiungo i "bit che passano" - B_output += iBlink; - - // calcolo QUALI valori (tra quelli blink) siano PASSATI da 0 a 1 --> init counters... - BitArray bBlinkStart = new BitArray(new byte[] { Convert.ToByte(iBlink) }); - int[] bitsUp = bBlinkStart.Cast().Select(bit => bit ? 1 : 0).ToArray(); - for (int i = 0; i < bitsUp.Length; i++) - { - // SE 1... impostiamo contatori al MAX - if (bitsUp[i] == 1) - { - // se era zero indico START blink... - if (i_counters[i] == 0) - { - lgInfo("START BLINK: B{0}", i); - } - // imposto comunque contatore al cambio fronte... - i_counters[i] = cIobConf.MAX_COUNTER_BLINK; - } - } - - // quelli che sono zero... LI RECUPERO E LI PROCESSO... - int iZero = ~B_input & cIobConf.BLINK_FILT; - BitArray bBlinkEnd = new BitArray(new byte[] { Convert.ToByte(iZero) }); - int[] bitsDown = bBlinkEnd.Cast().Select(bit => bit ? 1 : 0).ToArray(); - for (int i = 0; i < bitsDown.Length; i++) - { - // se era a zero (invertito...) - if (bitsDown[i] == 1) - { - // SE è in corso il conteggio... - if (i_counters[i] > 0) - { - // decremento! - i_counters[i] -= 1; - // se è zero NON faccio nulla, altrimenti SOMMO... - if (i_counters[i] > 0) - { - B_output += 1 << i; - } - else - { - lgInfo("END BLINK: B{0}", i); - } - } - } - } - } - } - - /// - /// Imposta eventuali altri valori default - /// - private void fixDefaultPar() - { - // parametro max tentativi PING... - string s_maxPingRetry = getOptPar("MAX_PING_RETRY"); - if (!string.IsNullOrEmpty(s_maxPingRetry)) - { - int numRetry = 5; - int.TryParse(s_maxPingRetry, out numRetry); - maxPingRetry = numRetry; - } - } - - /// - /// recupera valore salvato in persistence layer (se non c'è crea...) - /// - /// - /// - private string getStoredVal(string keyVal) - { - string value = ""; - try - { - if (persistenceLayer != null) - { - if (!persistenceLayer.TryGetValue(keyVal, out value)) - { - persistenceLayer.Add(keyVal, "0"); - } - } - } - catch (Exception exc) - { - lgError(string.Format("Eccezione in getStoredVal: {0}{1}", Environment.NewLine, exc)); - } - return value; - } - - /// - /// recupera valore salvato in persistence layer (se non c'è crea...) come double - /// - /// - /// - private double getStoredValDouble(string keyVal) - { - double answ = 0; - try - { - answ = Convert.ToDouble(getStoredVal(keyVal)); - } - catch (Exception exc) - { - lgError(string.Format("Eccezione in getStoredValDouble: {0}{1}", Environment.NewLine, exc)); - } - answ = (answ < (double.MaxValue / 10 * 9)) ? answ : 0; - return answ; - } - - /// - /// recupera valore salvato in persistence layer (se non c'è crea...) come INT - /// - /// - /// - private long getStoredValLong(string keyVal) - { - long answ = 0; - try - { - answ = Convert.ToInt64(getStoredVal(keyVal)); - } - catch - { } - // verifico che il valore sia minore di 9/10 del valore massimo... - answ = (answ < (long.MaxValue / 10 * 9)) ? answ : 0; - return answ; - } - - /// - /// recupera valore salvato in persistence layer (se non c'è crea...) come UINT - /// - /// - /// - private uint getStoredValUInt(string keyVal) - { - uint answ = 0; - try - { - answ = Convert.ToUInt32(getStoredVal(keyVal)); - } - catch (Exception exc) - { - lgError(string.Format("Eccezione in getStoredValUInt: {0}{1}", Environment.NewLine, exc)); - } - // verifico che il valore sia minore di 9/10 del valore massimo... - answ = (answ < (uint.MaxValue / 10 * 9)) ? answ : 0; - return answ; - } - - /// - /// Classe fittizia in caso di processing GLOBALE di tutto in 1 solo colpo... - /// - private void processAllMemory() - { - // init obj display - newDisplayData currDispData = new newDisplayData(); - // in primis SALVO valori previous/precedenti - B_previous = B_output; - // poi faccio lettura NUOVI valori - readAllData(ref currDispData); - // eseguo il filtering dei valori (per i bit "blinking") - filterData(); - // effettuo confronto valori vecchi/nuovi... SE trovo variazione OPPURE se è passato + di un timeout di controllo... - if (B_output != B_previous) - { - accodaSigIN(ref currDispData); - } - raiseRefresh(currDispData); - } - - /// - /// Effettua gestioen programma: legge e mostra su display... - /// - private void processProgram() - { - string currPrgName = ""; - // se abilitata lettura prgName - if (enablePrgName) - { - if (connectionOk) - { - currPrgName = getPrgName(); - } - else - { - lgError("Errore connessione mancante x getPrgName"); - } - } - else - { - currPrgName = lastPrgName; - } - // verifico SE sia cambiato il programma... - if (lastPrgName != currPrgName) - { - // salvo! - lastPrgName = currPrgName; - string sVal = string.Format("[PROG]{0}", currPrgName); - - // chiamo accodamento... - accodaFLog(sVal, qEncodeFLog("PROG", currPrgName)); - } - } - - /// - /// Processo lettura dati sysinfo - /// - private void processSysInfo() - { - if (utils.CRB("enableSysInfo")) - { - Dictionary currSysInfo = new Dictionary(); - - if (connectionOk) - { - currSysInfo = getSysInfo(); - } - else - { - lgError("Errore connessione mancante x getSysInfo"); - } - // verifico SE sia cambiato il programma... - if (lastSysInfo != currSysInfo["SYSINFO"]) - { - // salvo! - lastSysInfo = currSysInfo["SYSINFO"]; - // per ogni valore del dizionario mostro ed accodo! - string sVal = ""; - foreach (var item in currSysInfo) - { - sVal = string.Format("[SYSINFO]{0}|{1}", item.Key, item.Value); - // chiamo accodamento... - accodaFLog(sVal, qEncodeFLog(item.Key, item.Value)); - } - } - } - } - - private void reportDataProc() - { - // update valori visualizzazione... - parentForm.dataProcLabel = string.Format("RAW: {0} --> IN: {1} --> OUT: {2}", nReadIN, nReadFilt, nSendOut); - } - - /// - /// Imposto alcuni valori di default - /// - /// indica se sia richeisto di SVUOTARE le code delel info - private void setDefaults(bool resetQueue) - { - numSim = utils.CRI("numSim"); - lastPrgName = ""; - nReadIN = 0; - nReadFilt = 0; - nSendOut = 0; - currMode = 0; - lastAlarm = ""; - doStartMemDump = utils.CRB("doStartMemDump"); - doSampleMemory = utils.CRB("doSampleMemory"); - // svuoto code se richiesto - if (resetQueue) - { - QueueIN = new ConcurrentQueue(); - QueueFLog = new ConcurrentQueue(); - QueueAlarm = new ConcurrentQueue(); - QueueMessages = new ConcurrentQueue(); - } - // imposto contatori blink a zero... - i_counters = new int[32]; - lastPeriodicLog = DateTime.Now; - // fix parametri generali... - enablePrgName = true; - } - - private void svuotaCodaContapezzi() - { - // permetto al max 2 tentativi infruttuosi... - int maxTry = 2; - int oldContapezzi = contapezziIOB; - // se ho contapezzi OLTRE limite... - while ((MPOnline) && (contapezziPLC > contapezziIOB + minSendPzCountBlock)) - { - lgInfo($"Ciclo svuotaCodaContapezzi --> contapezziPLC: {contapezziPLC} | contapezziIOB: {contapezziIOB}"); - if (!isMulti) - { - pzCntReload(true); - } - // provo invio - trySendPzCountBlock(); - // verifica per evitare loop infinito invio fallito - if (oldContapezzi == contapezziIOB) - { - maxTry--; - } - else - { - maxTry = 2; - oldContapezzi = contapezziIOB; - } - // verifico maxTry: se li ho esauriti esco! - if (maxTry <= 0) - { - return; - } - // aspetto x dare tempo calcolo - Thread.Sleep(400); - } - } - - /// - /// Processo la coda FLog... - /// - private void svuotaCodaFLog() - { - //controllo se è passato oltre watchdog e non ho inviato nulla --> RE-INVIO (ultimo inviato)!!!! - if (DateTime.Now.Subtract(lastWatchDog).TotalSeconds > utils.CRI("watchdogMaxSec")) - { - string wdStatus = "elapsed"; - string sVal = string.Format("[WDST]{0}", wdStatus); - // chiamo accodamento... - accodaFLog(sVal, qEncodeFLog("WDST", wdStatus)); - lastWatchDog = DateTime.Now; - } - // verifico SE la coda abbia dei valori... - if (QueueFLog.Count > 0) - { - // invio pacchetto di dati (max da conf) - for (int i = 0; i < nMaxSend; i++) - { - // SE ho qualcosa in coda... - if (QueueFLog.Count > 0) - { - string currVal = ""; - if (MPOnline) - { - if (IobOnline) - { - // se ho + di 2 elementi in coda --> uso invio JSON in blocco... - if (QueueFLog.Count > 1) - { - List listaValori = new List(); - // se ho + di maxJsonData elementi --> invio un set di dati alla volta - if (QueueFLog.Count > maxJsonData) - { - // prendoi primi maxJsonDataValori - for (int j = 0; j < maxJsonData; j++) - { - QueueFLog.TryDequeue(out currVal); - listaValori.Add(currVal); - } - sendDataBlock(urlType.FLog, listaValori); - } - else - { - // invio in blocco - listaValori = QueueFLog.ToList(); - // invio - sendDataBlock(urlType.FLog, listaValori); - // svuoto! - QueueFLog = new ConcurrentQueue(); - } - } - else - { - // INVIO SINGOLO...!!! - QueueFLog.TryDequeue(out currVal); - sendToMoonPro(urlType.FLog, currVal); - } - } - else - { - break; - } - } - else - { - break; - } - } - else - { - break; - } - } - } - } - - /// - /// Cerca di inviare su un altro thread i vari dati accumulati... - /// - private void trySendValues() - { - // init obj display - newDisplayData currDispData = new newDisplayData(); - try - { - // verifico se risponde il server... - if (checkServerAlive) - { - bool iobOk = false; - if (utils.CRB("sendDataByThread")) - { - Task taskCheck = TaskEx.Run(() => iobOk = checkIobEnabled); - } - else - { - iobOk = checkIobEnabled; - } - // verifico SE posso inviare dati - if (iobOk) - { - currDispData.semOut = Semaforo.SV; - // verificare come gestire il task secondario senza interferenza (chiamate update su FORM da thread secondari danno errori) - if (utils.CRB("sendDataByThread")) - { - // invio con thread separato... - Task taskSigIN = TaskEx.Run(() => svuotaCodaSignIN()); - Task taskFlog = TaskEx.Run(() => svuotaCodaFLog()); - } - else - { - // gestione queue SignalIN (invio, display) - svuotaCodaSignIN(); - currDispData.counter = contapezziIOB; - raiseRefresh(currDispData); - // provo a svuotare coda contapezzi - svuotaCodaContapezzi(); - currDispData.counter = contapezziIOB; - raiseRefresh(currDispData); - // gestione queue FluxLog (invio, display) - svuotaCodaFLog(); - raiseRefresh(currDispData); - } - } - else - { - // mostro VETO-SEND x invio... GIALLO - currDispData.semOut = Semaforo.SG; - if (periodicLog) - { - lgInfo("IOB - VETO SEND"); - } - } - } - else - { - // mostro SERVER KO x invio... ROSSO - currDispData.semOut = Semaforo.SR; - if (periodicLog) - { - lgInfo("IOB - SERVER NOT READY"); - } - } - } - catch (Exception exc) - { - lgError($"Errore in fase trySendValues{Environment.NewLine}{exc}"); - currDispData.semOut = Semaforo.SR; - } - raiseRefresh(currDispData); - } - - /// - /// Aggiorna un valore del dizionario in INCREMENTO e lo restituisce - /// - /// - /// - /// - /// Nuovo valore incrementato - private double updateValDoubleByIncr(int i, double delta, string searchString) - { - // stringa da cercare.. - string keyVal = string.Format(searchString, i + 1); - // recupero valore precedente... - double contAct = getStoredValDouble(keyVal); - // nuovo valore... - contAct += delta; - // salvo in ram! - persistenceLayer[keyVal] = contAct.ToString(); - // rendo il valore! - return contAct; - } - - /// - /// Aggiorna un valore del dizionario in INCREMENTO e lo restituisce - /// - /// - /// - /// - /// Nuovo valore incrementato - private long updateValLongByIncr(int i, long delta, string searchString) - { - // stringa da cercare.. - string keyVal = string.Format(searchString, i + 1); - // recupero valore precedente... - long contAct = getStoredValLong(keyVal); - // nuovo valore... - contAct += delta; - // salvo in ram! - persistenceLayer[keyVal] = contAct.ToString(); - // rendo il valore! - return contAct; - } - - /// - /// Aggiorna un valore del dizionario in SOSTITUZIONE - /// - /// - /// - /// - /// Nuovo valore incrementato - private void updateValString(int i, string newVal, string searchString) - { - // stringa da cercare.. - string keyVal = string.Format(searchString, i + 1); - // salvo in ram! - persistenceLayer[keyVal] = newVal; - } - - /// - /// Aggiorna un valore del dizionario in SOSTITUZIONE e lo restituisce - /// - /// - /// - /// - /// Nuovo valore incrementato - private void updateValUInt(int i, uint newVal, string searchString) - { - // stringa da cercare.. - string keyVal = string.Format(searchString, i + 1); - // salvo in ram! - persistenceLayer[keyVal] = newVal.ToString(); - } - - /// - /// Aggiorna un valore del dizionario in INCREMENTO e lo restituisce - /// - /// - /// - /// - /// Nuovo valore incrementato - private uint updateValUIntByIncr(int i, uint delta, string searchString) - { - // stringa da cercare.. - string keyVal = string.Format(searchString, i + 1); - // recupero valore precedente... - uint contAct = getStoredValUInt(keyVal); - // nuovo valore... - contAct += delta; - // salvo in ram! - persistenceLayer[keyVal] = contAct.ToString(); - // rendo il valore! - return contAct; - } - - #endregion Private Methods - - #region Protected Methods - - /// - /// Decodifica file MAP (caso .bit) - /// - /// - /// - /// indirizzo Byte: indirizzo di partenza memoria - /// dimensione singolo slot in byte - /// indirizzo bit: numero riga x calcolo indice bit - /// - protected static otherData decodeBitData(string linea, char separator, int ByteNum, int memSize, int BitNum) - { - if (linea != null) - { - string[] valori = linea.Split(separator); - int shift = 0; - try - { - shift = Convert.ToInt32(valori[0]) - 1; - } - catch - { } - int resto = 0; - Math.DivRem(BitNum, 8, out resto); - string memAddr = string.Format("{0}.{1}", ByteNum + shift * memSize, resto); - return new otherData(valori[0], memAddr, valori[1].Trim(), valori[2].Trim()); - } - else - { - return null; - } - } - - /// - /// Decodifica file MAP generico - /// - /// - /// - /// - /// - /// - /// - protected static otherData decodeOtherData(string linea, char separator, string memPre, int baseAddr, int memSize) - { - if (linea != null) - { - string[] valori = linea.Split(separator); - int shift = 0; - try - { - shift = Convert.ToInt32(valori[0]) - 1; - } - catch - { } - string memAddr = string.Format("{0}{1}", memPre, baseAddr + shift * memSize); - return new otherData(valori[0], memAddr, valori[1].Trim(), valori[2].Trim()); - } - else - { - return null; - } - } - - /// - /// Decodifica valore della coda IN nel formato - /// answ[0]=dtEve - /// answ[1]=valore - /// answ[2]=counter - /// - /// dtEve + '#' + value + '#' + cont - /// - protected static string[] qDecodeIN(string queueVal) - { - string[] answ = null; - if (!string.IsNullOrEmpty(queueVal)) - { - try - { - answ = queueVal.Split('#'); - } - catch - { } - } - return answ; - } - - /// - /// Stringa raw dei parametri da scrivere... - /// - /// - protected string getParams2write() - { - string answ = ""; - string url2call = $"{urlGetParams2Write}"; - if (verboseLog) - { - lgInfo("chiamata URL " + url2call); - } - answ = utils.callUrlNow(url2call); - // se vuoto faccio seconda prova... - if (string.IsNullOrEmpty(answ)) - { - answ = utils.callUrlNow(url2call); - } - return answ; - } - - /// - /// Chiede elenco dei task da eseguire - /// - formato Json - /// - array di KVP / Dictionary - /// - formato definito da API x MP/IO/: - /// - KEY: task - /// - VALUE: array JSon KVP - /// - protected string getTask2exe() - { - string answ = ""; - if (checkServerAlive) - { - string url2call = $"{urlGetTask2Exe}"; - if (verboseLog) - { - lgInfo("chiamata URL " + url2call); - } - answ = utils.callUrlNow(url2call); - } - return answ; - } - - /// - /// Effettua logging ERROR corretto impostanto anche la variabile IOB prima di scrivere... - /// - /// - protected void lgError(string message, bool sendToForm = true) - { - lg.Factory.Configuration.Variables["codIOB"] = cIobConf.codIOB; - lg.Error(message); - if (sendToForm) - { - sendToLogWatch("ERROR", message); - } - } - - /// - /// Effettua logging ERROR corretto impostanto anche la variabile IOB prima di scrivere... - /// - /// - /// - protected void lgError(string message, params object[] args) - { - lg.Factory.Configuration.Variables["codIOB"] = cIobConf.codIOB; - lg.Error(message, args); - sendToLogWatch("ERROR", message, args); - } - - /// - /// Effettua logging ERROR corretto impostanto anche la variabile IOB prima di scrivere... - /// - /// - /// - /// - protected void lgError(Exception exception, string message, params object[] args) - { - lg.Factory.Configuration.Variables["codIOB"] = cIobConf.codIOB; - lg.Error(exception, message, args); - sendToLogWatch("ERROR", message, exception, args); - } - - /// - /// Effettua logging FATAL corretto impostanto anche la variabile IOB prima di scrivere... - /// - /// - protected void lgFatal(string message, bool sendToForm = true) - { - lg.Factory.Configuration.Variables["codIOB"] = cIobConf.codIOB; - lg.Fatal(message); - if (sendToForm) - { - sendToLogWatch("FATAL", message); - } - } - - /// - /// Effettua logging FATAL corretto impostanto anche la variabile IOB prima di scrivere... - /// - /// - /// - protected void lgFatal(string message, params object[] args) - { - lg.Factory.Configuration.Variables["codIOB"] = cIobConf.codIOB; - lg.Fatal(message, args); - sendToLogWatch("FATAL", message, args); - } - - /// - /// Effettua logging FATAL corretto impostanto anche la variabile IOB prima di scrivere... - /// - /// - /// - /// - protected void lgFatal(Exception exception, string message, params object[] args) - { - lg.Factory.Configuration.Variables["codIOB"] = cIobConf.codIOB; - lg.Fatal(exception, message, args); - sendToLogWatch("FATAL", message, exception, args); - } - - /// - /// Effettua logging INFO corretto impostanto anche la variabile IOB prima di scrivere... - /// - /// - protected void lgInfo(string message, bool sendToForm = true) - { - lg.Factory.Configuration.Variables["codIOB"] = cIobConf.codIOB; - lg.Info(message); - if (sendToForm) - { - sendToLogWatch("INFO", message); - } - } - - /// - /// Effettua logging INFO corretto impostanto anche la variabile IOB prima di scrivere... - /// - /// - /// - protected void lgInfo(string message, params object[] args) - { - lg.Factory.Configuration.Variables["codIOB"] = cIobConf.codIOB; - lg.Info(message, args); - sendToLogWatch("INFO", message, args); - } - - /// - /// Legge il file di conf di una MAP di informazioni da gestire con lettura set memoria - /// - /// nome vettore memoria - /// file origine - /// dimensione (in byte) della memoria - /// dimensione (in byte) della memoria - protected void loadConfFile(ref otherData[] vettoreConf, string nomeFile, int memSize, ref int numVett) - { - otherData lastData = new otherData(); - int totRighe = 0; - string linea; - totRighe = File.ReadLines(nomeFile).Count(); - // creo un vettore della dimensione corretta... conta anche commenti tanto poi riduco... - vettoreConf = new otherData[File.ReadLines(nomeFile).Count()]; - // carica da file... - StreamReader file = new StreamReader(nomeFile); - // leggo 1 linea alla volta... - int numRiga = 0; - int bitNum = 0; - int byteNum = 0; - while ((linea = file.ReadLine()) != null) - { - // SE non è un commento... - if (linea.Substring(0, 1) != "#") - { - // se finisce per BIT allora processo bit-a-bit... - if (linea.EndsWith("BOOL")) - { - try - { - string[] memIdx = linea.Split(utils.CRC("testCharSep"))[0].Split('.'); - // calcolo bit e byte number... - int.TryParse(memIdx[0], out byteNum); - if (memIdx.Length > 1) - { - int.TryParse(memIdx[1], out bitNum); - } - else - { - bitNum = 0; - } - } - catch - { - byteNum = 0; - bitNum = 0; - } - lastData = decodeBitData(linea, utils.CRC("testCharSep"), byteNum, 1, bitNum); - vettoreConf[numRiga] = lastData; - } - else - { - lastData = decodeOtherData(linea, utils.CRC("testCharSep"), "", 1, memSize); - vettoreConf[numRiga] = lastData; - } - numRiga++; - } - } - // salvo lunghezza file... - try - { - numVett = Convert.ToInt32(lastData.memAddr) + 1; - } - catch - { - numVett = numRiga + 1; - } - // chiudo file - file.Close(); - // ora trimmo vettore al solo numero VERO dei valori caricati... - Array.Resize(ref vettoreConf, numRiga); - - if (isVerboseLog) - { - lgInfo(string.Format("Fine caricamento vettore di {0} variabili per file {1}", numRiga, nomeFile)); - } - } - - /// - /// Lettura memorie conf speciali (json) - /// ...SE inserito in [OPTPAR] come PARAM_CONF=nome.json - /// - protected virtual void loadMemConf() - { - lgInfo("BEGIN loadMemConf"); - // variabili x gestione send contapezzi in blocco - string currPar = getOptPar("ENABLE_SEND_PZC_BLOCK"); - if (!string.IsNullOrEmpty(currPar)) - { - bool.TryParse(currPar, out enableSendPzCountBlock); - // se abilitato leggo num pezzi da reinviare in blocco - if (enableSendPzCountBlock) - { - int.TryParse(getOptPar("MAX_SEND_PZC_BLOCK"), out maxSendPzCountBlock); - int.TryParse(getOptPar("MIN_SEND_PZC_BLOCK"), out minSendPzCountBlock); - } - } - else - { - lgError("loadMemConf: parametro ENABLE_SEND_PZC_BLOCK non trovato, verificare anche MAX_SEND_PZC_BLOCK e MIN_SEND_PZC_BLOCK"); - } - // inizializzo LUT decodifica - string jsonConf = getOptPar("PARAM_CONF"); - if (!string.IsNullOrEmpty(jsonConf)) - { - string jsonFileName = $"{Application.StartupPath}/DATA/CONF/{jsonConf}"; - lgInfo($"Apertura file {jsonFileName}"); - StreamReader reader = new StreamReader(jsonFileName); - string jsonData = reader.ReadToEnd(); - if (!string.IsNullOrEmpty(jsonData)) - { - lgInfo($"File json composto da {jsonData.Length} caratteri"); - try - { - memMap = JsonConvert.DeserializeObject(jsonData); - lgInfo($"Decodifica aree memMap: trovati {memMap.mMapRead.Count} valori TSVC"); - lgInfo($"Decodifica aree memMap: trovati {memMap.mMapWrite.Count} parametri "); - // se ho variabili read --> genero dati TSVC... - if (memMap.mMapRead.Count > 0) - { - TSVC_Data.Clear(); - LastTSVC.Clear(); - VCData currConf; - int periodo = 0; - VC_func funz = VC_func.POINT; - // accodo nella conf... - foreach (var item in memMap.mMapRead) - { - funz = item.Value.func; - periodo = item.Value.period; - currConf = new VCData() - { - Funzione = funz, - Period = periodo, - DTStart = DateTime.Now.AddHours(-1), - dataArray = new List() - }; - TSVC_Data.Add(item.Key, currConf); - } - // documento... - foreach (var item in TSVC_Data) - { - lgInfo($"TSVC: {item.Key} | periodo: {item.Value.Period} | funz: {item.Value.Funzione}"); - // salvo i valori PREC... - LastTSVC.Add(item.Key, 0); - } - } - // infine se obj memoria valido salvo in MP-IO x sue applicazioni - if (memMap != null) - { - // invio su cloud conf memoria... - string rawData = JsonConvert.SerializeObject(memMap); - utils.callUrlNow($"{urlSaveMemMap}", rawData); - // salvo ANCHE come parametri i valori... - objItem currItem = new objItem(); - List allParam = new List(); - // valori WRITE - foreach (var item in memMap.mMapWrite) - { - currItem = new objItem() - { - uid = item.Value.name, - name = !string.IsNullOrEmpty(item.Value.description) ? item.Value.description : item.Value.name, - writable = true - }; - allParam.Add(currItem); - } - // valori READ - foreach (var item in memMap.mMapRead) - { - currItem = new objItem() - { - uid = item.Value.name, - name = !string.IsNullOrEmpty(item.Value.description) ? item.Value.description : item.Value.name, - writable = false - }; - allParam.Add(currItem); - } - // invio su cloud parametri! - rawData = JsonConvert.SerializeObject(allParam); - utils.callUrl($"{urlSaveAllParams}", rawData); - } - } - catch (Exception exc) - { - lgError($"Eccezione in decodifica conf json{Environment.NewLine}{exc}"); - } - } - else - { - lgError("Errore in loadMemConf: file json vuoto!"); - } - reader.Dispose(); - } - else - { - lgInfo("loadMemConf: non trovata opzione PARAM_CONF in file INI"); - } - // loggo - lgInfo("DONE loadMemConf"); - } - - /// - /// Metodo da overridare x scrivere DAVVERO i parametri sul PLC - /// - /// - protected virtual void plcWriteParams(List updatedPar) - { - // non faccio nulla di base... - } - - /// - /// Processa le richieste di scrittura memoria - /// - /// - protected string processMemWriteRequests() - { - string answ = ""; - // li salvo nei parametri in memoria locale (ogni adapter DOVREBBE salvare POI sul VERO PLC) - List writeList = new List(); - List updatedPar = new List(); - // recupero elenco delle cose da fare - string resp = getParams2write(); - if (!string.IsNullOrEmpty(resp)) - { - try - { - writeList = JsonConvert.DeserializeObject>(resp); - // se ho da fare chiamo esecuzione.. - if (writeList.Count > 0) - { - foreach (var item in writeList) - { - // scrivo in memoria - if (memMap.mMapWrite.ContainsKey(item.uid)) - { - memMap.mMapWrite[item.uid].value = item.reqValue; - // accodo in stringa taskVal... - answ += $" | Parameter {item.uid} --> {item.reqValue}"; - // sistemo valori - item.value = item.reqValue; - lgInfo($"Effettuato update parametro: actVal = {item.value} | reqVal = {item.reqValue}"); - item.reqValue = ""; - // salvo in lista da ritrasmettere - updatedPar.Add(item); - } - else - { - answ += $" | Error: parameter {item.uid} not found"; - } - } - // richiamo scrittura parametri su PLC - plcWriteParams(updatedPar); - // invio su cloud parametri! - string rawData = JsonConvert.SerializeObject(updatedPar); - utils.callUrl($"{urlUpdateWriteParams}", rawData); - } - } - catch (Exception exc) - { - lgError($"Eccezione in processServerRequests:{Environment.NewLine}{exc}"); - } - } - else - { - lgError("Non è stata ricevuta risposta x task da eseguire"); - } - return answ; - } - - protected void raiseRefresh(newDisplayData currDispData) - { - if (currDispData != null) - { - if (currDispData.hasData) - { - // segnalo refresh! - if (eh_refreshed != null) - { - eh_refreshed(this, new iobRefreshedEventArgs(currDispData)); - } - } - } - } - - /// - /// Cancella dal server i task eseguiti - /// - /// - /// - /// - protected string remTask2exe(string taskName, string esitoTask) - { - string answ = ""; - if (checkServerAlive) - { - string url2call = $"{urlRemTask2Exe}{taskName}"; - lgInfo($"Task2Exe | {esitoTask} | chiamata URL {url2call}"); - answ = utils.callUrlNow(url2call); - } - return answ; - } - - /// - /// Invia informazioni associazione IOB 2 machine - /// - protected void sendM2IOB() - { - if (checkServerAlive) - { - lgInfo("chiamata URL " + urlSetM2IOB); - utils.callUrlNow(urlSetM2IOB); - } - } - - /// - /// Invia al server IO i valori dei parametri opzionali (es counters) - /// - /// Nome parametro - /// Valore parametro - protected void sendOptVal(string paramName, string paramValue) - { - if (checkServerAlive) - { - string url2call = $"{urlSetOptVal}pName={paramName}&pValue={paramValue}"; - lgInfo("chiamata URL " + url2call); - utils.callUrlNow(url2call); - } - } - - /// - /// Invia al server IO i valori dei parametri opzionali (es counters) - /// - /// Nome parametro - /// Valore parametro INT - protected void sendOptVal(string paramName, int paramValueInt) - { - // override! - sendOptVal(paramName, paramValueInt.ToString()); - } - - /// - /// Invia messaggio a logWatcher - /// - /// - /// - protected void sendToLogWatch(string messType, string message) - { - newDisplayData currDispData = new newDisplayData(); - currDispData.newLiveLogData = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} | {messType} | {message}"; - parentForm.updateFormDisplay(currDispData); - } - - /// - /// Invia messaggio a logWatcher - /// - /// - /// - /// - protected void sendToLogWatch(string messType, string message, params object[] args) - { - try - { - string expString = string.Format(message, args); - newDisplayData currDispData = new newDisplayData(); - currDispData.newLiveLogData = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} | {messType} | {expString}"; - parentForm.updateFormDisplay(currDispData); - } - catch - { } - } - - /// - /// Invia messaggio a logWatcher - /// - /// - /// - /// - /// - protected void sendToLogWatch(string messType, string message, Exception exception, params object[] args) - { - try - { - string expString = string.Format(message, args); - newDisplayData currDispData = new newDisplayData(); - currDispData.newLiveLogData = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} | {messType} | {expString}{Environment.NewLine}{exception}"; - parentForm.updateFormDisplay(currDispData); - } - catch - { } - } - - /// - /// Invia messaggio a logWatcher - /// - /// - /// - protected void sendToTaskWatch(string messType, string message) - { - parentForm.taskWatcher = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} | {messType} | {message}"; - } - - /// - /// Impostazioni parametri PLC - /// - protected virtual void setParamPlc() - { - loadMemConf(); - fixDefaultPar(); - } - - #endregion Protected Methods - - #region Public Methods - - /// - /// Effettua chiamata URL e restituisce risultato - /// - /// - /// invio in modalità async (NON GARANTITO ordine...) - /// - public static string callUrl(string URL, bool doAsync) - { - string answ = ""; - // Chiamata ASINCRONA - if (doAsync) - { - //Task resp = utils.callUrlAsync(URL); - //answ = resp.Result; - answ = utils.callUrlAsync(URL); - } - // chiamata SOLO NORMALE SINCRONA... - else - { - answ = utils.callUrl(URL); - } - return answ; - } - - /// - /// Effettua chiamata URL e restituisce risultato - /// - /// - /// - /// invio in modalità async (NON GARANTITO ordine...) - /// - public static string callUrlWithPayload(string URL, string payload, bool doAsync) - { - string answ = ""; - // Chiamata ASINCRONA - if (doAsync) - { - answ = utils.callUrlAsync(URL, payload); - } - // chiamata SOLO NORMALE SINCRONA... - else - { - answ = utils.callUrl(URL, payload); - } - return answ; - } - - /// - /// processa dataLayer e se necessario salva/mostra - /// - public static void checkSavePersDataLayer() - { - } - - public static string GetMACAddress() - { - NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); - String sMacAddress = string.Empty; - foreach (NetworkInterface adapter in nics) - { - if (string.IsNullOrEmpty(sMacAddress))// only return MAC Address from first card - { - IPInterfaceProperties properties = adapter.GetIPProperties(); - //sMacAddress = adapter.GetPhysicalAddress().ToString(); - sMacAddress = string.Join(":", (from z in adapter.GetPhysicalAddress().GetAddressBytes() select z.ToString("X2")).ToArray()); - } - } - return sMacAddress; - } - - public static void resetDebugConsole() - { - } - - /// - /// Reset dei webclients - /// - public static void resetWebClients() - { - utils.resetWebClients(); - } - - /// - /// Accumula in coda i valori ALARM e logga... - /// - /// VALORE RAW (x display) - /// VALORE già processato con qEncodeFLog(...) - public void accodaAlarmLog(string val, string encodedVal) - { - // mostro dati variati letti... - displayOtherData(val); - // accodo IN PRIMIS al FluxLog --> accodo (valore già formattato)! - QueueFLog.Enqueue(encodedVal); - // accodo ANCHE alla coda allarmi che trasmetterò SOLO SE a scadenza impostata (10 sec?) ho allarmi perdurati... - - // loggo! - lgInfo(string.Format("[QUEUE-ALARM-LOG] {0}", encodedVal)); - counterFLog++; - if (counterFLog > 9999) - { - counterFLog = 0; - } - } - - /// - /// Accumula in coda i valori Flux Log e logga... - /// - /// VALORE RAW (x display) - /// VALORE già processato con qEncodeFLog(...) - public void accodaFLog(string val, string encodedVal) - { - // mostro dati variati letti... - displayOtherData(val); - // --> accodo (valore già formattato)! - QueueFLog.Enqueue(encodedVal); - // se abilitato controllo coda FLog (superiore a 0...) - if (maxQueueFLog > 0) - { - // se ho una coda superiore a max ammesso - if (QueueFLog.Count > maxQueueFLog) - { - // elimino valori iniziali fino a tornare al max ammesso... - while (QueueFLog.Count > maxQueueFLog) - { - string currVal = ""; - QueueFLog.TryDequeue(out currVal); - lgInfo($"Eliminazione ca coda FLog per superamento maxLengh: {currVal}"); - } - } - } - // loggo! - lgInfo(string.Format("[QUEUE-FLOG] {0}", encodedVal)); - counterFLog++; - if (counterFLog > 9999) - { - counterFLog = 0; - } - } - - /// - /// Accoda (visualizzando in cima allo stack) la nuova stringa di output per area OTHER DATA - /// - /// - public void accodaOtherData(string newLine) - { - // inserisco in cima allo stack, trimmo e aggiorno display - string strOtherData = limitLine2show(string.Format("{0}{1}{2}", newLine, Environment.NewLine, parentForm.dataMonitor_3)); - //parentForm.dataMonitor_3 = strOtherData; - parentForm.WriteTextSafe(strOtherData); - } - - /// - /// Accumula in coda i valori Signal IN e logga... - /// Parametri da aggiornare x display in form - /// - public void accodaSigIN(ref newDisplayData currDispData) - { - // mostro dati variati letti... - displayInData(ref currDispData); - // --> accodo (valore già formattato)! - QueueIN.Enqueue(qEncodeIN); - // loggo! - lgInfo(string.Format("[QUEUE-IN] {0}", qEncodeIN)); - // aggiorno counters ed eventuale reset - nReadFilt++; - if (nReadFilt > int.MaxValue - 1) - { - nReadFilt = 0; // per evitare buffer overflow... - } - - counterSigIN++; - if (counterSigIN > 9999) - { - counterSigIN = 0; - } - } - - /// - /// Update visualizzaizone BIT in ingresso - /// Parametri da aggiornare x display in form - /// - public void displayInData(ref newDisplayData currDispData) - { - if (currDispData != null) - { - // mostro update... - string newString = string.Format("{0:0000}|{1}", counterSigIN, utils.IntToBinStr(B_output, 8)); - currDispData.newSignalData = newString; - } - } - - /// - /// Mostra cosa ha/avrebbe inviato - /// - /// - public void displayOtherData(string newData) - { - // mostro update... - accodaOtherData(newData); - } - - /// - /// Esecuzione dei task richiesti e pulizia coda richieste eseguite - /// - /// - public virtual Dictionary executeTasks(Dictionary task2exe) - { - // Verificare il protocollo: dovrebbe togliere SOLO i task eseguiti... - Dictionary taskDone = new Dictionary(); - if (task2exe != null) - { - bool taskOk = false; - string taskVal = ""; - // cerco task specifici: se ho startSetup --> imposto bit DBB701.DBB0.4 - foreach (var item in task2exe) - { - taskOk = false; - taskVal = ""; - // converto richiesta in enum... - taskType tName = taskType.nihil; - Enum.TryParse(item.Key, out tName); - // controllo sulla KEY... - switch (tName) - { - case taskType.nihil: - case taskType.fixStopSetup: - case taskType.forceSetPzCount: - case taskType.sendWatchDogMes2Plc: - taskVal = $"taskReq: {tName} | key: {item.Key} | val: {item.Value} | SKIPPED | NO EXEC"; - lgInfo($"Chiamata senza processing: taskOk: {taskOk} | taskVal: {taskVal}"); - break; - - case taskType.setArt: - case taskType.setComm: - case taskType.setProg: - case taskType.setPzComm: - // recupero dati da memMap... - if (memMap.mMapWrite.ContainsKey(item.Key)) - { - dataConf currMem = memMap.mMapWrite[item.Key]; - string addr = currMem.memAddr; - taskVal = $"SET task: {item.Key} --> {item.Value} | mem: {currMem.memAddr} - {currMem.size} byte"; - // salvo il nuovo valore nella memoria... così prox invio lo trasmetterà - memMap.mMapWrite[item.Key].value = item.Value; - } - else - { - taskVal = $"NO DATA MEM, SET task: {item.Key} --> {item.Value}"; - } - break; - - case taskType.forceResetPzCount: - // reset contapezzi inizio setup - taskOk = resetcontapezziPLC(); - taskVal = taskOk ? "RESET PZ COUNT OK" : "PZ RESET DISABLED | NO EXEC"; - lgInfo($"Chiamata forceResetPzCount: taskOk: {taskOk} | taskVal: {taskVal}"); - break; - - case taskType.startSetup: - // reset contapezzi inizio setup - taskOk = resetcontapezziPLC(); - taskVal = taskOk ? "RESET: SETUP START" : "PZ RESET DISABLED | NO EXEC"; - lgInfo($"Chiamata startSetup: taskOk: {taskOk} | taskVal: {taskVal}"); - break; - - case taskType.stopSetup: - // reset contapezzi fine setup SE ESPLICITAMENTE IMPOSTATO - if (cIobConf.optPar.Count > 0 && getOptPar("ENABLE_PZ_RESET_stopSetup") == "TRUE") - { - taskOk = resetcontapezziPLC(); - } - taskVal = taskOk ? "RESET: SETUP END" : "PZ RESET DISABLED | NO EXEC"; - lgInfo($"Chiamata stopSetup: taskOk: {taskOk} | taskVal: {taskVal}"); - break; - - case taskType.setParameter: - // richiedo da URL i parametri WRITE da popolare - lgInfo("Chiamata processMemWriteRequests"); - taskVal = processMemWriteRequests(); - // se restituiscce "" faccio altra prova... - if (string.IsNullOrEmpty(taskVal)) - { - // i parametri me li aspetto come stringa composta paramName|paramvalue - if (item.Value.Contains("|")) - { - string[] paramsJob = item.Value.Split('|'); - taskVal = $"REQUEST SET PARAMETERS: {paramsJob[0]} --> {paramsJob[1]}"; - } - else - { - taskVal = $"WRONG REQUEST FOR SET PARAMETERS: {item.Value} doesnt contain pipe for splitting key/value"; - } - } - break; - - default: - taskVal = "SKIPPED | NO EXEC"; - lgInfo($"Chiamata default senza processing: taskOk: {taskOk} | taskVal: {taskVal}"); - break; - } - // aggiungo task! - taskDone.Add(item.Key, taskVal); - } - } - return taskDone; - } - - /// - /// Cerca parametri opzionali in modalità "like" del nome - /// - /// - /// - public Dictionary findOptPar(string keyStartSearch = "") - { - Dictionary answ = new Dictionary(); - // controllo SE keySearch !="" - if (!string.IsNullOrWhiteSpace(keyStartSearch)) - { - if (cIobConf.optPar.Count > 0) - { - // ciclo su tutti e cerco occorrenze che INIZINO... - foreach (var item in cIobConf.optPar) - { - if (item.Key.StartsWith(keyStartSearch)) - { - answ.Add(item.Key, item.Value); - } - } - } - } - return answ; - } - - /// - /// Effettua chiamata x split ODL - /// - /// - public bool forceSplitOdl() - { - bool fatto = false; - if (vetoSplit < DateTime.Now) - { - // imposto veto x 1 minuto ad altre chiamate... - vetoSplit = DateTime.Now.AddMinutes(1); - // eseguo SOLO SE sono online... - if (MPOnline && IobOnline) - { - string fullUrl = ""; - string rawSplit = ""; - string IOB_MULTI_CNAME = ""; - string[] elencoMulti = null; - - try - { - /*************************************************** - * Descrizione procedura (OK X SIMULATORI...) - * - * - chiamata su MP/IO - * - verifica che su DB sia abilitato AUTO ODL - * - il server inserisce un evento fine prod HW 1 minuto prima e inizio setup HW - * - viene duplicato e chiuso ODL corrente - * - viene fatto partire ODL nuovo ADESSO - * - num pezzi come ODL precedente (o da media 3 ODL precedenti) - * - conferme pezzi & co... gestione NULL (NON SERVONO si tratta di impianti SENZA gestione vera ODL) - * - reset contapezzi PLC locale... - * - * - * - * DA VALUTARE (x macchine tipo linea con + impianti... es valvital) SE - * - creare una gestione ALTERNATIVA sul server che preveda impianto LEADER e impianti follower (RIGIDAMENTE CONFIGURATI) - * - ogni volta che si fa setup LEADER --> si ripete su impianti FOLLOWER (eventi!!!) - * - viene fatto reset contapezzi sui follower (+ altre operazioni opzionali, ES imposstazione nome commessa, quantità, articolo...) - * - viene fatto reset + nuovo ODL (con stessi articoli e quantità) su follower, SENZA avere gestione x ODL di un codice esterno (quindi registra TUTTO ma NON RITORNERA' dati non avendo link verso esterno) - * - serve NUOVA TABELLA delle macchine LEADER | FOLLOWER (1:n) e gestione da MP/IO - * - * ***************************************************/ - - if (isMulti) - { - // devo chiamare cambio ODL x OGNI tavola: mi servono i parametri opzionali... - IOB_MULTI_CNAME = getOptPar("IOB_MULTI_CNAME"); - elencoMulti = IOB_MULTI_CNAME.Split(','); - } - // se normale splitto! - if (!isMulti) - { - // invio chiamata URL x reset ODL su macchina - rawSplit = callUrl(urlForceSplit, false); - fatto = (rawSplit != "KO") ? true : false; - } - // se multi gestisco il bit delle tavole... - else - { - foreach (string item in elencoMulti) - { - // invio chiamata URL x reset ODL su macchina, ATTENZIONE scriviamo | al posto di "#" che in URL sarebbe filtrato... - fullUrl = $"{urlForceSplit}|{item}"; - rawSplit = callUrl(fullUrl, false); - } - fatto = (rawSplit == "OK") ? true : false; - } - } - catch (Exception exc) - { - lgError($"Eccezione in forceSplitOdl{Environment.NewLine}{exc}"); - } - // se fatto --> resetto contapezzi!!! - if (fatto) - { - contapezziPLC = 0; - contapezziIOB = 0; - } - } - else - { - lgError("Richiesto forceSplitOdl ma MP/IOB offline --> NON eseguito"); - } - } - else - { - lgError("Richiesto forceSplitOdl ma veto attivo --> NON eseguito"); - } - return fatto; - } - - /// - /// effettua recupero dati ed invio valori modificati... - /// - /// - public void getAndSend(gatherCycle ciclo) - { - // init obj display - newDisplayData currDispData = new newDisplayData(); - // IN OGNI CASO a prima di tutto EFFETTUO GESTIONE INVII dati da code!!! - try - { - trySendValues(); - } - catch (Exception exc) - { - lgError(exc, "Errore in gestione svuotamento/invio preliminare code memoria"); - currDispData.semOut = Semaforo.SR; - } - // controllo connessione/connettività - if (connectionOk) - { - // controllo non sia già in esecuzione... - if (!adpCommAct) - { - // provo ad avviare - try - { - // imposto flag adapter running.. - adpCommAct = true; - adpStartRun = DateTime.Now; - } - catch (Exception exc) - { - string errore = $"Adapter NOT STARTED!!!{Environment.NewLine}{exc}"; - adpCommAct = false; - adpStartRun = DateTime.Now; - currDispData.newLiveLogData = errore; - } - if (adpCommAct) - { - // try / catch generale altrimenti segno che è disconnesso... - try - { - bool showDebugData = false; - if (ciclo == gatherCycle.VHF) - { - processVHF(); - } - // processing dati memoria (lettura, filtraggio, enqueque) - else if (ciclo == gatherCycle.HF) - { - processWhatchDog(); - processAllMemory(); - processMode(); - } - else if (ciclo == gatherCycle.MF) - { - processServerRequests(); - processOverride(); - processContapezzi(); - processCncAlarms(); - processDynData(); - } - else if (ciclo == gatherCycle.LF) - { - processOtherCounters(); - processProgram(); - // verifico se devo gestire cambio ODL in modo automatico - processAutoOdl(); - } - else if (ciclo == gatherCycle.VLF) - { - if (utils.CRB("enableContapezzi")) - { - // rilettura contapezzi da server... - lgInfo("Ciclo VLF: pzCntReload(true)"); - if (!isMulti) - { - pzCntReload(true); - } - // refresh associazione Macchina - IOB - sendM2IOB(); - } - // recupero dati SETUP (sysinfo) e li invio/mostro se variati... - processSysInfo(); - // checkLogDir x shrink! - checkShrinkDir(); - // eventuale log! - if (utils.CRB("recTime")) - { - logTimeResults(); - } - } - // mostra eventuali altri dati di processo... - reportDataProc(); - if (showDebugData) - { - // verifica se debba salvare e mostrare dati - checkSavePersDataLayer(); - } - } - catch (Exception exc) - { - // segnalo eccezione e indico disconnesso... - lgError(exc, string.Format("Errore in gestione ciclo principale ADP, fermo adapter{0}{1}", Environment.NewLine, exc)); - parentForm.fermaAdapter(true, false, true); - } - // tolgo flag running - adpCommAct = false; - } - else - { - if (periodicLog) - { - lgInfo("ADP not running..."); - } - } - } - else - { - // log ADP running - lgError("Non eseguo chiamata: ADP ancora in running"); - // se è bloccato da oltre maxSec lo sblocco... - if (DateTime.Now.Subtract(adpStartRun).TotalSeconds > utils.CRI("maxAdapterLockSec")) - { - // tolgo flag running - adpCommAct = false; - adpStartRun = DateTime.Now; - } - } - } - else - { - // provo a riconnettere SE abilitato tryRestart... - if (adpTryRestart && !connectionOk) - { - // controllo se sia scaduto periodi di veto al tryConnect... - int waitRecMSec = utils.CRI("waitRecMSec") * 2; - DateTime dtVeto = lastConnectTry.AddMilliseconds(waitRecMSec); - if (DateTime.Now > dtVeto) - { - lgInfo($"Retry Time Elapsed (waited for {waitRecMSec} ms)--> NOW tryConnect"); - lastConnectTry = DateTime.Now; - tryConnect(); - } - } - currDispData.semIn = Semaforo.SR; - } - raiseRefresh(currDispData); - } - - /// - /// Recupera eventuali allarmi CNC... - /// - public virtual Dictionary getCncAlarms() - { - Dictionary outVal = new Dictionary(); - return outVal; - } - - /// - /// Restituisce info DINAMICHE - /// - /// - public virtual Dictionary getDynData() - { - Dictionary outVal = new Dictionary(); - return outVal; - } - - /// - /// Cerca se esiste il parametro opzionale e lo restituisce - /// - /// - /// - public string getOptPar(string key) - { - string answ = ""; - if (cIobConf.optPar.Count > 0) - { - // controllo SE HO il parametro - if (cIobConf.optPar.ContainsKey(key)) - { - answ = cIobConf.optPar[key]; - } - } - return answ; - } - - /// - /// Restituisce info OVERRIDES - /// - /// - public virtual Dictionary getOverrides() - { - Dictionary outVal = new Dictionary(); - return outVal; - } - - /// - /// Restituisce programma in esecuzione - /// - public virtual string getPrgName() - { - return ""; - } - - /// - /// Restituisce info sistema - /// - /// - public virtual Dictionary getSysInfo() - { - Dictionary outVal = new Dictionary(); - return outVal; - } - - /// - /// Recupera la VC x TS, svuotando lista e resettando periodo partenza - /// - /// Nome della VC - /// Reimposta e resetta array VC - /// - public double getVal_TSVC(string VCName, bool doReset) - { - double answ = 0; - // cerco VC... - if (TSVC_Data.ContainsKey(VCName)) - { - // !!!FARE!!! vero calcolo... x ora FIX a MAX... - foreach (var item in TSVC_Data[VCName].dataArray) - { - answ = item > answ ? item : answ; - } - // ora resetto... SE richiesto... - if (doReset) - { - TSVC_Data[VCName].dataArray = new List(); - TSVC_Data[VCName].DTStart = DateTime.Now; - } - } - return answ; - } - - /// - /// Recupera la VC x TS, svuotando lista e resettando periodo partenza - /// - /// Nome della VC - /// Reimposta e resetta array VC - /// - public int getVal_TSVC_int(string VCName, bool doReset) - { - int answ = 0; - // cerco VC... - if (TSVC_Data.ContainsKey(VCName)) - { - // !!!FARE!!! vero calcolo... x ora FIX a MAX... - foreach (var item in TSVC_Data[VCName].dataArray) - { - answ = (int)item > answ ? (int)item : answ; - } - // ora resetto... SE richiesto.. - if (doReset) - { - TSVC_Data[VCName].dataArray = new List(); - TSVC_Data[VCName].DTStart = DateTime.Now; - } - } - return answ; - } - - /// - /// Restituisce un payload in formato json della lista di valori ricevuta - /// - /// Tipo di URL (eventi / FLog) - /// elenco di valori da coda string salvata - /// - public string jsonPayload(urlType tipoUrl, List elencoValori) - { - string answ = ""; - if (elencoValori != null) - { - if (tipoUrl == urlType.FLog) - { - flogData currData = new flogData(); - flogJsonPayload fullObj = new flogJsonPayload(); - fullObj.fluxData = new List(); - string[] valori; - int counter = 0; - DateTime dtEve = DateTime.Now; - // inizio processando ogni valore - foreach (var item in elencoValori) - { - valori = qDecodeIN(item); - //DateTime.TryParse(valori[0], out dtEve); - CultureInfo provider = CultureInfo.InvariantCulture; - DateTime.TryParseExact(valori[0], "yyyyMMddHHmmssfff", provider, DateTimeStyles.AssumeLocal, out dtEve); - int.TryParse(valori[3], out counter); - currData = new flogData() - { - flux = valori[1], - valore = valori[2], - dtEve = dtEve, - dtCurr = DateTime.Now, - cnt = counter - }; - fullObj.fluxData.Add(currData); - } - // conversione finale - try - { - answ = JsonConvert.SerializeObject(fullObj); - } - catch (Exception exc) - { - lgError($"Errore in costruzione jsonPayload:{Environment.NewLine}{exc}"); - } - } - else - { - evData currData = new evData(); - evJsonPayload fullObj = new evJsonPayload(); - fullObj.eventList = new List(); - string[] valori; - int counter = 0; - DateTime dtEve = DateTime.Now; - // inizio processando ogni valore - foreach (var item in elencoValori) - { - valori = qDecodeIN(item); - //DateTime.TryParse(valori[0], out dtEve); - CultureInfo provider = CultureInfo.InvariantCulture; - DateTime.TryParseExact(valori[0], "yyyyMMddHHmmssfff", provider, DateTimeStyles.AssumeLocal, out dtEve); - int.TryParse(valori[2], out counter); - currData = new evData() - { - valore = valori[1], - dtEve = dtEve, - dtCurr = DateTime.Now, - cnt = counter - }; - fullObj.eventList.Add(currData); - } - // conversione finale - try - { - answ = JsonConvert.SerializeObject(fullObj); - } - catch (Exception exc) - { - lgError($"Errore in costruzione jsonPayload:{Environment.NewLine}{exc}"); - } - } - } - return answ; - } - - /// - /// Effettua un trim della stringa al numero max di linee da mostrare a video - /// - /// - /// - public string limitLine2show(string newString) - { - // se num righe superiore a limite trimmo... - if (newString.Split('\n').Length > parentForm.nLine2show) - { - //int idx = newString.LastIndexOf('\r'); - int idx = newString.LastIndexOf(Environment.NewLine); - newString = newString.Substring(0, idx); - } - return newString; - } - - /// - /// riporta il log di tutti i dati di results temporali registrati - /// - public void logTimeResults() - { - if (TimingData.results.Count > 0) - { - lgInfo("{0}--------------- START TIMING DATA ---------------", Environment.NewLine); - int globNumCall = 0; - TimeSpan globAvgMsec = new TimeSpan(0); - foreach (TimeRec item in TimingData.results) - { - // loggo SOLO se del mio IOB corrente... - if (item.classCall == cIobConf.codIOB) - { - lgInfo("{4}|Chiamate {0}: effettuate {1}, tempo medio {2:N2} msec | impegno canale {3:P3}", item.codCall, item.numCall, item.avgMsec, item.totMsec.TotalSeconds / DateTime.Now.Subtract(dtAvvioAdp).TotalSeconds, cIobConf.codIOB); - globNumCall += item.numCall; - globAvgMsec += item.totMsec; - } - } - // riporto conteggio medio al secondo... - lgInfo("{4}|Chiamate GLOBALI: {0}, periodo: {1:N2} minuti.cent, tempo medio {2:N2} msec | impegno canale {3:P3}", globNumCall, DateTime.Now.Subtract(dtAvvioAdp).TotalMinutes, globAvgMsec.TotalMilliseconds / globNumCall, globAvgMsec.TotalSeconds / DateTime.Now.Subtract(dtAvvioAdp).TotalSeconds, cIobConf.codIOB); - lgInfo("{0}--------------- STOP TIMING DATA ---------------{0}", Environment.NewLine); - // mostro in form statistiche globali! - parentForm.updateComStats(string.Format("Periodo: {0:N2}min | {1} x {2:N2}ms | canale {3:P3}", DateTime.Now.Subtract(dtAvvioAdp).TotalMinutes, globNumCall, globAvgMsec.TotalMilliseconds / globNumCall, globAvgMsec.TotalSeconds / DateTime.Now.Subtract(dtAvvioAdp).TotalSeconds)); - } - } - - /// - /// Processa un monitoredItem, e ritorna boolean SE richiede invio (cambio o scadenza) - /// - /// - /// - /// - public bool monItem2Send(string newVal, DynDataItem item) - { - bool answ = false; - if (item != null) - { - // controllo in base al tipo di function... - switch (item.func) - { - case "SAMPLE": - // controllo se scaduto sample period... - if (item.DTScad < DateTime.Now) - { - answ = true; - } - break; - - case "CHANGE": - default: - // controllo se scaduto o se variato... - if (newVal != item.actVal || item.DTScad < DateTime.Now) - { - // aggiorno scadenza e che vada inviato - answ = true; - } - break; - } - } - return answ; - } - - /// - /// Verifica e processing x gestione ODL automatica - /// - public void processAutoOdl() - { - lgInfo("Richiesta processAutoOdl"); - bool fatto = false; - if (!string.IsNullOrEmpty(getOptPar("AUTO_CHANGE_ODL"))) - { - string IOB_MULTI_CNAME = ""; - string[] elencoMulti = null; - string fullUrl = ""; - if (isMulti) - { - // devo chiamare cambio ODL x OGNI tavola: mi servono i parametri opzionali... - IOB_MULTI_CNAME = getOptPar("IOB_MULTI_CNAME"); - elencoMulti = IOB_MULTI_CNAME.Split(','); - } - // controllo SIA abilitato... - bool doProc = false; - DateTime adesso = DateTime.Now; - bool.TryParse(getOptPar("AUTO_CHANGE_ODL"), out doProc); - if (doProc) - { - // carico i parametri di configurazione x reset ODL... - string CHANGE_ODL_HOURS = getOptPar("CHANGE_ODL_HOURS"); - string CHANGE_ODL_IDLE_MIN = getOptPar("CHANGE_ODL_IDLE_MIN"); - if (!string.IsNullOrEmpty(CHANGE_ODL_HOURS) && !string.IsNullOrEmpty(CHANGE_ODL_IDLE_MIN)) - { - int minOdlDurHours = -1; - int minPlcIdelMin = -1; - int.TryParse(CHANGE_ODL_HOURS, out minOdlDurHours); - int.TryParse(CHANGE_ODL_IDLE_MIN, out minPlcIdelMin); - // controllo parametri validi - if (minOdlDurHours > 0 && minPlcIdelMin >= 0) - { - // leggo da server inizio ODL... se non multi 1 solo... - DateTime inizioOdl = DateTime.Now; - string rawDataInizio = ""; - if (!isMulti) - { - rawDataInizio = callUrl(urlInizioOdlIob, false); - DateTime.TryParse(rawDataInizio, out inizioOdl); - } - else - { - DateTime tmpData = DateTime.Now; - // prendo il + vecchio... - foreach (var item in elencoMulti) - { - fullUrl = $"{urlInizioOdlIob}|{item}"; - rawDataInizio = callUrl(fullUrl, false); - DateTime.TryParse(rawDataInizio, out tmpData); - inizioOdl = (tmpData < inizioOdl) ? tmpData : inizioOdl; - } - } - // verifico se sia scaduto... - if (inizioOdl.AddHours(minOdlDurHours) < adesso) - { - string rawIdle = ""; - int idlePeriod = 0; - if (!isMulti) - { - // controllo SE sono fermo (spento o in manuale) per il periodo minimo richiesto... - rawIdle = callUrl(urlIdleTime, false); - int.TryParse(rawIdle, out idlePeriod); - } - else - { - int tmpIdle = 0; - // prendo il + grande... - foreach (var item in elencoMulti) - { - fullUrl = $"{urlIdleTime}|{item}"; - rawIdle = callUrl(fullUrl, false); - int.TryParse(rawIdle, out tmpIdle); - idlePeriod = tmpIdle > idlePeriod ? tmpIdle : idlePeriod; - } - } - if (idlePeriod >= minPlcIdelMin) - { - fatto = forceSplitOdl(); - lgInfo("Chiamata: processAutoOdl --> forceSplitODL"); - } - } - } - } - } - } - // loggo se fatto - if (fatto) - { - lgInfo($"Effettuato processAutoOdl"); - } - } - - /// - /// Effettua processing degli allarmi CNC SE disponibili - /// - public void processCncAlarms() - { - if (utils.CRB("enableAlarms")) - { - Dictionary currAlarms = new Dictionary(); - if (connectionOk) - { - currAlarms = getCncAlarms(); - } - else - { - lgError("Errore connessione mancante x getCncAlarms"); - } - // verifico SE sia cambiato il programma... - if (currAlarms.Count > 0) - { - try - { - if (lastAlarm != currAlarms["CNC_ALARM"]) - { - // salvo! - lastAlarm = currAlarms["CNC_ALARM"]; - // per ogni valore del dizionario mostro ed accodo! - string sVal = ""; - foreach (var item in currAlarms) - { - sVal = string.Format("[CNC_ALARM]{0}|{1}", item.Key, item.Value); - // chiamo accodamento... - accodaFLog(sVal, qEncodeFLog(item.Key, item.Value)); - } - } - } - catch (Exception exc) - { - lgError("Eccezione in processCncAlarms{0}{1}", Environment.NewLine, exc); - } - } - } - } - - /// - /// Effettua processing contapezzi (ed eventualmente alza il bit di contapezzo...) - /// - public virtual void processContapezzi() - { } - - /// - /// Effettua processing del recupero delle speed (RPM, feedrate) degli assi - /// - public void processDynData() - { - bool enableByApp = utils.CRB("enableDynData"); - bool enableByIob = (getOptPar("ENABLE_DYN_DATA") == "TRUE"); - bool forceSendByIob = (getOptPar("FORCE_DYN_DATA") == "TRUE"); - Dictionary currDynData = new Dictionary(); - - if (enableByApp || enableByIob) - { - lgInfo("Inizio processDynData"); - if (connectionOk) - { - currDynData = getDynData(); - } - else - { - lgError("Errore connessione mancante x getDynData"); - } - try - { - string sVal = ""; - // se richiesto send diretto... - if (forceSendByIob) - { - // per ogni valore del dizionario mostro ed accodo! - foreach (var item in currDynData) - { - sVal = string.Format("[DYNDATA]{0}|{1}", item.Key, item.Value); - // chiamo accodamento... - accodaFLog(sVal, qEncodeFLog(item.Key, item.Value)); - } - } - // altrimenti verifico SE sia cambiato il valore dei DynData... - else if (lastDynDataCtrlVal != currDynData["DYNDATA"]) - { - // salvo! - lastDynDataCtrlVal = currDynData["DYNDATA"]; - // per ogni valore del dizionario mostro ed accodo! - foreach (var item in currDynData) - { - sVal = string.Format("[DYNDATA]{0}|{1}", item.Key, item.Value); - // chiamo accodamento... - accodaFLog(sVal, qEncodeFLog(item.Key, item.Value)); - } - } - // salvo array... - lastDynData = currDynData; - } - catch (Exception exc) - { - lgError(exc, "Eccezione in processDynData"); - } - } - } - - /// - /// Processa gestione memoria x invio dati QUANDO IOB è disconnesso da CNC... - /// - public void processMemoryDiscon() - { - // init obj display - newDisplayData currDispData = new newDisplayData(); - // controllo contatore invio "keepalive"... invio solo a scadenza - if (DateTime.Now.Subtract(lastDisconnCheck).TotalSeconds > utils.CRI("disconMaxSec")) - { - // resetto tutti i vlaori BYTE IN/PREV/OUT... così invio macchina spenta... - B_input = 0; - B_output = 0; - B_previous = 0; - accodaSigIN(ref currDispData); - // update controllo - lastDisconnCheck = DateTime.Now; - } - raiseRefresh(currDispData); - } - - /// - /// Effettua processing mode/status (EDIT/MDI/...) - /// - public virtual void processMode() - { } - - /// - /// Effettua processing ALTRI contatori/parametri (ed invia ad IO) - /// - public virtual void processOtherCounters() - { } - - /// - /// Effettua processing del recupero delle OVERRIDE (spindle, feedrate, rapid) - /// - public virtual void processOverride() - { - bool enableByApp = utils.CRB("enableOverrides"); - bool enableByIob = (getOptPar("ENABLE_OVERRIDES") == "TRUE"); - Dictionary currOverride = new Dictionary(); - if (enableByApp || enableByIob) - { - lgInfo("Inizio processOverride"); - if (connectionOk) - { - currOverride = getOverrides(); - } - else - { - lgError("Errore connessione mancante x getOverrides"); - } - - // SE sono connesso... - if (connectionOk) - { - // se HO dei valori override... - if (currOverride.Count > 0) - { - // verifico SE sia cambiato il programma... - if (lastOverrideFS != currOverride["FEED_OVER"] || lastOverrideRapid != currOverride["RAPID_OVER"]) - { - // salvo! - lastOverrideFS = currOverride["FEED_OVER"]; - lastOverrideRapid = currOverride["RAPID_OVER"]; - // per ogni valore del dizionario mostro ed accodo! - string sVal = ""; - foreach (var item in currOverride) - { - sVal = string.Format("[OVERRIDES]{0}|{1}", item.Key, item.Value); - // chiamo accodamento... - accodaFLog(sVal, qEncodeFLog(item.Key, item.Value)); - } - } - } - } - } - } - - /// - /// Effettua ciclo controllo richieste server - /// - public void processServerRequests() - { - Dictionary task2exe = new Dictionary(); - Dictionary taskDone = new Dictionary(); - // recupero elenco delle cose da fare - string resp = getTask2exe(); - if (!string.IsNullOrEmpty(resp)) - { - try - { - task2exe = JsonConvert.DeserializeObject>(resp); - // se ho da fare chiamo esecuzione.. - if (task2exe.Count > 0) - { - taskDone = processTask(task2exe); - } - } - catch (Exception exc) - { - lgError($"Eccezione in processServerRequests:{Environment.NewLine}{exc}"); - } - } - } - - public Dictionary processTask(Dictionary task2exe) - { - Dictionary taskDone = new Dictionary(); - if (task2exe != null) - { - lgInfo($"Task2Exe: trovati {task2exe.Count} task da eseguire, procedo"); - // chiamo procedura esecutiva (diversa x ogni IOB) - taskDone = executeTasks(task2exe); - // loggo tutti i task done... - foreach (var item in taskDone) - { - sendToTaskWatch(item.Key, item.Value); - } - // ora chiamo la cancellazione dei task eseguiti... - foreach (var item in taskDone) - { - remTask2exe(item.Key, item.Value); - } - } - return taskDone; - } - - /// - /// Classe fittizia in caso di processing task in VHF - /// - public virtual void processVHF() - { - } - - /// - /// Classe fittizia in caso di processing watchdog data - /// - public virtual void processWhatchDog() - { - } - - /// - /// Effettua rilettura del contapezzi dal server MP/IO - /// - /// Forza rilettura da DB tempi ciclo rilevati - public void pzCntReload(bool forceCountRec) - { - // legge da IO server ULTIMO valore CONTPEZZI al riavvio... - string currServerCount = ""; - string lastIdxODL = ""; - if (checkServerAlive) - { - // leggo PRIMA ODL .... - lastIdxODL = utils.callUrl(urlGetCurrODL); - lgInfo("Lettura ODL dall'url {0} --> {1}", urlGetCurrODL, lastIdxODL); - // se ho valori in coda da trasmettere uso dati REDIS - if (forceCountRec) - { - // uso dati da TCiclo registrati... - currServerCount = utils.callUrl(urlGetPzCountRec); - lgInfo("Lettura contapezzi da TCiclo dall'url {0} --> num pz: {1}", urlGetPzCountRec, currServerCount); - } - else - { - // uso il contapezzi dichiarato dall'IOB stesso - currServerCount = utils.callUrl(urlGetPzCount); - lgInfo("Lettura contapezzi dall'url {0}", urlGetPzCount); - } - // controllo: SE NON HO ODL... - if (string.IsNullOrEmpty(lastIdxODL) || lastIdxODL == "0") - { - // NON AGGIORNO - contapezziIOB = contapezziPLC; - lgInfo($"Errore lettura ODL (vuoto) resta tutto invariato contapezzi: {contapezziIOB} | contapezziPLC {contapezziPLC}"); - } - else - { - if (!string.IsNullOrEmpty(currServerCount)) - { - // se "-1" resto a ultimo... - if (currServerCount != "-1") - { - int newVal = -1; - Int32.TryParse(currServerCount, out newVal); - contapezziIOB = newVal > -1 ? newVal : contapezziIOB; - lgInfo("Ricevuta conferma da server di {0} pezzi registrati per ODL", currServerCount); - } - else - { - // NON AGGIORNO - contapezziIOB = contapezziPLC; - lgInfo($"Errore lettura contapezzi (-1) - uso contapezziPLC --> {contapezziPLC}"); - } - } - else - { - // registro che ho UN NUOVO ODL - lgInfo($"Lettura ODL in pzCntReload, currIdxODL {currIdxODL} --> lastIdxODL {lastIdxODL}"); - // se ODL differente e NUOVO è zero --> resetto! - if (currIdxODL.ToString() != lastIdxODL && lastIdxODL == "0") - { - // cambiato ODL quindi reset... - contapezziIOB = 0; - lgInfo("Nuovo ODL==0, RESET contapezzi (-->ZERO)"); - } - // provo a salvare nuovo ODL - int.TryParse(lastIdxODL, out currIdxODL); - } - } - } - else - { - // se server NON pronto... - contapezziIOB = contapezziPLC; - lgError("Errore server NON pronto in pzCntReload"); - } - } - - /// - /// Fornisce il valore di flusso e valore in formato valido x messa in coda nel formato dtEve#flux#value#cont - /// Flusso dati - /// Valore da salvare - /// - public string qEncodeFLog(string flusso, string valore) - { - string answ = ""; - try - { - answ = string.Format("{0:yyyyMMddHHmmssfff}#{1}#{2}#{3}", DateTime.Now, flusso, valore, counterFLog); - } - catch - { } - return answ; - } - - /// - /// Fornisce il valore di flusso e valore in formato valido x messa in coda nel formato dtEve#flux#value#cont - /// DataOra evento registrato - /// Flusso dati - /// Valore da salvare - /// - public string qEncodeFLog(DateTime eventDT, string flusso, string valore) - { - string answ = ""; - try - { - answ = string.Format("{0:yyyyMMddHHmmssfff}#{1}#{2}#{3}", eventDT, flusso, valore, counterFLog); - } - catch - { } - return answ; - } - - /// - /// Effettua lettura dati - /// Parametri da aggiornare x display in form - /// - public virtual void readAllData(ref newDisplayData currDispData) - { - if (currDispData == null) - { - currDispData = new newDisplayData(); - } - try - { - if (DemoIn) - { - // segnalo che sono in Demo - currDispData.semIn = Semaforo.SV; - } - if (connectionOk) - { - readSemafori(ref currDispData); - lastReadPLC = DateTime.Now; - } - else - { - lgError("Errore connessione mancante x readSemafori"); - } - - nReadIN++; - // aggiorno valore mostrato... - displayRawData(ref currDispData); - } - catch - { - currDispData.semIn = Semaforo.SR; - } - raiseRefresh(currDispData); - } - - /// - /// Effettua lettura semafori principale - /// Parametri da aggiornare x display in form - /// - public virtual void readSemafori(ref newDisplayData currDispData) - { - lastReadPLC = DateTime.Now; - } - - /// - /// Aggiunge ai dati da inviare alla parentform i valori di RawInput rilevati - /// - public virtual void reportRawInput(ref newDisplayData currDispData) - { - // processo eventualmente aggiungendo ad elementi esistenti... - if (currDispData == null) - { - currDispData = new newDisplayData(); - } - try - { - StringBuilder sb = new StringBuilder(); - sb.Append($"B_input --> {(short)B_input}{Environment.NewLine}"); - sb.Append($"{baseUtils.binaryForm(B_input)}{Environment.NewLine}"); - sb.Append($"{Environment.NewLine}"); - sb.Append($"----------- RAW Data Memory -----------{Environment.NewLine}"); - int i = 0; - foreach (var item in RawInput) - { - sb.Append($"B{i:00} --> {baseUtils.binaryForm(item)} = {(short)item}{Environment.NewLine}"); - i++; - } - sb.Append("-------------------------------"); - currDispData.currBitmap = sb.ToString(); - } - catch - { } - } - - /// - /// Metodo generico di reset contapezzi... - /// - /// - public virtual bool resetcontapezziPLC() - { - return false; - } - - /// - /// metodo dummy x salvataggio aree memoria conf x CN - /// - /// tipo di DUMP - public virtual void saveMemDump(dumpType tipo) - { - } - - /// - /// Salva valori indicati in prod data - /// - /// Item KVP di cui salvare i dati in currProdData come chiave/valore - /// - public void saveProdData(KeyValuePair item) - { - // imposto i valori... - if (currProdData.ContainsKey(item.Key)) - { - currProdData[item.Key] = item.Value; - } - else - { - currProdData.Add(item.Key, item.Value); - } - } - - /// - /// - /// - /// - /// - /// - /// - public void saveValue(ref Dictionary outVal, double valore, string chiave) - { - //check obj preliminare - if (outVal == null) - { - outVal = new Dictionary(); - } - bool scaduto = stackVal_TSVC(chiave, valore); - // recupero VC - valore = getVal_TSVC(chiave, scaduto); - if (scaduto) - { - outVal.Add(chiave, $"{valore}"); - } - LastTSVC[chiave] = valore; - } - - /// - /// Invia una LISTA di valori - /// - /// - /// - public void sendDataBlock(urlType tipoUrl, List listQueueVal) - { - // init obj display - newDisplayData currDispData = new newDisplayData(); - if (listQueueVal != null) - { - try - { - // recupero e formatto URL dati da coda... - lastUrl = urlDataBlock(tipoUrl); - // in base al tipo di dato compongo il payload Json da inviare - string payload = jsonPayload(tipoUrl, listQueueVal); - // async a true SE FLog - bool doAsync = tipoUrl == urlType.FLog ? true : false; - // se NON sono in demo effettuo invio! - if (!DemoOut) - { - // SE server alive... - if (checkServerAlive) - { - // chiamo URL! - string answ = callUrlWithPayload(lastUrl, payload, doAsync); - // loggo! - lgInfo($"[SEND payload] TipoURL: {tipoUrl} | {listQueueVal.Count} records --> {answ}"); - // se "OK" verde, altrimenti errore --> ROSSO - if (answ.Contains("OK")) - { - currDispData.semOut = Semaforo.SV; - // se oltre 1 min NON era online --> check pezzi! - if (DateTime.Now.Subtract(lastIobOnline).TotalMinutes > 1 && !isMulti) - { - lgInfo($"sendDataBlock --> offline timeout ({lastIobOnline}) --> pzCntReload(true)"); - pzCntReload(true); - } - lastIobOnline = DateTime.Now; - } - else - { - currDispData.semOut = Semaforo.SR; - } - } - else - { - lgInfo($"[SERVER KO] {listQueueVal.Count}"); - } - } - else - { - currDispData.semOut = Semaforo.SV; - // loggo! - lgInfo($"{listQueueVal.Count} records --> [SIM]"); - } - nSendOut += listQueueVal.Count; - // riporto cosa inviato - currDispData.newUrlCallData = lastUrl; - // aggiorno data ultimo watchdog... - lastWatchDog = DateTime.Now; - } - catch - { - currDispData.semOut = Semaforo.SR; - } - } - raiseRefresh(currDispData); - } - - /// - /// Effettua invio a MoonPro del valore richiesto - /// - /// - /// Valore da trasmettere: es - /// INPUT: lo status rilevato in HEX - /// FLog: il valore da trasmettere per il flusso indicato - public void sendToMoonPro(urlType tipoUrl, string queueVal) - { - // init obj display - newDisplayData currDispData = new newDisplayData(); - try - { - // recupero e formatto URL dati da coda... - switch (tipoUrl) - { - case urlType.FLog: - lastUrl = urlFLog(queueVal); - break; - - case urlType.SignIN: - lastUrl = urlInput(queueVal); - break; - - default: - lastUrl = ""; - break; - } - // se NON sono in demo effettuo invio! - if (!DemoOut) - { - // SE server alive... - if (checkServerAlive) - { - // chiamo URL! - string answ = callUrl(lastUrl, false); - // loggo! - lgInfo(string.Format("[SEND] {0} -> {1}", queueVal, answ)); - // se oltre 1 min NON era online --> check pezzi! - if (DateTime.Now.Subtract(lastIobOnline).TotalMinutes > 1 && !isMulti) - { - lgInfo($"sendToMoonPro --> offline timeaout ({lastIobOnline}) --> pzCntReload(true)"); - pzCntReload(true); - } - // se richiesto effettuo refresh contapezzi - if (needRefreshPzCount && !isMulti) - { - pzCntReload(true); - needRefreshPzCount = false; - } - lastIobOnline = DateTime.Now; - // se "OK" verde, altrimenti errore --> ROSSO - if (answ == "OK") - { - currDispData.semOut = Semaforo.SV; - } - else - { - currDispData.semOut = Semaforo.SR; - } - } - else - { - lgInfo(string.Format("[SERVER KO] {0}", queueVal)); - } - } - else - { - currDispData.semOut = Semaforo.SV; - // loggo! - lgInfo(string.Format("{0} -> [SIM]", queueVal)); - } - nSendOut++; - // riporto cosa inviato -#if false - displayOutData(); -#endif - currDispData.newUrlCallData = lastUrl; - // aggiorno data ultimo watchdog... - lastWatchDog = DateTime.Now; - } - catch - { - currDispData.semOut = Semaforo.SR; - } - raiseRefresh(currDispData); - } - - /// - /// Metodo generico di IMPOSTAZIONE FORZATA del contapezzi... - /// - /// Pezzi richiesti - /// - public virtual bool setcontapezziPLC(int newPzCount) - { - return false; - } - - /// - /// Processing di Variabili Campionarie x TimeSeries, accoda valori x la VC (se esiste) e restituisce bool val se SCADUTO periodo controllo - /// - /// Nome della VC - /// Valore (nuovo) delal VC - /// - public bool stackVal_TSVC(string VCName, double VCVal) - { - bool answ = false; - // cerco VC... - if (TSVC_Data.ContainsKey(VCName)) - { - TSVC_Data[VCName].dataArray.Add(VCVal); - // ora verifico scadenza... - if (TSVC_Data[VCName].DTStart.AddSeconds(TSVC_Data[VCName].Period) < DateTime.Now) - { - answ = true; - } - } - return answ; - } - - /// - /// Avvia l'adapter sulla porta richiesta - /// - /// indica se sia richeisto di SVUOTARE le code delel info - public virtual void startAdapter(bool resetQueue) - { - lgInfo("Starting adapter..."); - maxJsonData = utils.CRI("maxJsonData"); - maxJsonDataEv = utils.CRI("maxJsonDataEv"); - parentForm.commPlcActive = false; - adpRunning = true; - dtAvvioAdp = DateTime.Now; - lastWatchDog = dtAvvioAdp; - lastPING = dtAvvioAdp; - lastReadPLC = dtAvvioAdp.AddMinutes(-1); - lastDisconnCheck = dtAvvioAdp; - TimingData.resetData(); - // aggiungo altri defaults - setDefaults(resetQueue); - adpTryRestart = true; - parentForm.displayTaskAndLog("Adapter Started!"); - } - - /// - /// ferma l'adapter... - /// - /// indica se si debba tentare di riavviare l'adapter (con caduta connessione viene fermato in automatico) - /// indica se sia richeisto di SVUOTARE le code delel info - public virtual void stopAdapter(bool tryRestart, bool forceDequeue) - { - if (forceDequeue) - { - // svuoto le code dei valori letti e non ancora trasmessi... - parentForm.displayTaskAndLog("[CLOSING] Svuotamento FORZATO coda segnali..."); - while (QueueIN.Count > 0) - { - // INVIO COMUNQUE...!!! - string valore = ""; - QueueIN.TryDequeue(out valore); - sendToMoonPro(urlType.SignIN, valore); - } - parentForm.displayTaskAndLog("[CLOSING] Svuotamento FORZATO coda FluxLOG..."); - // se ho + di 2 elementi in coda --> uso invio JSON in blocco... - if (QueueFLog.Count > minJsonData) - { - while (QueueFLog.Count > 0) - { - List listaValori = new List(); - // se ho + di maxJsonData elementi --> invio un set di dati alla volta - if (QueueFLog.Count > maxJsonData) - { - string currVal = ""; - // prendoi primi maxJsonDataValori - for (int i = 0; i < maxJsonData; i++) - { - QueueFLog.TryDequeue(out currVal); - listaValori.Add(currVal); - } - sendDataBlock(urlType.FLog, listaValori); - } - else - { - // invio in blocco - listaValori = QueueFLog.ToList(); - // invio - sendDataBlock(urlType.FLog, listaValori); - // svuoto! - QueueFLog = new ConcurrentQueue(); - } - } - // HO FINITO invio di FLog... - } - else - { - string currVal = ""; - while (QueueFLog.Count > 0) - { - // INVIO COMUNQUE...!!! - QueueFLog.TryDequeue(out currVal); - sendToMoonPro(urlType.FLog, currVal); - } - } - } - parentForm.displayTaskAndLog("[STOP] Stopping adapter..."); - adpTryRestart = false; - - parentForm.displayTaskAndLog("[STOP] Stopping adapter - last periodic data read..."); - - // chiudo la connessione all'adapter... - tryDisconnect(); - dtStopAdp = DateTime.Now; - adpTryRestart = tryRestart; - adpRunning = false; - // chiudo! - parentForm.displayTaskAndLog("Adapter Stopped."); - parentForm.commPlcActive = false; - } - - /// - /// Processo la coda SignalIN... - /// - public void svuotaCodaSignIN() - { - // verifico SE la coda abbia dei valori... - if (QueueIN.Count > 0) - { - // invio pacchetto di dati (max da conf) - for (int i = 0; i < nMaxSend; i++) - { - if (QueueIN.Count > 0) - { - string currVal = ""; - // se online provo - if (MPOnline) - { - if (IobOnline) - { - // se ho + di 2 elementi in coda --> uso invio JSON in blocco... - if (QueueIN.Count > 1) - { - List listaValori = new List(); - // se ho + di maxJsonData elementi --> invio un set di dati alla volta - if (QueueIN.Count > maxJsonDataEv) - { - // prendoi primi maxJsonDataValori - for (int j = 0; j < maxJsonDataEv; j++) - { - QueueIN.TryDequeue(out currVal); - listaValori.Add(currVal); - } - sendDataBlock(urlType.SignIN, listaValori); - } - else - { - // invio in blocco - listaValori = QueueIN.ToList(); - // invio - sendDataBlock(urlType.SignIN, listaValori); - // svuoto! - QueueIN = new ConcurrentQueue(); - } - } - else - { - // INVIO SINGOLO...!!! - QueueIN.TryDequeue(out currVal); - sendToMoonPro(urlType.SignIN, currVal); - } - // salvo come last signal in il currVal ultimo... SE !="" - if (!string.IsNullOrEmpty(currVal)) - { - lastSignInVal = currVal; - } - } - else - { - break; - } - } - else - { - break; - } - } - else - { - break; - } - } - } - } - - /// - /// Metodo base connessione... - /// - public virtual void tryConnect() - { - dtAvvioAdp = DateTime.Now; - } - - /// - /// Metodo base disconnessione... - /// - public virtual void tryDisconnect() - { - } - - /// - /// Effettua verifica se abilitato invio pezzi in blocco e nel caso - /// - invio in blocco pezzi - /// - aggiornamento del contapezzi (passato come ref) x nuovo valore post invio - /// - public void trySendPzCountBlock() - { - // in primis HA SENSO procedere SOLO SE server MP è Online... - if (MPOnline) - { - // SOLO SE online la macchina... - if (IobOnline) - { - int numIncr = 0; - int qtyAdded = 0; - // verifico se la funzione SIA abilitata - if (enableSendPzCountBlock) - { - int delta = contapezziPLC - contapezziIOB; - // se è abilitata verifico differenza: se ho DELTA > minSendPzCountBlock --> invio un blocco <= maxSendPzCountBlock - if (delta > minSendPzCountBlock) - { - // init obj display - newDisplayData currDispData = new newDisplayData(); - // resta indietro di ALMENO minSendPzCountBlock pezzi x recuperare 1:1... - numIncr = delta > maxSendPzCountBlock + minSendPzCountBlock ? maxSendPzCountBlock : delta - minSendPzCountBlock; - // invio il num max di pezzi ammesso in blocco! - lastUrl = $"{urlAddPzCount}{numIncr}"; - string resp = utils.callUrlNow(lastUrl); - if (!string.IsNullOrEmpty(resp)) - { - // dalla risposta (come numero) capisco SE ha aggiunto i pezzi (e quanti) - int.TryParse(resp, out qtyAdded); - if (qtyAdded > 0) - { - // aggiorno IL MIO contapezzi... - contapezziIOB += qtyAdded; - lgInfo($"Inviato incremento contapezzi: send: {numIncr} | resp: {qtyAdded} | contapezziIOB: {contapezziIOB}"); - // invio conferma contapezzi.. - string retVal = utils.callUrl($"{urlSetPzCount}{contapezziIOB}"); - // verifica se tutto OK - if (retVal != contapezziIOB.ToString()) - { - // errore salvataggio contapezzi - lgInfo($"trySendPzCountBlock: errore salvataggio contapezzi: contapezziIOB {contapezziIOB} | risposta: {retVal}"); - } - } - else - { - lgError($"Richiesto incremento {numIncr} ma NON registrato su server MP-IO"); - } - } - currDispData.newUrlCallData = lastUrl; - currDispData.counter = contapezziIOB; - currDispData.semOut = Semaforo.SV; - raiseRefresh(currDispData); - } - } - } - else - { - lgInfo("Impossibile trySendPzCountBlock: IobOnline è false"); - } - } - else - { - lgInfo("Impossibile trySendPzCountBlock: MPOnline è false"); - } - } - - /// - /// Formatta URL x invio in DataBlock Json dei dati FLog / eventi - /// - /// - /// - public string urlDataBlock(urlType tipoUrl) - { - // verifico la parte di link "tipoComando" - string tipoComando = tipoUrl == urlType.FLog ? cIobConf.serverData.CMDFLOG_JSON : cIobConf.serverData.CMDBASE_JSON; - // URL base x input - string answ = string.Format(@"http://{0}{1}{2}{3}", cIobConf.serverData.MPIP, cIobConf.serverData.MPURL, tipoComando, cIobConf.codIOB); - return answ; - } - - /// - /// Fornisce URL di tipo FluxLog - /// - /// valore salvato in coda nel formato dtEve#flux#valore#counter - /// - public string urlFLog(string queueVal) - { - // URL base x input - string answ = string.Format(@"http://{0}{1}{2}", cIobConf.serverData.MPIP, cIobConf.serverData.MPURL, cIobConf.serverData.CMDFLOG); - // decodifica valore! - string[] valori = qDecodeIN(queueVal); - // aggiungo macchina e valore... - answ += string.Format(@"{0}?flux={1}&&valore={2}", cIobConf.codIOB, valori[1], valori[2]); - // aggiondo dataOra evento e corrente + contatore... - answ += string.Format(@"&&dtEve={0}&&dtCurr={1:yyyyMMddHHmmssfff}&&cnt={2}", valori[0], DateTime.Now, valori[3]); - return answ; - } - - /// - /// Fornisce URL INPUT per i parametri richiesti - /// - /// valore salvato in coda formato dtEve#valore#counter - /// - public string urlInput(string queueVal) - { - // URL base x input - string answ = string.Format(@"http://{0}{1}{2}", cIobConf.serverData.MPIP, cIobConf.serverData.MPURL, cIobConf.serverData.CMDBASE); - // decodifica valore! - string[] valori = qDecodeIN(queueVal); - // aggiungo macchina e valore... - answ += string.Format(@"{0}?valore={1}", cIobConf.codIOB, valori[1]); - // aggiondo dataOra evento e corrente + contatore... - answ += string.Format(@"&&dtEve={0}&&dtCurr={1:yyyyMMddHHmmssfff}&&cnt={2}", valori[0], DateTime.Now, valori[2]); - return answ; - } - - #endregion Public Methods - } - - /// - /// Evento per incapsulare dati x refresh pagina - /// - public class iobRefreshedEventArgs : EventArgs - { - #region Private Fields - - /// - /// classe obj privata - /// - private readonly newDisplayData _newDisplayData; - - #endregion Private Fields - - #region Public Constructors - - /// - /// salvataggio obj - /// - /// - public iobRefreshedEventArgs(newDisplayData newObject) - { - _newDisplayData = newObject; - } - - #endregion Public Constructors - - #region Public Properties - - /// - /// Proprietà lettura displayData aggiornato - /// - public newDisplayData DisplayDataObject - { - get { return _newDisplayData; } - } - - #endregion Public Properties - } -} \ No newline at end of file diff --git a/IOB-WIN/IobMTC.cs.bak b/IOB-WIN/IobMTC.cs.bak deleted file mode 100644 index 2f0a908a..00000000 --- a/IOB-WIN/IobMTC.cs.bak +++ /dev/null @@ -1,1234 +0,0 @@ -using IOB_UT; -using MapoSDK; -using MTConnect.Clients; -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.IO; -using System.Net.NetworkInformation; -using System.Threading; -using System.Windows.Forms; -using MTConnectDevices = MTConnect.MTConnectDevices; -using MTConnectStreams = MTConnect.MTConnectStreams; - -namespace IOB_WIN -{ - public class IobMTC : IobGeneric - { - #region Private Fields - - /// - /// Struttura dove vengono memorizzati i dataitem ed i rispettivi valori x processing - /// - private Dictionary dataItemMem = new Dictionary(); - - #endregion Private Fields - - #region Protected Fields - - /// - /// Gestione filtraggio dati - /// - protected bool enableDataFilter = false; - - /// - /// Abilitazione restart (da opt par...) - /// - protected bool enableMtcRestart = false; - - /// - /// Determina se ha effettuata lettura items in memoria x confronto... - /// - protected bool hasReadItems = false; - - /// - /// Ultimo current received x gestione update periodico... - /// - protected DateTime lastCurrent = DateTime.Now; - - /// - /// Oggetto MAIN x connessione MTC - /// - protected MTConnectClient MTC_ref; - - /// - /// Veto controllos tatus x log... - /// - protected DateTime vetoCheckStatus = DateTime.Now; - - #endregion Protected Fields - - #region Public Constructors - - /// - /// Estende l'init della classe base, impiegando il pacchetto Nuget TrackHound - /// https://github.com/TrakHound/MTConnect.NET - /// - /// - /// - public IobMTC(AdapterForm caller, IobConfiguration IOBConf) : base(caller, IOBConf) - { - // gestione invio ritardato contapezzi - pzCountDelay = utils.CRI("pzCountDelay"); - // gestione data filtering... - if (!string.IsNullOrEmpty(getOptPar("ENABLE_DATA_FILTER"))) - { - bool.TryParse(getOptPar("ENABLE_DATA_FILTER"), out enableDataFilter); - } - // gestione restart MTC client... - if (!string.IsNullOrEmpty(getOptPar("ENABLE_MTC_RESTART"))) - { - bool.TryParse(getOptPar("ENABLE_MTC_RESTART"), out enableMtcRestart); - } - // init datetime counters - DateTime adesso = DateTime.Now; - lastPzCountSend = adesso; - lastWarnODL = adesso; - lastCurrent = adesso; - // ora leggo il file di conf specifico.... - string jsonFileName = getOptPar("MTC_PARAM_CONF"); - if (!string.IsNullOrEmpty(jsonFileName)) - { - // leggo il file... - loadMtcConf(jsonFileName); - } - } - - #endregion Public Constructors - - #region Protected Properties - - /// - /// Verifico se abbia ALMENO un errore... - /// - protected bool hasError - { - get - { - bool answ = false; - // controllo TUTTE le conditions... - foreach (var item in dataItemMem) - { - // se NON HO GIA' allarmi attivi... - if (!answ) - { - // se è una condition... - if (item.Value.Category == MTConnect.DataItemCategory.CONDITION) - { - // se ha valore !="" --> allarmi attivi - if (!string.IsNullOrEmpty(item.Value.value)) - { - answ = true; - } - } - } - } - return answ; - } - } - - /// - /// Indica se abbia emergenza premuta - /// - protected bool hasEStopTriggered - { - get - { - bool answ = false; - try - { - if (!string.IsNullOrEmpty(mtcParams.keyEStop)) - { - string currEStop = getDataItemValue(mtcParams.keyEStop); - answ = (currEStop == "TRIGGERED"); - } - } - catch - { } - return answ; - } - } - - /// - /// Parametri specifici MTC - /// - protected MtcParamConf mtcParams { get; set; } - - /// - /// URL x salvataggio elenco dataItems MTC - /// - protected string urlSaveDataItems - { - get - { - string answ = ""; - try - { - string machineName = Environment.MachineName; - answ = $@"http://{cIobConf.serverData.MPIP}{cIobConf.serverData.MPURL}{cIobConf.serverData.CMDALIVE}/saveDataItems/{cIobConf.codIOB}"; - } - catch (Exception exc) - { - lgError(exc, "Errore in composizione urlSaveDataItems"); - } - return answ; - } - } - - #endregion Protected Properties - - #region Private Methods - - /// - /// Verifica ed invia variazioni - /// - /// - /// - private void checkAndSend(MTConnectStreams.Document document, bool forceSend) - { - if (document != null) - { - foreach (var deviceStream in document.DeviceStreams) - { - string sVal = ""; - string descr = ""; - DateTime locTStamp = DateTime.Now; - // check su Conditions - try - { - // check su dataItems (conditions + events + samples) - foreach (var dataItem in deviceStream.Conditions) - { - descr = itemTranslation("C", dataItem.DataItemId); - locTStamp = dataItem.Timestamp.ToLocalTime(); - sVal = $"CONDITION: {locTStamp.ToString()} | Id: {dataItem.DataItemId} | | Name: {dataItem.Name} | descr: {descr} | Val: {dataItem.CDATA}"; - // condizion verboso SEMPRE! - lgInfo(sVal); - DateTime tStamp = dataItem.Timestamp; - var time2 = tStamp.ToLocalTime(); - // verifico se salvare - bool changed = checkSaveItem(dataItem); - if (changed || forceSend) - { - // accodare ed invia nella coda ALARMS (che POI salva in document MongoDB anche ultimi x minuti di FluxLog...) - accodaAlarmLog(sVal, qEncodeFLog(time2, descr, dataItem.CDATA)); - } - } - } - catch (Exception exc) - { - lgError($"Eccezione in decodifica Conditions x StreamSuccesfull{Environment.NewLine}{exc}", false); - } - // check su events - try - { - // check su dataItems (conditions + events + samples) - foreach (var dataItem in deviceStream.Events) - { - descr = itemTranslation("E", dataItem.DataItemId); - locTStamp = dataItem.Timestamp.ToLocalTime(); - sVal = $"EVENT: {locTStamp.ToString()} | descr: {descr} | Id: {dataItem.DataItemId} | Name: {dataItem.Name} | Val: {dataItem.CDATA}"; - if (isVerboseLog) - { - lgInfo(sVal); - } - DateTime tStamp = dataItem.Timestamp; - var time2 = tStamp.ToLocalTime(); - // verifico se salvare - bool changed = checkSaveItem(dataItem); - // cerco se non sia un dato filtrato in FLUXLOG... - - if (changed || forceSend) - { - accodaFLog(sVal, qEncodeFLog(time2, descr, dataItem.CDATA)); - } - } - } - catch (Exception exc) - { - lgError($"Eccezione in decodifica Events x StreamSuccesfull{Environment.NewLine}{exc}", false); - } - - // check su samples - try - { - // check su dataItems (conditions + events + samples) - foreach (var dataItem in deviceStream.Samples) - { - descr = itemTranslation("S", dataItem.DataItemId); - locTStamp = dataItem.Timestamp.ToLocalTime(); - sVal = $"SAMPLE: {locTStamp.ToString()} | descr: {descr} | Id: {dataItem.DataItemId} | | Name: {dataItem.Name} | Val: {dataItem.CDATA}"; - if (isVerboseLog) - { - lgInfo(sVal); - } - DateTime tStamp = dataItem.Timestamp; - var time2 = tStamp.ToLocalTime(); - // verifico se salvare - bool changed = checkSaveSample(dataItem); - // cerco se non sia un dato filtrato in FLUXLOG... - bool isFiltered = mtcParams.fluxLogVeto.Contains(dataItem.DataItemId); - if (isFiltered) - { - if (isVerboseLog) - { - lgInfo($"NON ACCODATO sample per {dataItem.DataItemId} poiché trovato VETO in fluxLogVeto", false); - } - } - else - { - if (changed || forceSend) - { - accodaFLog(sVal, qEncodeFLog(time2, descr, dataItem.CDATA)); - } - else - { - if (isVerboseLog) - { - lgInfo($"NON ACCODATO sample per {dataItem.DataItemId} poiché verifica variazione SAMPLE ha dato esito negativo", false); - } - } - } - } - } - catch (Exception exc) - { - lgError($"Eccezione in decodifica Samples x StreamSuccesfull{Environment.NewLine}{exc}"); - } - } - } - else - { - lgError("StreamsSuccessful ERROR: document è null"); - } - } - - /// - /// Effettua decodifica aree memoria alla bitmap usata x MAPO - /// - private void decodeToBaseBitmap() - { - // init a zero... - B_input = 0; - - /* ----------------------------------------------------- - * bitmap MAPO - * B0: POWER_ON - * B1: RUN - * B2: pzCount - * B3: allarme - * B4: manuale - * B5: emergenza - ----------------------------------------------------- */ - - // Controllo booleano PING e POWERON... - string currPowerOn = getDataItemValue(mtcParams.condPowerOn.keyName); - // se valido il check ping lo eseguo... altrimenti lo do x buono - bool checkPing = !mtcParams.pingAsPowerOn; - if (!checkPing) - { - checkPing = (testPingMachine == IPStatus.Success); - } - // verifico da target value richiesto... - bool checkPowerOn = (currPowerOn == mtcParams.condPowerOn.targetValue); - - // bit 0 (poweron) imposto a 1 SE pingo o PowerOn=="ON"... - B_input = (checkPing || checkPowerOn) ? 1 : 0; - - // variabili RUN... - string currRun = getDataItemValue(mtcParams.keyRunMode); - - // controllo RUN MODE preliminare... CABLATO poiché è GENERALE x MTC - if (currRun == "AUTOMATIC" || currRun == "SEMI_AUTO" || currRun == "SEMI_AUTOMATIC") - { - int numCond = mtcParams.condWork.Count; - int numCondOk = 0; - // cerco nell'elenco delle condizioni che indicano lavora se sono ok faccio +1 conteggio...... - foreach (var item in mtcParams.condWork) - { - if (getDataItemValue(item.keyName) == item.targetValue) - { - numCondOk++; - } - } - // se tutte condizioni rispettate --> lavora! - if (numCond == numCondOk) - { - // RUN = LAVORA! - B_input += (1 << 1); - } - } - // se ho emergenza premuta --> emergenza! - else if (hasEStopTriggered) - { - B_input += (1 << 5); - } - // se ho almeno 1 allarme E NON SONO IN AUTO --> ALARM! - else if (hasError) - { - B_input += (1 << 3); - } - else - { - // se ho run mode != auto --> manual - B_input += (1 << 4); - } - - DateTime adesso = DateTime.Now; - int vFactor = 1; - // controllo SE HO dati per fare verifiche... - if (string.IsNullOrEmpty(currRun)) - { - // se ho parametro x gestione reset... - if (enableMtcRestart) - { - // controllo se ho ricevuto il current da OLTRE 1 minuto... - if (lastCurrent.AddMinutes(3) < adesso) - { - lastCurrent = adesso; - // stop... - lgInfo("Fermato MTC_ref per mancanza dati current"); - MTC_ref.Stop(); - Thread.Sleep(1000); - // restart - lgInfo("Riavviato MTC_ref per mancanza dati current"); - MTC_ref.Start(); - } - } - } - else - { - vFactor = 6; - } - - // solo se non ho veto check - if (vetoCheckStatus < adesso) - { - lgInfo($"Stato variabili: currRun: {currRun}"); - // imposto veto per vetoSeconds... - vetoCheckStatus = adesso.AddSeconds(vetoSeconds * vFactor); - } - // log opzionale! - if (verboseLog) - { - lgInfo($"Trasformazione B_input: {B_input} | currRun = {currRun}"); - } - } - - /// - /// Vera connessione ad MTC - /// - /// - private short doConnect() - { - short esitoLink = 0; - // reset memoria dataItem.. - dataItemMem = new Dictionary(); - // predisposizione conf oggetto di comunicazione MTC - short port = 5000; - short.TryParse(cIobConf.cncPort, out port); - // test probe! - try - { - var probe = new Probe($"http://{cIobConf.cncIpAddr}:{port}").Execute(); - // se valido loggo! - if (probe != null) - { - lgInfo($"Effettuata correttamente PROBE per device MTC all'URL {probe.Url} | vers: {probe.Version} | send: {probe.Header.Sender}"); - lgInfo($"---------------- Elenco Devices ----------------"); - // loggo devices principali... - logDevicesList(probe.Devices); - } - } - catch (Exception exc) - { - lgError($"Eccezione durante test probe:{Environment.NewLine}{exc}"); - } - // attendo 1 sec... - Thread.Sleep(1000); - // ora avvio - try - { - lgInfo($"Chiamata apertura MTC Client: {cIobConf.cncIpAddr}:{port}"); - MTC_ref = new MTConnectClient($"http://{cIobConf.cncIpAddr}:{port}"); - // Subscribe to the Event handlers to receive the MTConnect documents - MTC_ref.ProbeReceived += DevicesSuccessful; - MTC_ref.CurrentReceived += CurrentSuccessful; - MTC_ref.SampleReceived += StreamsSuccessful; - - // attendo 1 sec... - Thread.Sleep(1000); - MTC_ref.Start(); - esitoLink = 1; - - // fix tempi! - DateTime adesso = DateTime.Now; - lastPzCountSend = adesso; - lastWarnODL = adesso; - lastCurrent = adesso; - } - catch - { } - return esitoLink; - } - - /// - /// Formatta un dataitem da uno stream SAMPLE - /// - /// - /// - /// - /// - /// - private MtcDataItemExt formatDataItem(ref int dSamplePeriod, ref int threshDBand, ref string uuid, MTConnectStreams.Sample DISample) - { - // creo il nuovo dataitem da sample... - MTConnectDevices.DataItem newDataItem = new MTConnectDevices.DataItem() - { - Category = DISample.Category, - Id = DISample.DataItemId, - Name = DISample.Name, - SampleRate = DISample.SampleRate, - Statistic = DISample.Statistic, - SubType = DISample.SubType, - Type = DISample.Type - }; - return formatDataItem(ref dSamplePeriod, ref threshDBand, ref uuid, newDataItem); - } - - /// - /// Formatta un dataitem da uno stream GENERICO - /// - /// - /// - /// - /// - /// - private MtcDataItemExt formatDataItem(ref int dSamplePeriod, ref int threshDBand, ref string uuid, MTConnectStreams.DataItem DIGen) - { - // creo il nuovo dataitem da sample... - MTConnectDevices.DataItem newDataItem = new MTConnectDevices.DataItem() - { - Category = DIGen.Category, - Id = DIGen.DataItemId, - Name = DIGen.Name, - SubType = DIGen.SubType, - Type = DIGen.Type - }; - return formatDataItem(ref dSamplePeriod, ref threshDBand, ref uuid, newDataItem); - } - - /// - /// Formatta un dataitem x salvataggio in memoria locale - /// - /// - /// - /// - /// - /// - private MtcDataItemExt formatDataItem(ref int dSamplePeriod, ref int threshDBand, ref string uuid, MTConnectDevices.DataItem dataItem) - { - MtcDataItemExt currDataItem; - // uuid e parametri secondo categoria... - switch (dataItem.Category) - { - case MTConnect.DataItemCategory.CONDITION: - uuid = $"C_{dataItem.Id}"; - threshDBand = 0; - dSamplePeriod = 0; - break; - - case MTConnect.DataItemCategory.EVENT: - uuid = $"E_{dataItem.Id}"; - threshDBand = 0; - dSamplePeriod = 0; - break; - - case MTConnect.DataItemCategory.SAMPLE: - uuid = $"S_{dataItem.Id}"; - // SOLO SE è abilitato il datafiltering... - if (enableDataFilter) - { - threshDBand = 1; - // controllo SE ho conf x deadband... - if (mtcParams.paramsEndThresh.Count > 0) - { - // ciclo su tutti i parametri indicati... - foreach (var item in mtcParams.paramsEndThresh) - { - if (dataItem.Id.EndsWith(item.Key)) - { - threshDBand = item.Value; - } - } - } - } - else - { - threshDBand = 0; - } - dSamplePeriod = 60; - break; - - default: - break; - } - // salvo oggetto x "uso interno" - currDataItem = new MtcDataItemExt() - { - Id = dataItem.Id, - Category = dataItem.Category, - Constraints = dataItem.Constraints, - CoordinateSystem = dataItem.CoordinateSystem, - Name = dataItem.Name, - NativeScale = dataItem.NativeScale, - NativeUnits = dataItem.NativeUnits, - SampleRate = dataItem.SampleRate, - Representation = dataItem.Representation, - SignificantDigits = dataItem.SignificantDigits, - Source = dataItem.Source, - Statistic = dataItem.Statistic, - SubType = dataItem.SubType, - Type = dataItem.Type, - TypePath = dataItem.TypePath, - Units = dataItem.Units, - XPath = dataItem.XPath, - uid = uuid, - thresholdDeadBand = threshDBand, - samplePeriod = dSamplePeriod - }; - // log x capire COME ho chiamato alcune cosette... - if (dataItem.Id.Contains("EXE_MODE") || dataItem.Id.Contains("RUN_MODE") || dataItem.Id.Contains("POWER") || dataItem.Id.EndsWith("_Status")) - { - lgInfo($"DEBUG DATA | dataItem.Id : {dataItem.Id}"); - } - - return currDataItem; - } - - /// - /// Effettua lettura file di conf specifico MTC da oggetto serializzato json - /// Nome file da cui leggere i parametri json - /// - private void loadMtcConf(string fileName) - { - string jsonFullPath = $"{Application.StartupPath}/DATA/CONF/{fileName}"; - lgInfo($"Apertura file {jsonFullPath}"); - StreamReader reader = new StreamReader(jsonFullPath); - string jsonData = reader.ReadToEnd().Replace("\n", "").Replace("\r", ""); - if (!string.IsNullOrEmpty(jsonData)) - { - lgInfo($"File json composto da {jsonData.Length} caratteri"); - try - { - mtcParams = JsonConvert.DeserializeObject(jsonData); - lgInfo($"Decodifica aree MtcParamConf: trovati {mtcParams.paramsEndThresh.Count} valori paramsEndThresh"); - } - catch (Exception exc) - { - lgError($"Eccezione in decodifica conf json MTC:{Environment.NewLine}{exc}"); - } - } - else - { - lgError("Errore in loadMtcConf: file json vuoto!"); - } - reader.Dispose(); - } - - /// - /// Effettua invio a MP/IO dell'elenco serializzato dei dataItems - /// - /// - private void sendDataItemsList(List dataItems) - { - string rawData = JsonConvert.SerializeObject(dataItems); - utils.callUrlNow($"{urlSaveDataItems}", rawData); - } - - #endregion Private Methods - - #region Protected Methods - - /// - /// Verifica un DataItem e se il valore corrisponde a quello indicato come "true value" restituisce true - /// - /// - /// - /// - protected bool checkDataItem(string itemName, string trueVal) - { - bool answ = false; - MtcDataItemExt currValue = null; - try - { - currValue = dataItemMem[itemName]; - answ = (currValue.value.Equals(trueVal)); - } - catch - { - lgError($"Errore in decodifica valore per {itemName} rispetto a {trueVal} | recuperato {currValue} / {currValue.value}"); - } - return answ; - } - - /// - /// Verifica / Salva valore generico (NON SAMPLE) - /// - /// - /// - protected bool checkSaveItem(MTConnectStreams.DataItem newValue) - { - bool answ = !enableDataFilter; - - if (newValue != null) - { - if (isVerboseLog) - { - lgInfo($"Richiesta checkSaveItem per {newValue} | id: {newValue.DataItemId} | CDATA: {newValue.CDATA}"); - } - // verifico in memoria se ho l'oggetto condition ed il suo valore.. - if (dataItemMem.ContainsKey(newValue.DataItemId)) - { - // salvo sempre! - dataItemMem[newValue.DataItemId].value = newValue.CDATA; - dataItemMem[newValue.DataItemId].valueTimestamp = newValue.Timestamp; - answ = true; - } - else - { - // registro non trovato da aggiungere... - lgInfo($"DataItem non trovato in checkSaveItem: {newValue.DataItemId}"); - try - { - // provo a creare oggetot in memoria... - List elencoDataItems = new List(); - int dSamplePeriod = 0; - int threshDBand = 0; - string uuid = ""; - var currDataItem = formatDataItem(ref dSamplePeriod, ref threshDBand, ref uuid, newValue); - // aggiungo - dataItemMem.Add(newValue.DataItemId, currDataItem); - // salvo oggetto x registrazione su server MP-IO - var currMapoDataItem = new machDataItem() - { - uuid = newValue.DataItemId, - Category = (DataItemCategory)newValue.Category, - Name = newValue.Name, - Type = newValue.Type, - SubType = newValue.SubType, - //Units = newValue.Units - }; - // aggiungo - elencoDataItems.Add(currMapoDataItem); - // invio il dataItem serializzato... - sendDataItemsList(elencoDataItems); - } - catch (Exception exc) - { - lgError($"Eccezione in checkSaveSample{Environment.NewLine}{exc}"); - } - } - } - else - { - lgError("Attenzione: checkSaveItem con newValue null!"); - } - return answ; - } - - /// - /// Verifica / Salva valore SAMPLE e restitusice SE sia variato (e quindi da inviare...) - /// - /// - /// - protected bool checkSaveSample(MTConnectStreams.Sample newValue) - { - bool answ = !enableDataFilter; - double oldVal = 0; - double newVal = 0; - if (newValue != null) - { - if (isVerboseLog) - { - lgInfo($"Richiesta checkSaveSample per {newValue} | id: {newValue.DataItemId} | CDATA: {newValue.CDATA}"); - } - // verifico in memoria se ho l'oggetto condition ed il suo valore.. - if (dataItemMem.ContainsKey(newValue.DataItemId)) - { - MtcDataItemExt currDataItemMem = dataItemMem[newValue.DataItemId]; - // controllo SE SIA scaduto il tempo massimo... - if (Math.Abs(dataItemMem[newValue.DataItemId].valueTimestamp.Subtract(newValue.Timestamp).TotalSeconds) > currDataItemMem.samplePeriod) - { - answ = true; - } - else - { - // ALTRIMENTI controllo SE diverso - if (dataItemMem[newValue.DataItemId].value != newValue.CDATA) - { - // controllo SE ho DeadBand... - if (dataItemMem[newValue.DataItemId].thresholdDeadBand > 0) - { - if (isVerboseLog) - { - lgInfo($"Test deadband: oldVal: {oldVal} | newVal: {newVal}"); - } - // recupero i valori e testo DeadBand... - double.TryParse(dataItemMem[newValue.DataItemId].value.Replace(".", ","), out oldVal); - double.TryParse(newValue.CDATA.Replace(".", ","), out newVal); - // test deadband! - if (Math.Abs(newVal - oldVal) > dataItemMem[newValue.DataItemId].thresholdDeadBand) - { - // indico da salvare.. - answ = true; - } - } - } - } - if (answ) - { - // salvo! - dataItemMem[newValue.DataItemId].value = newValue.CDATA; - dataItemMem[newValue.DataItemId].valueTimestamp = newValue.Timestamp; - } - } - else - { - // registro non trovato da aggiungere... - lgInfo($"DataItem non trovato in checkSaveSample: {newValue.DataItemId}"); - // provo a creare oggetto in memoria... - try - { - List elencoDataItems = new List(); - int dSamplePeriod = 0; - int threshDBand = 0; - string uuid = ""; - var currDataItem = formatDataItem(ref dSamplePeriod, ref threshDBand, ref uuid, newValue); - // aggiungo - dataItemMem.Add(newValue.DataItemId, currDataItem); - // salvo oggetto x registrazione su server MP-IO - var currMapoDataItem = new machDataItem() - { - uuid = newValue.DataItemId, - Category = (DataItemCategory)newValue.Category, - Name = newValue.Name, - Type = newValue.Type, - SubType = newValue.SubType, - //Units = newValue.Units - }; - // aggiungo - elencoDataItems.Add(currMapoDataItem); - // invio il dataItem serializzato... - sendDataItemsList(elencoDataItems); - } - catch (Exception exc) - { - lgError($"Eccezione in checkSaveSample{Environment.NewLine}{exc}"); - } - } - } - else - { - lgError("Attenzione: checkSaveItem con newValue null!"); - } - return answ; - } - - /// - /// Effettuata discovery iniziale valori CURRENT - /// - /// - /// - protected void CurrentSuccessful(MTConnectStreams.Document document) - { - if (document != null) - { - lgInfo($"DiscoverySuccessful: discovery per {document.Url}"); - if (document.DeviceStreams != null) - { - lgInfo($"DiscoverySuccessful: trovati {document.DeviceStreams.Count} streams"); - } - checkAndSend(document, true); - } - else - { - lgError("StreamsSuccessful ERROR: document è null"); - } - } - - /// - /// Evento lanciato alla corretta ricezione del PROBE - /// - /// - protected void DevicesSuccessful(MTConnectDevices.Document document) - { - lgInfo("STEP 01 DevicesSuccessful reached!"); - MtcDataItemExt currDataItem = null; - machDataItem currMapoDataItem = null; - List elencoDataItems = new List(); - int dSamplePeriod = 0; - int threshDBand = 0; - string uuid = ""; - if (document != null) - { - foreach (var device in document.Devices) - { - List dataItems = device.GetDataItems(); - lgInfo($"Inizio STEP 02 per caricare {dataItems.Count} dataItems"); - foreach (var dataItem in dataItems) - { - try - { - currDataItem = formatDataItem(ref dSamplePeriod, ref threshDBand, ref uuid, dataItem); - // aggiungo se non c'è... - if (!dataItemMem.ContainsKey(dataItem.Id)) - { - dataItemMem.Add(dataItem.Id, currDataItem); - } - // salvo oggetto x registrazione su server MP-IO - currMapoDataItem = new machDataItem() - { - uuid = dataItem.Id, - Category = (DataItemCategory)dataItem.Category, - Name = dataItem.Name, - Type = dataItem.Type, - SubType = dataItem.SubType, - Units = dataItem.Units - }; - // aggiungo se non ci fosse - if (!elencoDataItems.Contains(currMapoDataItem)) - { - elencoDataItems.Add(currMapoDataItem); - } - } - catch (Exception exc) - { - lgError($"Eccezione in DevicesSuccessful / DataItem:{Environment.NewLine}{exc}"); - } - } - } - // invio IN BLOCCO il dataItem serializzati... - if (elencoDataItems.Count > 0) - { - lgInfo($"STEP 04 invio dati di {elencoDataItems.Count} records"); - sendDataItemsList(elencoDataItems); - } - hasReadItems = true; - lgInfo($"STEP 05: memorizzati {dataItemMem.Count} oggetti in memoria"); - } - else - { - lgError("STEP 06 error: document null!"); - } - } - - /// - /// Effettua traduzione ITEM da LUT parametrica (key: tipo+id) del file di conf, se non trovo uso key - /// - /// - /// - /// - protected string itemTranslation(string tipo, string id) - { - string answ = ""; - string lemma = $"{tipo}_{id}"; - // cerco nel dizionario delle traduzioni SE esiste un valore e prendo quello, altrimenti uso il lemma... - if (mtcParams.itemTranslation.ContainsKey(lemma)) - { - answ = mtcParams.itemTranslation[lemma]; - } - else - { - answ = lemma; - } - return answ; - } - - /// - /// Effettua log di un elenco componenti - /// - /// - protected void logComponentsList(List elencoComponenti) - { - if (elencoComponenti != null) - { - foreach (var item in elencoComponenti) - { - lgInfo($"Component data | ID: {item.Id} | Name: {item.Name} | Type: {item.Type} | # items: {item.DataItems.Count}"); - // se ho sottocomponenti richiamo... - if (item.SubComponents != null) - { - if (item.SubComponents.Components.Count > 0) - { - logComponentsList(item.SubComponents.Components); - } - } - if (item.DataItems.Count > 0) - { - logDataItemList(item.DataItems); - } - } - } - } - - /// - /// Log elenco DataItems - /// - /// - protected void logDataItemList(List elencoItems) - { - if (elencoItems != null) - { - // loggo devices principali... - foreach (var item in elencoItems) - { - lgInfo($"Device data | ID: {item.Id} | Name: {item.Name} | Category: {item.Category} | # Type: {item.Type}"); - } - } - } - - /// - /// Effettua log di un devices (ed eventualmente dei sub-devices... - /// - /// - protected void logDevicesList(List elencoDevices) - { - if (elencoDevices != null) - { - // loggo devices principali... - foreach (var item in elencoDevices) - { - lgInfo($"Device data | ID: {item.Id} | Name: {item.Name} | UUID: {item.Uuid} | # items: {item.DataItems.Count}"); - // se ho subItems descrivo pure loro... - if (item.DataItems.Count > 0) - { - logDataItemList(item.DataItems); - } - if (item.Components.Components.Count > 0) - { - logComponentsList(item.Components.Components); - } - } - } - } - - /// - /// Ricevuta modifica come stream da campionamenti ricevuti - /// - /// - protected void StreamsSuccessful(MTConnectStreams.Document document) - { - checkAndSend(document, false); - } - - #endregion Protected Methods - - #region Public Methods - - /// - /// Processo i task richiesti e li elimino dalla coda 1:1 - /// - /// - public override Dictionary executeTasks(Dictionary task2exe) - { - // uso metodo base x ora - return base.executeTasks(task2exe); - } - - /// - /// Recupera uno specifico dataItem - /// - /// - /// - public string getDataItemValue(string diKey) - { - string answ = ""; - try - { - var currDataItem = dataItemMem[diKey]; - answ = currDataItem.value; - } - catch (Exception exc) - { - Logging.Instance.Error($"Errore in getDataItemValue per {diKey}{Environment.NewLine}{exc}"); - } - return answ; - } - - /// - /// Recupero dati dinamici... - /// - public override Dictionary getDynData() - { - Dictionary outVal = new Dictionary(); - return outVal; - } - - /// - /// Effettua vero processing contapezzi - /// - public override void processContapezzi() - { - if (utils.CRB("enableContapezzi")) - { - // cerco parametro contapezzi... - string currPzCount = getDataItemValue(mtcParams.keyPartCount); - - // se ho un contapezzi... processo... - if (!string.IsNullOrEmpty(currPzCount)) - { - int newVal = -1; - Int32.TryParse(currPzCount, out newVal); - contapezziPLC = newVal > -1 ? newVal : contapezziPLC; - } - } - } - - /// - /// Effettua lettura semafori principale - /// Parametri da aggiornare x display in form - /// - public override void readSemafori(ref newDisplayData currDispData) - { - base.readSemafori(ref currDispData); - try - { - if (verboseLog) - { - lgInfo("inizio read semafori"); - } - - currDispData.semIn = Semaforo.SV; - - // decodifica e gestione - decodeToBaseBitmap(); - reportRawInput(ref currDispData); - } - catch (Exception exc) - { - currDispData.semIn = Semaforo.SR; - lgError($"Eccezione in readSemafori:{Environment.NewLine}{exc}"); - } - } - - /// - /// Effettua reset del contapezzi, NON POSSIBILE per MTC (read only) - /// - /// - public override bool resetcontapezziPLC() - { - bool answ = false; - return answ; - } - - /// - /// Effettua IMPOSTAZIONE FORZATA del contapezzi, NON POSSIBILE per MTC (read only) - /// - /// - public override bool setcontapezziPLC(int newPzCount) - { - bool answ = false; - return answ; - } - - /// - /// Override connessione - /// - public override void tryConnect() - { - if (!connectionOk) - { - // controllo che il ping sia stato tentato almeno pingTestSec fa... - if (DateTime.Now.Subtract(lastPING).TotalSeconds > utils.CRI("pingTestSec")) - { - if (verboseLog || periodicLog) - { - lgInfo("MTC: ConnKO - tryConnect"); - } - // in primis salvo data ping... - lastPING = DateTime.Now; - // se passa il ping faccio il resto... - if (testPingMachine == IPStatus.Success) - { - string szStatusConnection = ""; - try - { - // ora provo connessione... - parentForm.commPlcActive = true; - short esitoLink = doConnect(); - lgInfo($"szStatusConnection MTC, esitoLink: {esitoLink}"); - parentForm.commPlcActive = false; - connectionOk = true; - // refresh stato allarmi!!! - if (connectionOk) - { - if (adpRunning) - { - lgInfo("Connessione OK"); - } - } - else - { - lgError("Impossibile procedere, connessione mancante..."); - } - } - catch (Exception exc) - { - lgFatal($"Errore nella connessione all'adapter MTC: {szStatusConnection}{Environment.NewLine}{exc}"); - connectionOk = false; - lgInfo($"Eccezione in TryConnect, Adapter MTC NON running, pausa di {utils.CRI("waitRecMSec")} msec prima di ulteriori tentativi di riconnessione"); - } - } - else - { - // loggo no risposta ping ... - connectionOk = false; - if (verboseLog || periodicLog) - { - lgInfo($"Attenzione: MTC controllo PING fallito per IP {cIobConf.cncIpAddr}"); - } - } - } - } - else - { - needRefresh = true; - } - // se non è ancora connesso faccio procesisng memoria caso disconnesso... - if (!connectionOk) - { - // processo semafori ed invio... - processMemoryDiscon(); - } - } - - /// - /// Override disconnessione - /// - public override void tryDisconnect() - { - if (connectionOk) - { - string szStatusConnection = ""; - try - { - MTC_ref.Stop(); - connectionOk = false; - lgInfo(szStatusConnection); - lgInfo("Effettuata disconnessione adapter MTC!"); - } - catch (Exception exc) - { - lgFatal(exc, "Errore nella disconnessione dall'adapter MTC"); - } - } - else - { - lgError("IMPOSSIBILE effettuare disconnessione MTC: Connessione non disponibile..."); - } - } - - #endregion Public Methods - } -} \ No newline at end of file diff --git a/IOB-WIN/Objects.cs.bak b/IOB-WIN/Objects.cs.bak deleted file mode 100644 index 33055394..00000000 --- a/IOB-WIN/Objects.cs.bak +++ /dev/null @@ -1,46 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace IOB_WIN -{ - /// - /// Classe di estensione x oggetti DataItems con struttura e valori - /// - public class MtcDataItemExt : MTConnect.MTConnectDevices.DataItem - { - #region Public Properties - - /// - /// Valore (in sec) del periodo di downsampling (0 --> NON usato) - /// - public int samplePeriod { get; set; } = 60; - - /// - /// Valore soglia DeadBand (0 --> non usata) - /// - public double thresholdDeadBand { get; set; } = 0; - - /// - /// UUID univoco dell'oggetto --> flusso - /// - public string uid { get; set; } = ""; - - /// - /// Valore Registrato in formato stringa - /// - public string value { get; set; } = ""; - - /// - /// Timestamp data-ora evento registrato - /// - public DateTime valueTimestamp { get; set; } = DateTime.Now; - - #endregion Public Properties - } - - public class Objects - { - } -} \ No newline at end of file