398 lines
20 KiB
C#

using Adaptation.Ifx.Eaf.EquipmentConnector.File.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Adaptation.Shared.Metrology
{
public class ConfigDataBase
{
public bool UseCyclicalForDescription { get; protected set; }
public Dictionary<string, string> CellNames { get; protected set; }
public Dictionary<string, string> MesEntities { get; protected set; }
public IProcessDataDescription ProcessDataDescription { get; protected set; }
public bool IsEvent { get; private set; }
public bool EafHosted { get; private set; }
public string CellName { get; private set; }
public bool IsSourceTimer { get; private set; }
public EquipmentType EquipmentType => _EquipmentType;
public string EquipmentElementName { get; private set; }
public bool IsDatabaseExportToIPDSF { get; private set; }
public EquipmentType? EquipmentConnection => _EquipmentConnection;
public FileConnectorConfiguration FileConnectorConfiguration { get; private set; }
protected readonly EventName _EventName;
protected readonly EquipmentType _EquipmentType;
protected readonly EquipmentType? _EquipmentConnection;
protected readonly Dictionary<string, string> _Reactors;
public ConfigDataBase(string cellName, string cellInstanceConnectionName, FileConnectorConfiguration fileConnectorConfiguration, string equipmentTypeName, string parameterizedModelObjectDefinitionType, bool isEAFHosted)
{
CellName = cellName;
EafHosted = isEAFHosted;
EquipmentType equipmentTypeValue;
_Reactors = new Dictionary<string, string>();
CellNames = new Dictionary<string, string>();
MesEntities = new Dictionary<string, string>();
EquipmentElementName = cellInstanceConnectionName;
FileConnectorConfiguration = fileConnectorConfiguration;
string[] segments = parameterizedModelObjectDefinitionType.Split('.');
IsSourceTimer = (fileConnectorConfiguration.SourceFileFilter.StartsWith("*Timer.txt"));
string cellInstanceConnectionNameBase = cellInstanceConnectionName.Replace("-", string.Empty);
IsDatabaseExportToIPDSF = (fileConnectorConfiguration.SourceFileLocation.Contains("DatabaseExport"));
if (!Enum.TryParse(segments[segments.Length - 1], out EventName eventNameValue))
throw new Exception(cellInstanceConnectionName);
if (!Enum.TryParse(cellInstanceConnectionNameBase, out equipmentTypeValue))
_EquipmentConnection = null;
else
_EquipmentConnection = equipmentTypeValue;
string suffix;
switch (eventNameValue)
{
case EventName.FileRead: suffix = string.Empty; break;
case EventName.FileReadDaily: suffix = "_Daily"; break;
case EventName.FileReadWeekly: suffix = "_Weekly"; break;
case EventName.FileReadMonthly: suffix = "_Monthly"; break;
case EventName.FileReadVerification: suffix = "_Verification"; break;
default: throw new Exception(cellInstanceConnectionName);
}
string parameterizedModelObjectDefinitionTypeAppended = string.Concat(segments[0], suffix);
IsEvent = cellInstanceConnectionNameBase != parameterizedModelObjectDefinitionTypeAppended;
_EventName = eventNameValue;
if (!Enum.TryParse(parameterizedModelObjectDefinitionTypeAppended, out equipmentTypeValue))
throw new Exception(cellInstanceConnectionName);
_EquipmentType = equipmentTypeValue;
if (!isEAFHosted && equipmentTypeName != parameterizedModelObjectDefinitionTypeAppended)
throw new Exception(cellInstanceConnectionName);
}
public string GetEventName()
{
string result = _EventName.ToString();
return result;
}
public EventName GetEventNameValue()
{
EventName result = _EventName;
return result;
}
public string GetEquipmentType()
{
string result;
if (_EquipmentConnection is null)
result = _EquipmentType.ToString();
else
result = _EquipmentConnection.Value.ToString();
return result;
}
public string GetEventDescription()
{
string result = ProcessDataDescription.GetEventDescription();
return result;
}
public IProcessDataDescription GetDefault(ILogic logic)
{
IProcessDataDescription result = ProcessDataDescription.GetDefault(logic, this);
return result;
}
public IProcessDataDescription GetDisplayNames(ILogic logic)
{
IProcessDataDescription result = ProcessDataDescription.GetDisplayNames(logic, this);
return result;
}
public List<string> GetDetailNames(ILogic logic)
{
List<string> results = ProcessDataDescription.GetDetailNames(logic, this);
return results;
}
public List<string> GetHeaderNames(ILogic logic)
{
List<string> results = ProcessDataDescription.GetHeaderNames(logic, this);
return results;
}
public List<string> GetNames(ILogic logic)
{
List<string> results = ProcessDataDescription.GetNames(logic, this);
return results;
}
public List<string> GetPairedParameterNames(ILogic logic)
{
List<string> results = ProcessDataDescription.GetPairedParameterNames(logic, this);
return results;
}
public List<string> GetParameterNames(ILogic logic)
{
List<string> results = ProcessDataDescription.GetParameterNames(logic, this);
return results;
}
public List<IProcessDataDescription> GetDescription(ILogic logic, List<Test> tests, IProcessData iProcessData)
{
List<IProcessDataDescription> results = ProcessDataDescription.GetDescription(logic, this, tests, iProcessData);
return results;
}
public string GetCurrentReactor(ILogic logic)
{
string result = string.Empty;
foreach (KeyValuePair<string, string> keyValuePair in _Reactors)
{
foreach (string filePrefix in keyValuePair.Value.Split('|'))
{
if (logic.Logistics.MID.StartsWith(filePrefix) || (_EventName != EventName.FileRead && MesEntities.ContainsKey(logic.Logistics.JobID) && keyValuePair.Value == MesEntities[logic.Logistics.JobID]))
{
result = keyValuePair.Key;
break;
}
}
}
if (string.IsNullOrEmpty(result) && _Reactors.Count == 1)
result = _Reactors.ElementAt(0).Key;
return result;
}
protected JsonElement GetDefaultJsonElement(ILogic logic)
{
JsonElement result;
IProcessDataDescription processDataDescription = ProcessDataDescription.GetDefault(logic, this);
string json = JsonSerializer.Serialize(processDataDescription, processDataDescription.GetType());
object @object = JsonSerializer.Deserialize<object>(json);
result = (JsonElement)@object;
return result;
}
public Dictionary<string, List<Tuple<Enum, string, string, object>>> GetParameterInfo(ILogic logic, bool allowNull)
{
Dictionary<string, List<Tuple<Enum, string, string, object>>> results = new Dictionary<string, List<Tuple<Enum, string, string, object>>>();
string description;
Enum param;
Tuple<Enum, string, string, object> tuple;
JsonElement defaultJsonElement = GetDefaultJsonElement(logic);
Dictionary<string, string> keyValuePairs = GetDisplayNamesJsonElement(logic);
foreach (JsonProperty jsonProperty in defaultJsonElement.EnumerateObject())
{
if (jsonProperty.Value.ValueKind == JsonValueKind.Null && !allowNull)
throw new Exception();
if (jsonProperty.Value.ValueKind == JsonValueKind.Object || jsonProperty.Value.ValueKind == JsonValueKind.Array)
{
description = string.Empty;
param = Description.Param.StructuredType;
//jValue = jObject.Value<JValue>("Item1");
throw new NotImplementedException("Item1");
}
else
{
switch (jsonProperty.Value.ValueKind)
{
case JsonValueKind.String: param = Description.Param.String; break;
case JsonValueKind.Number: param = Description.Param.Double; break;
case JsonValueKind.True:
case JsonValueKind.False: param = Description.Param.Boolean; break;
case JsonValueKind.Null: param = Description.Param.String; break;
default: param = Description.Param.StructuredType; break;
}
}
if (!keyValuePairs.ContainsKey(jsonProperty.Name))
description = string.Empty;
else
description = keyValuePairs[jsonProperty.Name];
tuple = new Tuple<Enum, string, string, object>(param, jsonProperty.Name, description, jsonProperty.Value.ToString());
if (!results.ContainsKey(jsonProperty.Name))
results.Add(jsonProperty.Name, new List<Tuple<Enum, string, string, object>>());
results[jsonProperty.Name].Add(tuple);
}
return results;
}
protected void WriteExportAliases(ILogic logic, string cellName, string equipmentElementName)
{
int i = 0;
Enum param;
object value;
Enum[] @params;
string description;
StringBuilder stringBuilder = new StringBuilder();
string shareRoot = @"\\messv02ecc1.ec.local\EC_EDA";
string shareDirectory = string.Concat(shareRoot, @"\Staging\Pdsf\", cellName, @"\ExportAliases\", equipmentElementName);
Dictionary<string, List<Tuple<Enum, string, string, object>>> keyValuePairs;
if (!(logic is null))
keyValuePairs = GetParameterInfo(logic, allowNull: false);
else
keyValuePairs = new Dictionary<string, List<Tuple<Enum, string, string, object>>>();
stringBuilder.AppendLine("\"AliasName\";\"Condition\";\"EventId\";\"ExceptionId\";\"Formula\";\"HardwareId\";\"OrderId\";\"ParameterName\";\"Remark\";\"ReportName\";\"SourceId\";\"Use\"");
if (!Directory.Exists(shareRoot))
return;
if (!Directory.Exists(shareDirectory))
Directory.CreateDirectory(shareDirectory);
string shareFile = string.Concat(shareDirectory, @"\", DateTime.Now.Ticks, ".csv");
foreach (KeyValuePair<string, List<Tuple<Enum, string, string, object>>> keyValuePair in keyValuePairs)
{
i += 1;
@params = (from l in keyValuePair.Value select l.Item1).Distinct().ToArray();
if (@params.Length != 1)
throw new Exception();
if (keyValuePair.Value[0].Item2 != keyValuePair.Key)
throw new Exception();
param = @params[0];
if (!(param is Description.Param.String))
stringBuilder.AppendLine($"\"{keyValuePair.Key}\";\"\";\"\";\"\";\"\";\"\";\"{i}\";\"{cellName}/{EquipmentElementName}/{keyValuePair.Key}\";\"\";\"{cellName}/{EquipmentElementName}/{_EventName}\";\"\";\"True\"");
else
{
description = keyValuePair.Value[0].Item3.Split('|')[0];
if (string.IsNullOrEmpty(description))
continue;
value = keyValuePair.Value[0].Item4;
stringBuilder.AppendLine($"\"'{description}'\";\"\";\"\";\"\";\"\";\"\";\"{i}\";\"{cellName}/{EquipmentElementName}/{value}\";\"\";\"{cellName}/{EquipmentElementName}/{_EventName}\";\"\";\"True\"");
}
}
if (keyValuePairs.Any())
File.WriteAllText(shareFile, stringBuilder.ToString());
}
public Dictionary<string, string> GetDisplayNamesJsonElement(ILogic logic)
{
Dictionary<string, string> results = new Dictionary<string, string>();
IProcessDataDescription processDataDescription = ProcessDataDescription.GetDisplayNames(logic, this);
string json = JsonSerializer.Serialize(processDataDescription, processDataDescription.GetType());
JsonElement jsonElement = JsonSerializer.Deserialize<JsonElement>(json);
foreach (JsonProperty jsonProperty in jsonElement.EnumerateObject())
{
if (!results.ContainsKey(jsonProperty.Name))
results.Add(jsonProperty.Name, string.Empty);
if (jsonProperty.Value is JsonElement jsonPropertyValue)
results[jsonProperty.Name] = jsonPropertyValue.ToString();
}
return results;
}
public List<string> GetIgnoreParameterNames(ILogic logic, Test test, bool includePairedParameterNames)
{
List<string> results = ProcessDataDescription.GetIgnoreParameterNames(logic, this, test);
if (includePairedParameterNames)
{
string value;
List<string> pairedParameterNames = ProcessDataDescription.GetPairedParameterNames(logic, this);
IProcessDataDescription processDataDescription = ProcessDataDescription.GetDisplayNames(logic, this);
string json = JsonSerializer.Serialize(processDataDescription, processDataDescription.GetType());
object @object = JsonSerializer.Deserialize<object>(json);
if (!(@object is JsonElement jsonElement))
throw new Exception();
foreach (JsonProperty jsonProperty in jsonElement.EnumerateObject())
{
if (jsonProperty.Value.ValueKind == JsonValueKind.Object || jsonProperty.Value.ValueKind == JsonValueKind.Array)
throw new Exception();
value = jsonProperty.Value.ToString();
if (!results.Contains(jsonProperty.Name) && pairedParameterNames.Contains(jsonProperty.Name) && (string.IsNullOrEmpty(value) || value[0] == '|'))
results.Add(jsonProperty.Name);
}
}
return results;
}
public List<Duplicator.Description> GetProcessDataDescriptions(JsonElement jsonElement)
{
List<Duplicator.Description> results;
if (jsonElement.ValueKind != JsonValueKind.Array)
throw new Exception();
JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions { NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.WriteAsString };
results = JsonSerializer.Deserialize<List<Duplicator.Description>>(jsonElement.ToString(), jsonSerializerOptions);
return results;
}
public Dictionary<Test, List<Duplicator.Description>> GetKeyValuePairs(List<Duplicator.Description> processDataDescriptions)
{
Dictionary<Test, List<Duplicator.Description>> results = new Dictionary<Test, List<Duplicator.Description>>();
Test testKey;
for (int i = 0; i < processDataDescriptions.Count; i++)
{
testKey = (Test)processDataDescriptions[i].Test;
if (!results.ContainsKey(testKey))
results.Add(testKey, new List<Duplicator.Description>());
results[testKey].Add(processDataDescriptions[i]);
}
return results;
}
public Dictionary<string, List<string>> GetKeyValuePairs(JsonElement jsonElement, List<Duplicator.Description> processDataDescriptions, Test test)
{
Dictionary<string, List<string>> results = new Dictionary<string, List<string>>();
Test testKey;
if (jsonElement.ValueKind != JsonValueKind.Array)
throw new Exception();
JsonElement[] jsonElements = jsonElement.EnumerateArray().ToArray();
if (processDataDescriptions.Count != jsonElements.Length)
throw new Exception();
for (int i = 0; i < processDataDescriptions.Count; i++)
{
testKey = (Test)processDataDescriptions[i].Test;
if (testKey != test)
continue;
foreach (JsonProperty jsonProperty in jsonElements[i].EnumerateObject())
{
if (jsonProperty.Value.ValueKind == JsonValueKind.Object || jsonProperty.Value.ValueKind == JsonValueKind.Array)
throw new Exception();
if (!results.ContainsKey(jsonProperty.Name))
results.Add(jsonProperty.Name, new List<string>());
results[jsonProperty.Name].Add(jsonProperty.Value.ToString());
}
}
return results;
}
protected void VerifyProcessDataDescription(ILogic logic)
{
string description;
bool allowNull = false;
JsonElement defaultJsonElement = GetDefaultJsonElement(logic);
Dictionary<string, string> keyValuePairs = GetDisplayNamesJsonElement(logic);
JsonProperty[] jsonProperties = defaultJsonElement.EnumerateObject().ToArray();
foreach (JsonProperty jsonProperty in jsonProperties)
{
if (jsonProperty.Value.ValueKind == JsonValueKind.Null && !allowNull)
throw new Exception();
if (!(jsonProperty.Value.ValueKind is JsonValueKind.String) || !keyValuePairs.ContainsKey(jsonProperty.Name))
description = string.Empty;
else
description = keyValuePairs[jsonProperty.Name].Split('|')[0];
}
}
public List<IProcessDataDescription> GetIProcessDataDescriptions(JsonElement jsonElement)
{
List<IProcessDataDescription> results = new List<IProcessDataDescription>();
if (jsonElement.ValueKind != JsonValueKind.Array)
throw new Exception();
object @object;
Type type = ProcessDataDescription.GetType();
JsonElement[] jsonElements = jsonElement.EnumerateArray().ToArray();
JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions { NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.WriteAsString };
for (int i = 0; i < jsonElements.Length; i++)
{
@object = JsonSerializer.Deserialize(jsonElements[i].ToString(), type, jsonSerializerOptions);
if (!(@object is IProcessDataDescription processDataDescription))
continue;
results.Add(processDataDescription);
}
return results;
}
}
}