HelperEDADatabase
HelperEAFProgramData HelperCompass HelperInfinityQS HelperSerial HelperTCP dotnet_analyzer_diagnostic
This commit is contained in:
178
Helpers/EDA/Common.cs
Normal file
178
Helpers/EDA/Common.cs
Normal file
@ -0,0 +1,178 @@
|
||||
using System.Text;
|
||||
|
||||
namespace File_Watcher.Helpers.EDA;
|
||||
|
||||
[Serializable]
|
||||
public class Common
|
||||
{
|
||||
|
||||
public string? ConfigurationProductiveState { get; set; }
|
||||
public string? ConfigurationState { get; set; }
|
||||
public string? ContainerName { get; set; }
|
||||
public ModuleInstanceTypeName? ObjectType { get; set; }
|
||||
public string? UnitName { get; set; }
|
||||
//
|
||||
public string Filename { get; set; }
|
||||
public string StartTimeFormat { get; set; }
|
||||
public string[] StoragePaths { get; set; }
|
||||
//
|
||||
public List<string[]> GeneralTriggers { get; set; }
|
||||
public List<string[]> LogisticsAttributes { get; set; }
|
||||
public List<string[]> LogisticsColumns { get; set; }
|
||||
public string LogisticsEquipmentAlias { get; set; }
|
||||
public List<string?[]> LogisticsTriggers { get; set; }
|
||||
public Dictionary<int, List<string[]>> LogisticsTriggersCallDefinitionAttributes { get; set; }
|
||||
public Dictionary<int, string[]> LogisticsTriggersKeysKeyMapping { get; set; }
|
||||
public List<string?[]> Parameters { get; set; }
|
||||
public string ParametersAsCsv { get; set; }
|
||||
public string Source { get; set; }
|
||||
public List<string[]> StartTriggersDCP { get; set; }
|
||||
public List<string[]> StopTriggersDCP { get; set; }
|
||||
|
||||
[Obsolete("Only for DeserializeObject")]
|
||||
public Common()
|
||||
{
|
||||
Parameters = [];
|
||||
ObjectType = null;
|
||||
StoragePaths = [];
|
||||
GeneralTriggers = [];
|
||||
StopTriggersDCP = [];
|
||||
LogisticsColumns = [];
|
||||
Source = string.Empty;
|
||||
StartTriggersDCP = [];
|
||||
LogisticsTriggers = [];
|
||||
Filename = string.Empty;
|
||||
UnitName = string.Empty;
|
||||
LogisticsAttributes = [];
|
||||
ContainerName = string.Empty;
|
||||
ParametersAsCsv = string.Empty;
|
||||
StartTimeFormat = string.Empty;
|
||||
ConfigurationState = string.Empty;
|
||||
LogisticsTriggersKeysKeyMapping = [];
|
||||
LogisticsEquipmentAlias = string.Empty;
|
||||
ConfigurationProductiveState = string.Empty;
|
||||
LogisticsTriggersCallDefinitionAttributes = [];
|
||||
}
|
||||
|
||||
public Common(ModuleInstanceTypeName objectType, object unitName, object containerName, object configurationState, object configurationProductiveState)
|
||||
{
|
||||
Parameters = [];
|
||||
StoragePaths = [];
|
||||
GeneralTriggers = [];
|
||||
StopTriggersDCP = [];
|
||||
LogisticsColumns = [];
|
||||
Source = string.Empty;
|
||||
StartTriggersDCP = [];
|
||||
LogisticsTriggers = [];
|
||||
Filename = string.Empty;
|
||||
ObjectType = objectType;
|
||||
LogisticsAttributes = [];
|
||||
ParametersAsCsv = string.Empty;
|
||||
StartTimeFormat = string.Empty;
|
||||
UnitName = unitName.ToString();
|
||||
LogisticsTriggersKeysKeyMapping = [];
|
||||
LogisticsEquipmentAlias = string.Empty;
|
||||
ContainerName = containerName.ToString();
|
||||
LogisticsTriggersCallDefinitionAttributes = [];
|
||||
ConfigurationState = configurationState.ToString();
|
||||
ConfigurationProductiveState = configurationProductiveState.ToString();
|
||||
}
|
||||
|
||||
public void Update(PDSFConfiguration configuration)
|
||||
{
|
||||
if (configuration.Settings.StoragePaths is null)
|
||||
StoragePaths = [];
|
||||
else
|
||||
StoragePaths = configuration.Settings.StoragePaths;
|
||||
StartTimeFormat = configuration.Settings.StartTimeFormat;
|
||||
Filename = configuration.Settings.Filename;
|
||||
//
|
||||
Source = configuration.DataCollection.Source;
|
||||
LogisticsEquipmentAlias = configuration.DataCollection.Logistics.EquipmentAlias;
|
||||
//if (LogisticsEquipmentAlias == "R47-PLC")
|
||||
//{ }
|
||||
foreach (PDSFConfigurationDataCollectionLogisticsAttribute item in from l in configuration.DataCollection.Logistics.Attributes orderby l.Use descending, l.Order select l)
|
||||
LogisticsAttributes.Add([item.Use.ToString(), item.Order.ToString("000"), item.Key, item.Placeholder]);
|
||||
foreach (PDSFConfigurationDataCollectionLogisticsColumn item in configuration.DataCollection.Logistics.Columns)
|
||||
LogisticsColumns.Add([item.ID.ToString(), item.Prefix]);
|
||||
foreach (PDSFConfigurationDataCollectionParameter1 item in from l in configuration.DataCollection.VirtualParameters orderby l.Use descending, l.Order select l)
|
||||
{
|
||||
if (item?.Conditions is null)
|
||||
continue;
|
||||
if (string.IsNullOrEmpty(item.Alias) && !string.IsNullOrEmpty(item.Conditions.ConditionModel?.Name))
|
||||
{
|
||||
if (item.Use)
|
||||
Parameters.Add([item.Use.ToString(), item.Order.ToString("000"), item.FullName, item.Conditions?.ConditionModel?.Name, item.HardWareId, item.Description, item.Conditions?.ConditionModel?.Formula, true.ToString(), (configuration.DataCollection.Logistics.Columns.Length + 1 + item.Order).ToString("000")]);
|
||||
else
|
||||
Parameters.Add([item.Use.ToString(), item.Order.ToString("000"), item.FullName, item.Conditions?.ConditionModel?.Name, item.HardWareId, item.Description, string.Empty, true.ToString(), (configuration.DataCollection.Logistics.Columns.Length + 1 + item.Order).ToString("000")]);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (item.Use)
|
||||
Parameters.Add([item.Use.ToString(), item.Order.ToString("000"), item.FullName, item.Alias, item.HardWareId, item.Description, item.Conditions?.ConditionModel?.Formula, true.ToString(), (configuration.DataCollection.Logistics.Columns.Length + 1 + item.Order).ToString("000")]);
|
||||
else
|
||||
Parameters.Add([item.Use.ToString(), item.Order.ToString("000"), item.FullName, item.Alias, item.HardWareId, item.Description, string.Empty, true.ToString(), (configuration.DataCollection.Logistics.Columns.Length + 1 + item.Order).ToString("000")]);
|
||||
}
|
||||
}
|
||||
foreach (PDSFConfigurationDataCollectionParameter item in from l in configuration.DataCollection.Parameters orderby l.Use descending, l.Order select l)
|
||||
{
|
||||
if (string.IsNullOrEmpty(item.Alias) && !string.IsNullOrEmpty(item.Conditions?.ConditionModel?.Name))
|
||||
{
|
||||
if (item.Use)
|
||||
Parameters.Add([item.Use.ToString(), item.Order.ToString("000"), item.FullName, item.Conditions?.ConditionModel?.Name, item.HardWareId, item.Description, item.Conditions?.ConditionModel?.Formula, false.ToString(), (configuration.DataCollection.Logistics.Columns.Length + 1 + item.Order).ToString("000")]);
|
||||
else
|
||||
Parameters.Add([item.Use.ToString(), item.Order.ToString("000"), item.FullName, item.Conditions?.ConditionModel?.Name, item.HardWareId, item.Description, string.Empty, false.ToString(), (configuration.DataCollection.Logistics.Columns.Length + 1 + item.Order).ToString("000")]);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (item is null)
|
||||
continue;
|
||||
if (item.Use)
|
||||
Parameters.Add([item.Use.ToString(), item.Order.ToString("000"), item.FullName, item.Alias, item.HardWareId, item.Description, item.Conditions?.ConditionModel?.Formula, false.ToString(), (configuration.DataCollection.Logistics.Columns.Length + 1 + item.Order).ToString("000")]);
|
||||
else
|
||||
Parameters.Add([item.Use.ToString(), item.Order.ToString("000"), item.FullName, item.Alias, item.HardWareId, item.Description, string.Empty, false.ToString(), (configuration.DataCollection.Logistics.Columns.Length + 1 + item.Order).ToString("000")]);
|
||||
}
|
||||
}
|
||||
Parameters = (from l in Parameters orderby l[0] descending, l[1] select l).ToList();
|
||||
StringBuilder text = new();
|
||||
//text.AppendLine("\"AliasName\";\"Condition\";\"EventId\";\"ExceptionId\";\"Formula\";\"HardwareId\";\"OrderId\";\"ParameterName\";\"Remark\";\"ReportName\";\"SourceId\";\"Use\"");
|
||||
//"Test";"";"";"";"";"";"1";"MICROSCOPE01/MET08MESMICROSCOPE/Test";"";"MICROSCOPE01/MET08MESMICROSCOPE/FileRead";"";"True""
|
||||
_ = text.AppendLine("\"Use\";\"OrderId\";\"ReportName\";\"ParameterName\";\"AliasName\";\"HardwareId\";\"Remark\";\"Formula\"");
|
||||
foreach (string?[] parameter in Parameters)
|
||||
{
|
||||
for (int i = 0; i < 7; i++)
|
||||
_ = text.Append('"').Append(parameter[i]).Append("\";");
|
||||
_ = text.Remove(text.Length - 1, 1);
|
||||
_ = text.AppendLine();
|
||||
}
|
||||
ParametersAsCsv = text.ToString();
|
||||
foreach (PDSFConfigurationDataCollectionGeneralTriggers item in configuration.DataCollection.GeneralTriggers)
|
||||
{
|
||||
foreach (PDSFConfigurationDataCollectionGeneralTriggersVariableModel gv in item.GlobalVariables)
|
||||
GeneralTriggers.Add([item.Name, gv.Name, gv.ParameterName, gv.Formula]);
|
||||
}
|
||||
{
|
||||
PDSFConfigurationDataCollectionStartTriggersDCP item = configuration.DataCollection.StartTriggers.DCP;
|
||||
if (item is not null)
|
||||
StartTriggersDCP.Add([item.Name, item.Rule, item.ResolveGlobalVariableBeforeTrigger.ToString()]);
|
||||
}
|
||||
if (configuration.DataCollection.Logistics.Triggers.UpdateTrigger is not null)
|
||||
{
|
||||
foreach (PDSFConfigurationDataCollectionLogisticsTriggersUpdateTriggerLogisticRequest item in configuration.DataCollection.Logistics.Triggers.UpdateTrigger.LogisticRequest)
|
||||
{
|
||||
LogisticsTriggers.Add([item.Name.ToString(), item.LogisticsColumn.Fixed.ToString(), item.Rule, item.Keys.Scenario, item.Keys.DefaultJobIndex.ToString(), item.Keys.DefaultCarrierIndex.ToString(), item.Keys.DefaultSlotIndex.ToString(), item.DataPool.ToString()]);
|
||||
if (item.Keys.KeyMapping is not null)
|
||||
LogisticsTriggersKeysKeyMapping.Add(item.Name, [item.Keys.KeyMapping.KeyName, item.Keys.KeyMapping.ParameterName, item.Keys.KeyMapping.Formula]);
|
||||
LogisticsTriggersCallDefinitionAttributes.Add(item.Name, []);
|
||||
foreach (PDSFConfigurationDataCollectionLogisticsTriggersUpdateTriggerLogisticRequestCallDefinitionLogisticCallDefinitionAttribute att in item.CallDefinition.Attributes)
|
||||
LogisticsTriggersCallDefinitionAttributes[item.Name].Add([att.LogisticsKey, att.Source, att.MappedParameterName, att.Formula]);
|
||||
}
|
||||
}
|
||||
{
|
||||
PDSFConfigurationDataCollectionStopTriggersDCP item = configuration.DataCollection.StopTriggers.DCP;
|
||||
if (item is not null)
|
||||
StopTriggersDCP.Add([item.Name, item.Rule, item.ResolveGlobalVariableBeforeTrigger.ToString(), item.ResetGlobalVariablesAfterTrigger.ToString()]);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
453
Helpers/EDA/DCP.cs
Normal file
453
Helpers/EDA/DCP.cs
Normal file
@ -0,0 +1,453 @@
|
||||
using System.Dynamic;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace File_Watcher.Helpers.EDA;
|
||||
|
||||
public class DCP
|
||||
{
|
||||
|
||||
internal static string GetEdaObjectToHtml(string edaObjectFile, Common common)
|
||||
{
|
||||
StringBuilder result = new();
|
||||
string title = string.Concat(Path.GetFileName(edaObjectFile), " - ", common.Source);
|
||||
_ = result.AppendLine("<!DOCTYPE html>");
|
||||
_ = result.AppendLine("<html lang=\"en\">");
|
||||
_ = result.AppendLine("<head>");
|
||||
_ = result.AppendLine("<style>table, th, td{border:1px solid black;} td{padding:2px}</style>");
|
||||
_ = result.Append("<title>").Append(title).AppendLine("</title>");
|
||||
_ = result.AppendLine("</head>");
|
||||
_ = result.AppendLine("<body>");
|
||||
_ = result.AppendLine("<table>");
|
||||
_ = result.AppendLine("<tr>");
|
||||
_ = result.Append("<th nowrap>").Append("Unit Name").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Container Name").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Configuration State").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Configuration Productive State").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("LogisticsEquipmentAlias").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Source").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("StoragePath(s)").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("StartTimeFormat").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Filename").AppendLine("</th>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
_ = result.AppendLine("<tr>");
|
||||
_ = result.Append("<td nowrap>").Append(common.UnitName).AppendLine("</td>");
|
||||
_ = result.Append("<td nowrap>").Append(common.ContainerName).AppendLine("</td>");
|
||||
_ = result.Append("<td nowrap>").Append(common.ConfigurationState).AppendLine("</td>");
|
||||
_ = result.Append("<td nowrap>").Append(common.ConfigurationProductiveState).AppendLine("</td>");
|
||||
_ = result.Append("<td nowrap>").Append(common.LogisticsEquipmentAlias).AppendLine("</td>");
|
||||
_ = result.Append("<td nowrap>").Append(common.Source).AppendLine("</td>");
|
||||
_ = result.Append("<td nowrap>").Append(string.Join("</br >", common.StoragePaths)).AppendLine("</td>");
|
||||
_ = result.Append("<td nowrap>").Append(common.StartTimeFormat).AppendLine("</td>");
|
||||
_ = result.Append("<td nowrap>").Append(common.Filename).AppendLine("</td>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
_ = result.AppendLine("</table>");
|
||||
_ = result.AppendLine("<hr>");
|
||||
_ = result.AppendLine("<table>");
|
||||
_ = result.AppendLine("<tr>");
|
||||
_ = result.Append("<th nowrap>").Append("Use").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Order").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Key").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Placeholder").AppendLine("</th>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
foreach (string[] item in common.LogisticsAttributes)
|
||||
{
|
||||
if (item.Length > 2 && !item[2].StartsWith("Z_"))
|
||||
{
|
||||
_ = result.AppendLine("<tr>");
|
||||
foreach (string value in item)
|
||||
_ = result.Append("<td nowrap>").Append(value).AppendLine("</td>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
}
|
||||
}
|
||||
_ = result.AppendLine("</table>");
|
||||
_ = result.AppendLine("<hr>");
|
||||
_ = result.AppendLine("<table>");
|
||||
_ = result.AppendLine("<tr>");
|
||||
_ = result.Append("<th nowrap>").Append("ID").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Prefix").AppendLine("</th>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
foreach (string[] item in common.LogisticsColumns)
|
||||
{
|
||||
_ = result.AppendLine("<tr>");
|
||||
foreach (string value in item)
|
||||
_ = result.Append("<td nowrap>").Append(value).AppendLine("</td>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
}
|
||||
_ = result.AppendLine("</table>");
|
||||
_ = result.AppendLine("<hr>");
|
||||
_ = result.AppendLine("<table>");
|
||||
_ = result.AppendLine("<tr>");
|
||||
_ = result.Append("<th nowrap>").Append("Use").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Order").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("FullName").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Alias").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("HardWareId").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Description").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Formula").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Virtual").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Column#").AppendLine("</th>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
foreach (string?[] item in common.Parameters)
|
||||
{
|
||||
_ = result.AppendLine("<tr>");
|
||||
foreach (string? value in item)
|
||||
_ = result.Append("<td nowrap>").Append(value).AppendLine("</td>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
}
|
||||
_ = result.AppendLine("</table>");
|
||||
_ = result.AppendLine("<hr>");
|
||||
_ = result.AppendLine("<table>");
|
||||
_ = result.AppendLine("<tr>");
|
||||
_ = result.Append("<th nowrap>").Append("Parent Name").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Name").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("ParameterName").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Formula").AppendLine("</th>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
foreach (string[] item in common.GeneralTriggers)
|
||||
{
|
||||
_ = result.AppendLine("<tr>");
|
||||
foreach (string value in item)
|
||||
_ = result.Append("<td nowrap>").Append(value).AppendLine("</td>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
}
|
||||
_ = result.AppendLine("</table>");
|
||||
_ = result.AppendLine("<hr>");
|
||||
_ = result.AppendLine("<table>");
|
||||
_ = result.AppendLine("<tr>");
|
||||
_ = result.Append("<th nowrap>").Append("Name").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Rule").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("ResolveGlobalVariableBeforeTrigger").AppendLine("</th>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
foreach (string[] item in common.StartTriggersDCP)
|
||||
{
|
||||
_ = result.AppendLine("<tr>");
|
||||
foreach (string value in item)
|
||||
_ = result.Append("<td nowrap>").Append(value).AppendLine("</td>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
}
|
||||
_ = result.AppendLine("</table>");
|
||||
_ = result.AppendLine("<hr>");
|
||||
_ = result.AppendLine("<table>");
|
||||
_ = result.AppendLine("<tr>");
|
||||
_ = result.Append("<th nowrap>").Append("Name").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Fixed").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Rule").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Scenario").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("DefaultJobIndex").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("DefaultCarrierIndex").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("DefaultSlotIndex").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("DataPool").AppendLine("</th>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
foreach (string?[] item in common.LogisticsTriggers)
|
||||
{
|
||||
if (item is null)
|
||||
continue;
|
||||
_ = result.AppendLine("<tr>");
|
||||
foreach (string? value in item)
|
||||
_ = result.Append("<td nowrap>").Append(value).AppendLine("</td>");
|
||||
_ = result.AppendLine("<td>");
|
||||
_ = result.AppendLine("<table>");
|
||||
_ = result.AppendLine("<tr>");
|
||||
_ = result.Append("<th nowrap>").Append("KeyName").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("ParameterName").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Formula").AppendLine("</th>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
foreach (KeyValuePair<int, string[]> keyValuePair in common.LogisticsTriggersKeysKeyMapping)
|
||||
{
|
||||
_ = result.AppendLine("<tr>");
|
||||
foreach (string value in keyValuePair.Value)
|
||||
_ = result.Append("<td nowrap>").Append(value).AppendLine("</td>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
}
|
||||
_ = result.AppendLine("</table>");
|
||||
_ = result.AppendLine("</td>");
|
||||
_ = result.AppendLine("<td>");
|
||||
_ = result.AppendLine("<table>");
|
||||
_ = result.AppendLine("<tr>");
|
||||
_ = result.Append("<th nowrap>").Append("LogisticsKey").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Source").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("MappedParameterName").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Formula").AppendLine("</th>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
foreach (KeyValuePair<int, List<string[]>> keyValuePair in common.LogisticsTriggersCallDefinitionAttributes)
|
||||
{
|
||||
foreach (string[] values in keyValuePair.Value)
|
||||
{
|
||||
if (values.Length > 0 && !values[0].StartsWith("Z_"))
|
||||
{
|
||||
_ = result.AppendLine("<tr>");
|
||||
foreach (string value in values)
|
||||
_ = result.Append("<td nowrap>").Append(value).AppendLine("</td>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
}
|
||||
}
|
||||
}
|
||||
_ = result.AppendLine("</table>");
|
||||
_ = result.AppendLine("</td>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
}
|
||||
_ = result.AppendLine("</table>");
|
||||
_ = result.AppendLine("<hr>");
|
||||
_ = result.AppendLine("<table>");
|
||||
_ = result.AppendLine("<tr>");
|
||||
_ = result.Append("<th nowrap>").Append("Name").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("Rule").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("ResolveGlobalVariableBeforeTrigger").AppendLine("</th>");
|
||||
_ = result.Append("<th nowrap>").Append("ResetGlobalVariablesAfterTrigger").AppendLine("</th>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
foreach (string[] item in common.StopTriggersDCP)
|
||||
{
|
||||
_ = result.AppendLine("<tr>");
|
||||
foreach (string value in item)
|
||||
_ = result.Append("<td nowrap>").Append(value).AppendLine("</td>");
|
||||
_ = result.AppendLine("</tr>");
|
||||
}
|
||||
_ = result.AppendLine("</table>");
|
||||
_ = result.AppendLine("<hr>");
|
||||
_ = result.AppendLine("</body>");
|
||||
_ = result.AppendLine("</html>");
|
||||
return result.ToString();
|
||||
}
|
||||
|
||||
private static string? ReplaceNull(object @object)
|
||||
{
|
||||
if (@object is null)
|
||||
return string.Empty;
|
||||
else
|
||||
return @object.ToString();
|
||||
}
|
||||
|
||||
private static void TextResolveEntry(StringBuilder result, dynamic expandoObject, int level, string super, int? i, bool group)
|
||||
{
|
||||
level += 1;
|
||||
foreach (dynamic entry in expandoObject)
|
||||
{
|
||||
if (entry.Value is ExpandoObject)
|
||||
TextResolveEntry(result, entry.Value, level, string.Concat(super, " : ", entry.Key), i, group);
|
||||
else
|
||||
{
|
||||
if (entry.Value is not ICollection<object>)
|
||||
{
|
||||
if (i is null)
|
||||
result.Append(level).Append(") ").Append(super).Append(" : ").Append(entry.Key).Append("--->").AppendLine(ReplaceNull(entry.Value));
|
||||
else
|
||||
result.Append(level).Append(") ").Append(super).Append(" : ").Append(entry.Key).Append("[").Append(i.Value).Append("]--->").AppendLine(ReplaceNull(entry.Value));
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!group)
|
||||
{
|
||||
for (i = 0; i.Value < entry.Value.Count; i++)
|
||||
{
|
||||
if (entry.Value[i.Value] is ExpandoObject)
|
||||
TextResolveEntry(result, entry.Value[i.Value], level, string.Concat(super, " : ", entry.Key), i.Value, group);
|
||||
else
|
||||
result.Append(level).Append(") ").Append(super).Append(" : ").Append(entry.Key).Append("[").Append(i.Value).Append("]--->").AppendLine(ReplaceNull(entry.Value[i.Value]));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (i = 0; i.Value < entry.Value.Count; i++)
|
||||
{
|
||||
if (entry.Value[i.Value] is not ExpandoObject)
|
||||
result.Append(level).Append(") ").Append(super).Append(" : ").Append(entry.Key).Append("[").Append(i.Value).Append("]--->").AppendLine(ReplaceNull(entry.Value[i.Value]));
|
||||
}
|
||||
for (i = 0; i.Value < entry.Value.Count; i++)
|
||||
{
|
||||
if (entry.Value[i.Value] is ExpandoObject)
|
||||
TextResolveEntry(result, entry.Value[i.Value], level, string.Concat(super, " : ", entry.Key), i.Value, group);
|
||||
}
|
||||
}
|
||||
i = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
level -= 1;
|
||||
if (level == 0)
|
||||
{ }
|
||||
}
|
||||
|
||||
internal static string GetText(string edaObjectFile, Common common, string json)
|
||||
{
|
||||
StringBuilder result = new();
|
||||
if (result.Length > 0) //Skipping because System.Text.Json changed the way Expando works
|
||||
{
|
||||
string title = string.Concat(Path.GetFileName(edaObjectFile), " - ", common.Source);
|
||||
dynamic? expandoObject = JsonSerializer.Deserialize<ExpandoObject>(json);
|
||||
_ = result.AppendLine(title);
|
||||
_ = result.AppendLine("Loop -> \"Normal\"");
|
||||
_ = result.AppendLine(edaObjectFile);
|
||||
_ = result.AppendLine();
|
||||
TextResolveEntry(result, expandoObject, 0, string.Empty, null, group: false);
|
||||
_ = result.AppendLine();
|
||||
_ = result.AppendLine();
|
||||
_ = result.AppendLine();
|
||||
_ = result.AppendLine(title);
|
||||
_ = result.AppendLine("Loop -> \"Grouped\"");
|
||||
_ = result.AppendLine(edaObjectFile);
|
||||
_ = result.AppendLine();
|
||||
TextResolveEntry(result, expandoObject, 0, string.Empty, null, group: true);
|
||||
}
|
||||
return result.ToString();
|
||||
}
|
||||
|
||||
internal static string GetEdaObjectToDMSGridFormat(string edaObjectFile, Common common, bool useAlias)
|
||||
{
|
||||
StringBuilder result = new();
|
||||
if (string.IsNullOrEmpty(edaObjectFile))
|
||||
{ }
|
||||
string? value;
|
||||
string[] segments;
|
||||
int? recordStart = null;
|
||||
bool hasRecordStart = false;
|
||||
string name = string.Concat(common.LogisticsEquipmentAlias, "_", common.ContainerName);
|
||||
_ = result.AppendLine("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
|
||||
_ = result.Append("<Format Name=\"").Append(name).Append("\">").AppendLine();
|
||||
_ = result.AppendLine(" <General RecordStart=\"\" RecordLength=\"0\" ReadCommand=\"\" DecimalSeparator=\".\">");
|
||||
_ = result.AppendLine(" <RecordTerminator><13><10></RecordTerminator>");
|
||||
_ = result.AppendLine(" <ColumnSeparator><9></ColumnSeparator>");
|
||||
_ = result.AppendLine(" </General>");
|
||||
_ = result.AppendLine(" <Fields>");
|
||||
for (int i = 0; i < common.Parameters.Count; i++)
|
||||
{
|
||||
if (common.Parameters[i][3] == "RECORD_START")
|
||||
{
|
||||
hasRecordStart = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < common.Parameters.Count; i++)
|
||||
{
|
||||
if (recordStart is null && common.Parameters[i][3] == "RECORD_START")
|
||||
recordStart = i;
|
||||
if ((!hasRecordStart || (hasRecordStart && recordStart.HasValue)) && common.Parameters[i][0] == "True")
|
||||
{
|
||||
if (useAlias && !string.IsNullOrEmpty(common.Parameters[i][3]))
|
||||
{
|
||||
value = common.Parameters[i][3];
|
||||
value ??= string.Empty;
|
||||
name = value.Replace("'", string.Empty);
|
||||
}
|
||||
else
|
||||
{
|
||||
value = common.Parameters[i][2];
|
||||
value ??= string.Empty;
|
||||
segments = value.Split('/');
|
||||
name = segments[^1];
|
||||
}
|
||||
_ = result.Append(" <Field Name=\"").Append(name).Append("\" ColumnNumber=\"").Append(i + common.LogisticsColumns.Count + 2).Append("\" StartPosition=\"\" Length=\"\" DataType=\"Text\" NullReplacement=\"\" />").AppendLine();
|
||||
}
|
||||
}
|
||||
_ = result.AppendLine(" </Fields>");
|
||||
_ = result.AppendLine(" <Conditions>");
|
||||
_ = result.AppendLine(" <Column />");
|
||||
_ = result.AppendLine(" <Row>");
|
||||
_ = result.AppendLine(" <Condition>");
|
||||
_ = result.AppendLine(" <SkipHeaderCount>7</SkipHeaderCount>");
|
||||
_ = result.AppendLine(" <SkipRowFilter>0</SkipRowFilter>");
|
||||
_ = result.AppendLine(" <SkipRowValue>");
|
||||
_ = result.AppendLine(" </SkipRowValue>");
|
||||
_ = result.AppendLine(" </Condition>");
|
||||
_ = result.AppendLine(" </Row>");
|
||||
_ = result.AppendLine(" </Conditions>");
|
||||
_ = result.AppendLine("</Format>");
|
||||
return result.ToString();
|
||||
}
|
||||
|
||||
internal static string GetEdaObjectToAPCParameter(string edaObjectFile, Common common)
|
||||
{
|
||||
StringBuilder result = new();
|
||||
if (string.IsNullOrEmpty(edaObjectFile))
|
||||
{ }
|
||||
string? value;
|
||||
string parameter;
|
||||
string[] segments;
|
||||
string parameterSub35;
|
||||
_ = result.AppendLine("ExportFileVersion=1.0.6");
|
||||
_ = result.AppendLine("ExportFromTabsheet=Para");
|
||||
_ = result.AppendLine("FieldName\tLongName\tMatchMode\tEquipment\tName\tPdsfNameConvCol\tPdsfNameDataType\tType\tChamberInfo\tUnifiedPara\tDateFormat\tUsername\tId\tWorkcenterId\tSite\tArea\tWorkcenter\tValidFrom\tValidTo");
|
||||
_ = result.AppendLine("TIME_PREV_DIFF\tTIME_PREV_DIFF\tEXACT\t*\tTIME_PREV_DIFF\t\tNUMERIC\tRUN\t\tTIME_PREV_DIFF\t\tPHARES\t95069\t4571\tMesa\t\t\t4/15/2020 6:10 PM");
|
||||
_ = result.AppendLine("TIME\tTIME\tEXACT\t*\tTIME\t\tNUMERIC\tRUN\t\tTIME\t\tPHARES\t95070\t4571\tMesa\t\t\t4/15/2020 6:10 PM");
|
||||
for (int i = 0; i < common.Parameters.Count; i++)
|
||||
{
|
||||
if (common.Parameters[i][0] == "True")
|
||||
{
|
||||
value = common.Parameters[i][2];
|
||||
value ??= string.Empty;
|
||||
segments = value.Split('/');
|
||||
parameter = segments[^1];
|
||||
if (parameter.Length < 35)
|
||||
parameterSub35 = parameter;
|
||||
else
|
||||
parameterSub35 = parameter[..35];
|
||||
_ = result.Append(parameterSub35).Append("\tDIVERSE\tEXACT\t*\t").Append(parameterSub35).AppendLine("\t\tNUMERIC\tRUN\t\t\t\tPHARES\t9000000012\t4571\tMesa\t\t\t4/15/2020 6:10 PM");
|
||||
}
|
||||
}
|
||||
_ = result.AppendLine();
|
||||
_ = result.AppendLine();
|
||||
_ = result.AppendLine();
|
||||
for (int i = 0; i < common.Parameters.Count; i++)
|
||||
{
|
||||
if (common.Parameters[i][0] == "True")
|
||||
{
|
||||
value = common.Parameters[i][2];
|
||||
value ??= string.Empty;
|
||||
segments = value.Split('/');
|
||||
parameter = segments[^1];
|
||||
_ = result.Append(parameter).Append("\tDIVERSE\tEXACT\t*\t").Append(parameter).AppendLine("\t\tNUMERIC\tRUN\t\t\t\tPHARES\t9000000012\t4571\tMesa\t\t\t4/15/2020 6:10 PM");
|
||||
}
|
||||
}
|
||||
return result.ToString();
|
||||
}
|
||||
|
||||
internal static string GetEdaObjectToAPCRunKeyNumber(string edaObjectFile, Common common)
|
||||
{
|
||||
StringBuilder result = new();
|
||||
if (string.IsNullOrEmpty(edaObjectFile))
|
||||
{ }
|
||||
string? value;
|
||||
string parameter;
|
||||
string[] segments;
|
||||
string parameterSub21;
|
||||
string parameterSub35;
|
||||
_ = result.AppendLine("ExportFileVersion=1.0.6");
|
||||
_ = result.AppendLine("ExportFromTabsheet=Run-Keynumbers");
|
||||
_ = result.AppendLine("FeatureName\tShortName\tChamber\tComments\tVarMode\tPara\tExclude0\tTrigOn1\tTrigOn2\tTrigOn3\tTrigOff1\tTrigOff2\tTrigOff3\tTrigDelay\tTrigNorm\tTrigNvl\tTrigTrg\tAddCondOn\tActive\tFilter1\tFilter2\tFilter3\tFilter4\tUnit\tId\tWorkcenterId\tSite\tArea\tWorkcenter\tUsername\tValidFrom\tValidTo");
|
||||
for (int i = 0; i < common.Parameters.Count; i++)
|
||||
{
|
||||
if (common.Parameters[i][0] == "True")
|
||||
{
|
||||
value = common.Parameters[i][2];
|
||||
value ??= string.Empty;
|
||||
segments = value.Split('/');
|
||||
parameter = segments[^1];
|
||||
if (parameter.Length < 35)
|
||||
parameterSub35 = parameter;
|
||||
else
|
||||
parameterSub35 = parameter[..35];
|
||||
if (parameter.Length < 21)
|
||||
parameterSub21 = parameter;
|
||||
else
|
||||
parameterSub21 = parameter[..21];
|
||||
_ = result.Append(parameterSub21).Append("_MIN\t").Append(parameterSub21).Append("_MIN\t\t\tMIN\t").Append(parameterSub35).AppendLine("\t0\tTIME\t=\tRUNSTART\tTIME\t=\tRUNEND\t\t\t\t\t\t1\t\t\t\t\t\t-1\t-1\t\t\t\tECPHARES\t5/2/2017 2:44 PM");
|
||||
}
|
||||
}
|
||||
_ = result.AppendLine();
|
||||
_ = result.AppendLine();
|
||||
_ = result.AppendLine();
|
||||
for (int i = 0; i < common.Parameters.Count; i++)
|
||||
{
|
||||
if (common.Parameters[i][0] == "True")
|
||||
{
|
||||
value = common.Parameters[i][2];
|
||||
value ??= string.Empty;
|
||||
segments = value.Split('/');
|
||||
parameter = segments[^1];
|
||||
_ = result.Append(parameter).Append("_MIN\t").Append(parameter).Append("_MIN\t\t\tMIN\t").Append(parameter).AppendLine("\t0\tTIME\t=\tRUNSTART\tTIME\t=\tRUNEND\t\t\t\t\t\t1\t\t\t\t\t\t-1\t-1\t\t\t\tECPHARES\t5/2/2017 2:44 PM");
|
||||
}
|
||||
}
|
||||
return result.ToString();
|
||||
}
|
||||
|
||||
}
|
2502
Helpers/EDA/EDA - A.cs
Normal file
2502
Helpers/EDA/EDA - A.cs
Normal file
File diff suppressed because it is too large
Load Diff
6
Helpers/EDA/ModuleInstanceTypeName.cs
Normal file
6
Helpers/EDA/ModuleInstanceTypeName.cs
Normal file
@ -0,0 +1,6 @@
|
||||
namespace File_Watcher.Helpers.EDA;
|
||||
|
||||
public enum ModuleInstanceTypeName
|
||||
{
|
||||
Pdsf
|
||||
}
|
118
Helpers/HelperCompass.cs
Normal file
118
Helpers/HelperCompass.cs
Normal file
@ -0,0 +1,118 @@
|
||||
using File_Watcher.Models;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
|
||||
namespace File_Watcher.Helpers;
|
||||
|
||||
internal static partial class HelperCompass
|
||||
{
|
||||
|
||||
private static bool _FirstRun = true;
|
||||
|
||||
private static void MapDrives(AppSettings appSettings, ILogger<Worker> logger)
|
||||
{
|
||||
Process? process;
|
||||
string arguments;
|
||||
string decrypted;
|
||||
string? pathRoot;
|
||||
string[] segments;
|
||||
string standardError;
|
||||
string standardOutput;
|
||||
string fileName = "net";
|
||||
StringBuilder stringBuilder = new();
|
||||
if (appSettings.DriveConfiguration.Use is not null && appSettings.DriveConfiguration.Use.Value)
|
||||
{
|
||||
pathRoot = Path.GetPathRoot(appSettings.DriveConfiguration.Share);
|
||||
if (!string.IsNullOrEmpty(pathRoot) && !Directory.Exists(pathRoot))
|
||||
{
|
||||
if (string.IsNullOrEmpty(appSettings.DriveConfiguration.Password))
|
||||
decrypted = string.Empty;
|
||||
else
|
||||
decrypted = RijndaelEncryption.Decrypt(appSettings.DriveConfiguration.Password, appSettings.Company);
|
||||
arguments = $"use {appSettings.DriveConfiguration.Letter}: \"{appSettings.DriveConfiguration.Share}\" /p:yes /user:{appSettings.DriveConfiguration.User} {decrypted}";
|
||||
_ = stringBuilder.Clear();
|
||||
segments = arguments.Split(' ');
|
||||
for (int j = 0; j < segments.Length - 1; j++)
|
||||
_ = stringBuilder.Append(segments[j]).Append(' ');
|
||||
logger.LogInformation("// {output}", stringBuilder);
|
||||
ProcessStartInfo processStartInfo = new(fileName, arguments)
|
||||
{
|
||||
RedirectStandardError = true,
|
||||
RedirectStandardOutput = true,
|
||||
UseShellExecute = false
|
||||
};
|
||||
try
|
||||
{
|
||||
process = Process.Start(processStartInfo);
|
||||
if (process is not null)
|
||||
{
|
||||
for (int j = 1; j < 45; j++)
|
||||
{
|
||||
_ = process.WaitForExit(1000);
|
||||
if (process.HasExited)
|
||||
break;
|
||||
}
|
||||
if (!process.HasExited)
|
||||
logger.LogError("// Never exited!");
|
||||
else
|
||||
{
|
||||
standardError = process.StandardError.ReadToEnd();
|
||||
standardOutput = process.StandardOutput.ReadToEnd();
|
||||
logger.LogInformation("// {error}{line}{line}// {output}", standardError, Environment.NewLine, Environment.NewLine, standardOutput);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Error:");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static ReadOnlyCollection<string> GetFiles(AppSettings appSettings, string directory)
|
||||
{
|
||||
ReadOnlyCollection<string> results;
|
||||
if (!Directory.Exists(directory))
|
||||
_ = Directory.CreateDirectory(directory);
|
||||
results = new(Directory.GetFiles(directory, appSettings.CompassConfiguration.Pattern, SearchOption.TopDirectoryOnly));
|
||||
return results;
|
||||
}
|
||||
|
||||
private static void CopyFiles(AppSettings appSettings, ReadOnlyCollection<string> files)
|
||||
{
|
||||
string checkFile;
|
||||
foreach (string file in files)
|
||||
{
|
||||
checkFile = Path.Combine(appSettings.CompassConfiguration.Destination, Path.GetFileName(file));
|
||||
if (File.Exists(checkFile))
|
||||
continue;
|
||||
File.Copy(file, checkFile);
|
||||
}
|
||||
}
|
||||
|
||||
internal static bool CopyFile(AppSettings appSettings, ILogger<Worker> logger)
|
||||
{
|
||||
if (_FirstRun)
|
||||
{
|
||||
_FirstRun = false;
|
||||
MapDrives(appSettings, logger);
|
||||
logger.LogCritical("MapDrives Done");
|
||||
}
|
||||
string directory;
|
||||
ReadOnlyCollection<string> files;
|
||||
DateTime[] dateTimes = [DateTime.Now, DateTime.Now.AddHours(-appSettings.CompassConfiguration.HoursBack)];
|
||||
foreach (DateTime dateTime in dateTimes)
|
||||
{
|
||||
directory = Path.Combine(appSettings.CompassConfiguration.Source, dateTime.ToString(appSettings.CompassConfiguration.YearPattern), dateTime.ToString(appSettings.CompassConfiguration.MonthPattern));
|
||||
if (!Directory.Exists(directory))
|
||||
_ = Directory.CreateDirectory(directory);
|
||||
files = GetFiles(appSettings, directory);
|
||||
logger.LogDebug("Found {Files}", files);
|
||||
CopyFiles(appSettings, files);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
37
Helpers/HelperEAFProgramData.cs
Normal file
37
Helpers/HelperEAFProgramData.cs
Normal file
@ -0,0 +1,37 @@
|
||||
using File_Watcher.Models;
|
||||
|
||||
namespace File_Watcher.Helpers;
|
||||
|
||||
internal static partial class HelperEAFProgramData
|
||||
{
|
||||
|
||||
internal static bool MoveFiles(AppSettings appSettings, ILogger<Worker> logger)
|
||||
{
|
||||
string checkFile;
|
||||
string checkDirectory;
|
||||
string source = Path.GetFullPath(appSettings.EAFProgramDataConfiguration.Source);
|
||||
string[] files = Directory.GetFiles(source, "*", SearchOption.AllDirectories);
|
||||
logger.LogInformation("After {MillisecondsDelay} with search pattern '{SearchPattern}' found {files}", appSettings.MillisecondsDelay, appSettings.EAFLogConfiguration.SearchPattern, files.Length);
|
||||
foreach (string file in files)
|
||||
{
|
||||
Thread.Sleep(500);
|
||||
checkFile = file.Replace(source, appSettings.EAFProgramDataConfiguration.Destination);
|
||||
if (checkFile == file)
|
||||
throw new NotSupportedException("Replace failed!");
|
||||
checkDirectory = Path.GetDirectoryName(checkFile) ?? throw new NotSupportedException();
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(checkDirectory))
|
||||
_ = Directory.CreateDirectory(checkDirectory);
|
||||
if (File.Exists(checkFile))
|
||||
continue;
|
||||
File.Move(file, checkFile);
|
||||
Thread.Sleep(500);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{ logger.LogInformation(ex, "Inner loop error!"); }
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
280
Helpers/HelperEDADatabase.cs
Normal file
280
Helpers/HelperEDADatabase.cs
Normal file
@ -0,0 +1,280 @@
|
||||
using File_Watcher.Helpers.EDA;
|
||||
using File_Watcher.Models;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Xml;
|
||||
using System.Xml.Serialization;
|
||||
|
||||
namespace File_Watcher.Helpers;
|
||||
|
||||
internal static partial class HelperEDADatabase
|
||||
{
|
||||
|
||||
private static Calendar? _Calendar;
|
||||
private static string? _EDADataCollectionPlansLastRun;
|
||||
|
||||
[GeneratedRegex("[a-zA-Z0-9]{1,}")]
|
||||
private static partial Regex RegexAZ09();
|
||||
|
||||
private static Stream ToStream(string @this)
|
||||
{
|
||||
MemoryStream? stream = new();
|
||||
StreamWriter? writer = new(stream);
|
||||
writer.Write(@this);
|
||||
writer.Flush();
|
||||
stream.Position = 0;
|
||||
return stream;
|
||||
}
|
||||
|
||||
private static T? ParseXML<T>(string @this, bool throwExceptions) where T : class
|
||||
{
|
||||
object? result = null;
|
||||
try
|
||||
{
|
||||
Stream stream = ToStream(@this.Trim());
|
||||
XmlReader? reader = XmlReader.Create(stream, new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Document });
|
||||
XmlSerializer xmlSerializer = new(typeof(T), typeof(T).GetNestedTypes());
|
||||
result = xmlSerializer.Deserialize(reader);
|
||||
stream.Dispose();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
if (throwExceptions)
|
||||
throw;
|
||||
}
|
||||
return result as T;
|
||||
}
|
||||
|
||||
private static void EvaluateRows(string workingDirectory, Dictionary<string, Dictionary<ModuleInstanceTypeName, List<List<object>>>> rows, CancellationToken cancellationToken)
|
||||
{ // cSpell:disable
|
||||
// int moduleinstancetypename = 0;
|
||||
int unitname = 1;
|
||||
// int modulename = 2;
|
||||
int containername = 3;
|
||||
int configurationstate = 4;
|
||||
int configurationproductivestate = 5;
|
||||
// int containermodifiername = 6;
|
||||
int containermodifieddate = 7;
|
||||
int containerconfiguration = 8;
|
||||
int configurationmodifieddate = 9;
|
||||
// cSpell:enable
|
||||
string csv;
|
||||
string? xml;
|
||||
string json;
|
||||
string text;
|
||||
string html;
|
||||
Common common;
|
||||
string emptyAPC;
|
||||
string fileName;
|
||||
string? modifiedDate;
|
||||
string edaObjectFile;
|
||||
string goldDirectory;
|
||||
string replace = "$$$";
|
||||
string edaObjectDirectory;
|
||||
DateTime lastModifiedDate;
|
||||
string objectTypeDirectory;
|
||||
DateTime containerModifiedDate;
|
||||
PDSFConfiguration? configuration;
|
||||
DateTime configurationModifiedDate;
|
||||
JsonSerializerOptions jsonSerializerOptions = new() { WriteIndented = true };
|
||||
foreach (KeyValuePair<string, Dictionary<ModuleInstanceTypeName, List<List<object>>>> databaseElement in rows)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
break;
|
||||
emptyAPC = string.Concat(workingDirectory, @"\", databaseElement.Key, @"\EmptyAPC.xlsx");
|
||||
foreach (KeyValuePair<ModuleInstanceTypeName, List<List<object>>> tableNameElement in databaseElement.Value)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
break;
|
||||
objectTypeDirectory = string.Concat(workingDirectory, @"\", databaseElement.Key, @"\", tableNameElement.Key);
|
||||
foreach (List<object> rowItem in tableNameElement.Value)
|
||||
{ // cSpell:disable
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
break;
|
||||
// foreach (var item in rowItem)
|
||||
// Print(item.ToString());
|
||||
// if (!rowItem[containername].ToString().Contains("Plan_Pdsf_Health_Cp2Mg"))
|
||||
// if (!rowItem[unitname].ToString().Contains("HGCV1") || !rowItem[containername].ToString().Contains("Plan_Pdsf"))
|
||||
// continue;
|
||||
modifiedDate = rowItem[containermodifieddate].ToString();
|
||||
if (string.IsNullOrEmpty(modifiedDate))
|
||||
continue;
|
||||
containerModifiedDate = DateTime.Parse(modifiedDate);
|
||||
modifiedDate = rowItem[configurationmodifieddate].ToString();
|
||||
if (string.IsNullOrEmpty(modifiedDate))
|
||||
continue;
|
||||
configurationModifiedDate = DateTime.Parse(modifiedDate);
|
||||
if (containerModifiedDate < configurationModifiedDate)
|
||||
lastModifiedDate = configurationModifiedDate;
|
||||
else
|
||||
lastModifiedDate = containerModifiedDate;
|
||||
goldDirectory = string.Concat(objectTypeDirectory, @"\", rowItem[unitname], @"\", rowItem[containername], @"\Gold");
|
||||
if (!Directory.Exists(goldDirectory))
|
||||
_ = Directory.CreateDirectory(goldDirectory);
|
||||
edaObjectDirectory = string.Concat(objectTypeDirectory, @"\", rowItem[unitname], @"\", rowItem[containername], @"\", rowItem[configurationstate], @"\", rowItem[configurationproductivestate], @"\", lastModifiedDate.ToString("yyyy-MM-dd_"), new TimeSpan(lastModifiedDate.Ticks - new DateTime(lastModifiedDate.Year, lastModifiedDate.Month, lastModifiedDate.Day).Ticks).TotalSeconds);
|
||||
if (!Directory.Exists(edaObjectDirectory))
|
||||
_ = Directory.CreateDirectory(edaObjectDirectory);
|
||||
edaObjectFile = string.Concat(edaObjectDirectory, @"\", rowItem[unitname], " ", rowItem[containername], " - ", replace, " - ", rowItem[configurationstate].ToString(), " ", rowItem[configurationproductivestate].ToString());
|
||||
xml = rowItem[containerconfiguration].ToString();
|
||||
if (string.IsNullOrEmpty(xml))
|
||||
continue;
|
||||
fileName = string.Concat(edaObjectFile.Replace(replace, "Raw"), ".xml");
|
||||
File.WriteAllText(fileName, xml);
|
||||
try
|
||||
{ File.SetCreationTime(fileName, lastModifiedDate); File.SetLastWriteTime(fileName, lastModifiedDate); }
|
||||
catch (Exception) { }
|
||||
common = new Common(ModuleInstanceTypeName.Pdsf, rowItem[unitname], rowItem[containername], rowItem[configurationstate], rowItem[configurationproductivestate]);
|
||||
configuration = ParseXML<PDSFConfiguration>(xml, throwExceptions: true);
|
||||
if (configuration is null)
|
||||
continue;
|
||||
// cSpell:enable
|
||||
common.Update(configuration);
|
||||
json = JsonSerializer.Serialize(configuration, configuration.GetType(), jsonSerializerOptions);
|
||||
if (common?.UnitName is null)
|
||||
continue;
|
||||
fileName = string.Concat(edaObjectFile.Replace(replace, "Partial"), ".csv");
|
||||
File.WriteAllText(fileName, common.ParametersAsCsv);
|
||||
try
|
||||
{ File.SetCreationTime(fileName, lastModifiedDate); File.SetLastWriteTime(fileName, lastModifiedDate); }
|
||||
catch (Exception) { }
|
||||
fileName = string.Concat(edaObjectFile.Replace(replace, "Partial"), ".json");
|
||||
File.WriteAllText(fileName, json);
|
||||
text = DCP.GetText(edaObjectFile, common, json);
|
||||
fileName = string.Concat(edaObjectFile.Replace(replace, "Partial"), ".txt");
|
||||
File.WriteAllText(fileName, text);
|
||||
try
|
||||
{ File.SetCreationTime(fileName, lastModifiedDate); File.SetLastWriteTime(fileName, lastModifiedDate); }
|
||||
catch (Exception) { }
|
||||
html = DCP.GetEdaObjectToHtml(edaObjectFile, common);
|
||||
fileName = string.Concat(edaObjectFile.Replace(replace, "Partial"), ".html");
|
||||
File.WriteAllText(fileName, html);
|
||||
try
|
||||
{ File.SetCreationTime(fileName, lastModifiedDate); File.SetLastWriteTime(fileName, lastModifiedDate); }
|
||||
catch (Exception) { }
|
||||
xml = DCP.GetEdaObjectToDMSGridFormat(edaObjectFile, common, useAlias: false);
|
||||
fileName = string.Concat(edaObjectFile.Replace(replace, "DMSGridFormat"), ".xml");
|
||||
File.WriteAllText(fileName, xml);
|
||||
try
|
||||
{ File.SetCreationTime(fileName, lastModifiedDate); File.SetLastWriteTime(fileName, lastModifiedDate); }
|
||||
catch (Exception) { }
|
||||
xml = DCP.GetEdaObjectToDMSGridFormat(edaObjectFile, common, useAlias: true);
|
||||
fileName = string.Concat(edaObjectFile.Replace(replace, "DMSGridFormat - Alias"), ".xml");
|
||||
File.WriteAllText(fileName, xml);
|
||||
try
|
||||
{ File.SetCreationTime(fileName, lastModifiedDate); File.SetLastWriteTime(fileName, lastModifiedDate); }
|
||||
catch (Exception) { }
|
||||
csv = DCP.GetEdaObjectToAPCParameter(edaObjectFile, common);
|
||||
fileName = string.Concat(edaObjectFile.Replace(replace, "APCParameter"), ".csv");
|
||||
File.WriteAllText(fileName, csv);
|
||||
try
|
||||
{ File.SetCreationTime(fileName, lastModifiedDate); File.SetLastWriteTime(fileName, lastModifiedDate); }
|
||||
catch (Exception) { }
|
||||
csv = DCP.GetEdaObjectToAPCRunKeyNumber(edaObjectFile, common);
|
||||
fileName = string.Concat(edaObjectFile.Replace(replace, "APCRunKeyNumber"), ".csv");
|
||||
File.WriteAllText(fileName, csv);
|
||||
try
|
||||
{ File.SetCreationTime(fileName, lastModifiedDate); File.SetLastWriteTime(fileName, lastModifiedDate); }
|
||||
catch (Exception) { }
|
||||
fileName = string.Concat(edaObjectFile.Replace(replace, "APC"), ".xlsx");
|
||||
if (File.Exists(emptyAPC) && !File.Exists(fileName))
|
||||
{
|
||||
File.Copy(emptyAPC, fileName);
|
||||
try
|
||||
{ File.SetCreationTime(fileName, lastModifiedDate); File.SetLastWriteTime(fileName, lastModifiedDate); }
|
||||
catch (Exception) { }
|
||||
}
|
||||
if (common.StoragePaths.Length == 0)
|
||||
continue;
|
||||
foreach (string? storagePath in common.StoragePaths)
|
||||
{
|
||||
if (string.IsNullOrEmpty(storagePath) || !Directory.Exists(Path.GetPathRoot(storagePath)))
|
||||
continue;
|
||||
if (Directory.Exists(storagePath))
|
||||
continue;
|
||||
_ = Directory.CreateDirectory(storagePath);
|
||||
}
|
||||
}
|
||||
try
|
||||
{ Directory.SetLastWriteTime(objectTypeDirectory, DateTime.Now); }
|
||||
catch (Exception) { }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void DataCollectionPlans(AppSettings appSettings, ILogger<Worker> logger, Calendar calendar, CancellationToken cancellationToken)
|
||||
{
|
||||
int fieldCount;
|
||||
object @object;
|
||||
string? @string;
|
||||
List<object> row;
|
||||
StringBuilder sql = new();
|
||||
string objectTypeDirectory;
|
||||
Array objectTypes = Enum.GetValues(typeof(ModuleInstanceTypeName));
|
||||
Dictionary<string, Dictionary<ModuleInstanceTypeName, List<List<object>>>> rows = [];
|
||||
string decrypted = RijndaelEncryption.Decrypt(appSettings.EDADatabaseConfiguration.Password, appSettings.Company);
|
||||
string connectionString = $"Data Source={appSettings.EDADatabaseConfiguration.TNS}; User Id={appSettings.EDADatabaseConfiguration.UserName}; Password={decrypted};";
|
||||
rows.Add(appSettings.EDADatabaseConfiguration.Name, []);
|
||||
foreach (ModuleInstanceTypeName objectType in objectTypes)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
break;
|
||||
if (string.IsNullOrEmpty(_EDADataCollectionPlansLastRun))
|
||||
{
|
||||
objectTypeDirectory = Path.Combine(appSettings.EDADatabaseConfiguration.FileShare, appSettings.EDADatabaseConfiguration.Name, objectType.ToString());
|
||||
if (!Directory.Exists(objectTypeDirectory))
|
||||
_ = Directory.CreateDirectory(objectTypeDirectory);
|
||||
else
|
||||
_EDADataCollectionPlansLastRun = new DirectoryInfo(objectTypeDirectory).LastWriteTime.ToString(appSettings.EDADatabaseConfiguration.CSharpDateTimeFormat);
|
||||
}
|
||||
if (!rows[appSettings.EDADatabaseConfiguration.Name].ContainsKey(objectType))
|
||||
rows[appSettings.EDADatabaseConfiguration.Name].Add(objectType, []);
|
||||
using (Oracle.ManagedDataAccess.Client.OracleConnection oracleConnection = new(connectionString))
|
||||
{
|
||||
_ = sql.Clear();
|
||||
oracleConnection.Open(); // cSpell:disable
|
||||
_ = sql.Append(" select v.moduleinstancetypename, v.unitname, ").
|
||||
Append(" v.modulename, v.containername, v.configurationstate, ").
|
||||
Append(" v.configurationproductivestate, v.containermodifiername, ").
|
||||
Append(" v.containermodifieddate, v.containerconfiguration, v.configurationmodifieddate ").
|
||||
Append(" from veditconfiguration v ").
|
||||
Append(" where v.moduleinstancetypename = '").Append(objectType.ToString()).Append("' ");
|
||||
// Append(" and v.containerversion in ('4.80', '4.111') ");
|
||||
if (!string.IsNullOrEmpty(_EDADataCollectionPlansLastRun))
|
||||
_ = sql.Append(" and greatest(v.containermodifieddate, v.configurationmodifieddate) >= to_date('").Append(_EDADataCollectionPlansLastRun).Append("', '").Append(appSettings.EDADatabaseConfiguration.OracleDateTimeFormat).Append("') ");
|
||||
logger.LogDebug(sql.ToString());
|
||||
using Oracle.ManagedDataAccess.Client.OracleCommand oracleCommand = new(sql.ToString(), oracleConnection); // cSpell:enable
|
||||
using Oracle.ManagedDataAccess.Client.OracleDataReader oracleDataReader = oracleCommand.ExecuteReader();
|
||||
fieldCount = oracleDataReader.FieldCount;
|
||||
while (oracleDataReader.Read())
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
break;
|
||||
row = [];
|
||||
for (int c = 0; c < fieldCount; c++)
|
||||
{
|
||||
@object = oracleDataReader.GetValue(c);
|
||||
row.Add(@object);
|
||||
if (@object is null)
|
||||
continue;
|
||||
@string = @object.ToString();
|
||||
// if (@string.Length < 128)
|
||||
// _Logger.LogDebug(@string);
|
||||
}
|
||||
rows[appSettings.EDADatabaseConfiguration.Name][objectType].Add(row);
|
||||
}
|
||||
};
|
||||
}
|
||||
if (rows.Count != 0)
|
||||
EvaluateRows(appSettings.EDADatabaseConfiguration.FileShare, rows, cancellationToken);
|
||||
}
|
||||
|
||||
internal static bool SaveDataCollectionPlans(AppSettings appSettings, ILogger<Worker> logger, CancellationToken cancellationToken)
|
||||
{
|
||||
_Calendar ??= new CultureInfo("en-US").Calendar;
|
||||
DataCollectionPlans(appSettings, logger, _Calendar, cancellationToken);
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
27
Helpers/HelperInfinityQS.cs
Normal file
27
Helpers/HelperInfinityQS.cs
Normal file
@ -0,0 +1,27 @@
|
||||
using File_Watcher.Models;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace File_Watcher.Helpers;
|
||||
|
||||
internal static partial class HelperInfinityQS
|
||||
{
|
||||
|
||||
internal static bool RunMI(AppSettings appSettings, ILogger<Worker> logger)
|
||||
{
|
||||
#pragma warning disable CA1416
|
||||
logger.LogInformation(appSettings.Company);
|
||||
ProcessStartInfo processStartInfo = new("iispcmi.exe")
|
||||
{
|
||||
Domain = "Infineon",
|
||||
UseShellExecute = false,
|
||||
UserName = "ecfisysadmin",
|
||||
PasswordInClearText = "j(1(P%xB=g}3w9db",
|
||||
WorkingDirectory = "C:/Program Files (x86)/InfinityQS International/ProFicient/Applications"
|
||||
};
|
||||
Process process = Process.Start(processStartInfo) ?? throw new NullReferenceException(nameof(Process));
|
||||
process.WaitForExit();
|
||||
#pragma warning restore CA1416
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
@ -62,7 +62,7 @@ internal static partial class HelperMetrologyFiles
|
||||
}
|
||||
}
|
||||
|
||||
private static void Delete(MetrologyConfiguration metrologyConfiguration, ILogger<Worker> logger, Calendar calendar)
|
||||
private static void Delete(MetrologyConfiguration metrologyConfiguration, ILogger<Worker> logger)
|
||||
{
|
||||
string directory;
|
||||
DateTime dateTime;
|
||||
@ -102,7 +102,7 @@ internal static partial class HelperMetrologyFiles
|
||||
CultureInfo cultureInfo = new("en-US");
|
||||
Calendar calendar = cultureInfo.Calendar;
|
||||
Sort(appSettings.MetrologyConfiguration, logger, calendar);
|
||||
Delete(appSettings.MetrologyConfiguration, logger, calendar);
|
||||
Delete(appSettings.MetrologyConfiguration, logger);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
281
Helpers/HelperSerial.cs
Normal file
281
Helpers/HelperSerial.cs
Normal file
@ -0,0 +1,281 @@
|
||||
using File_Watcher.Models;
|
||||
using System.Diagnostics;
|
||||
using System.IO.Ports;
|
||||
|
||||
namespace File_Watcher.Helpers;
|
||||
|
||||
internal static partial class HelperSerial
|
||||
{
|
||||
|
||||
private record Record(List<byte> Data,
|
||||
string Destination,
|
||||
ILogger<Worker> Logger,
|
||||
CancellationToken CancellationToken);
|
||||
|
||||
private static Record? _Record;
|
||||
private static SerialPort? _SerialPort;
|
||||
|
||||
private static void PCLToPDF(string fullPath)
|
||||
{
|
||||
string ghostPCLFileName = Path.Combine(AppContext.BaseDirectory, "gpcl6win64.exe");
|
||||
if (!File.Exists(ghostPCLFileName))
|
||||
throw new Exception("Ghost PCL FileName doesn't Exist!");
|
||||
string lincPDFCFileName = Path.Combine(AppContext.BaseDirectory, "LincPDFC.exe");
|
||||
if (!File.Exists(lincPDFCFileName))
|
||||
throw new Exception("Linc PDFC FileName doesn't Exist!");
|
||||
string pdfFile;
|
||||
string fileName;
|
||||
string arguments;
|
||||
for (int i = 1; i < 3; i++)
|
||||
{
|
||||
if (i == 1)
|
||||
{
|
||||
fileName = ghostPCLFileName;
|
||||
pdfFile = $"{fullPath}-ghost.pdf";
|
||||
arguments = $"-dSAFER -dBATCH -dNOPAUSE -sOutputFile=\"{pdfFile}\" -sDEVICE=pdfwrite \"{fullPath}\"";
|
||||
// arguments = $"-dSAFER -dBATCH -dNOPAUSE -dFIXEDMEDIA -dFitPage -dAutoRotatePages=/All -dDEVICEWIDTHPOINTS=792 -dDEVICEHEIGHTPOINTS=612 -sOutputFile=\"{pdfFile}\" -sDEVICE=pdfwrite \"{fullPath}\"";
|
||||
}
|
||||
else if (i == 2)
|
||||
{
|
||||
fileName = lincPDFCFileName;
|
||||
pdfFile = $"{fullPath}-linc.pdf";
|
||||
arguments = $"-i \"{fullPath}\" -o \"{pdfFile}\"";
|
||||
}
|
||||
else
|
||||
throw new Exception();
|
||||
Process process = Process.Start(fileName, arguments);
|
||||
long breakAfter = DateTime.Now.AddSeconds(30).Ticks;
|
||||
for (short j = 0; j < short.MaxValue; j++)
|
||||
{
|
||||
if (process.HasExited || process.WaitForExit(500) || DateTime.Now.Ticks > breakAfter)
|
||||
break;
|
||||
}
|
||||
if (!File.Exists(pdfFile))
|
||||
throw new Exception("PDF file wasn't created");
|
||||
}
|
||||
}
|
||||
|
||||
private static List<byte> GetBytes(List<byte> bytes)
|
||||
{
|
||||
List<byte> results = [];
|
||||
foreach (byte @byte in bytes)
|
||||
results.Add(@byte);
|
||||
return results;
|
||||
}
|
||||
|
||||
private static void SerialPortWrite(string destination, DateTime dateTime, List<byte> bytes, string v, bool convert)
|
||||
{
|
||||
if (_SerialPort is null)
|
||||
throw new NullReferenceException(nameof(_SerialPort));
|
||||
string directory = Path.Combine(destination, _SerialPort.PortName);
|
||||
if (!Directory.Exists(destination))
|
||||
_ = Directory.CreateDirectory(destination);
|
||||
string fileName = Path.Combine(directory, $"{_SerialPort.PortName}-{v}-{dateTime:yyyyMMddHHmmssfff}.pcl");
|
||||
File.WriteAllBytes(fileName, bytes.ToArray());
|
||||
if (convert)
|
||||
PCLToPDF(fileName);
|
||||
}
|
||||
|
||||
private static int? SearchBytes(byte[] haystack, byte[] needle)
|
||||
{
|
||||
int? result = null;
|
||||
int k;
|
||||
int len = needle.Length;
|
||||
int limit = haystack.Length - len;
|
||||
for (int i = 0; i <= limit; i++)
|
||||
{
|
||||
k = 0;
|
||||
for (; k < len; k++)
|
||||
{
|
||||
if (needle[k] != haystack[i + k])
|
||||
break;
|
||||
}
|
||||
if (k == len)
|
||||
{
|
||||
result = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static bool Contains()
|
||||
{
|
||||
if (_Record is null)
|
||||
throw new NullReferenceException(nameof(_Record));
|
||||
bool result;
|
||||
// char endOfLine = '\u001b';
|
||||
// lock (_Record)
|
||||
// result = _Record.Data.Contains(Convert.ToByte(endOfLine));
|
||||
// if (!result)
|
||||
// {
|
||||
// }
|
||||
int? index = null;
|
||||
// byte[] pageDelimiter =
|
||||
// {
|
||||
// Convert.ToByte(27),
|
||||
// Convert.ToByte(69)
|
||||
// };
|
||||
lock (_Record)
|
||||
{
|
||||
byte[] bytes = _Record.Data.ToArray();
|
||||
// index = Array.IndexOf(bytes, pageDelimiter);
|
||||
// if (index == -1)
|
||||
// {
|
||||
// }
|
||||
byte[] documentDelimiter =
|
||||
[
|
||||
Convert.ToByte(32),
|
||||
Convert.ToByte(83),
|
||||
Convert.ToByte(116),
|
||||
Convert.ToByte(97),
|
||||
Convert.ToByte(116),
|
||||
Convert.ToByte(105),
|
||||
Convert.ToByte(115),
|
||||
Convert.ToByte(116),
|
||||
Convert.ToByte(105),
|
||||
Convert.ToByte(99),
|
||||
Convert.ToByte(115),
|
||||
Convert.ToByte(58)
|
||||
];
|
||||
index = SearchBytes(bytes, documentDelimiter);
|
||||
}
|
||||
result = index is not null;
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void PinChanged(object sender, SerialPinChangedEventArgs serialPinChangedEventArgs)
|
||||
{
|
||||
if (_Record is null)
|
||||
throw new NullReferenceException(nameof(_Record));
|
||||
try
|
||||
{ _Record.Logger.LogDebug($"EventType = {serialPinChangedEventArgs.EventType}"); }
|
||||
catch (Exception exception) { _Record.Logger.LogError(exception, "Error"); }
|
||||
}
|
||||
|
||||
private static void DataReceived(object? sender, SerialDataReceivedEventArgs dataReceivedEventArgs)
|
||||
{
|
||||
if (_Record is null)
|
||||
throw new NullReferenceException(nameof(_Record));
|
||||
if (_SerialPort is null)
|
||||
throw new NullReferenceException(nameof(_SerialPort));
|
||||
DateTime dateTime = DateTime.Now;
|
||||
try
|
||||
{
|
||||
_Record.Logger.LogDebug($"EventType = {dataReceivedEventArgs.EventType}");
|
||||
List<byte>? bytes;
|
||||
lock (_Record)
|
||||
{
|
||||
byte[] buffer = new byte[_SerialPort.BytesToRead];
|
||||
int count = _SerialPort.Read(buffer, 0, buffer.Length);
|
||||
if (count == 0)
|
||||
bytes = null;
|
||||
else
|
||||
{
|
||||
_Record.Data.AddRange(buffer.Take(count));
|
||||
bytes = dataReceivedEventArgs.EventType != SerialData.Eof ? null : GetBytes(_Record.Data);
|
||||
}
|
||||
}
|
||||
if (bytes is not null)
|
||||
SerialPortWrite(_Record.Destination, dateTime, bytes, nameof(SerialData.Eof), convert: false);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
string fileName = Path.Combine(_Record.Destination, _SerialPort.PortName, $"{dateTime:yyyyMMddHHmmssfff}.err");
|
||||
File.WriteAllLines(fileName, [exception.Message, Environment.NewLine, Environment.NewLine, string.Concat(exception.StackTrace)]);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ErrorReceived(object sender, SerialErrorReceivedEventArgs serialErrorReceivedEventArgs)
|
||||
{
|
||||
if (_Record is null)
|
||||
throw new NullReferenceException(nameof(_Record));
|
||||
try
|
||||
{ _Record.Logger.LogDebug($"EventType = {serialErrorReceivedEventArgs.EventType}"); }
|
||||
catch (Exception exception) { _Record.Logger.LogError(exception, "Error"); }
|
||||
}
|
||||
|
||||
private static void SerialPortWriteConditionally(SerialConfiguration serialConfiguration, ILogger<Worker> logger)
|
||||
{
|
||||
if (_Record is null)
|
||||
throw new NullReferenceException(nameof(_Record));
|
||||
DateTime dateTime = DateTime.Now;
|
||||
logger.LogDebug($"Worker:Process:SerialPort running at: {dateTime} serial port {serialConfiguration.PortName} status with Length = {_Record.Data.Count}.");
|
||||
bool contains = Contains();
|
||||
if (contains)
|
||||
{
|
||||
List<byte> bytes;
|
||||
if (_Record is null)
|
||||
throw new NullReferenceException(nameof(_Record));
|
||||
lock (_Record)
|
||||
{
|
||||
bytes = GetBytes(_Record.Data);
|
||||
_Record.Data.Clear();
|
||||
}
|
||||
SerialPortWrite(_Record.Destination, dateTime, bytes, nameof(Contains), convert: true);
|
||||
}
|
||||
}
|
||||
|
||||
private static void SerialPortClose()
|
||||
{
|
||||
if (_SerialPort is not null)
|
||||
{
|
||||
if (_Record is null)
|
||||
throw new NullReferenceException(nameof(_Record));
|
||||
lock (_Record)
|
||||
{
|
||||
_SerialPort.Close();
|
||||
int length = _Record is null ? 0 : _Record.Data.Count;
|
||||
if (_Record is null)
|
||||
throw new NullReferenceException(nameof(_Record));
|
||||
_Record.Logger.LogDebug($"Serial port {_SerialPort.PortName} closed with Length = {length}.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static bool ReadWrite(AppSettings appSettings, ILogger<Worker> logger, CancellationToken cancellationToken)
|
||||
{
|
||||
_Record ??= new([], appSettings.SerialConfiguration.Destination, logger, cancellationToken);
|
||||
if (_SerialPort is null)
|
||||
{
|
||||
string ghostPCLFileName = Path.Combine(AppContext.BaseDirectory, appSettings.SerialConfiguration.GhostPCLFileName);
|
||||
if (!File.Exists(ghostPCLFileName))
|
||||
throw new Exception("Ghost PCL FileName doesn't Exist!");
|
||||
string lincPDFCFileName = Path.Combine(AppContext.BaseDirectory, appSettings.SerialConfiguration.LincPDFCFileName);
|
||||
if (!File.Exists(lincPDFCFileName))
|
||||
throw new Exception("Linc PDFC FileName doesn't Exist!");
|
||||
_SerialPort = new SerialPort
|
||||
{
|
||||
PortName = appSettings.SerialConfiguration.PortName,
|
||||
// BaudRate = 9600,
|
||||
BaudRate = 115200,
|
||||
DataBits = 8,
|
||||
Parity = Parity.None,
|
||||
StopBits = StopBits.One,
|
||||
// Handshake = Handshake.None,
|
||||
Handshake = Handshake.RequestToSend,
|
||||
// DtrEnable = true,
|
||||
// RtsEnable = true,
|
||||
ReadTimeout = 5000
|
||||
};
|
||||
string[] portNames = SerialPort.GetPortNames();
|
||||
string[] matchPortNames = (from l in portNames where l == appSettings.SerialConfiguration.PortName select l).ToArray();
|
||||
if (matchPortNames.Length == 0)
|
||||
throw new Exception($"Didn't find matching COM port! {string.Join(Environment.NewLine, portNames)}");
|
||||
if (matchPortNames.Length != 1)
|
||||
throw new Exception($"Matching count is more than one! {string.Join(Environment.NewLine, portNames)}");
|
||||
_SerialPort.Open();
|
||||
_SerialPort.DiscardInBuffer();
|
||||
_SerialPort.DiscardOutBuffer();
|
||||
logger.LogDebug("Waiting for data.");
|
||||
_SerialPort.PinChanged += PinChanged;
|
||||
_SerialPort.DataReceived += DataReceived;
|
||||
_SerialPort.ErrorReceived += ErrorReceived;
|
||||
}
|
||||
SerialPortWriteConditionally(appSettings.SerialConfiguration, logger);
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
SerialPortClose();
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
157
Helpers/HelperTCP.cs
Normal file
157
Helpers/HelperTCP.cs
Normal file
@ -0,0 +1,157 @@
|
||||
using File_Watcher.Models;
|
||||
using System.Diagnostics;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace File_Watcher.Helpers;
|
||||
|
||||
internal static partial class HelperTCP
|
||||
{
|
||||
|
||||
private record Record(BinaryReader BinaryReader,
|
||||
BinaryWriter BinaryWriter,
|
||||
NetworkStream NetworkStream);
|
||||
|
||||
private static long _LastWrite;
|
||||
private static Record? _Record;
|
||||
private static TcpListener? _TcpListener;
|
||||
private static readonly object _Lock = new();
|
||||
|
||||
private static void OnAccept(IAsyncResult asyncResult)
|
||||
{
|
||||
if (_TcpListener is null)
|
||||
throw new NullReferenceException(nameof(_TcpListener));
|
||||
lock (_Lock)
|
||||
{
|
||||
TcpClient tcpClient = _TcpListener.EndAcceptTcpClient(asyncResult);
|
||||
NetworkStream networkStream = tcpClient.GetStream();
|
||||
_Record = new(new(networkStream), new(networkStream), networkStream);
|
||||
}
|
||||
}
|
||||
|
||||
private static string ConvertSourceFileToPdf(string ghostPCLFileName, string reportFullPath)
|
||||
{
|
||||
string result = Path.ChangeExtension(reportFullPath, ".pdf");
|
||||
if (!File.Exists(result))
|
||||
{
|
||||
//string arguments = string.Concat("-i \"", sourceFile, "\" -o \"", result, "\"");
|
||||
string arguments = string.Concat("-dSAFER -dBATCH -dNOPAUSE -sOutputFile=\"", result, "\" -sDEVICE=pdfwrite \"", reportFullPath, "\"");
|
||||
//Process process = Process.Start(configData.LincPDFCFileName, arguments);
|
||||
Process process = Process.Start(ghostPCLFileName, arguments);
|
||||
_ = process.WaitForExit(30000);
|
||||
if (!File.Exists(result))
|
||||
throw new Exception("PDF file wasn't created");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void BeginAcceptTcpClient()
|
||||
{
|
||||
if (_TcpListener is null)
|
||||
throw new NullReferenceException(nameof(_TcpListener));
|
||||
_ = _TcpListener.BeginAcceptTcpClient(OnAccept, null);
|
||||
}
|
||||
|
||||
private static void ReadFiles(TransmissionControlProtocolConfiguration transmissionControlProtocolConfiguration)
|
||||
{
|
||||
List<byte> bytes = [];
|
||||
// byte nullByte = Convert.ToByte('\0');
|
||||
string[] files = Directory.GetFiles(transmissionControlProtocolConfiguration.Destination, $"{transmissionControlProtocolConfiguration.IPAddress}-*.raw", SearchOption.TopDirectoryOnly);
|
||||
foreach (string file in files)
|
||||
{
|
||||
foreach (byte @byte in File.ReadAllBytes(file))
|
||||
{
|
||||
// if (@byte.Equals(nullByte))
|
||||
// continue;
|
||||
bytes.Add(@byte);
|
||||
}
|
||||
}
|
||||
if (bytes.Count > 0)
|
||||
{
|
||||
string bytesFile = Path.Combine(transmissionControlProtocolConfiguration.Destination, $"{transmissionControlProtocolConfiguration.IPAddress}-{DateTime.Now.Ticks}.pcl");
|
||||
File.WriteAllBytes(bytesFile, bytes.ToArray());
|
||||
string ghostPCLFileName = Path.Combine(AppContext.BaseDirectory, "gpcl6win64.exe");
|
||||
if (!File.Exists(ghostPCLFileName))
|
||||
throw new Exception("Ghost PCL FileName doesn't Exist!");
|
||||
string sourceFileNamePdf = ConvertSourceFileToPdf(ghostPCLFileName, bytesFile);
|
||||
if (string.IsNullOrEmpty(sourceFileNamePdf))
|
||||
throw new Exception("Ghost PCL FileName doesn't Exist!");
|
||||
}
|
||||
}
|
||||
|
||||
private static void CreateClient(AppSettings appSettings, ILogger<Worker> logger)
|
||||
{
|
||||
logger.LogDebug(appSettings.TransmissionControlProtocolConfiguration.IPAddress);
|
||||
TcpClient tcpClient = new(appSettings.TransmissionControlProtocolConfiguration.IPAddress, appSettings.TransmissionControlProtocolConfiguration.Port);
|
||||
NetworkStream networkStream = tcpClient.GetStream();
|
||||
_Record = new(new(networkStream), new(networkStream), networkStream);
|
||||
}
|
||||
|
||||
private static void CreateTcpListener(AppSettings appSettings)
|
||||
{
|
||||
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
|
||||
_TcpListener = new(ipAddress, appSettings.TransmissionControlProtocolConfiguration.Port);
|
||||
_TcpListener.Start();
|
||||
BeginAcceptTcpClient();
|
||||
}
|
||||
|
||||
private static void NetworkStreamCanRead(TransmissionControlProtocolConfiguration transmissionControlProtocolConfiguration, NetworkStream networkStream)
|
||||
{
|
||||
List<byte> results = [];
|
||||
byte[] bytes = new byte[1024];
|
||||
string directory = Path.Combine(transmissionControlProtocolConfiguration.Destination, transmissionControlProtocolConfiguration.IPAddress);
|
||||
if (!Directory.Exists(directory))
|
||||
_ = Directory.CreateDirectory(directory);
|
||||
do
|
||||
{
|
||||
int count = networkStream.Read(bytes, 0, bytes.Length);
|
||||
if (count > 0)
|
||||
results.AddRange(bytes.Take(count));
|
||||
}
|
||||
while (networkStream.DataAvailable);
|
||||
if (results.Count > 0)
|
||||
File.WriteAllBytes(string.Concat(directory, $"-{DateTime.Now.Ticks}{directory[^1]}.raw"), results.ToArray());
|
||||
}
|
||||
|
||||
internal static bool ReadWrite(AppSettings appSettings, ILogger<Worker> logger)
|
||||
{
|
||||
lock (_Lock)
|
||||
{
|
||||
if (!appSettings.TransmissionControlProtocolConfiguration.Server)
|
||||
ReadFiles(appSettings.TransmissionControlProtocolConfiguration);
|
||||
if (!appSettings.TransmissionControlProtocolConfiguration.Server && _Record is not null)
|
||||
{
|
||||
TimeSpan timeSpan = new(DateTime.Now.Ticks - _LastWrite);
|
||||
if (_LastWrite == 0 || timeSpan.TotalMinutes > 1)
|
||||
{
|
||||
try
|
||||
{
|
||||
_Record.NetworkStream.WriteByte(Convert.ToByte('\0'));
|
||||
_LastWrite = DateTime.Now.Ticks;
|
||||
}
|
||||
catch (Exception)
|
||||
{ }
|
||||
}
|
||||
}
|
||||
if (!appSettings.TransmissionControlProtocolConfiguration.Server && (_Record?.NetworkStream is null || !_Record.NetworkStream.Socket.Connected))
|
||||
CreateClient(appSettings, logger);
|
||||
else if (appSettings.TransmissionControlProtocolConfiguration.Server && _TcpListener is null)
|
||||
CreateTcpListener(appSettings);
|
||||
if (_Record?.NetworkStream is not null && _Record.NetworkStream.CanRead && _Record.NetworkStream.DataAvailable)
|
||||
NetworkStreamCanRead(appSettings.TransmissionControlProtocolConfiguration, _Record.NetworkStream);
|
||||
if (appSettings.TransmissionControlProtocolConfiguration.Server && _TcpListener is not null && _Record?.NetworkStream is not null && _Record.NetworkStream.CanWrite)
|
||||
{
|
||||
try
|
||||
{
|
||||
_Record.BinaryWriter.Write("json");
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
BeginAcceptTcpClient();
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
Reference in New Issue
Block a user