using Adaptation.Shared; using Adaptation.Shared.Methods; using log4net; using System; using System.Collections.Generic; using System.Data; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; using System.Text.RegularExpressions; namespace Adaptation.FileHandlers.QS408M; public partial class ProcessData : IProcessData { private readonly List _Details; public string JobID { get; set; } public string MesEntity { get; set; } public string Batch { get; set; } public string Cassette { get; set; } public DateTime Date { get; set; } public string Employee { get; set; } public string Layer { get; set; } public string MeanThickness { get; set; } public string PSN { get; set; } public string PassFail { get; set; } public string RDS { get; set; } public string RVThickness { get; set; } public string Reactor { get; set; } public string Recipe { get; set; } public string StdDev { get; set; } public string Title { get; set; } public string UniqueId { get; set; } public string Wafer { get; set; } public string Zone { get; set; } List Shared.Properties.IProcessData.Details => _Details; private int _I; private string _Data; private readonly ILog _Log; public ProcessData() { } public ProcessData(IFileRead fileRead, Logistics logistics, List fileInfoCollection, string originalDataBioRad, ProcessData lastProcessData, long tickOffset) { JobID = logistics.JobID; fileInfoCollection.Clear(); _Details = new List(); MesEntity = logistics.MesEntity; _Log = LogManager.GetLogger(typeof(ProcessData)); Parse(fileRead, logistics, fileInfoCollection, originalDataBioRad, lastProcessData, tickOffset); } string IProcessData.GetCurrentReactor(IFileRead fileRead, Logistics logistics, Dictionary reactors) => throw new Exception(string.Concat("See ", nameof(Parse))); Tuple> IProcessData.GetResults(IFileRead fileRead, Logistics logistics, List fileInfoCollection) { Tuple> results; List tests = new(); foreach (object item in _Details) tests.Add(Test.BioRadQS408M); List descriptions = fileRead.GetDescriptions(fileRead, tests, this); if (tests.Count != descriptions.Count) throw new Exception(); for (int i = 0; i < tests.Count; i++) { if (descriptions[i] is not Description description) throw new Exception(); if (description.Test != (int)tests[i]) throw new Exception(); } List fileReadDescriptions = (from l in descriptions select (Description)l).ToList(); string json = JsonSerializer.Serialize(fileReadDescriptions, fileReadDescriptions.GetType()); JsonElement[] jsonElements = JsonSerializer.Deserialize(json); results = new Tuple>(logistics.Logistics1[0], tests.ToArray(), jsonElements, fileInfoCollection); return results; } private string GetBefore(string text) { string str; string str1; int num = _Data.IndexOf(text, _I); if (num <= -1) { str = _Data.Substring(_I); _I = _Data.Length; str1 = str.Trim(); } else { str = _Data.Substring(_I, num - _I); _I = num + text.Length; str1 = str.Trim(); } return str1; } private string GetBefore(string text, bool trim) { string str; string before; if (!trim) { int num = _Data.IndexOf(text, _I); if (num <= -1) { str = _Data.Substring(_I); _I = _Data.Length; before = str; } else { str = _Data.Substring(_I, num - _I); _I = num + text.Length; before = str; } } else { before = GetBefore(text); } return before; } private string GetToEOL() { string result; if (_Data.IndexOf("\n", _I) > -1) result = GetBefore("\n"); else result = GetBefore(Environment.NewLine); return result; } private string GetToEOL(bool trim) { string str; if (_Data.IndexOf("\n", _I) > -1) str = !trim ? GetBefore("\n", false) : GetToEOL(); else str = !trim ? GetBefore(Environment.NewLine, false) : GetToEOL(); return str; } private string GetToken() { while (true) { if (_I >= _Data.Length || !IsNullOrWhiteSpace(_Data.Substring(_I, 1))) { break; } _I++; } int num = _I; while (true) { if (num >= _Data.Length || IsNullOrWhiteSpace(_Data.Substring(num, 1))) { break; } num++; } string str = _Data.Substring(_I, num - _I); _I = num; return str.Trim(); } private string GetToText(string text) { string str = _Data.Substring(_I, _Data.IndexOf(text, _I) - _I).Trim(); return str; } private bool IsBlankLine() { int num = _Data.IndexOf("\n", _I); return IsNullOrWhiteSpace(num > -1 ? _Data.Substring(_I, num - _I) : _Data.Substring(_I)); } private static bool IsNullOrWhiteSpace(string text) { bool flag; int num = 0; while (true) { if (num >= text.Length) { flag = true; break; } else if (char.IsWhiteSpace(text[num])) { num++; } else { flag = false; break; } } return flag; } private string PeekNextLine() { int num = _I; string toEOL = GetToEOL(); _I = num; return toEOL; } private void ScanPast(string text) { int num = _Data.IndexOf(text, _I); if (num <= -1) { _I = _Data.Length; } else { _I = num + text.Length; } } internal static DateTime GetDateTime(Logistics logistics, long tickOffset, string dateTimeText) { DateTime result; string inputDateFormat = "ddd mmm dd HH:mm:ss yyyy"; if (dateTimeText.Length != inputDateFormat.Length) result = logistics.DateTimeFromSequence; else { if (!DateTime.TryParseExact(dateTimeText, inputDateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dateTimeParsed)) result = logistics.DateTimeFromSequence; else { if (dateTimeParsed < logistics.DateTimeFromSequence.AddDays(1) && dateTimeParsed > logistics.DateTimeFromSequence.AddDays(-1)) result = new(dateTimeParsed.Ticks + tickOffset); else result = logistics.DateTimeFromSequence; } } return result; } private static (string, string) GetReactorAndRDS(string defaultReactor, string defaultRDS, string text, string formattedText, string[] segments, bool hasRDS) { string rds; string reactor; if (string.IsNullOrEmpty(text) || segments.Length == 0 || string.IsNullOrEmpty(formattedText) || (segments.Length > 1 && !hasRDS)) reactor = defaultReactor; else reactor = segments[0]; if (segments.Length <= 1 || !int.TryParse(segments[1], out int rdsValue) || rdsValue < 99) rds = defaultRDS; else rds = segments[1]; if (reactor.Length > 3) { rds = reactor; reactor = defaultReactor; } return new(reactor, rds); } private static (string, string) GetLayerAndPSN(string defaultLayer, string defaultPSN, string[] segments, bool hasRDS) { string psn; string layer; if (segments.Length <= 2 || (segments.Length > 1 && !hasRDS)) { psn = defaultPSN; layer = defaultLayer; } else { string[] segmentsB = segments[2].Split('.'); psn = segmentsB[0]; if (segmentsB.Length <= 1) layer = defaultLayer; else { layer = segmentsB[1]; if (layer.Length > 1 && layer[0] == '0') layer = layer.Substring(1); } } return (layer, psn); } private static string GetZone(string[] segments) { string result; if (segments.Length <= 3) result = string.Empty; else { result = segments[3]; if (result.Length > 1 && result[0] == '0') result = result.Substring(1); } return result; } public static Descriptor GetDescriptor(string text) { Descriptor result; string psn; string rds; string zone; string layer; string wafer; string reactor; string employee; string defaultPSN = string.Empty; string defaultRDS = string.Empty; string defaultZone = string.Empty; string defaultLayer = string.Empty; string defaultReactor = string.Empty; string defaultEmployee = string.Empty; if (string.IsNullOrEmpty(text) || (text.Length is 2 or 3 && Regex.IsMatch(text, "^[a-zA-z]{2,3}"))) { wafer = text; employee = text; psn = defaultPSN; rds = defaultRDS; zone = defaultZone; layer = defaultLayer; reactor = defaultReactor; } else if (Regex.IsMatch(text, @"^[0-9]{2}[.][0-9]{1}[.]?[0-9]{0,1}")) { string[] segments = text.Split('.'); wafer = text; psn = defaultPSN; rds = defaultRDS; layer = segments[1]; reactor = segments[0]; employee = defaultEmployee; if (segments.Length <= 2) zone = defaultZone; else zone = segments[2]; } else { // Remove illegal characters \/:*?"<>| found in the Batch wafer = Regex.Replace(text, @"[\\,\/,\:,\*,\?,\"",\<,\>,\|]", "_").Split('\r')[0].Split('\n')[0]; if (wafer.Length > 2 && wafer[0] == '1' && (wafer[1] == 'T' || wafer[1] == 't')) wafer = wafer.Substring(2); string[] segments = wafer.Split('-'); bool hasRDS = Regex.IsMatch(wafer, "[-]?[0-9]{5,}[-]?"); (reactor, rds) = GetReactorAndRDS(defaultReactor, defaultRDS, text, wafer, segments, hasRDS); (layer, psn) = GetLayerAndPSN(defaultLayer, defaultPSN, segments, hasRDS); zone = GetZone(segments); if (segments.Length <= 4) employee = defaultEmployee; else employee = segments[4]; } result = new(employee, layer, psn, rds, reactor, wafer, zone); return result; } private void Set(Logistics logistics, ProcessData lastProcessData, long tickOffset, string receivedData) { string psn; string rds; string zone; string batch; string layer; string title; string wafer; DateTime date; string recipe; string reactor; string cassette; string employee; title = GetBefore("Recipe:"); recipe = GetToken(); string dateTimeText = GetToEOL(); if (dateTimeText.EndsWith(".")) dateTimeText = dateTimeText.Remove(dateTimeText.Length - 1, 1); date = GetDateTime(logistics, tickOffset, dateTimeText); ScanPast("operator:"); employee = GetBefore("batch:"); batch = GetToEOL(); // Remove illegal characters \/:*?"<>| found in the Batch batch = Regex.Replace(batch, @"[\\,\/,\:,\*,\?,\"",\<,\>,\|]", "_").Split('\r')[0].Split('\n')[0]; ScanPast("cassette:"); cassette = GetBefore("wafer:"); if (string.IsNullOrEmpty(batch)) { _I = 0; _Data = receivedData; ScanPast("wafer:"); } wafer = GetToEOL(); _ = GetToEOL(); _ = GetToEOL(); if (string.IsNullOrEmpty(wafer)) throw new Exception("Wafer field is missing."); Descriptor descriptor = GetDescriptor(wafer); psn = descriptor.PSN; rds = descriptor.RDS; zone = descriptor.Zone; wafer = descriptor.Wafer; layer = descriptor.Layer; reactor = descriptor.Reactor; if (employee != wafer) employee = descriptor.Employee; if (logistics.DateTimeFromSequence > DateTime.Now.AddHours(-24)) { if (string.IsNullOrEmpty(lastProcessData.Wafer)) { lastProcessData.Batch = JobID; lastProcessData.Cassette = JobID; lastProcessData.Employee = JobID; lastProcessData.Recipe = JobID; lastProcessData.Title = JobID; } lastProcessData.Wafer = wafer; lastProcessData.Reactor = reactor; lastProcessData.RDS = rds; string check = "--------"; if (string.IsNullOrEmpty(batch) || batch.Contains(check)) batch = lastProcessData.Batch; else lastProcessData.Batch = batch; if (string.IsNullOrEmpty(cassette) || cassette.Contains(check)) cassette = lastProcessData.Cassette; else lastProcessData.Cassette = cassette; if (string.IsNullOrEmpty(employee) || employee.Contains(check)) employee = lastProcessData.Employee; else lastProcessData.Employee = employee; if (string.IsNullOrEmpty(recipe) || recipe.Contains(check)) recipe = lastProcessData.Recipe; else lastProcessData.Recipe = recipe; if (string.IsNullOrEmpty(title) || title.Contains(check)) title = lastProcessData.Title; else lastProcessData.Title = title; } //fix title StringBuilder titleFixed = new(); foreach (char c in title) { if (char.IsLetterOrDigit(c) || c == '-' || c == '.') _ = titleFixed.Append(c); } //fix wafer StringBuilder waferFixed = new(); foreach (char c in wafer) { if (char.IsLetterOrDigit(c) || c == '-' || c == '.') _ = waferFixed.Append(c); } PSN = psn; RDS = rds; Date = date; Zone = zone; Batch = batch; Layer = layer; Recipe = recipe; Reactor = reactor; Cassette = cassette; Employee = employee; JobID = logistics.JobID; Title = titleFixed.ToString(); Wafer = waferFixed.ToString(); UniqueId = string.Concat(title, '_', wafer, '_', logistics.DateTimeFromSequence.ToString("yyyyMMddHHmmssffff"), '_', logistics.TotalSecondsSinceLastWriteTimeFromSequence); } private void Parse(IFileRead fileRead, Logistics logistics, List fileInfoCollection, string originalDataBioRad, ProcessData lastProcessData, long tickOffset) { if (fileRead is null) { } _I = 0; _Data = string.Empty; List details = new(); string receivedData = File.ReadAllText(logistics.ReportFullPath); _Log.Debug($"****ParseData - Source file contents:"); _Log.Debug(receivedData); string[] files = Directory.GetFiles(Path.GetDirectoryName(logistics.ReportFullPath), string.Concat(originalDataBioRad, logistics.Sequence, "*"), SearchOption.TopDirectoryOnly); foreach (string file in files) fileInfoCollection.Add(new FileInfo(file)); // occasionally there are multiple blocks of results, get the last one as earlier ones may be aborted runs. int index = receivedData.LastIndexOf("Bio-Rad"); if (index > -1) receivedData = receivedData.Substring(index); _Log.Debug($"****ParseData - Source file contents to be parsed:"); _Log.Debug(receivedData); if (!string.IsNullOrEmpty(receivedData)) { _I = 0; _Data = receivedData; Set(logistics, lastProcessData, tickOffset, receivedData); string token = GetToken(); int counter = 1; while (true) { if (string.IsNullOrEmpty(token) || !char.IsDigit(token[0])) break; Detail detail = new() { Position = token, Thickness = GetToken(), UniqueId = string.Concat("_Point-", counter) }; details.Add(detail); token = GetToken(); counter++; } ScanPast("mean thickness ="); MeanThickness = GetBefore(", std. dev ="); StdDev = GetToken(); PassFail = GetToEOL(); ScanPast("thickness"); RVThickness = GetToEOL(); } foreach (Detail detail in details) { detail.HeaderUniqueId = UniqueId; detail.UniqueId = string.Concat(UniqueId, detail.UniqueId); } //trace datatype _Log.Debug("BioRad parsed information:"); _Log.Debug(string.Format("Batch: {0}", Batch)); _Log.Debug(string.Format("Cassette: {0}", Cassette)); _Log.Debug(string.Format("Date: {0}", Date)); foreach (Detail bioRadDetail in details) _Log.Debug(string.Format("Details: {0} - {1}", bioRadDetail.Position, bioRadDetail.Thickness)); _Log.Debug(string.Format("Mean Thickness: {0}", MeanThickness)); _Log.Debug(string.Format("Operator: {0}", Employee)); _Log.Debug(string.Format("Pass/Fail: {0}", PassFail)); _Log.Debug(string.Format("Recipe: {0}", Recipe)); _Log.Debug(string.Format("RV Thickness: {0}", RVThickness)); _Log.Debug(string.Format("Std Dev: {0}", StdDev)); _Log.Debug(string.Format("Title: {0}", Title)); _Log.Debug(string.Format("Wafer: {0}", Wafer)); fileInfoCollection.Add(logistics.FileInfo); _Details.AddRange(details); } #nullable enable internal static List GetDescriptions(JsonElement[] jsonElements) { List results = new(); Description? description; JsonSerializerOptions jsonSerializerOptions = new() { NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.WriteAsString }; foreach (JsonElement jsonElement in jsonElements) { if (jsonElement.ValueKind != JsonValueKind.Object) throw new Exception(); description = JsonSerializer.Deserialize(jsonElement.ToString(), jsonSerializerOptions); if (description is null) continue; results.Add(description); } return results; } }