using Microsoft.Extensions.Configuration; using MP.Data.Conf; using MP.Data.DatabaseModels; using Newtonsoft.Json; using NLog; using StackExchange.Redis; using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MP.Data.Services { public class StatusData : IDisposable { #region Public Constructors public StatusData(IConfiguration configuration) { _configuration = configuration; // setup compoenti REDIS redisConn = ConnectionMultiplexer.Connect(_configuration.GetConnectionString("Redis")); redisDb = redisConn.GetDatabase(); // conf DB string connStr = _configuration.GetConnectionString("Mp.Mon"); if (string.IsNullOrEmpty(connStr)) { Log.Error("ConnString empty!"); } else { dbController = new MP.Data.Controllers.MpMonController(configuration); StringBuilder sb = new StringBuilder(); sb.AppendLine($"StatusData | MpMonController OK"); Log.Info(sb.ToString()); } // setup time refresh if (!string.IsNullOrEmpty(_configuration.GetValue("ServerConf:maxAge"))) { maxAge = _configuration.GetValue("ServerConf:maxAge"); } else if (!string.IsNullOrEmpty(_configuration.GetValue("OptConf:msRefresh"))) { maxAge = _configuration.GetValue("OptConf:msRefresh"); } // setup conf IOB da dizionario tryLoadIobTags(); } #endregion Public Constructors #region Public Properties public static MP.Data.Controllers.MpMonController dbController { get; set; } = null!; /// /// Dizionario dei tag configurati per IOB /// public Dictionary> currTagConf { get; set; } = new Dictionary>(); #endregion Public Properties #region Public Methods public Task> ConfigGetAll() { return Task.FromResult(dbController.ConfigGetAll().ToList()); } public void Dispose() { // Clear database controller dbController.Dispose(); } /// /// Elenco setup dei tag conf correnti /// /// public Task>> getAllTags() { return Task.FromResult(currTagConf); } /// /// restituisce il valore da REDIS associato al tag richeisto /// /// Chiave in cui cercare il valore /// public string getTagConf(string redKey) { string outVal = ""; // cerco in REDIS la conf x l'IOB var rawData = redisDb.StringGet(redKey); if (!string.IsNullOrEmpty(rawData)) { outVal = $"{rawData}"; } return outVal; } public Task> MacchineGetAll() { return Task.FromResult(dbController.MacchineGetAll()); } public async Task> MseGetAll(bool forceDb = false) { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); List? result = new List(); // cerco in redis... RedisValue rawData = redisDb.StringGet(Constants.redisMseKey); if (rawData.HasValue && !forceDb) { result = JsonConvert.DeserializeObject>($"{rawData}"); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; Log.Debug($"Read from REDIS: {ts.TotalMilliseconds}ms"); } else { result = await Task.FromResult(dbController.MseGetAll(maxAge)); // serializzp e salvo... rawData = JsonConvert.SerializeObject(result); await redisDb.StringSetAsync(Constants.redisMseKey, rawData, TimeSpan.FromMilliseconds(maxAge)); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; Log.Debug($"Read from DB: {ts.TotalMilliseconds}ms"); } if (result == null) { result = new List(); } return result; } /// /// Restituisce numPezzi (ultimo) x macchina /// /// /// public int MachNumPzGet(string idxMacchina) { int answ = 0; if (MachineNumPz.ContainsKey(idxMacchina)) { answ = MachineNumPz[idxMacchina]; } return answ; } /// /// Salva numPezzi x macchina /// /// /// /// public bool MachNumPzSet(string idxMacchina, int numPz) { bool answ = false; if (MachineNumPz.ContainsKey(idxMacchina)) { MachineNumPz[idxMacchina] = numPz; } else { MachineNumPz.Add(idxMacchina, numPz); } answ = true; return answ; } /// /// Restituisce numPezzi (ultimo) x macchina /// /// /// public StatoProdModel MachProdStGet(string idxMacchina) { StatoProdModel answ = new StatoProdModel(); if (MachineProdStatus.ContainsKey(idxMacchina)) { answ = MachineProdStatus[idxMacchina]; } return answ; } /// /// Salva numPezzi x macchina /// /// /// /// public bool MachProdStSet(string idxMacchina, StatoProdModel currStatus) { bool answ = false; if (MachineProdStatus.ContainsKey(idxMacchina)) { MachineProdStatus[idxMacchina] = currStatus; } else { MachineProdStatus.Add(idxMacchina, currStatus); } answ = true; return answ; } private Dictionary MachineNumPz { get; set; } = new Dictionary(); private Dictionary MachineProdStatus { get; set; } = new Dictionary(); #endregion Public Methods #region Protected Fields /// /// Oggetto per connessione a REDIS /// protected ConnectionMultiplexer redisConn = null!; //ISubscriber sub = redis.GetSubscriber(); /// /// Oggetto DB redis da impiegare x chiamate R/W /// protected IDatabase redisDb = null!; #endregion Protected Fields #region Private Fields private static IConfiguration _configuration = null!; private static NLog.Logger Log = LogManager.GetCurrentClassLogger(); private int maxAge = 2000; #if false private string redisMseKey = "MP:MON:Cache:MSE"; #endif #endregion Private Fields #region Private Methods /// /// Prova a caricare da file la conf degli IOB se presente /// private void tryLoadIobTags() { Dictionary> currConf = new Dictionary>(); string strExeFilePath = System.Reflection.Assembly.GetExecutingAssembly().Location; if (!string.IsNullOrEmpty(strExeFilePath)) { string? strWorkPath = Path.GetDirectoryName(strExeFilePath); if (!string.IsNullOrEmpty(strWorkPath)) { string filePath = $"{strWorkPath}/Conf/iobTagsConf.json"; if (File.Exists(filePath)) { string rawData = File.ReadAllText(filePath); if (!string.IsNullOrEmpty(rawData)) { var fileConfData = JsonConvert.DeserializeObject(rawData); if (fileConfData != null) { // effettuo esplosione conf SE contenesse il valore "***" = tutti // gli IOB if (fileConfData.IobSetup.ContainsKey("***")) { // recupero elenco macchine... var elencoMacc = dbController.MacchineGetAll(); // x ogni macchina creo le righe standard da conf... var baseConf = fileConfData.IobSetup.Where(x => x.Key == "***").FirstOrDefault(); foreach (var item in elencoMacc) { if (!string.IsNullOrEmpty(item.IdxMacchina)) { // converto i valori x la macchina corrente... clono in // nuovo oggetto var specVal = baseConf.Value.Select(i => i.Clone()).ToList(); // sostituisco segnaposto foreach (var singleVal in specVal) { singleVal.TagLocation = singleVal.TagLocation.Replace("***", item.IdxMacchina); } // ora aggiungo eventuali valori in override... if (fileConfData.IobSetup.ContainsKey(item.IdxMacchina)) { var otConf = fileConfData.IobSetup.Where(x => x.Key == item.IdxMacchina).FirstOrDefault(); //verifico x ogni valore other... foreach (var otTag in otConf.Value) { var ovrTag = specVal.Where(x => x.ColNum == otTag.ColNum && x.RowNum == otTag.RowNum).FirstOrDefault(); // se contiene --> sovrascrivo if (ovrTag != null) { //ovrTag = otTag.Clone(); specVal.Remove(ovrTag); specVal.Add(otTag.Clone()); } // se non contiene --> aggiungo else { specVal.Add(otTag); } } } currConf.Add(item.IdxMacchina, specVal); } } } // altrimenti copio ed ho finito else { currConf = fileConfData.IobSetup; } } } } if (currConf != null) { currTagConf = currConf; } } } } #endregion Private Methods } }