using Newtonsoft.Json;
using YamlDotNet.Serialization.NamingConventions;
using YamlDotNet.Serialization;
using static ConfMan.IOB.Core.EnumConf;
using NLog;
//
// This is here so CodeMaid doesn't reorganize this document
//
namespace ConfMan.IOB.Core
{
///
/// Albero configurazione globale IOB
///
[Serializable]
public class IobConfTree
{
///
/// Init classe configurazione
///
public IobConfTree()
{ }
///
/// Restituisce un oggetto di conf leggendo INI ed effettuando conversione
///
///
///
public static IobConfTree LoadFromINI(string iniFilePath)
{
IobConfTree newConfObj = new IobConfTree();
try
{
// leggo file INI
IniFile fIni = new IniFile(iniFilePath);
string codIob= Path.GetFileNameWithoutExtension(iniFilePath);
// effettuo conversione...
// Dati generali (vendor, modello...)
newConfObj.CodIOB = fIni.ReadString("IOB", "IOB_NAME", codIob);
newConfObj.Vendor = fIni.ReadString("MACHINE", "VENDOR", "STEAMWARE");
newConfObj.Model = fIni.ReadString("MACHINE", "MODEL", "NONE");
newConfObj.ConfFileName = Path.GetFileName(iniFilePath);
// tipo adapter// verifico tipo adapter
try
{
newConfObj.IobType = (AdapterType)Enum.Parse(typeof(AdapterType), fIni.ReadString("IOB", "CNCTYPE", "ND"));
}
catch (Exception exc)
{
newConfObj.IobType = AdapterType.ND;
string rawVal = fIni.ReadString("IOB", "CNCTYPE", "DEMO");
//newConfObj.lgError($"Eccezione in conversione tipo adapter: richiesto {rawVal} | tipo non codificato...{Environment.NewLine}{exc}");
}
//newConfObj.GeneralCom = (ComType)Enum.Parse(typeof(ComType), fIni.ReadString("IOB", "CNCFAMILY", "ND"));
// recupero NUOVI dati TAGS
newConfObj.GeneralCom = (ComType)Enum.Parse(typeof(ComType), fIni.ReadString("TAGS", "ComType", "ND"));
newConfObj.Customer = fIni.ReadString("TAGS", "Customer", "ND");
newConfObj.HostData.OS = fIni.ReadString("TAGS", "HostOS", "WIN");
newConfObj.HostData.HostName = fIni.ReadString("TAGS", "HostName", "localhost");
newConfObj.HostData.HostAddr = fIni.ReadString("TAGS", "HostAddr", "127.0.0.1");
// CNC
newConfObj.CncData.pingMsTimeout = fIni.ReadInteger("IOB", "PING_MS_TIMEOUT", 500);
newConfObj.CncData.IpAddr = fIni.ReadString("CNC", "IP", "::1");
newConfObj.CncData.Port = fIni.ReadString("CNC", "PORT", "0");
newConfObj.CncData.CpuType = fIni.ReadString("CNC", "CPUTYPE", "");
newConfObj.CncData.Rack = (short)fIni.ReadInteger("CNC", "RACK", 0);
newConfObj.CncData.Slot = (short)fIni.ReadInteger("CNC", "SLOT", 0);
// BLINK
newConfObj.InputDataProc.BlinkMaxCounter = Convert.ToInt32(fIni.ReadString("BLINK", "MAX_COUNTER_BLINK", "1"));
newConfObj.InputDataProc.BlinkFilterMask = Convert.ToInt32(fIni.ReadString("BLINK", "BLINK_FILT", "0"));
newConfObj.TempoCiclo.MaxDelayFactor = Convert.ToDouble(fIni.ReadString("OPTPAR", "TC_MAX_TC_FACTOR", "1.2").Replace(".", ","));
newConfObj.TempoCiclo.Lambda = Convert.ToDouble(fIni.ReadString("OPTPAR", "TC_LAMBDA", "0.5").Replace(".", ","));
newConfObj.TempoCiclo.MaxIncrPz = Convert.ToDouble(fIni.ReadString("OPTPAR", "TC_MAX_INCR", "5").Replace(".", ","));
// Server
string MpIp=fIni.ReadString("SERVER", "MPIP", "::1");
if (!string.IsNullOrEmpty(MpIp))
{
newConfObj.ServerMES.Transport = MpIp.StartsWith("https://") ? "https" : "http";
newConfObj.ServerMES.IpAddr = MpIp.Replace($"{newConfObj.ServerMES.Transport}://", ""); // tolgo http/https...
}
//newConfObj.ServerMES.Commands.Alive
// Altro (versione, ...)
newConfObj.ReleaseVers = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
newConfObj.IobManConf.MinDeltaSec = fIni.ReadInteger("IOB", "MinDeltaSec", 6);
// OptPar
Dictionary optParRead = new Dictionary();
string[] optParRows = fIni.ReadSection("OPTPAR");
if (optParRows.Length > 0)
{
try
{
string[] kvp;
foreach (var item in optParRows)
{
kvp = item.Split('=');
optParRead.Add(kvp[0], kvp[1]);
}
//newConfObj.lgDebug($"Caricati {optParRead.Count} parametri opzionali da OPTPAR");
}
catch (Exception exc)
{
//newConfObj.lgError(string.Format("EXCEPTION in fase di lettura OPTPAR: {0}{1}", Environment.NewLine, exc));
}
}
// riordino alfabeticamente
optParRead = optParRead.OrderBy(x => x.Key).ToDictionary(x => x.Key, x => x.Value);
newConfObj.OptPar = optParRead;
}
catch
{ }
return newConfObj;
}
#region Logging
///
/// oggetto logging
///
protected Logger Log;// = LogManager.GetCurrentClassLogger();
///
/// Effettua logging DEBUG corretto impostanto anche la variabile IOB prima di scrivere...
///
///
protected void lgDebug(string txt2log)
{
Log.Factory.Configuration.Variables["codIOB"] = this.CodIOB;
Log.Debug(txt2log);
}
///
/// Effettua logging ERROR corretto impostanto anche la variabile IOB prima di scrivere...
///
///
protected void lgError(string txt2log)
{
if (!string.IsNullOrEmpty(txt2log))
{
Log.Factory.Configuration.Variables["codIOB"] = this.CodIOB;
Log.Error(txt2log);
}
}
///
/// Effettua logging INFO corretto impostanto anche la variabile IOB prima di scrivere...
///
///
protected void lgInfo(string txt2log)
{
Log.Factory.Configuration.Variables["codIOB"] = this.CodIOB;
Log.Info(txt2log);
}
///
/// Effettua logging TRACE corretto impostanto anche la variabile IOB prima di scrivere...
///
///
protected void lgTrace(string txt2log)
{
Log.Factory.Configuration.Variables["codIOB"] = this.CodIOB;
Log.Trace(txt2log);
}
#endregion
///
/// Codice Cliente/Installazione
///
public string Customer { get; set; } = "SteamWare";
///
/// Codice univoco IOB
///
public string CodIOB { get; set; } = "ND";
///
/// Dati relaviti all'Host corrente
///
public HostInfo HostData { get; set; } = new HostInfo();
///
/// Costruttore
///
public string Vendor { get; set; } = "ACME";
///
/// Codice modello
///
public string Model { get; set; } = "NONE";
///
/// Nome file di configurazione
///
public string ConfFileName { get; set; } = "";
///
/// Tipologia generale dell'adapter
///
public ComType GeneralCom { get; set; } = ComType.ND;
///
/// Tipo Adapter specifico (implementazione)
///
public AdapterType IobType { get; set; } = AdapterType.ND;
///
/// Setup server MP da chiamare
///
public ServerMapo ServerMES { get; set; } = new ServerMapo();
///
/// Setup info verso IOB-MAN
///
public RedisPub IobManConf { get; set; } = new RedisPub();
///
/// Dati configurazione CNC
///
public CncConf CncData { get; set; } = new CncConf();
///
/// Setup processing dati in ingresso (es: blink segnali)
///
public InputSignalProcess InputDataProc { get; set; } = new InputSignalProcess();
///
/// Dati relativi ai parametri gestione tempo ciclo
///
public TCData TempoCiclo { get; set; } = new TCData();
///
/// Dizionario dei parametri opzionali
///
public Dictionary OptPar { get; set; } = new Dictionary();
///
/// Versione software IOB
///
public string ReleaseVers { get; set; } = "0.0.0.0";
#region Metodi Serializzazione
///
/// Restituisce conf serializzata in formato JSON
///
///
///
public string GetJson()
{
string rawdata = JsonConvert.SerializeObject(this, Formatting.Indented);
return rawdata;
}
///
/// Restituisce conf serializzata in formato YAML
///
///
///
public string GetYaml()
{
var serializer = new SerializerBuilder()
.WithNamingConvention(CamelCaseNamingConvention.Instance)
.Build();
var rawdata = serializer.Serialize(this);
return rawdata;
}
#endregion
#region Metodi Load/Save
///
/// Scrive conf serializzata in formato JSON
///
///
///
public bool SaveJson(string filePath)
{
bool answ = false;
try
{
string rawdata = GetJson();
File.WriteAllText(filePath, rawdata);
answ = true;
}
catch
{ }
return answ;
}
///
/// Scrive conf serializzata in formato YAML
///
///
///
public bool SaveYaml(string filePath)
{
bool answ = false;
try
{
var rawdata = GetYaml();
File.WriteAllText(filePath, rawdata);
answ = true;
}
catch
{ }
return answ;
}
#endregion
}
}