using Adaptation.Eaf.Management.ConfigurationData.CellAutomation; using Adaptation.Ifx.Eaf.EquipmentConnector.File.Configuration; using Adaptation.Shared; using Adaptation.Shared.Duplicator; using Adaptation.Shared.Methods; using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net.Sockets; using System.Reflection; using System.Text; using System.Text.Json; using System.Threading; namespace Adaptation.FileHandlers.wc; public class FileRead : Shared.FileRead, IFileRead { #nullable enable private readonly int _Port; private readonly Timer _Timer; private readonly string _Hostname; private static PropertyInfo? _PropertyInfo; private static NetworkStream? _NetworkStream; public FileRead(ISMTP smtp, Dictionary fileParameter, string cellInstanceName, int? connectionCount, string cellInstanceConnectionName, FileConnectorConfiguration fileConnectorConfiguration, string equipmentTypeName, string parameterizedModelObjectDefinitionType, IList modelObjectParameters, string equipmentDictionaryName, Dictionary> dummyRuns, Dictionary> staticRuns, bool useCyclicalForDescription, bool isEAFHosted) : base(new Description(), false, smtp, fileParameter, cellInstanceName, connectionCount, cellInstanceConnectionName, fileConnectorConfiguration, equipmentTypeName, parameterizedModelObjectDefinitionType, modelObjectParameters, equipmentDictionaryName, dummyRuns, staticRuns, useCyclicalForDescription, isEAFHosted: connectionCount is null) { if (_FileConnectorConfiguration.FileScanningIntervalInSeconds is null) throw new NullReferenceException(nameof(_FileConnectorConfiguration.FileScanningIntervalInSeconds)); _MinFileLength = 10; _NetworkStream = null; _Logistics = new(this); _NullData = string.Empty; if (_FileParameter is null) throw new Exception(cellInstanceConnectionName); if (_ModelObjectParameterDefinitions is null) throw new Exception(cellInstanceConnectionName); if (_IsDuplicator) throw new Exception(cellInstanceConnectionName); Type type = typeof(NetworkStream); PropertyInfo? propertyInfo = type.GetProperty("Socket", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetProperty); if (propertyInfo is null) throw new NullReferenceException(nameof(propertyInfo)); _PropertyInfo = propertyInfo; _Timer = new Timer(Callback, null, Timeout.Infinite, Timeout.Infinite); string port = GetPropertyValue(cellInstanceConnectionName, modelObjectParameters, "TCP.Port"); _Hostname = GetPropertyValue(cellInstanceConnectionName, modelObjectParameters, string.Concat("CellInstance.", cellInstanceName, ".TCP.Hostname")); _Port = int.Parse(port); WaferCounterHelper.Initialize(fileConnectorConfiguration); if (Debugger.IsAttached || fileConnectorConfiguration.PreProcessingMode == FileConnectorConfiguration.PreProcessingModeEnum.Process) Callback(null); else { TimeSpan timeSpan = new(DateTime.Now.AddSeconds(_FileConnectorConfiguration.FileScanningIntervalInSeconds.Value).Ticks - DateTime.Now.Ticks); _ = _Timer.Change((long)timeSpan.TotalMilliseconds, Timeout.Infinite); } } void IFileRead.Move(Tuple> extractResults, Exception exception) => Move(extractResults); void IFileRead.WaitForThread() => WaitForThread(thread: null, threadExceptions: null); string IFileRead.GetEventDescription() { string result = _Description.GetEventDescription(); return result; } List IFileRead.GetHeaderNames() { List results = _Description.GetHeaderNames(); return results; } string[] IFileRead.Move(Tuple> extractResults, string to, string from, string resolvedFileLocation, Exception exception) { string[] results = Move(extractResults, to, from, resolvedFileLocation, exception); return results; } JsonProperty[] IFileRead.GetDefault() { JsonProperty[] results = _Description.GetDefault(this, _Logistics); return results; } Dictionary IFileRead.GetDisplayNamesJsonElement() { Dictionary results = _Description.GetDisplayNamesJsonElement(this); return results; } List IFileRead.GetDescriptions(IFileRead fileRead, List tests, IProcessData processData) { List results = _Description.GetDescriptions(fileRead, _Logistics, tests, processData); return results; } Tuple> IFileRead.GetExtractResult(string reportFullPath, string eventName) => throw new Exception(string.Concat("See ", nameof(Callback))); Tuple> IFileRead.ReExtract() => throw new Exception(string.Concat("See ", nameof(Callback))); private static void NetworkStreamDataAvailable(string cellInstanceName, FileConnectorConfiguration fileConnectorConfiguration, Calendar calendar, NetworkStream networkStream) { int length; string read; byte[] bytes = new byte[1024]; StringBuilder stringBuilder = new(); do { length = networkStream.Read(bytes, 0, bytes.Length); read = Encoding.ASCII.GetString(bytes, 0, length); foreach (char item in read) { if (item is '\0') continue; _ = stringBuilder.Append(item); } } while (networkStream.DataAvailable); if (stringBuilder.Length > 0) { DateTime dateTime = DateTime.Now; string contents = stringBuilder.ToString(); string fileName = $"{dateTime.Ticks}{fileConnectorConfiguration.TargetFileName}"; string fullFileName = Path.Combine(fileConnectorConfiguration.TargetFileLocation, fileName); if (contents[0] != 'T') File.WriteAllText(fullFileName, contents); else { string json = WaferCounterHelper.GetJson(cellInstanceName, dateTime, contents); File.WriteAllText(fullFileName, contents); Archive.FileRead.Notify(fileConnectorConfiguration, calendar, dateTime, fileName, fullFileName, json); } } } private void Callback() { if (_NetworkStream is null) { TcpClient tcpClient = new(_Hostname, _Port); _NetworkStream = tcpClient.GetStream(); } if (_PropertyInfo is null) throw new NullReferenceException(nameof(_PropertyInfo)); if (_PropertyInfo.GetValue(_NetworkStream) is not Socket socket) throw new NotSupportedException(); if (!socket.Connected) { TcpClient tcpClient = new(_Hostname, _Port); _NetworkStream = tcpClient.GetStream(); } if (_NetworkStream is null) throw new NullReferenceException(nameof(_NetworkStream)); if (_NetworkStream.CanRead && _NetworkStream.DataAvailable) NetworkStreamDataAvailable(_CellInstanceName, _FileConnectorConfiguration, _Calendar, _NetworkStream); if (File.Exists("")) { DateTime dateTime = DateTime.Now; Archive.FileRead.Notify(_FileConnectorConfiguration, _Calendar, dateTime, ".json", "D:/EAF/EAF Deployment Storage/Adaptation_MET08AWCT/.json", "json"); } } private void Callback(object? state) { if (_FileConnectorConfiguration.FileScanningIntervalInSeconds is null) throw new NullReferenceException(nameof(_FileConnectorConfiguration.FileScanningIntervalInSeconds)); try { Callback(); } catch (Exception exception) { string subject = string.Concat("Exception:", _CellInstanceConnectionName); string body = string.Concat(exception.Message, Environment.NewLine, Environment.NewLine, exception.StackTrace); try { _SMTP.SendHighPriorityEmailMessage(subject, body); } catch (Exception) { } } try { TimeSpan timeSpan = new(DateTime.Now.AddSeconds(_FileConnectorConfiguration.FileScanningIntervalInSeconds.Value).Ticks - DateTime.Now.Ticks); _ = _Timer.Change((long)timeSpan.TotalMilliseconds, Timeout.Infinite); } catch (Exception exception) { string subject = string.Concat("Exception:", _CellInstanceConnectionName); string body = string.Concat(exception.Message, Environment.NewLine, Environment.NewLine, exception.StackTrace); try { _SMTP.SendHighPriorityEmailMessage(subject, body); } catch (Exception) { } } } }