Files
mapo-core/MP.MON/Components/Pages/Index.razor.cs
T
2025-03-15 12:42:57 +01:00

394 lines
13 KiB
C#

using Microsoft.AspNetCore.Components;
using MP.Data;
using MP.Core.Conf;
using MP.Data.DbModels;
using MP.Data.Services;
using MP.MON;
using Newtonsoft.Json;
using NLog;
using System;
using static Org.BouncyCastle.Math.EC.ECCurve;
using MP.Core.DTO;
using MP.Data.Translate;
namespace MP.MON.Components.Pages
{
public partial class Index : ComponentBase, IDisposable
{
#region Public Methods
public void Dispose()
{
MMDataService.dataPipe.EA_NewMessage -= DataPipe_EA_NewMessage;
MMDataService.blinkPipe.EA_NewMessage -= BlinkPipe_EA_NewMessage;
disposeTimers();
}
public async void ElapsedSlowTimer(object? source, System.Timers.ElapsedEventArgs e)
{
ListMSE = null;
await Task.Delay(10);
Log.Info("Elapsed Slow Timer --> full page reload");
// dispongo i vari timers...
disposeTimers();
await Task.Delay(10);
// reload pagina intera
NavManager.NavigateTo(NavManager.Uri, true);
}
public void StartTimer()
{
// timer lento
slowTimer = new System.Timers.Timer(slowRefreshMs);
slowTimer.Elapsed += ElapsedSlowTimer;
slowTimer.Enabled = true;
slowTimer.Start();
}
#endregion Public Methods
#region Protected Fields
protected bool doAnimate = true;
protected bool scrollText = false;
protected int fastRefreshMs = 1000;
protected int keepAliveMin = 1;
protected int maxCol = 6;
protected bool newDisplay = true;
protected string showArt = "";
protected int slowRefreshSec = 300;
#endregion Protected Fields
#region Protected Properties
[Inject]
protected IConfiguration config { get; set; } = null!;
/// <summary>
/// Numero righe mappa: calcolato da num elementi e numMax x riga...
/// </summary>
protected int mapNRow
{
get
{
int answ = 1;
int numElems = ListMSE != null ? ListMSE.Count : 1;
answ = (int)Math.Ceiling((double)numElems / maxCol);
return answ;
}
}
[Inject]
protected MonDataFeeder MMDataService { get; set; } = null!;
[Inject]
protected NavigationManager NavMan { get; set; } = null!;
[Inject]
protected NavigationManager NavManager { get; set; } = null!;
protected int slowRefreshMs
{
get
{
// tempo variabile tra +/- 10% del target
int answ = rnd.Next(900, 1100) * slowRefreshSec;
return answ;
}
}
#endregion Protected Properties
#region Protected Methods
/// <summary>
/// Recupera il valore e se trovato aggiorna
/// </summary>
/// <param name="chiave">Valore da cercare</param>
/// <param name="varObj">String in cui salvare il valore se trovato</param>
/// <returns></returns>
protected bool getConfVal(string chiave, ref string varObj)
{
bool answ = false;
if (CurrConfig != null && CurrConfig.Count > 0)
{
// sistemo i parametri opzionali...
ConfigModel? risultato = CurrConfig.FirstOrDefault(x => x.Chiave == chiave);
if (risultato != null)
{
varObj = risultato.Valore;
answ = !string.IsNullOrEmpty(risultato.Valore);
}
}
return answ;
}
/// <summary>
/// Recupera il valore e se trovato aggiorna
/// </summary>
/// <param name="chiave">Valore da cercare</param>
/// <returns></returns>
protected bool getConfValBool(string chiave)
{
bool answ = false;
if (CurrConfig != null && CurrConfig.Count > 0)
{
// sistemo i parametri opzionali...
ConfigModel? risultato = CurrConfig.FirstOrDefault(x => x.Chiave == chiave);
if (risultato != null)
{
bool.TryParse(risultato.Valore, out answ);
}
}
return answ;
}
/// <summary>
/// Recupera il valore e se trovato aggiorna
/// </summary>
/// <param name="chiave">Valore da cercare</param>
/// <param name="varObj">Int in cui salvare il valore se trovato</param>
/// <returns></returns>
protected bool getConfValInt(string chiave, ref int varObj)
{
bool answ = false;
if (CurrConfig != null && CurrConfig.Count > 0)
{
// sistemo i parametri opzionali...
ConfigModel? risultato = CurrConfig.FirstOrDefault(x => x.Chiave == chiave);
if (risultato != null)
{
answ = int.TryParse(risultato.Valore, out varObj);
}
}
return answ;
}
/// <summary>
/// Recupera da conf eventuale setup tag dell'IOB indicato
/// </summary>
/// <param name="codIob"></param>
/// <returns></returns>
protected List<TagData>? getIobTag(string codIob)
{
List<TagData>? answ = null;
if (MMDataService.currTagConf != null)
{
// cerco x chiave IOB...
if (MMDataService.currTagConf.ContainsKey(codIob))
{
answ = MMDataService.currTagConf[codIob];
}
}
return answ;
}
/// <summary>
/// Recupera da redis (in una chiamata soltanto) tutti i valori richiesti e compone un
/// dizionario x ottimizzare visualizzazione
/// </summary>
/// <param name="codIob"></param>
/// <returns></returns>
protected Dictionary<string, string> getTagVal(string codIob)
{
Dictionary<string, string> answ = new Dictionary<string, string>();
// recupero conf tags...
var currTags = getIobTag(codIob);
if (currTags != null && currTags.Count > 0)
{
// FIXME TODO !!!! FARE !!!! - da verificare
answ = currTags.ToDictionary(x => x.TagLocation, x => MMDataService.getTagConf(x.TagLocation));
}
return answ;
}
/// <summary>
/// restituisce MSE dato indice
/// </summary>
/// <param name="mseIdx">Indice MSE richiesto</param>
/// <returns></returns>
protected MappaStatoExplDTO? MseById(int mseIdx)
{
MappaStatoExplDTO? answ = null;
try
{
if (ListMSE != null && ListMSE.Count > mseIdx)
{
answ = DbDto.Mse2DTO(ListMSE[mseIdx]);
}
}
catch (Exception exc)
{
Log.Error($"Eccezione in recupero MSE: richiesto idx {mseIdx} | trovati {listMacchine.Count}{Environment.NewLine}{exc}");
}
return answ;
}
protected override async Task OnInitializedAsync()
{
await setupConf();
MMDataService.dataPipe.EA_NewMessage += DataPipe_EA_NewMessage;
MMDataService.blinkPipe.EA_NewMessage += BlinkPipe_EA_NewMessage;
Random rnd = new Random();
cssOverlayOff = config.GetValue<string>("ServerConf:cssOverlayOff") ?? "";
maxChar4Scroll = config.GetValue<int>("ServerConf:maxChar4Scroll");
await Task.Delay(rnd.Next(50, 150));
StartTimer();
}
#endregion Protected Methods
#region Private Fields
//private static System.Timers.Timer fastTimer = new System.Timers.Timer(4000);
private static NLog.Logger Log = LogManager.GetCurrentClassLogger();
private static System.Timers.Timer slowTimer = new System.Timers.Timer(300000);
private string CodGruppo = "";
private string cssOverlayOff = "bg-dark text-light opacity-100";
private List<ConfigModel>? CurrConfig = null;
private bool doBlink = false;
private List<Macchine> listMacchine = new List<Macchine>();
private List<MappaStatoExpl>? ListMSE = null;
/// <summary>
/// num max caratteri prima di abilitare scrolling testo
/// </summary>
private int maxChar4Scroll = 10;
private Random rnd = new Random();
#endregion Private Fields
#region Private Properties
#endregion Private Properties
#region Private Methods
/// <summary>
/// Ricezione evento blink
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BlinkPipe_EA_NewMessage(object? sender, EventArgs e)
{
PubSubEventArgs currArgs = (PubSubEventArgs)e;
// conversione on-the-fly List<string> --> allarmi
if (!string.IsNullOrEmpty(currArgs.newMessage))
{
try
{
var dataRaw = JsonConvert.DeserializeObject<string>(currArgs.newMessage);
if (dataRaw != null)
{
bool.TryParse($"{dataRaw}", out doBlink);
}
}
catch
{ }
InvokeAsync(() =>
{
StateHasChanged();
});
}
}
/// <summary>
/// Ricevuto nuovi dati da mostrare!
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <exception cref="NotImplementedException"></exception>
private void DataPipe_EA_NewMessage(object? sender, EventArgs e)
{
PubSubEventArgs currArgs = (PubSubEventArgs)e;
// conversione on-the-fly List<string> --> allarmi
if (!string.IsNullOrEmpty(currArgs.newMessage))
{
try
{
List<MappaStatoExpl>? dataList = JsonConvert.DeserializeObject<List<MappaStatoExpl>>(currArgs.newMessage);
if (dataList != null)
{
// se ho filtro macchine --> tengo solo quelle che mi tornano...
if (listMacchine != null && listMacchine.Count > 0)
{
List<MappaStatoExpl> listaFilt = new List<MappaStatoExpl>();
foreach (var item in listMacchine)
{
var rigaFilt = dataList.FirstOrDefault(x => x.IdxMacchina == item.IdxMacchina);
if (rigaFilt != null)
{
listaFilt.Add(rigaFilt);
}
}
dataList = listaFilt;
}
#if DEBUG
// hack: legge 3 volte i dati x stressare sistema
var singleData = dataList;
ListMSE = new List<MappaStatoExpl>();
for (int i = 0; i < 3; i++)
{
ListMSE.AddRange(singleData);
}
#else
ListMSE = dataList;
#endif
}
}
catch
{ }
}
InvokeAsync(() =>
{
StateHasChanged();
});
}
private void disposeTimers()
{
slowTimer.Elapsed -= ElapsedSlowTimer;
slowTimer.Stop();
slowTimer.Dispose();
}
private async Task setupConf()
{
CurrConfig = await MMDataService.ConfigGetAll();
if (CurrConfig != null && CurrConfig.Count > 0)
{
// sistemo i parametri opzionali...
getConfValInt("keepAliveMin", ref keepAliveMin);
getConfValInt("MON_maxCol", ref maxCol);
newDisplay = getConfValBool("MON_newDisplay");
string rawData = "";
getConfVal("doAnimate", ref rawData);
doAnimate = rawData == "1";
getConfVal("MON_scrollText", ref rawData);
scrollText = rawData.ToLower() == "true";
getConfValInt("pageRefreshSec", ref slowRefreshSec);
getConfVal("sART", ref showArt);
Log.Info($"setupConf | Effettuato setup parametri | keepAlive: {keepAliveMin} | MaxCol: {maxCol} | doAnimate: {doAnimate} | slowRefreshSec: {slowRefreshSec} | fastRefreshMs: {fastRefreshMs}");
}
// verifico se ho richiesta filtro x codGruppo...
CodGruppo = NavMan.ExtractQueryStringByKey<string>("CodGruppo");
if (!string.IsNullOrEmpty(CodGruppo))
{
listMacchine = await MMDataService.MacchineGetByGruppo(CodGruppo);
}
}
#endregion Private Methods
}
}