using Newtonsoft.Json; using YamlDotNet.Serialization.NamingConventions; using YamlDotNet.Serialization; using static IobConf.Core.EnumConf; using NLog; using System.Runtime.CompilerServices; // // This is here so CodeMaid doesn't reorganize this document // namespace IobConf.Core { /// /// Albero configurazione globale IOB /// [Serializable] public class IobConfTree { /// /// Init classe configurazione /// public IobConfTree() { Log = LogManager.GetCurrentClassLogger(); } /// /// Init classe configurazione da file /// public IobConfTree(string confFilePath) { Log = LogManager.GetCurrentClassLogger(); if (File.Exists(confFilePath)) { IobConfTree newConfObj = new IobConfTree(); // verifico TIPO file... string fileExt = Path.GetExtension(confFilePath); string fileName = Path.GetFileName(confFilePath); string rawData = File.ReadAllText(confFilePath); if (!string.IsNullOrEmpty(rawData)) { // leggo in base al tipo... switch (fileExt) { case "yaml": case "yml": var deserializer = new DeserializerBuilder() .WithNamingConvention(CamelCaseNamingConvention.Instance) .Build(); try { newConfObj = deserializer.Deserialize(rawData); } catch (Exception exc) { //lgError($"Eccezione in LoadFromYaml{Environment.NewLine}{exc}"); } break; default: break; } if (newConfObj != null) { // ora copio in oggetto corrente... CncData = newConfObj.CncData; CodIOB = newConfObj.CodIOB; ConfFileName = fileName; Customer = newConfObj.Customer; GeneralCom = newConfObj.GeneralCom; InputDataProc = newConfObj.InputDataProc; IobManConf = newConfObj.IobManConf; IobType = newConfObj.IobType; Model = newConfObj.Model; OptPar = newConfObj.OptPar; ReleaseVers = newConfObj.ReleaseVers; ServerMES = newConfObj.ServerMES; TempoCiclo = newConfObj.TempoCiclo; Vendor = newConfObj.Vendor; } } } } /// /// 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 = (ComLayer)Enum.Parse(typeof(ComLayer), fIni.ReadString("IOB", "CNCFAMILY", "ND")); // 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... } // Altro (versione, ...) newConfObj.ReleaseVers = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Version}"; 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; } /// /// Restituisce un oggetto di conf deserializzando lo Yaml relativo /// /// /// public static IobConfTree LoadFromYaml(string yamlFilePath) { IobConfTree newConfObj = new IobConfTree(); if (File.Exists(yamlFilePath)) { string rawData = File.ReadAllText(yamlFilePath); if (!string.IsNullOrEmpty(rawData)) { var deserializer = new DeserializerBuilder() .WithNamingConvention(CamelCaseNamingConvention.Instance) .Build(); try { newConfObj = deserializer.Deserialize(rawData); } catch (Exception exc) { //lgError($"Eccezione in LoadFromYaml{Environment.NewLine}{exc}"); } } } 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"; /// /// 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 ComLayer GeneralCom { get; set; } = ComLayer.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 } }