diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index ab1573d9..eb600f32 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -82,6 +82,7 @@ stages:
- installer
- release
+# ----- Start BUILD -----
LAND:build:
stage: build
tags:
@@ -173,7 +174,21 @@ CONF:build:
script:
- dotnet build $env:APP_NAME/$env:APP_NAME.csproj
+IOC:build:
+ stage: build
+ tags:
+ - win
+ variables:
+ APP_NAME: MP.IOC
+ SOL_NAME: MP-IOC
+ before_script:
+ - *nuget-fix
+ - dotnet restore "$env:SOL_NAME.sln"
+ script:
+ - dotnet build $env:APP_NAME/$env:APP_NAME.csproj
+
+# ----- Start DEPLOY develop (IIS01) -----
LAND:IIS01:deploy:
stage: deploy
tags:
@@ -293,6 +308,24 @@ CONF:IIS01:deploy:
- dotnet build $env:APP_NAME/$env:APP_NAME.csproj
- dotnet publish -p:PublishProfile=IIS01.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release -p:username=jenkins -p:Password=$IIS_PASSWD -p:AllowUntrustedCertificate=true -p:verbosity=quiet $env:APP_NAME/$env:APP_NAME.csproj
+IOC:IIS01:deploy:
+ stage: deploy
+ tags:
+ - win
+ variables:
+ APP_NAME: MP.IOC
+ SOL_NAME: MP-IOC
+ before_script:
+ - *nuget-fix
+ - dotnet restore "$env:SOL_NAME.sln"
+ only:
+ - develop
+ needs: ["IOC:build"]
+ script:
+ - dotnet build $env:APP_NAME/$env:APP_NAME.csproj
+ - dotnet publish -p:PublishProfile=IIS01.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release -p:username=jenkins -p:Password=$IIS_PASSWD -p:AllowUntrustedCertificate=true -p:verbosity=quiet $env:APP_NAME/$env:APP_NAME.csproj
+
+# ----- Start DEPLOY master (IIS02/IIS03) -----
LAND:IIS02:deploy:
stage: deploy
tags:
@@ -419,6 +452,25 @@ CONF:IIS02:deploy:
- dotnet publish -p:PublishProfile=IIS02.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release -p:username=jenkins -p:Password=$IIS_PASSWD -p:AllowUntrustedCertificate=true -p:verbosity=quiet $env:APP_NAME/$env:APP_NAME.csproj
- dotnet publish -p:PublishProfile=IIS03.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release -p:username=jenkins -p:Password=$IIS_PASSWD -p:AllowUntrustedCertificate=true -p:verbosity=quiet $env:APP_NAME/$env:APP_NAME.csproj
+IOC:IIS02:deploy:
+ stage: deploy
+ tags:
+ - win
+ variables:
+ APP_NAME: MP.IOC
+ SOL_NAME: MP-IOC
+ before_script:
+ - *nuget-fix
+ - dotnet restore "$env:SOL_NAME.sln"
+ only:
+ - develop
+ needs: ["IOC:build"]
+ script:
+ - dotnet build $env:APP_NAME/$env:APP_NAME.csproj
+ - dotnet publish -p:PublishProfile=IIS02.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release -p:username=jenkins -p:Password=$IIS_PASSWD -p:AllowUntrustedCertificate=true -p:verbosity=quiet $env:APP_NAME/$env:APP_NAME.csproj
+ - dotnet publish -p:PublishProfile=IIS03.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release -p:username=jenkins -p:Password=$IIS_PASSWD -p:AllowUntrustedCertificate=true -p:verbosity=quiet $env:APP_NAME/$env:APP_NAME.csproj
+
+# ----- Start INSTALLER (develop/master) -----
LAND:installer:
stage: installer
tags:
@@ -573,6 +625,29 @@ INVE:installer:
# - *hashBuild
# - *nexusUpload
+IOC:installer:
+ stage: installer
+ tags:
+ - win
+ variables:
+ APP_NAME: MP.IOC
+ SOL_NAME: MP-IOC
+ NEXUS_PATH: MP-IOC
+ before_script:
+ - *nuget-fix
+ - dotnet restore "$env:SOL_NAME.sln"
+ only:
+ - develop
+ - master
+ needs: ["IOC:build"]
+ script:
+ - dotnet build $env:APP_NAME/$env:APP_NAME.csproj
+ - dotnet publish -p:PublishProfile=IISProfile.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release $env:APP_NAME/$env:APP_NAME.csproj -o:publish -p:verbosity=quiet
+ # qui il deploy su nexus...
+ - *hashBuild
+ - *nexusUpload
+
+# ----- Start RELEASE (tags only) -----
LAND:release:
stage: release
tags:
@@ -585,8 +660,6 @@ LAND:release:
- *nuget-fix
- dotnet restore "$env:SOL_NAME.sln"
only:
- #- feature/Deploy_CI_CD
- # - master
- tags
except:
- branches
@@ -740,3 +813,26 @@ CONF:release:
- dotnet build $env:APP_NAME/$env:APP_NAME.csproj
- dotnet publish -c Release -o ./publish $env:APP_NAME/$env:APP_NAME.csproj -p:verbosity=quiet
+IOC:release:
+ stage: release
+ tags:
+ - win
+ variables:
+ APP_NAME: MP.IOC
+ SOL_NAME: MP-IOC
+ NEXUS_PATH: MP-IOC
+ before_script:
+ - *nuget-fix
+ - dotnet restore "$env:SOL_NAME.sln"
+ only:
+ - tags
+ except:
+ - branches
+ needs: ["IOC:build"]
+ artifacts:
+ paths:
+ - publish/
+ script:
+ - dotnet build $env:APP_NAME/$env:APP_NAME.csproj
+ - dotnet publish -c Release -o ./publish $env:APP_NAME/$env:APP_NAME.csproj -p:verbosity=quiet
+
diff --git a/MP-IOC.sln b/MP-IOC.sln
new file mode 100644
index 00000000..a64b294c
--- /dev/null
+++ b/MP-IOC.sln
@@ -0,0 +1,31 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 17
+VisualStudioVersion = 17.4.33205.214
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MP.Data", "MP.Data\MP.Data.csproj", "{A0C7A1E7-6E5F-41BA-8ED0-C4A6C581C1B3}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MP.IOC", "MP.IOC\MP.IOC.csproj", "{B9F508BF-8503-4C25-B9BA-0FAC411C44C5}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Release|Any CPU = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {A0C7A1E7-6E5F-41BA-8ED0-C4A6C581C1B3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {A0C7A1E7-6E5F-41BA-8ED0-C4A6C581C1B3}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {A0C7A1E7-6E5F-41BA-8ED0-C4A6C581C1B3}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {A0C7A1E7-6E5F-41BA-8ED0-C4A6C581C1B3}.Release|Any CPU.Build.0 = Release|Any CPU
+ {B9F508BF-8503-4C25-B9BA-0FAC411C44C5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {B9F508BF-8503-4C25-B9BA-0FAC411C44C5}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {B9F508BF-8503-4C25-B9BA-0FAC411C44C5}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {B9F508BF-8503-4C25-B9BA-0FAC411C44C5}.Release|Any CPU.Build.0 = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ SolutionGuid = {8030DF52-992F-46A3-A9F1-5FF64A9D5D9D}
+ EndGlobalSection
+EndGlobal
diff --git a/MP.Data/Controllers/MpIocController.cs b/MP.Data/Controllers/MpIocController.cs
new file mode 100644
index 00000000..9b52a93a
--- /dev/null
+++ b/MP.Data/Controllers/MpIocController.cs
@@ -0,0 +1,391 @@
+using Microsoft.Data.SqlClient;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Configuration;
+using MP.Data.DatabaseModels;
+using NLog;
+using System;
+using System.Collections.Generic;
+using System.Data;
+using System.Linq;
+using System.Threading.Tasks;
+
+namespace MP.Data.Controllers
+{
+ public class MpIocController : IDisposable
+ {
+ #region Public Constructors
+
+ public MpIocController(IConfiguration configuration)
+ {
+ _configuration = configuration;
+ Log.Info("Avviata classe MpIocController");
+ }
+
+ #endregion Public Constructors
+
+ #region Public Methods
+
+
+ ///
+ /// Elenco da tabella Config
+ ///
+ ///
+ public List ConfigGetAll()
+ {
+ List dbResult = new List();
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ dbResult = dbCtx
+ .DbSetConfig
+ .AsNoTracking()
+ .OrderBy(x => x.Chiave)
+ .ToList();
+ }
+ return dbResult;
+ }
+
+ ///
+ /// Update record config
+ ///
+ ///
+ public bool ConfigUpdate(ConfigModel updRec)
+ {
+ bool fatto = false;
+ ConfigModel dbResult = new ConfigModel();
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ dbResult = dbCtx
+ .DbSetConfig
+ .Where(x => x.Chiave == updRec.Chiave)
+ .FirstOrDefault();
+ if (dbResult != null)
+ {
+ dbResult.Valore = updRec.Valore;
+ dbCtx.SaveChanges();
+ fatto = true;
+ }
+ }
+ return fatto;
+ }
+
+ ///
+ /// Intera tab dati macchina
+ ///
+ ///
+ public List DatiMacchineGetAll()
+ {
+ List dbResult = new List();
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ dbResult = dbCtx
+ .DbSetDatiMacchine
+ .AsNoTracking()
+ .OrderBy(x => x.IdxMacchina)
+ .ToList();
+ }
+ return dbResult;
+ }
+
+ public void Dispose()
+ {
+ _configuration = null;
+ }
+
+
+ ///
+ /// Aggiunta record EventList
+ ///
+ ///
+ ///
+ public async Task EvListInsert(EventListModel newRec)
+ {
+ bool fatto = false;
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ try
+ {
+ var currRec = dbCtx
+ .DbSetEvList
+ .Add(newRec);
+ await dbCtx.SaveChangesAsync();
+ }
+ catch (Exception exc)
+ {
+ Log.Error($"Eccezione durante EvListInsert{Environment.NewLine}{exc}");
+ }
+ }
+ await Task.Delay(1);
+ return fatto;
+ }
+
+ ///
+ /// Elenco ultimi n record flux log dato macchina e flusso (ordinato x data registrazione)
+ ///
+ /// Data massima x eventi
+ /// Data minima x eventi
+ /// * = tutte, altrimenti solo x una data macchina
+ /// *=tutti, altrimenti solo selezionato
+ /// numero massimo record da restituire
+ ///
+ public List FluxLogGetLastFilt(DateTime DtMax, DateTime DtMin, string IdxMacchina, string CodFlux, int MaxRec)
+ {
+ List dbResult = new List();
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ dbResult = dbCtx
+ .DbSetFluxLog
+ .AsNoTracking()
+ .Where(x => (x.dtEvento >= DtMin && x.dtEvento <= DtMax) && (IdxMacchina == "*" || x.IdxMacchina == IdxMacchina) && (CodFlux == "*" || x.CodFlux == CodFlux))
+ .OrderByDescending(x => x.dtEvento)
+ .Take(MaxRec)
+ .ToList();
+ }
+ return dbResult;
+ }
+
+ public bool KeepAliveUpsert(string IdxMacc, DateTime OraServer, DateTime OraMacc)
+ {
+ bool fatto = false;
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ var currRec = dbCtx
+ .DbSetKeepAlive
+ .Where(x => x.IdxMacchina == IdxMacc)
+ .FirstOrDefault();
+ if (currRec != null)
+ {
+ currRec.DataOraServer = OraServer;
+ currRec.DataOraMacchina = OraMacc;
+ dbCtx.Entry(currRec).State = EntityState.Modified;
+ }
+ else
+ {
+ KeepAliveModel newRec = new KeepAliveModel()
+ {
+ IdxMacchina = IdxMacc,
+ DataOraMacchina = OraMacc,
+ DataOraServer = OraServer,
+ DataOraStart = DateTime.Now
+ };
+ dbCtx
+ .DbSetKeepAlive
+ .Add(newRec);
+ }
+ dbCtx.SaveChanges();
+ fatto = true;
+ }
+ return fatto;
+ }
+
+
+ public List ListLinkFilt(string tipoLink)
+ {
+ List dbResult = new List();
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ dbResult = dbCtx
+ .DbSetLinkMenu
+ .Where(x => x.TipoLink == tipoLink)
+ .AsNoTracking()
+ .OrderBy(x => x.ordine)
+ .ToList();
+ }
+ return dbResult;
+ }
+
+ ///
+ /// Intera tabella relazione master/slave in machine (gestione setup master --> slave)
+ ///
+ ///
+ public List Macchine2Slave()
+ {
+ List dbResult = new List();
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ dbResult = dbCtx
+ .DbSetM2S
+ .AsNoTracking()
+ .OrderBy(x => x.IdxMacchina)
+ .ToList();
+ }
+ return dbResult;
+ }
+
+ ///
+ /// Elenco da tabella Macchine
+ ///
+ ///
+ ///
+ public List MacchineGetFilt(string codGruppo)
+ {
+ List dbResult = new List();
+ try
+ {
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ if (codGruppo == "*")
+ {
+ dbResult = dbCtx
+ .DbSetMacchine
+ .AsNoTracking()
+ .OrderBy(x => x.IdxMacchina)
+ .ToList();
+ }
+ else
+ {
+ dbResult = dbCtx
+ .DbSetGrp2Macc
+ .Where(g => g.CodGruppo == codGruppo)
+ .Join(dbCtx.DbSetMacchine,
+ g => g.IdxMacchina,
+ m => m.IdxMacchina,
+ (g, m) => m
+ )
+ .AsNoTracking()
+ .OrderBy(x => x.IdxMacchina)
+ .ToList();
+ }
+ }
+ }
+ catch (Exception exc)
+ {
+ Log.Error($"Eccezione in MacchineGetFilt{Environment.NewLine}{exc}");
+ }
+ return dbResult;
+ }
+
+ ///
+ /// Elenco da tabella MappaStatoExpl
+ ///
+ ///
+ public List MseGetAll(int maxAge = 2000)
+ {
+ List dbResult = new List();
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ var maxAgeSec = new SqlParameter("@maxAgeSec", maxAge);
+
+ dbResult = dbCtx
+ .DbSetMSE
+ .FromSqlRaw("EXEC stp_MSE_getData @maxAgeSec", maxAgeSec)
+ .AsNoTracking()
+ .ToList();
+ }
+ return dbResult;
+ }
+
+ ///
+ /// Annulla modifiche su una specifica entity (cancel update)
+ ///
+ ///
+ ///
+ public bool RollBackEntity(object item)
+ {
+ bool answ = false;
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ try
+ {
+ if (dbCtx.Entry(item).State == Microsoft.EntityFrameworkCore.EntityState.Deleted || dbCtx.Entry(item).State == Microsoft.EntityFrameworkCore.EntityState.Modified)
+ {
+ dbCtx.Entry(item).Reload();
+ }
+ }
+ catch (Exception exc)
+ {
+ Log.Error($"Eccezione in rollBackEntity{Environment.NewLine}{exc}");
+ }
+ }
+ return answ;
+ }
+
+ ///
+ /// Intera tabella relazione master/slave in machine (gestione setup master --> slave)
+ ///
+ ///
+ public List StateMachineIngressi(int idxFam)
+ {
+ List dbResult = new List();
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ var IdxFamIn = new SqlParameter("@IdxFamigliaIngresso", idxFam);
+ dbResult = dbCtx
+ .DbSetSMI
+ .FromSqlRaw("exec dbo.stp_TRI_getByIdxFamIng @IdxFamigliaIngresso", IdxFamIn)
+ .AsNoTracking()
+ .AsEnumerable()
+ .ToList();
+ }
+ return dbResult;
+ }
+
+ ///
+ /// Stato prod macchina
+ ///
+ ///
+ ///
+ public StatoProdModel StatoProdMacchina(string idxMacchina)
+ {
+ StatoProdModel dbResult = new StatoProdModel();
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina);
+ dbResult = dbCtx
+ .DbSetStatoProd
+ .FromSqlRaw("EXEC stp_PzProd_getByMacchina @IdxMacchina", IdxMacchina)
+ .AsNoTracking()
+ .FirstOrDefault();
+ }
+ return dbResult;
+ }
+
+ ///
+ /// Intera vista v_MSFD
+ ///
+ ///
+ public List VMSFDGetAll()
+ {
+ List dbResult = new List();
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ dbResult = dbCtx
+ .DbSetMSFD
+ .AsNoTracking()
+ .OrderBy(x => x.IdxMacchina)
+ .ToList();
+ }
+ return dbResult;
+ }
+
+ ///
+ /// Vista v_MSFD CALCOALTA x singola macchina (da stored) - singolo record
+ ///
+ ///
+ public List VMSFDGetByMacc(string idxMacc)
+ {
+ List dbResult = new List();
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacc);
+
+ dbResult = dbCtx
+ .DbSetMSFD
+ .FromSqlRaw("exec dbo.stp_MSFD_getMacc @IdxMacchina", IdxMacchina)
+ .AsNoTracking()
+ .AsEnumerable()
+ .ToList();
+ }
+ return dbResult;
+ }
+
+ #endregion Public Methods
+
+ #region Private Fields
+
+ private static IConfiguration _configuration;
+
+ private static NLog.Logger Log = LogManager.GetCurrentClassLogger();
+
+ #endregion Private Fields
+ }
+}
\ No newline at end of file
diff --git a/MP.Data/Controllers/MpSpecController.cs b/MP.Data/Controllers/MpSpecController.cs
index 94b5d405..c73563aa 100644
--- a/MP.Data/Controllers/MpSpecController.cs
+++ b/MP.Data/Controllers/MpSpecController.cs
@@ -294,6 +294,24 @@ namespace MP.Data.Controllers
return fatto;
}
+ ///
+ /// Intera tab dati macchina
+ ///
+ ///
+ public List DatiMacchineGetAll()
+ {
+ List dbResult = new List();
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ dbResult = dbCtx
+ .DbSetDatiMacchine
+ .AsNoTracking()
+ .OrderBy(x => x.IdxMacchina)
+ .ToList();
+ }
+ return dbResult;
+ }
+
public void Dispose()
{
_configuration = null;
@@ -727,7 +745,7 @@ namespace MP.Data.Controllers
}
}
}
- catch(Exception exc)
+ catch (Exception exc)
{
Log.Error($"Eccezione in MacchineGetFilt{Environment.NewLine}{exc}");
}
@@ -828,32 +846,6 @@ namespace MP.Data.Controllers
return dbResult;
}
-#if false
-
- ///
- /// Elenco PODL non avviati filtrati x articolo, KeyRich (che contiene stato)
- ///
- /// Cod articolo
- /// KeyRich (parziale) da cercare (es cod stato x yacht)
- ///
- public List ListPODLFiltNOOdl(string codArt, string keyRichPart)
- {
- List dbResult = new List();
- using (var dbCtx = new MoonProContext(_configuration))
- {
- dbResult = dbCtx
- .DbSetPODL
- .Where(x => (x.IdxOdl != 0) && (x.KeyRichiesta.Contains(keyRichPart) || keyRichPart == "*") && (codArt == "*" || x.CodArticolo.Contains(codArt)))
- .AsNoTracking()
- .Include(m => m.MachineNav)
- .Include(a => a.ArticoloNav)
- .OrderByDescending(x => x.InsertDate)
- .ToList();
- }
- return dbResult;
- }
-#endif
-
///
/// Chiusura ODL con eventuale conferma pezzi
///
diff --git a/MP.Data/DatabaseModels/DatiMacchineModel.cs b/MP.Data/DatabaseModels/DatiMacchineModel.cs
new file mode 100644
index 00000000..329a6a1f
--- /dev/null
+++ b/MP.Data/DatabaseModels/DatiMacchineModel.cs
@@ -0,0 +1,33 @@
+using System;
+using System.Collections.Generic;
+
+namespace MP.Data.DatabaseModels
+{
+ public partial class DatiMacchineModel
+ {
+ public string IdxMacchina { get; set; }
+ public bool? PalletChange { get; set; }
+ public string CodArticoloA { get; set; }
+ public string CodArticoloB { get; set; }
+ public string SerialPort { get; set; }
+ public int? RefreshPeriod { get; set; }
+ public bool? Simulazione { get; set; }
+ public bool? SimplePallet { get; set; }
+ ///
+ /// definisce se l'INSERT sia abilitato per la macchina (disabilitato in fase di ricostruzione batch...)
+ ///
+ public bool? InsEnabled { get; set; }
+ ///
+ /// definisce se sia abilitata la registrazione di TUTTI gli invii di dati in ingresso da questa specifica macchina
+ ///
+ public bool SLogEnabled { get; set; }
+ ///
+ /// Abilita o meno il trigger su DiarioDiBordo x ricalcolo eventi
+ ///
+ public bool? IsTrigerDbon { get; set; }
+ ///
+ /// Indica se la macchina abbia un COUNTER (assoluto) o meno, tipicamente true x IOB-WIN, false per IOB-PI
+ ///
+ public bool HasCounter { get; set; }
+ }
+}
diff --git a/MP.Data/DatabaseModels/KeepAliveModel.cs b/MP.Data/DatabaseModels/KeepAliveModel.cs
new file mode 100644
index 00000000..a30ac535
--- /dev/null
+++ b/MP.Data/DatabaseModels/KeepAliveModel.cs
@@ -0,0 +1,13 @@
+using System;
+using System.Collections.Generic;
+
+namespace MP.Data.DatabaseModels
+{
+ public partial class KeepAliveModel
+ {
+ public string IdxMacchina { get; set; }
+ public DateTime? DataOraServer { get; set; }
+ public DateTime? DataOraMacchina { get; set; }
+ public DateTime? DataOraStart { get; set; }
+ }
+}
diff --git a/MP.Data/DatabaseModels/Macchine2SlaveModel.cs b/MP.Data/DatabaseModels/Macchine2SlaveModel.cs
new file mode 100644
index 00000000..6643c7d0
--- /dev/null
+++ b/MP.Data/DatabaseModels/Macchine2SlaveModel.cs
@@ -0,0 +1,11 @@
+using System;
+using System.Collections.Generic;
+
+namespace MP.Data.DatabaseModels
+{
+ public partial class Macchine2SlaveModel
+ {
+ public string IdxMacchina { get; set; }
+ public string IdxMacchinaSlave { get; set; }
+ }
+}
diff --git a/MP.Data/DatabaseModels/TransizioneIngressiModel.cs b/MP.Data/DatabaseModels/TransizioneIngressiModel.cs
new file mode 100644
index 00000000..72e3ad15
--- /dev/null
+++ b/MP.Data/DatabaseModels/TransizioneIngressiModel.cs
@@ -0,0 +1,14 @@
+using System;
+using System.Collections.Generic;
+
+namespace MP.Data.DatabaseModels
+{
+ public partial class TransizioneIngressiModel
+ {
+ public int IdxFamigliaIngresso { get; set; }
+ public int IdxMicroStato { get; set; }
+ public int ValoreIngresso { get; set; }
+ public int? IdxTipoEvento { get; set; }
+ public int NextIdxMicroStato { get; set; }
+ }
+}
diff --git a/MP.Data/DatabaseModels/VMSFDModel.cs b/MP.Data/DatabaseModels/VMSFDModel.cs
new file mode 100644
index 00000000..f9745bbf
--- /dev/null
+++ b/MP.Data/DatabaseModels/VMSFDModel.cs
@@ -0,0 +1,34 @@
+using System;
+using System.Collections.Generic;
+
+namespace MP.Data.DatabaseModels
+{
+ public partial class VMSFDModel
+ {
+ public string IdxMacchina { get; set; }
+ public string Codmacchina { get; set; }
+ public bool PalletChange { get; set; }
+ public string CodArticoloA { get; set; }
+ public string CodArticoloB { get; set; }
+ public bool SimplePallet { get; set; }
+ public bool InsEnabled { get; set; }
+ public bool SLogEnabled { get; set; }
+ public int IdxFamigliaIngresso { get; set; }
+ public int Multi { get; set; }
+ public int BitFilt { get; set; }
+ public int MaxVal { get; set; }
+ public int Bsr { get; set; }
+ public bool ExplodeBit { get; set; }
+ public int NumBit { get; set; }
+ public int IdxMicroStato { get; set; }
+ public int IdxFamiglia { get; set; }
+ public int IdxStato { get; set; }
+ public string LastVal { get; set; }
+ public string CodArticolo { get; set; }
+ public double TempoCicloBase { get; set; }
+ public int PzPalletProd { get; set; }
+ public int MatrOpr { get; set; }
+ public string Pallet { get; set; }
+ public string CodMaccArticolo { get; set; }
+ }
+}
diff --git a/MP.Data/MoonProContext.cs b/MP.Data/MoonProContext.cs
index c971d028..d25b9ddf 100644
--- a/MP.Data/MoonProContext.cs
+++ b/MP.Data/MoonProContext.cs
@@ -56,6 +56,11 @@ namespace MP.Data
public virtual DbSet DbSetVocabolario { get; set; }
public virtual DbSet DbOperatori { get; set; }
public virtual DbSet DbSetGrp2Macc { get; set; }
+ public virtual DbSet DbSetDatiMacchine { get; set; }
+ public virtual DbSet DbSetMSFD { get; set; }
+ public virtual DbSet DbSetM2S { get; set; }
+ public virtual DbSet DbSetSMI { get; set; }
+ public virtual DbSet DbSetKeepAlive { get; set; }
#endregion Public Properties
@@ -322,6 +327,146 @@ namespace MP.Data
});
+ modelBuilder.Entity(entity =>
+ {
+ entity.HasKey(e => e.IdxMacchina);
+
+ entity.ToTable("DatiMacchine");
+
+ entity.Property(e => e.IdxMacchina)
+ .HasMaxLength(50)
+ .HasColumnName("idxMacchina");
+
+ entity.Property(e => e.CodArticoloA)
+ .HasMaxLength(50)
+ .HasColumnName("CodArticolo_A");
+
+ entity.Property(e => e.CodArticoloB)
+ .HasMaxLength(50)
+ .HasColumnName("CodArticolo_B");
+
+ entity.Property(e => e.HasCounter)
+ .HasColumnName("hasCounter")
+ .HasComment("Indica se la macchina abbia un COUNTER (assoluto) o meno, tipicamente true x IOB-WIN, false per IOB-PI");
+
+ entity.Property(e => e.InsEnabled)
+ .HasColumnName("insEnabled")
+ .HasDefaultValueSql("((1))")
+ .HasComment("definisce se l'INSERT sia abilitato per la macchina (disabilitato in fase di ricostruzione batch...)");
+
+ entity.Property(e => e.IsTrigerDbon)
+ .IsRequired()
+ .HasColumnName("isTrigerDBOn")
+ .HasDefaultValueSql("((1))")
+ .HasComment("Abilita o meno il trigger su DiarioDiBordo x ricalcolo eventi");
+
+ entity.Property(e => e.PalletChange).HasColumnName("palletChange");
+
+ entity.Property(e => e.RefreshPeriod).HasColumnName("refreshPeriod");
+
+ entity.Property(e => e.SLogEnabled)
+ .HasColumnName("sLogEnabled")
+ .HasComment("definisce se sia abilitata la registrazione di TUTTI gli invii di dati in ingresso da questa specifica macchina");
+
+ entity.Property(e => e.SerialPort)
+ .HasMaxLength(50)
+ .HasColumnName("serialPort");
+
+ entity.Property(e => e.SimplePallet).HasColumnName("simplePallet");
+
+ entity.Property(e => e.Simulazione).HasColumnName("simulazione");
+ });
+
+
+ modelBuilder.Entity(entity =>
+ {
+ entity.HasNoKey();
+
+ entity.ToView("v_MSFD");
+
+ entity.Property(e => e.Bsr).HasColumnName("BSR");
+
+ entity.Property(e => e.CodArticolo)
+ .IsRequired()
+ .HasMaxLength(50);
+
+ entity.Property(e => e.CodArticoloA)
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnName("CodArticolo_A");
+
+ entity.Property(e => e.CodArticoloB)
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnName("CodArticolo_B");
+
+ entity.Property(e => e.CodMaccArticolo)
+ .IsRequired()
+ .HasMaxLength(103);
+
+ entity.Property(e => e.Codmacchina)
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnName("codmacchina");
+
+ entity.Property(e => e.IdxMacchina)
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnName("idxmacchina");
+
+ entity.Property(e => e.InsEnabled).HasColumnName("insEnabled");
+
+ entity.Property(e => e.LastVal)
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnName("lastVal");
+
+ entity.Property(e => e.Pallet)
+ .IsRequired()
+ .HasMaxLength(20)
+ .HasColumnName("pallet");
+
+ entity.Property(e => e.PalletChange).HasColumnName("palletChange");
+
+ entity.Property(e => e.SLogEnabled).HasColumnName("sLogEnabled");
+
+ entity.Property(e => e.SimplePallet).HasColumnName("simplePallet");
+ });
+
+ modelBuilder.Entity(entity =>
+ {
+ entity.HasKey(e => new { e.IdxMacchina, e.IdxMacchinaSlave })
+ .HasName("PK_Macc2Slave");
+
+ entity.ToTable("Macchine2Slave");
+
+ entity.Property(e => e.IdxMacchina).HasMaxLength(50);
+
+ entity.Property(e => e.IdxMacchinaSlave).HasMaxLength(50);
+ });
+
+ modelBuilder.Entity(entity =>
+ {
+ entity.HasKey(e => new { e.IdxFamigliaIngresso, e.IdxMicroStato, e.ValoreIngresso });
+
+ entity.ToTable("TransizioneIngressi");
+
+ entity.Property(e => e.NextIdxMicroStato).HasColumnName("next_IdxMicroStato");
+ });
+
+ modelBuilder.Entity(entity =>
+ {
+ entity.HasKey(e => e.IdxMacchina);
+
+ entity.ToTable("KeepAlive");
+
+ entity.Property(e => e.IdxMacchina).HasMaxLength(50);
+
+ entity.Property(e => e.DataOraMacchina).HasColumnType("datetime");
+
+ entity.Property(e => e.DataOraStart).HasColumnType("datetime");
+ });
+
OnModelCreatingPartial(modelBuilder);
}
diff --git a/MP.Data/Utils.cs b/MP.Data/Utils.cs
index ff70a27a..56e56b6d 100644
--- a/MP.Data/Utils.cs
+++ b/MP.Data/Utils.cs
@@ -1,5 +1,5 @@
using MP.Data.DatabaseModels;
-using Newtonsoft.Json;
+using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@@ -43,6 +43,16 @@ namespace MP.Data
return answ;
}
+ ///
+ /// Hash dati STATUS x la macchina specificata
+ ///
+ ///
+ ///
+ public static RedisKey dtMaccHash(string idxMacchina)
+ {
+ return (RedisKey)$"{redisBaseAddr}DtMac:{idxMacchina}";
+ }
+
public static string FormDurata(double durataMinuti)
{
string answ = "";
@@ -58,6 +68,16 @@ namespace MP.Data
return answ;
}
+ ///
+ /// RedisKey calcolata x tabella HSI
+ ///
+ ///
+ ///
+ public static RedisKey hSMI(int idxFamIn)
+ {
+ return (RedisKey)$"{redisBaseAddr}hSMI:{idxFamIn}";
+ }
+
///
/// Inizializzazione con periodo e arrotondamento
///
@@ -72,19 +92,39 @@ namespace MP.Data
}
///
- /// Nome della variabile HASH da utilizzare (dato CodModulo / Server / DB impiegato da
- /// funzionalita' DbConfig) + keyName richiesto...
+ /// Nome della variabile HASH da utilizzare (dato CodModulo / Server / DB impiegato
+ /// dafunzionalita' DbConfig) + idxMacchina richiesto...
///
- public static string RedHash(string keyName)
+ ///
+ ///
+ public static RedisKey OptParHash(string idxMacchina)
{
- string answ = keyName;
- try
- {
- answ = $"MP:Data:{keyName}";
- }
- catch
- { }
- return answ;
+ return (RedisKey)$"{redisBaseAddr}OpPar:{idxMacchina}";
+ }
+
+ ///
+ /// Nome della variabile HASH da utilizzare (dato CodModulo / Server / DB impiegato da
+ /// funzionalita' DbConfig) + idxMacchina richiesto...
+ ///
+ public static RedisKey RedHash(string keyName)
+ {
+ return (RedisKey)$"MP:Data:{keyName}";
+ }
+
+ ///
+ /// Formato RedisKey delal chaive richeista (completa)
+ ///
+ public static RedisKey RedKeyHash(string keyName)
+ {
+ return (RedisKey)$"{redisBaseAddr}{keyName}";
+ }
+
+ ///
+ /// Formato RedisValue delal chaive richeista (completa)
+ ///
+ public static RedisValue RedValue(string keyName)
+ {
+ return (RedisValue)$"{redisBaseAddr}{keyName}";
}
///
@@ -179,5 +219,35 @@ namespace MP.Data
}
#endregion Public Classes
+
+ #region Private Fields
+
+ public const string redisActionReq = redisBaseAddr + "Action:Req";
+ public const string redisAnagGruppi = redisBaseAddr + "Cache:AnagGruppi";
+ public const string redisArtByDossier = redisBaseAddr + "Cache:ArtByDossier";
+ public const string redisArtList = redisBaseAddr + "Cache:ArtList";
+ public const string redisBaseAddr = "MP:";
+ public const string redisConfKey = redisBaseAddr + "Cache:Config";
+ public const string redisDossByMac = redisBaseAddr + "Cache:DossByMac";
+ public const string redisFluxByMac = redisBaseAddr + "Cache:FluxByMac";
+ public const string redisFluxLogFilt = redisBaseAddr + "Cache:FluxLogFilt";
+ public const string redisGiacenzaList = redisBaseAddr + "Cache:GiacenzaList";
+ public const string redisMacByFlux = redisBaseAddr + "Cache:MacByFlux";
+ public const string redisMacList = redisBaseAddr + "Cache:MacList";
+ public const string redisMacRecipe = redisBaseAddr + "Cache:Recipe";
+ public const string redisOdlByBatch = redisXdlData + "OdlByBatch";
+ public const string redisOdlCurrByMac = redisXdlData + "OdlByMac";
+ public const string redisOdlList = redisXdlData + "OdlList";
+ public const string redisParamPageExp = redisBaseAddr + "Cache:ParamPage";
+ public const string redisPOdlByOdl = redisXdlData + "POdlByOdl";
+ public const string redisPOdlByPOdl = redisXdlData + "POdlByPOdl";
+ public const string redisPOdlList = redisXdlData + "POdlList";
+ public const string redisRecipeConf = redisBaseAddr + "Cache:Recipe:Conf";
+ public const string redisStatoCom = redisBaseAddr + "Cache:StatoCom";
+ public const string redisTipoArt = redisBaseAddr + "Cache:TipoArt";
+ public const string redisVocabolario = redisBaseAddr + "Cache:Vocabolario";
+ public const string redisXdlData = redisBaseAddr + "Cache:XDL:";
+
+ #endregion Private Fields
}
}
\ No newline at end of file
diff --git a/MP.IOC/.config/dotnet-tools.json b/MP.IOC/.config/dotnet-tools.json
new file mode 100644
index 00000000..b0e38abd
--- /dev/null
+++ b/MP.IOC/.config/dotnet-tools.json
@@ -0,0 +1,5 @@
+{
+ "version": 1,
+ "isRoot": true,
+ "tools": {}
+}
\ No newline at end of file
diff --git a/MP.IOC/Controllers/BenchController.cs b/MP.IOC/Controllers/BenchController.cs
new file mode 100644
index 00000000..c0671a00
--- /dev/null
+++ b/MP.IOC/Controllers/BenchController.cs
@@ -0,0 +1,378 @@
+using Microsoft.AspNetCore.Mvc;
+using MP.Data;
+using MP.IOC.Data;
+using NLog;
+using System.Diagnostics;
+
+namespace MP.IOC.Controllers
+{
+ [Route("api/[controller]")]
+ [ApiController]
+ public class BenchController : ControllerBase
+ {
+ #region Public Constructors
+
+ public BenchController(IConfiguration configuration, MpDataService DataService)
+ {
+ Log.Info("Starting BenchController");
+ _configuration = configuration;
+ DService = DataService;
+ Log.Info("Avviata BenchController");
+ }
+
+ #endregion Public Constructors
+
+ #region Public Methods
+
+ ///
+ /// Conteggio chiavi REDIS dato pattern api/Bench/CountKeys
+ ///
+ ///
+ ///
+ [HttpGet("CountKeys")]
+ public string CountKeys(string? id)
+ {
+ string answ = "ND";
+ if (id == null) id = "";
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ // conto quanti oggetti ho in memoria REDIS...
+ string groupHash = ""; // DataLayer.mHash("");
+ if (id.Length > 0)
+ {
+ groupHash += id + ":";
+ }
+ groupHash += "*";
+ answ = $"Trovate {DService.RedisCountKey(groupHash)} Hash per {groupHash}";
+ stopWatch.Stop();
+ // Get the elapsed time as a TimeSpan value.
+ TimeSpan ts = stopWatch.Elapsed;
+ // accodo tempo!
+ answ += $"{Environment.NewLine}Elapsed: {ts.TotalMilliseconds}ms";
+ // ritorno
+ return answ;
+ }
+
+ ///
+ /// Bench recupero dati macchina api/Bench/DtMac?id=SIMUL_01
+ ///
+ ///
+ ///
+ [HttpGet("DatiMacc")]
+ public string DatiMacc(string id)
+ {
+ string answ = "ND";
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ // se id nullo --> KO!
+ if (id == null)
+ {
+ answ = "KO";
+ }
+ else
+ {
+ answ = "";
+ try
+ {
+ Dictionary valori = DService.ResetDatiMacchina(id);
+ foreach (var item in valori)
+ {
+ answ += $"{item.Key}|{item.Value}{Environment.NewLine}";
+ }
+ }
+ catch
+ { }
+ }
+ stopWatch.Stop();
+ // Get the elapsed time as a TimeSpan value.
+ TimeSpan ts = stopWatch.Elapsed;
+ // accodo tempo!
+ answ += $"{Environment.NewLine}Elapsed: {ts.TotalMilliseconds}ms";
+ // ritorno
+ return answ;
+ }
+
+ /// Recupera riga traduzione microstato x processing da HASH table
+ /// api/Bench/FindSMI?id=60&idxMS=3&valore=1
+ [HttpGet("FindSMI")]
+ public string FindSMI(int? id, int? idxMS, int? valore)
+ {
+ string answ = "ND";
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ // se id nullo --> KO!
+ if (id == null)
+ {
+ answ = "KO";
+ }
+ else
+ {
+ // recupero dati x sapere quale famiglia SMI è necessaria e quale stato / segnale si
+ // sia ricevuto
+ int idxFamIn = Convert.ToInt32(id);
+ int idxMicroStato = Convert.ToInt32(idxMS);
+ int valIOB = Convert.ToInt32(valore);
+ // recupero microstato macchina da chiave relativa
+ answ = "";
+ try
+ {
+ var fiHASH = Utils.hSMI(idxFamIn);
+ string outVal = "";
+ bool trovato = DService.RedisHashPresent(fiHASH);
+ if (!trovato)
+ {
+ // ricarico tabella!
+ KeyValuePair[] valori = DService.StateMachInByKey(idxFamIn);
+ answ = string.Format("Ricaricata SMI per famiglia {0}
", fiHASH);
+ }
+
+ // recupero singolo valore (stringa) x chiave
+ outVal = DService.ValoreSMI(idxFamIn, idxMicroStato, valIOB);
+ // mostro output
+ answ += $"idxFamIN: {idxFamIn} | idxMS: {idxMicroStato} | valIOB: {valIOB} | out: {outVal}";
+ }
+ catch
+ { }
+ }
+ stopWatch.Stop();
+ // Get the elapsed time as a TimeSpan value.
+ TimeSpan ts = stopWatch.Elapsed;
+ // accodo tempo!
+ answ += $"{Environment.NewLine}Total Time Elapsed: {ts.TotalMilliseconds}ms";
+ // ritorno
+ return answ;
+ }
+
+ ///
+ /// Test verifica insert enabled x macchina
+ ///
+ ///
+ ///
+ [HttpGet("InsEnab")]
+ public string InsEnab(string id)
+ {
+ string answ = "ND";
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ // se id nullo --> KO!
+ if (id == null)
+ {
+ answ = "KO";
+ }
+ else
+ {
+ // recupero microstato macchina da chiave relativa
+ answ = "";
+ try
+ {
+ answ += $"Macchina {id}, insEnabled {DService.IobInsEnab(id)}{Environment.NewLine}";
+ }
+ catch
+ { }
+ }
+ stopWatch.Stop();
+ // Get the elapsed time as a TimeSpan value.
+ TimeSpan ts = stopWatch.Elapsed;
+ // accodo tempo!
+ answ += $"{Environment.NewLine}Total Time Elapsed: {ts.TotalMilliseconds}ms";
+ // ritorno
+ return answ;
+ }
+
+ ///
+ /// pulizia dati api/Bench/RClean?id=100
+ ///
+ ///
+ ///
+ [HttpGet("RClean")]
+ public string RClean(int? id)
+ {
+ string answ = "ND";
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ // se id nullo --> KO!
+ if (id == null)
+ {
+ answ = "KO";
+ }
+ else
+ {
+ string chiave;
+ KeyValuePair[] valori = new KeyValuePair[2];
+ try
+ {
+ // svuoto i precedenti hash... CICLO!
+ for (int i = 0; i < id; i++)
+ {
+ chiave = string.Format("test:{0}", i);
+ DService.RedisDelKey(chiave);
+ }
+ answ = "OK";
+ }
+ catch
+ { }
+ }
+ stopWatch.Stop();
+ // Get the elapsed time as a TimeSpan value.
+ TimeSpan ts = stopWatch.Elapsed;
+ // accodo tempo!
+ answ += $"{Environment.NewLine}Elapsed: {ts.TotalMilliseconds}ms";
+ // ritorno
+ return answ;
+ }
+
+ //// GET: IOB (è un check alive)
+ //public string Index()
+ //{
+ // return "OK";
+ //}
+ ///
+ /// Setup dati di test hash api/Bench/RSetup?id=100
+ ///
+ ///
+ ///
+ [HttpGet("RSetup")]
+ public string RSetup(int? id)
+ {
+ string answ = "ND";
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ // se id nullo --> KO!
+ if (id == null)
+ {
+ answ = "KO";
+ }
+ else
+ {
+ string chiave;
+ KeyValuePair[] valori = new KeyValuePair[2];
+ try
+ {
+ // salvo il datasetet come insieme di hash in redis...
+ for (int i = 0; i < id; i++)
+ {
+ chiave = string.Format("test:{0}", i);
+ valori[0] = new KeyValuePair("numero", i.ToString());
+ valori[1] = new KeyValuePair("doppio", (i * 2).ToString());
+ DService.RedisSetHash(chiave, valori);
+ }
+ answ = "OK";
+ }
+ catch
+ { }
+ }
+ stopWatch.Stop();
+ // Get the elapsed time as a TimeSpan value.
+ TimeSpan ts = stopWatch.Elapsed;
+ // accodo tempo!
+ answ += $"{Environment.NewLine}Elapsed: {ts.TotalMilliseconds}ms";
+ // ritorno
+ return answ;
+ }
+
+ ///
+ /// Recupero singolo valore hash api/Bench/RSingleHash?id=50
+ ///
+ ///
+ ///
+ [HttpGet("RSingleHash")]
+ public string RSingleHash(int? id)
+ {
+ string answ = "ND";
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ // se id nullo --> KO!
+ if (id == null)
+ {
+ answ = "KO";
+ }
+ else
+ {
+ answ = "";
+ string chiave;
+ KeyValuePair[] valori = new KeyValuePair[2];
+ try
+ {
+ // ora restituisco record completo dell'hash con ID indicato
+ chiave = string.Format("test:{0}", id);
+ valori = DService.RedisGetHash(chiave);
+ foreach (var item in valori)
+ {
+ answ += string.Format("{0}|{1}
", item.Key, item.Value);
+ }
+ }
+ catch
+ { }
+ }
+ stopWatch.Stop();
+ // Get the elapsed time as a TimeSpan value.
+ TimeSpan ts = stopWatch.Elapsed;
+ // accodo tempo!
+ answ += $"{Environment.NewLine}Elapsed: {ts.TotalMilliseconds}ms";
+ // ritorno
+ return answ;
+ }
+
+ ///
+ /// Lettura tab StateMachineIngressi
+ ///
+ ///
+ ///
+ [HttpGet("StateMachineIn")]
+ public string StateMachineIn(int? id)
+ {
+ string answ = "ND";
+ long splitTime = 0;
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ // se id nullo --> KO!
+ if (id == null)
+ {
+ answ = "KO";
+ }
+ else
+ {
+ int idxFamIn = Convert.ToInt32(id);
+ answ = "";
+ try
+ {
+ KeyValuePair[] valori = DService.StateMachInByKey(idxFamIn);
+ splitTime = stopWatch.ElapsedMilliseconds;
+ foreach (var item in valori)
+ {
+ answ += $"{item.Key}|{item.Value}{Environment.NewLine}";
+ }
+ }
+ catch
+ { }
+ }
+ stopWatch.Stop();
+ // Get the elapsed time as a TimeSpan value.
+ TimeSpan ts = stopWatch.Elapsed;
+ // accodo tempo!
+ answ += $"{Environment.NewLine}ReadTime: {splitTime}ms
Total Time Elapsed: {ts.TotalMilliseconds}ms";
+ // ritorno
+ return answ;
+ }
+
+ #endregion Public Methods
+
+ #region Protected Properties
+
+ ///
+ /// Dataservice x accesso DB
+ ///
+ protected MpDataService DService { get; set; }
+
+ #endregion Protected Properties
+
+ #region Private Fields
+
+ private static IConfiguration _configuration = null!;
+
+ private static Logger Log = LogManager.GetCurrentClassLogger();
+
+ #endregion Private Fields
+ }
+}
\ No newline at end of file
diff --git a/MP.IOC/Controllers/IOBController.cs b/MP.IOC/Controllers/IOBController.cs
new file mode 100644
index 00000000..be7837e9
--- /dev/null
+++ b/MP.IOC/Controllers/IOBController.cs
@@ -0,0 +1,2241 @@
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Configuration;
+using MP.Data;
+using MP.IOC.Data;
+using Newtonsoft.Json;
+using NLog;
+using NLog.Fluent;
+using System.Data;
+using System.Globalization;
+using System.IO;
+
+namespace MP.IOC.Controllers
+{
+ [Route("api/[controller]")]
+ [ApiController]
+ public class IOBController : ControllerBase
+ {
+
+ public IOBController(IConfiguration configuration, MpDataService DataService)
+ {
+ Log.Info("Starting IOBController");
+ _configuration = configuration;
+ DService = DataService;
+ Log.Info("Avviato IOBController");
+ }
+
+
+ private static IConfiguration _configuration = null!;
+
+ private static Logger Log = LogManager.GetCurrentClassLogger();
+
+ ///
+ /// Dataservice x accesso DB
+ ///
+ protected MpDataService DService { get; set; }
+
+ #region Public Methods
+
+ /// SALVA x macchina KVP parametro/valore:
+ ///
+ /// GET: api/IOB/addOptPar/SIMUL_03?pName=PZREQ&pValue=1000
+ ///
+ ///
+ [HttpGet("addOptPar/{id}")]
+ public string addOptPar(string id, string pName, string pValue)
+ {
+ string answ = "";
+ DService.ScriviKeepAlive(id, DateTime.Now);
+ try
+ {
+ DService.AddOptPar4Machine(id, pName, pValue);
+ answ = getOptPar(id);
+ }
+ catch
+ { }
+ return answ;
+ }
+ ///
+ /// Recupera TASK richiesto x macchina:
+ ///
+ /// GET: IOB/getOptPar/SIMUL_03
+ ///
+ ///
+ /// Json contenente 1..n task da eseguire
+ [HttpGet("getOptPar/{id}")]
+ public string getOptPar(string id)
+ {
+ string answ = "";
+ // scrivo keep alive!!! (se necessario, altrimenti è in cache...)
+ DService.ScriviKeepAlive(id, DateTime.Now);
+ try
+ {
+ // leggo da REDIS eventuale elenco task x macchina...
+ Dictionary valori = DService.mOptParMacchina(id);
+ answ = JsonConvert.SerializeObject(valori);
+ }
+ catch
+ { }
+ return answ;
+ }
+
+ ///// AGGIUNGE TASK richiesto x macchina:
+ /////
+ ///// GET: IOB/addTask2Exe/3010?taskName=startSetup&taskVal=T190406101512
+ ///// GET: IOB/addTask2Exe/3010?taskName=stopSetup&taskVal=T190406101512
+ ///// GET: IOB/addTask2Exe/SIMUL_03?taskName=setProg&taskVal=P00000001
+ ///// GET: IOB/addTask2Exe/SIMUL_03?taskName=setComm&taskVal=ODL_0000123
+ ///// GET: IOB/addTask2Exe/SIMUL_03?taskName=setArt&taskVal=ART_0000321
+ /////
+ /////
+ //public string addTask2Exe(string id, string taskName, string taskVal)
+ //{
+ // string answ = "";
+ // // scrivo keep alive!!! (se necessario, altrimenti è in cache...)
+ // MapoDb.MapoDb connDb = new MapoDb.MapoDb();
+ // DataLayer DataLayerObj = new DataLayer();
+ // connDb.scriviKeepAlive(id, DateTime.Now);
+ // try
+ // {
+ // // converto stringa in tipo task...
+ // taskType tName = taskType.nihil;
+ // bool fatto = Enum.TryParse(taskName, out tName);
+ // if (fatto)
+ // {
+ // DataLayerObj.addTask4Machine(id, tName, taskVal);
+ // }
+ // else
+ // {
+ // logger.lg.scriviLog($"addTask2Exe: impossibile riconoscere il comando {taskName} come uno dei tipi ammessi, NON aggiunto", tipoLog.ERROR);
+ // }
+ // answ = getTask2Exe(id);
+ // }
+ // catch
+ // { }
+ // return answ;
+ //}
+
+ /////
+ ///// Richiesta chiusura manuale ODL x macchina (popup utente):
+ /////
+ ///// GET: IOB/askCloseODL/SIMUL_03?idxOdl=123
+ /////
+ ///// id macchina
+ ///// idx dell'ODL da chiudere
+ ///// bool esecuzione
+ //public bool askCloseODL(string id, int idxOdl)
+ //{
+ // bool answ = false;
+ // // init obj DataLayer
+ // DataLayer DataLayerObj = new DataLayer();
+ // try
+ // {
+ // // preparo una richiesta di chiusura...
+ // DisplayAction CurrAction = new DisplayAction()
+ // {
+ // Topic = "Chiusura ODL",
+ // Message = "Rilevato possibile fine operazioni, Vuoi chiudere la commessa?",
+ // ShowCancel = true,
+ // ShowClose = true,
+ // ShowConfirm = true,
+ // CancelAction = "DisableAction",
+ // ConfirmAction = "CloseODL",
+ // DtReq = DateTime.Now,
+ // IsActive = true,
+ // Parameter = $"{idxOdl}"
+ // };
+ // answ = DataLayerObj.ActionSetReq(CurrAction);
+ // }
+ // catch
+ // { }
+ // return answ;
+ //}
+
+ /////
+ ///// Chiude ODL x macchina:
+ /////
+ ///// GET: IOB/closeODL/SIMUL_03?idxOdl=123
+ /////
+ ///// id macchina
+ ///// idx dell'ODL da chiudere
+ ///// bool esecuzione
+ //public bool closeODL(string id, int idxOdl)
+ //{
+ // bool answ = false;
+
+ // // init obj DataLayer
+ // DataLayer DataLayerObj = new DataLayer();
+ // try
+ // {
+ // // chiamata diretta sul DB...
+ // DataLayerObj.taODL.forceClose(idxOdl, id);
+ // answ = true;
+ // }
+ // catch
+ // { }
+ // return answ;
+ //}
+
+ //// GET: IOB/enabled/SIMUL_03
+ //public string enabled(string id)
+ //{
+ // string answ = "ND";
+ // // se id nullo --> KO!
+ // if (id == null)
+ // {
+ // answ = "KO";
+ // }
+ // else
+ // {
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // // salvo risposta!
+ // answ = DataLayerObj.insEnab(id) ? "OK" : "NO";
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog(string.Format("Errore in enabled{0}{1}", Environment.NewLine, exc));
+ // answ = "NO";
+ // }
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Processa una chiamata POST per l'invio di un array Json di oggetti input (EVENTI)
+ ///// POST: IOB/evListJson/SIMUL_03
+ /////
+ ///// ID dell'IOB
+ /////
+ //[HttpPost]
+ //public string evListJson(string id)
+ //{
+ // int insDone = 0;
+ // string answ = "-";
+ // // questa classe è derivata da Controller.Response... x cui recupero lo stream in altro modo...
+ // string content = "";
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // using (var reader = new StreamReader(
+ // Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true))
+ // {
+ // content = reader.ReadToEnd();
+ // }
+ // //Rest
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // // se ho dati...
+ // if (content != "")
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // // procedo a deserializzare in blocco l'oggetto...
+ // evJsonPayload receivedData = new evJsonPayload();
+ // try
+ // {
+ // // deserializzo.
+ // receivedData = JsonConvert.DeserializeObject(content);
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in fase deserializzazione inputJson{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // // se ho qualcosa da processare...
+ // if (receivedData != null)
+ // {
+ // // per ogni valore --> processo!
+ // try
+ // {
+ // foreach (var item in receivedData.eventList)
+ // {
+ // if (memLayer.ML.CRI("_logLevel") > 6)
+ // {
+ // logger.lg.scriviLog($"Valori letti: idxMacchina: {id} | valore: {item.valore}", tipoLog.INFO);
+ // }
+
+ // // formato datetime come yyyyMMddHHmmssfff -->es: 20181223180600000
+ // answ = DataLayerObj.processInput(id, item.valore, item.dtEve.ToString("yyyyMMddHHmmssfff"), item.dtCurr.ToString("yyyyMMddHHmmssfff"), item.cnt.ToString());
+ // insDone++;
+ // }
+ // // se vuoto --> OK!
+ // if (string.IsNullOrEmpty(answ))
+ // {
+ // answ = $"OK {insDone} processed";
+ // }
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in fase invio valori inputJson{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // }
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Sistema Dossier/Snapshot giornalieri x impianto indicato, andando a generare 1 Dossier
+ ///// giornaliero x ogni giornata dall'ultimo registrato alla data corrente
+ ///// es: http://url_site/MP/IO/IOB/fixDailyDossier/SIMUL_03
+ /////
+ /////
+ /////
+ //public string fixDailyDossier(string id)
+ //{
+ // string answ = "";
+ // // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il
+ // // carattere "|" che poi trasformiamo ora in "#"
+ // id = id.Replace("|", "#");
+ // // effettuo processing
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // // verifico se si possa processare, ovvero tab ConfFlux x macchina sia valorizzata...
+ // var confDataMach = DataLayerObj.confFluxMach(id);
+ // if (confDataMach.Count > 0)
+ // {
+ // // determino ultima data da processare (inizio oggi, a mezzanotte)
+ // DateTime dtTo = DateTime.Today;
+ // DateTime dtFrom = dtTo;
+ // // determino data di partenza, prima da dossier esistenti
+ // var listaDoss = DataLayerObj.dossierLastByMach(id);
+ // if (listaDoss.Count > 0)
+ // {
+ // // primo giorno DOPO ultima registrazione
+ // dtFrom = listaDoss.OrderByDescending(x => x).FirstOrDefault().AddDays(1);
+ // }
+ // else
+ // {
+ // // ...o da fluxLog acquisiti...
+ // var listaFL = DataLayerObj.fluxLogFirstByMach(id);
+ // if (listaFL.Count > 0)
+ // {
+ // // giorno successivo a prima registrazione
+ // dtFrom = listaFL.OrderBy(x => x).FirstOrDefault().AddDays(1);
+ // }
+ // }
+ // string caller = $"takeFlogSnapshot({id})";
+ // DateTime dtStart = dtFrom.Date;
+ // DateTime dtEnd = dtFrom;
+ // int maxAdd = 5;
+ // if (dtStart < dtTo)
+ // {
+ // // verifico di avere almeno 1 dossier da produrre ciclo fino ad esaurire le
+ // // date da processare
+ // while (dtStart < dtTo && maxAdd > 0)
+ // {
+ // // sistemo end
+ // dtEnd = dtStart.AddDays(1);
+ // // effettuo chiamata registrazione snapshot!
+ // answ = doSaveFLSnapshot(id, dtStart, dtEnd, caller);
+ // // incremento START...
+ // dtStart = dtEnd;
+ // // riduco il numero di chiamate ammesse x singolo task
+ // maxAdd--;
+ // }
+ // // reset cache dossier...
+ // DataLayerObj.dossierLastByMachReset(id);
+ // }
+ // else
+ // {
+ // answ = "NO more to add";
+ // }
+ // }
+ // else
+ // {
+ // answ = "NO ConfFluxData";
+ // }
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Eccezione in recupero fixDailyDossier{Environment.NewLine}{exc}", tipoLog.EXCEPTION);
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Sistema ODL giornalieri x impianto indicato, andando a generare 1 ODL giornaliero x ogni
+ ///// giornata dall'ultimo ODL aperto alla data corrente
+ ///// es: http://url_site/MP/IO/IOB/fixDailyOdl/SIMUL_03
+ /////
+ /////
+ /////
+ //public string fixDailyOdl(string id)
+ //{
+ // string answ = "";
+ // // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il
+ // // carattere "|" che poi trasformiamo ora in "#"
+ // id = id.Replace("|", "#");
+ // // chiamo metodo redis/db...
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // // recupero ultimo ODL macchina...
+ // var lastOdlStarted = DataLayerObj.taODL.getLastByMacc(id);
+ // if (lastOdlStarted != null && lastOdlStarted.Count > 0)
+ // {
+ // // calcolo data ultimo avviato e chiedo dal giorno dopo...
+ // DateTime dtFrom = lastOdlStarted[0].DataInizio.AddDays(1);
+ // DateTime dtTo = DateTime.Today;
+ // if (dtTo >= dtFrom)
+ // {
+ // string codArt = lastOdlStarted[0].CodArticolo;
+ // // chiamo la stored x sistemare gli ODL
+ // DataLayerObj.taODL.AutoDayGener(id, dtFrom, dtTo, codArt);
+ // }
+ // answ = "OK";
+ // }
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Eccezione in recupero fixDailyOdl{Environment.NewLine}{exc}", tipoLog.EXCEPTION);
+ // }
+ // return answ;
+ //}
+
+ //// GET: IOB/flog/SIMUL_03?flux=PROG&valore=P0001&dtEve=20161223180600000&dtCurr=20161223180600000&cnt=999
+ //public string flog(string id, string flux, string valore, string dtEve, string dtCurr, string cnt)
+ //{
+ // string answ = "";
+ // // formato yyyymmddHHMMSSnnn ovvero da anno a millisecondi
+ // if (cnt == null)
+ // {
+ // cnt = "0";
+ // }
+
+ // DateTime dataOraEvento = DateTime.Now;
+ // if (memLayer.ML.CRI("_logLevel") > 6)
+ // {
+ // logger.lg.scriviLog($"Valori letti: idxMacchina: {id} | flux: {flux} valore: {valore}", tipoLog.INFO);
+ // }
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // int count = 0;
+ // Int32.TryParse(cnt, out count);
+ // answ = DataLayerObj.processFluxLog(id, flux, valore, dtEve, dtCurr, count);
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in flog{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Processa una chiamata POST per l'invio di un array Json di oggetti fluxLog
+ ///// PUT: IOB/flogJson/SIMUL_03
+ /////
+ ///// ID dell'IOB
+ /////
+ //[HttpPost]
+ //public string flogJson(string id)
+ //{
+ // int insDone = 0;
+ // string answ = "-";
+ // // questa classe è derivata da Controller.Response... x cui recupero lo stream in altro modo...
+ // string content = "";
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // using (var reader = new StreamReader(
+ // Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true))
+ // {
+ // content = reader.ReadToEnd();
+ // }
+ // //Rest
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // // se ho dati...
+ // if (content != "")
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // // procedo a deserializzare in blocco l'oggetto...
+ // flogJsonPayload receivedData = new flogJsonPayload();
+ // try
+ // {
+ // // deserializzo.
+ // receivedData = JsonConvert.DeserializeObject(content);
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in fase deserializzazione flogJson{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // // se ho qualcosa da processare...
+ // if (receivedData != null)
+ // {
+ // // per ogni valore --> salvo!
+ // try
+ // {
+ // foreach (var item in receivedData.fluxData)
+ // {
+ // // formato datetime come yyyyMMddHHmmssfff -->es: 20181223180600000
+ // answ = DataLayerObj.processFluxLog(id, item.flux, item.valore, item.dtEve.ToString("yyyyMMddHHmmssfff"), item.dtCurr.ToString("yyyyMMddHHmmssfff"), item.cnt);
+ // }
+ // // se vuoto --> OK!
+ // if (string.IsNullOrEmpty(answ))
+ // {
+ // answ = $"OK {insDone} processed";
+ // }
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in fase invio valori flogJson{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // // leggo parametri correnti...
+ // try
+ // {
+ // List currParams = DataLayerObj.getCurrObjItems(id);
+ // // ora per ogni valore RICEVUTO costruisco un oggetto in innovazioni da
+ // // inviare...x salvare in stato parametri...
+ // List innovazioni = new List();
+ // foreach (var item in receivedData.fluxData)
+ // {
+ // // flux = uuid del parametro
+ // objItem trovato = currParams.Find(obj => obj.uid == item.flux);
+ // // se lo trovo aggiorno...
+ // if (trovato != null)
+ // {
+ // // aggiorno valore e data
+ // trovato.value = item.valore;
+ // trovato.lastRead = DateTime.Now;
+ // // se fosse un valore WRITE e mi ha dato un valore vuoto --> mando
+ // // un fix x riscrittura
+ // if (trovato.writable && string.IsNullOrEmpty(item.valore))
+ // {
+ // logger.lg.scriviLog($"flogJson | verifica parametri | {trovato.uid} | reqVal: {trovato.reqValue}");
+ // taskType currTask = (taskType)Enum.Parse(typeof(taskType), trovato.uid);
+ // DataLayerObj.addCheckTask4Machine(id, currTask, item.valore);
+ // }
+ // }
+ // // altrimenti AGGIUNGO (READ ONLY)...
+ // else
+ // {
+ // trovato = new objItem
+ // {
+ // uid = item.flux,
+ // name = item.flux,
+ // value = item.valore,
+ // lastRead = DateTime.Now,
+ // writable = false
+ // };
+ // }
+ // // lo carico in innovation
+ // innovazioni.Add(trovato);
+ // }
+ // // faccio upsert innovations!
+ // DataLayerObj.upsertCurrObjItems(id, innovazioni);
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in fase salvataggio innovazioni parametri correnti da flogJson{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // }
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Chiude ODL precedente ed avvia uno nuovo (duplicandolo e sitemando quantità RIMANENTE),
+ ///// e CONFERMA produzione...
+ /////
+ ///// GET: IOB/forceSplitOdl/SIMUL_03
+ /////
+ /////
+ ///// Esito chiamata (OK/vuoto)
+ //public string forceSplitOdl(string id)
+ //{
+ // // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il
+ // // carattere "|" che poi trasformiamo ora in "#"
+ // id = id.Replace("|", "#");
+ // DataLayer DataLayerObj = new DataLayer();
+ // return DataLayerObj.AutoStartOdl(id, true, true, 100, "");
+ //}
+
+ ///// Chiude ODL precedente ed avvia uno nuovo (duplicandolo e sitemando quantità
+ ///// RIMANENTE), e CONFERMA produzione...
+ /////
+ ///// GET: IOB/forceSplitOdl/SIMUL_03?doConfirm=true&qtyFromLast=true&roundStep=150&extOrderCode=ABCDE1234
+ /////
+ ///// id impianto Cod esterno da legare all'ODL x tracciare lotti prod
+ ///// Esito chiamata (OK/vuoto)
+ //public string forceSplitOdlFull(string id, bool doConfirm, bool qtyFromLast, int? roundStep, string keyRichiesta = "")
+ //{
+ // // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il
+ // // carattere "|" che poi trasformiamo ora in "#"
+ // id = id.Replace("|", "#");
+ // DataLayer DataLayerObj = new DataLayer();
+ // if (roundStep == null)
+ // {
+ // roundStep = 100;
+ // }
+ // return DataLayerObj.AutoStartOdl(id, doConfirm, qtyFromLast, (int)roundStep, keyRichiesta);
+ //}
+
+ /////
+ ///// Avvia PODL indicato
+ ///// - se esistesse un ODL da altro PODL --> chiude
+ ///// - se fosse già in essere ODL collegato --> lascia aperto
+ ///// - se fosse chiuso ODL collegato --> duplica PODL e poi avvia nuovo ODL.
+ /////
+ ///// GET: IOB/forceStartPOdl/SIMUL_03?idxPODL=123
+ /////
+ /////
+ ///// idx del PDL da avviare
+ ///// Esito chiamata (OK/vuoto)
+ //public string forceStartPOdl(string id, int idxPODL)
+ //{
+ // // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il
+ // // carattere "|" che poi trasformiamo ora in "#"
+ // id = id.Replace("|", "#");
+ // DataLayer DataLayerObj = new DataLayer();
+ // return DataLayerObj.ForceStartPOdl(id, idxPODL, true);
+ //}
+
+ /////
+ ///// Recupera elenco articoli dei PODL correnti:
+ /////
+ ///// GET: IOB/getArtCurrPODL
+ /////
+ ///// Json contenente lista oggetti ARTICOLI serializzati
+ //public string getArtCurrPODL()
+ //{
+ // string answ = "";
+
+ // // init obj DataLayer
+ // DataLayer DataLayerObj = new DataLayer();
+ // try
+ // {
+ // // recupero dati macchina...
+ // var elencoArt = DataLayerObj.taAnagArt.getByCurrPODL();
+
+ // answ = JsonConvert.SerializeObject(elencoArt);
+ // }
+ // catch
+ // { }
+ // return answ;
+ //}
+
+ /////
+ ///// Recupera elenco articoli USATI:
+ /////
+ ///// GET: IOB/getArtUsed
+ /////
+ ///// Json contenente lista oggetti ARTICOLI serializzati
+ //public string getArtUsed()
+ //{
+ // string answ = "";
+
+ // // init obj DataLayer
+ // DataLayer DataLayerObj = new DataLayer();
+ // try
+ // {
+ // // recupero dati macchina...
+ // var elencoArt = DataLayerObj.taAnagArt.getUsed();
+
+ // answ = JsonConvert.SerializeObject(elencoArt);
+ // }
+ // catch
+ // { }
+ // return answ;
+ //}
+
+ /////
+ ///// Recupera COUNTER x macchina:
+ /////
+ ///// GET: IOB/getCounter/5
+ /////
+ /////
+ /////
+ //public string getCounter(string id)
+ //{
+ // string answ = "";
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // answ = DataLayerObj.pzCounter(id).ToString();
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog(string.Format("Errore in counter (get){0}{1}", Environment.NewLine, exc));
+ // answ = "NO";
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Recupera COUNTER x macchina dal CONTEGGIO dei TCRecorded:
+ /////
+ ///// GET: IOB/getCounterTCRec/5
+ /////
+ /////
+ /////
+ //public string getCounterTCRec(string id)
+ //{
+ // string answ = "";
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // answ = DataLayerObj.pzCounterTC(id).ToString();
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog(string.Format("Errore in counter TC (get){0}{1}", Environment.NewLine, exc));
+ // answ = "NO";
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Recupera DATI correnti x macchina:
+ /////
+ ///// GET: IOB/getCurrData/SIMUL_03
+ /////
+ /////
+ ///// Json contenente la riga di stato macchina
+ //public string getCurrData(string id)
+ //{
+ // // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il
+ // // carattere "|" che poi trasformiamo ora in "#"
+ // id = id.Replace("|", "#");
+ // string answ = "";
+ // // scrivo keep alive!!! (se necessario, altrimenti è in cache...)
+ // MapoDb.MapoDb connDb = new MapoDb.MapoDb();
+ // DataLayer DataLayerObj = new DataLayer();
+ // connDb.scriviKeepAlive(id, DateTime.Now);
+ // try
+ // {
+ // // recupero dati macchina...
+ // Dictionary valori = DataLayerObj.mDatiMacchine(id);
+ // answ = JsonConvert.SerializeObject(valori);
+ // }
+ // catch
+ // { }
+ // return answ;
+ //}
+
+ /////
+ ///// Recupera ODL corrente x macchina:
+ /////
+ ///// GET: IOB/getCurrODL/SIMUL_03
+ /////
+ /////
+ /////
+ //public string getCurrODL(string id)
+ //{
+ // // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il
+ // // carattere "|" che poi trasformiamo ora in "#"
+ // id = id.Replace("|", "#");
+ // string answ = "";
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // answ = $"{DataLayerObj.currODL(id)}";
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog(string.Format("Errore in currODL (get){0}{1}", Environment.NewLine, exc));
+ // answ = "NO";
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Restituisce intera riga dell'odl correntemente in lavorazione sulla macchina...
+ ///// GET: IOB/getCurrOdlRow/SIMUL_01
+ /////
+ /////
+ /////
+ //public string getCurrOdlRow(string id)
+ //{
+ // // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il
+ // // carattere "|" che poi trasformiamo ora in "#"
+ // id = id.Replace("|", "#");
+ // string answ = "";
+ // DS_ProdTempi.ODLDataTable currData = null;
+ // // chiamo metodo redis/db...
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // currData = DataLayerObj.currODLRowTab(id);
+ // answ = JsonConvert.SerializeObject(currData);
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Eccezione in recupero getCurrOdlRow{Environment.NewLine}{exc}", tipoLog.EXCEPTION);
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Restituisce data-ora inizio dell'odl correntemente in lavorazione sulla macchina...
+ ///// es: http://url_site/MP/IO/IOB/getCurrOdlStart/SIMUL_03
+ /////
+ /////
+ /////
+ //public string getCurrOdlStart(string id)
+ //{
+ // // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il
+ // // carattere "|" che poi trasformiamo ora in "#"
+ // id = id.Replace("|", "#");
+ // DateTime answ = new DateTime(DateTime.Now.Year - 1, 12, 31);
+ // // chiamo metodo redis/db...
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // DS_ProdTempi.ODLDataTable currTab = DataLayerObj.currODLRowTab(id);
+ // if (currTab.Count > 0)
+ // {
+ // DS_ProdTempi.ODLRow odlRow = currTab[0];
+ // answ = odlRow.DataInizio;
+ // }
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Eccezione in recupero getCurrOdlStart{Environment.NewLine}{exc}", tipoLog.EXCEPTION);
+ // }
+ // return answ.ToString("yyyy-MM-dd HH:mm:ss");
+ //}
+
+ /////
+ ///// Recupera DATI PODL correnti x macchina:
+ /////
+ ///// GET: IOB/getCurrPODL/SIMUL_03
+ /////
+ ///// id macchina, se "" mostra tutto
+ ///// Json contenente lista oggetti PODL serializzati
+ //public string getCurrPODL(string id)
+ //{
+ // // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il
+ // // carattere "|" che poi trasformiamo ora in "#"
+ // if (!string.IsNullOrEmpty(id))
+ // {
+ // id = id.Replace("|", "#");
+ // }
+ // string answ = "";
+
+ // // init obj DataLayer
+ // DataLayer DataLayerObj = new DataLayer();
+ // try
+ // {
+ // // recupero dati macchina...
+ // var elencoOdl = DataLayerObj.taPODL.getByMaccArt(id, "", "", true);
+ // answ = JsonConvert.SerializeObject(elencoOdl);
+ // }
+ // catch
+ // { }
+ // return answ;
+ //}
+
+ /////
+ ///// Restituisce intera riga dello stato di macchina...
+ ///// GET: IOB/getCurrStatoRow/SIMUL_01
+ /////
+ /////
+ /////
+ //public string getCurrStatoRow(string id)
+ //{
+ // // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il
+ // // carattere "|" che poi trasformiamo ora in "#"
+ // id = id.Replace("|", "#");
+ // string answ = "";
+ // DS_applicazione.StatoMacchineDataTable currData = null;
+ // // chiamo metodo redis/db...
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // currData = DataLayerObj.currSMTab(id);
+ // answ = JsonConvert.SerializeObject(currData);
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Eccezione in recupero getCurrStatoRow{Environment.NewLine}{exc}", tipoLog.EXCEPTION);
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Restituisce un array JSon di files di una IOB
+ ///// PUT: IOB/getFiles/SIMUL_03
+ /////
+ ///// ID dell'IOB
+ ///// Oggetto Json in formato MapoSDK.fileEmbed
+ //public string getFiles(string id)
+ //{
+ // string answ = "";
+ // // procedo a deserializzare in blocco l'oggetto...
+ // try
+ // {
+ // // recupero TUTTI i files della folder dell'IOB richiesta
+ // string basePath = Server.MapPath(memLayer.ML.CRS("uploadFileDir"));
+ // string dirPath = $"{basePath}\\{id}";
+ // var fileList = fileMover.obj.elencoFilesDir(dirPath);
+ // fileEmbed objFiles = new fileEmbed();
+ // MapoSDK.smallFile currFile = null;
+ // string fileContent = "";
+ // foreach (var item in fileList)
+ // {
+ // fileContent = System.IO.File.ReadAllText($"{dirPath}\\{item.Nome}");
+ // currFile = new MapoSDK.smallFile()
+ // {
+ // fileName = item.Nome,
+ // content = fileContent.Replace("\r\n", Environment.NewLine)
+ // };
+ // objFiles.fileList.Add(currFile);
+ // }
+ // // serializzo
+ // answ = JsonConvert.SerializeObject(objFiles);
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in uploadFile{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Restituisce il valore dello stato di IDLE della macchina, quindi SOLO SE NON é in lavoro
+ ///// e già convertito in minuti...
+ ///// GET: IOB/getIdlePeriod/SIMUL_01
+ /////
+ /////
+ /////
+ //public int getIdlePeriod(string id)
+ //{
+ // // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il
+ // // carattere "|" che poi trasformiamo ora in "#"
+ // id = id.Replace("|", "#");
+ // int answ = 0;
+ // DataLayer DataLayerObj = new DataLayer();
+ // DS_applicazione.StatoMacchineDataTable currData = null;
+ // // chiamo metodo redis/db...
+ // try
+ // {
+ // currData = DataLayerObj.currSMTab(id);
+ // if (currData.Count > 0)
+ // {
+ // // recupero da redis elenco stati
+ // DS_applicazione.AnagraficaStatiDataTable anagStati = DataLayerObj.AnagraficaStati();
+ // DS_applicazione.AnagraficaStatiRow currStato = anagStati.FindByIdxStato(currData[0].IdxStato);
+ // // calcolo SE sia idle... OVVERO SEMAFORO NON VERDE!!!
+ // if (currStato.Semaforo != "sVe")
+ // {
+ // // calcolo durata...
+ // answ = (int)DateTime.Now.Subtract(currData[0].InizioStato).TotalMinutes;
+ // }
+ // }
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Eccezione in recupero getIdlePeriod{Environment.NewLine}{exc}", tipoLog.EXCEPTION);
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Restituisce il (primo) codice IOB da dover gestire (se un IOBMAN chiede di gestirne uno
+ ///// in +...)
+ /////
+ ///// IP del Gateway
+ /////
+ //public string getIob2call(string GWIP)
+ //{
+ // string answ = "";
+
+ // // !!!FARE!!! temporanemanete genera a caso vuoto o 3000 x permettere test... altrimenti
+ // // gestisce VERA coda... secondi pari...
+ // int resto = 0;
+ // Math.DivRem(DateTime.Now.Second, 2, out resto);
+ // if (resto == 0)
+ // {
+ // answ = "3000";
+ // }
+
+ // return answ;
+ //}
+
+ /////
+ ///// Recupera elenco articoli USATI per ultimi:
+ ///// - quelli dei PODL correnti
+ ///// - quelli degli ultimi n (DOSS_LastArt in config) ODL lavorati
+ /////
+ ///// GET: IOB/getArtByMacc
+ /////
+ ///// Json contenente lista oggetti ARTICOLI serializzati
+ //public string getLastArtByMacc(string id)
+ //{
+ // string answ = "";
+
+ // // init obj DataLayer
+ // DataLayer DataLayerObj = new DataLayer();
+ // try
+ // {
+ // // recupero dati macchina...
+ // var elencoArt = DataLayerObj.taAnagArt.getLastByMacc(id);
+
+ // answ = JsonConvert.SerializeObject(elencoArt);
+ // }
+ // catch
+ // { }
+ // return answ;
+ //}
+
+ /////
+ ///// Recupera DATI dell'ultimo dossier dato articolo:
+ /////
+ ///// GET: IOB/getLastDossArt/cod_articolo
+ /////
+ ///// codice articolo, se vuoto --> non fa nulla
+ ///// Json contenente lista oggetti DOSSIER serializzati
+ //public string getLastDossArt(string id)
+ //{
+ // string answ = "";
+ // // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il
+ // // carattere "|" che poi trasformiamo ora in "#"
+ // if (string.IsNullOrEmpty(id))
+ // {
+ // answ = "N.A.";
+ // }
+ // else
+ // {
+ // id = id.Replace("|", "#");
+
+ // // init obj DataLayer
+ // DataLayer DataLayerObj = new DataLayer();
+ // try
+ // {
+ // // recupero dati macchina...
+ // var elencoDoss = DataLayerObj.taDOSS.getLastByArt(id);
+
+ // answ = JsonConvert.SerializeObject(elencoDoss);
+ // }
+ // catch
+ // { }
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Recupera DATI dell'ultimo dossier dato articolo:
+ /////
+ ///// GET: IOB/getLastDossArt/cod_articolo
+ /////
+ ///// codice articolo, se vuoto --> non fa nulla
+ ///// Json contenente lista oggetti DOSSIER serializzati
+ //public string getLastDossByMacc(string id)
+ //{
+ // string answ = "";
+ // // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il
+ // // carattere "|" che poi trasformiamo ora in "#"
+ // if (string.IsNullOrEmpty(id))
+ // {
+ // answ = "N.A.";
+ // }
+ // else
+ // {
+ // id = id.Replace("|", "#");
+
+ // // init obj DataLayer
+ // DataLayer DataLayerObj = new DataLayer();
+ // try
+ // {
+ // // recupero dati macchina...
+ // var elencoDoss = DataLayerObj.taDOSS.getLastByMacc(id);
+
+ // answ = JsonConvert.SerializeObject(elencoDoss);
+ // }
+ // catch
+ // { }
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Recupera DATI dell'ultimo dossier dato PODL correnti:
+ /////
+ ///// GET: IOB/getLastDossPODL
+ /////
+ ///// Json contenente lista oggetti DOSSIER serializzati
+ //public string getLastDossPODL()
+ //{
+ // string answ = "";
+
+ // // init obj DataLayer
+ // DataLayer DataLayerObj = new DataLayer();
+ // try
+ // {
+ // // recupero dati macchina...
+ // var elencoDoss = DataLayerObj.taDOSS.getLastByPODL();
+
+ // answ = JsonConvert.SerializeObject(elencoDoss);
+ // }
+ // catch
+ // { }
+ // return answ;
+ //}
+
+ /////
+ ///// Recupera elenco ListValues data tabella:
+ /////
+ ///// GET: IOB/getListValByTable
+ /////
+ ///// nome tabella x cui filtrare risultati, se "" mostra tutto
+ ///// Json contenente lista oggetti ListValue serializzati
+ //public string getListValByTable(string id)
+ //{
+ // string answ = "";
+
+ // // init obj DataLayer
+ // DataLayer DataLayerObj = new DataLayer();
+ // try
+ // {
+ // // recupero dati macchina...
+ // var elencoOdl = DataLayerObj.taListVal.getByTableField(id, "*");
+ // answ = JsonConvert.SerializeObject(elencoOdl);
+ // }
+ // catch
+ // { }
+ // return answ;
+ //}
+
+ /////
+ ///// Restituisce dati di associazione tra macchina, device IOB chiamante e sue info
+ /////
+ ///// Id della macchina
+ /////
+ //public string getM2IOB(string id)
+ //{
+ // string answ = "";
+ // try
+ // {
+ // // recupero da redis...
+ // string hM2IOB = DataLayer.hM2IOB(id);
+ // string dataSer = memLayer.ML.getRSV(hM2IOB);
+ // if (dataSer != "" && dataSer != null)
+ // {
+ // // restituisco Json
+ // answ = dataSer;
+ // }
+ // else
+ // {
+ // answ = "NO";
+ // }
+ // }
+ // catch
+ // {
+ // answ = "KO";
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// restituisce elenco parametri correnti come una List Json di oggetti objItem
+ ///// GET: IOB/getObjItems/SIMUL_03
+ /////
+ ///// ID dell'IOB
+ /////
+ //public string getObjItems(string id)
+ //{
+ // string answ = "";
+ // if (string.IsNullOrWhiteSpace(id))
+ // {
+ // answ = "Missing IOB";
+ // }
+ // else
+ // {
+ // // procedo a recuperare l'oggetto...
+ // List currParams = new List();
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // // deserializzo
+ // currParams = DataLayerObj.getCurrObjItems(id);
+ // // se != null --> salvo!
+ // if (currParams != null)
+ // {
+ // answ = JsonConvert.SerializeObject(currParams);
+ // }
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in getObjItems{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// restituisce elenco parametri CHE RICHIEDONO scrittura su PLC come una List Json di
+ ///// oggetti objItem
+ ///// GET: IOB/getObjItems2Write/SIMUL_03
+ /////
+ ///// ID dell'IOB
+ /////
+ //public string getObjItems2Write(string id)
+ //{
+ // string answ = "";
+ // if (string.IsNullOrWhiteSpace(id))
+ // {
+ // answ = "Missing IOB";
+ // }
+ // else
+ // {
+ // // procedo a recuperare l'oggetto...
+ // List currParams = new List();
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // // deserializzo
+ // currParams = DataLayerObj.getCurrObjItemsPendigWrite(id);
+ // // se != null --> salvo!
+ // if (currParams != null)
+ // {
+ // answ = JsonConvert.SerializeObject(currParams);
+ // }
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in getCurrParams{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Recupera ODL x macchina e data, se + di 1 quello di durata maggiore:
+ /////
+ ///// GET: IOB/getOdlAtDate/SIMUL_03
+ /////
+ ///// IdxMacchina
+ ///// DataRiferimento, formato yyyyMMdd (8 cifre)
+ /////
+ //public string getOdlAtDate(string id, string dateRif)
+ //{
+ // string answ = "";
+ // // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il
+ // // carattere "|" che poi trasformiamo ora in "#"
+ // id = id.Replace("|", "#");
+ // // converto la data in formato dateTime... e ottengo intervallo data indicata da
+ // // mezzanotte a 23:59:59...
+ // CultureInfo provider = CultureInfo.InvariantCulture;
+ // DateTime dtFrom = DateTime.Today;
+ // bool fatto = DateTime.TryParseExact(dateRif, "yyyyMMdd", provider, DateTimeStyles.None, out dtFrom);
+ // if (fatto)
+ // {
+ // // data fine giorno dopo
+ // DateTime dtTo = dtFrom.AddDays(1);
+ // // cerco ODL alla data (validi)
+ // DataLayer DataLayerObj = new DataLayer();
+ // DS_ProdTempi.ODLDataTable odlList = DataLayerObj.taODL.getByMacchinaPeriodoNoNull(id, dtFrom, dtTo);
+ // // se non trovo aumento ricerca all'indietro...
+ // int maxTry = 14;
+ // while (odlList.Count == 0 && maxTry > 0)
+ // {
+ // dtFrom = dtFrom.AddDays(-1);
+ // odlList = DataLayerObj.taODL.getByMacchinaPeriodoNoNull(id, dtFrom, dtTo);
+ // maxTry++;
+ // }
+ // int idxOdl = 0;
+ // // se > 1 --> prendo il + durevole
+ // if (odlList.Count > 1)
+ // {
+ // double maxPeriod = 0;
+ // foreach (var item in odlList)
+ // {
+ // DateTime dtStart = item.DataInizio > dtFrom ? item.DataInizio : dtFrom;
+ // DateTime dtEnd = item.DataFine < dtTo ? item.DataFine : dtTo;
+ // double currPeriod = dtEnd.Subtract(dtStart).TotalMinutes;
+ // if (currPeriod > maxPeriod)
+ // {
+ // maxPeriod = currPeriod;
+ // idxOdl = item.IdxODL;
+ // }
+ // }
+ // }
+ // else if (odlList.Count == 1)
+ // {
+ // idxOdl = odlList[0].IdxODL;
+ // }
+ // else
+ // {
+ // // cerco ODL prendendo qualche gg prima...
+ // }
+ // // conversione!
+ // answ = $"{idxOdl}";
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Recupera TASK richiesto x macchina:
+ /////
+ ///// GET: IOB/getOptPar/SIMUL_03
+ /////
+ /////
+ ///// Json contenente 1..n task da eseguire
+ //public string getOptPar(string id)
+ //{
+ // string answ = "";
+ // // scrivo keep alive!!! (se necessario, altrimenti è in cache...)
+ // MapoDb.MapoDb connDb = new MapoDb.MapoDb();
+ // connDb.scriviKeepAlive(id, DateTime.Now);
+ // try
+ // {
+ // // leggo da REDIS eventuale elenco task x macchina...
+ // DataLayer DataLayerObj = new DataLayer();
+ // Dictionary valori = DataLayerObj.mOptParMacchina(id);
+ // answ = JsonConvert.SerializeObject(valori);
+ // }
+ // catch
+ // { }
+ // return answ;
+ //}
+
+ /////
+ ///// Recupera TASK richiesto x macchina:
+ /////
+ ///// GET: IOB/getTask2Exe/SIMUL_03
+ /////
+ /////
+ ///// Json contenente 1..n task da eseguire
+ //public string getTask2Exe(string id)
+ //{
+ // string answ = "";
+ // // scrivo keep alive!!! (se necessario, altrimenti è in cache...)
+ // MapoDb.MapoDb connDb = new MapoDb.MapoDb();
+ // DataLayer DataLayerObj = new DataLayer();
+ // connDb.scriviKeepAlive(id, DateTime.Now);
+ // try
+ // {
+ // // leggo da REDIS eventuale elenco task x macchina...
+ // Dictionary valori = DataLayerObj.mTaskMacchina(id);
+ // answ = JsonConvert.SerializeObject(valori);
+ // }
+ // catch
+ // { }
+ // return answ;
+ //}
+
+ //// GET: IOB (è un check alive del server)
+ //public string Index()
+ //{
+ // if (memLayer.ML.CRB("IOB_RedEnab"))
+ // {
+ // // conto la richiesta nel contatore REDIS
+ // long nCall = memLayer.ML.setRCntI(DataLayer.mHash("COUNT:pCall:IOB_INDEX"));
+ // //... se == nCall2Log scrivo su log e resetto
+ // long nCall2Log = memLayer.ML.cdvi("nCall2Log");
+ // if (nCall >= nCall2Log)
+ // {
+ // // loggo
+ // logger.lg.scriviLog(string.Format("IOB_INDEX: effettuate {0} call", nCall), tipoLog.INFO);
+ // // resetto!
+ // memLayer.ML.resetRCnt(DataLayer.mHash("COUNT:pCall:IOB_INDEX"));
+ // }
+ // }
+ // return "OK";
+ //}
+
+ //// GET: IOB/input/SIMUL_03?valore=3&dtEve=20181206180600000&dtCurr=20181206180600000&cnt=999
+ //public string input(string id, string valore, string dtEve, string dtCurr, string cnt)
+ //{
+ // string answ = "";
+ // // formato yyyymmddHHMMSSnnn ovvero da anno a millisecondi
+ // if (cnt == null)
+ // {
+ // cnt = "0";
+ // }
+
+ // DateTime dataOraEvento = DateTime.Now;
+ // if (memLayer.ML.CRI("_logLevel") > 6)
+ // {
+ // logger.lg.scriviLog($"Valori letti: idxMacchina: {id} | valore: {valore}", tipoLog.INFO);
+ // }
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // answ = DataLayerObj.processInput(id, valore, dtEve, dtCurr, cnt);
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog(string.Format("Errore in processInput{0}{1}", Environment.NewLine, exc));
+ // answ = "NO";
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Processa una chiamata POST per l'invio di un array Json di oggetti LIVE REC
+ ///// PUT: IOB/liveJson/SIMUL_03
+ /////
+ ///// ID dell'IOB
+ /////
+ //[HttpPost]
+ //public string liveJson(string id)
+ //{
+ // string answ = "-";
+ // // questa classe è derivata da Controller.Response... x cui recupero lo stream in altro modo...
+ // string content = "";
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // using (var reader = new StreamReader(
+ // Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true))
+ // {
+ // content = reader.ReadToEnd();
+ // }
+ // //Rest
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // // procedo a deserializzare in blocco l'oggetto...
+ // try
+ // {
+ // // deserializzo.
+ // liveIOB receivedData = JsonConvert.DeserializeObject(content);
+ // DataLayer DataLayerObj = new DataLayer();
+ // answ = DataLayerObj.processLiveJson(id, receivedData);
+ // // se vuoto --> OK!
+ // if (string.IsNullOrEmpty(answ))
+ // {
+ // answ = "OK 1 done";
+ // }
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in liveJson{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // return answ;
+ //}
+
+ //// GET: IOB/liveRec/SIMUL_03?&liveData=chiave1|valore1#chiave2|valore#|chiave3|valore3
+ //public string liveRec(string id, string liveData)
+ //{
+ // string answ = "";
+ // DateTime dataOraEvento = DateTime.Now;
+ // if (memLayer.ML.CRI("_logLevel") > 6)
+ // {
+ // logger.lg.scriviLog($"Valori Live:{Environment.NewLine}idxMacchina: {id}{Environment.NewLine}liveData: {liveData}", tipoLog.INFO);
+ // }
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // answ = DataLayerObj.processLiveRec(id, liveData);
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in liveRec{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Processa una chiamata POST per l'invio di un array Json di oggetti rawTransfer
+ ///// (generiche info da deserializzare)
+ ///// POST: IOB/rawTransfJson/SIMUL_03
+ /////
+ ///// ID dell'IOB
+ /////
+ //[HttpPost]
+ //public string rawTransfJson(string id)
+ //{
+ // int insDone = 0;
+ // string answ = "";
+ // // questa classe è derivata da Controller.Response... x cui recupero lo stream in altro modo...
+ // string content = "";
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // using (var reader = new StreamReader(
+ // Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true))
+ // {
+ // content = reader.ReadToEnd();
+ // }
+ // //Rest
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // // se ho dati...
+ // if (content != "")
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // MagDataLayer DataLayerMagObj = new MagDataLayer();
+ // // deserializzo come un dictionary generico di oggetti rawDataType/string
+ // List receivedData = new List();
+ // // procedo a deserializzare in blocco l'oggetto...
+ // try
+ // {
+ // // deserializzo.
+ // receivedData = JsonConvert.DeserializeObject>(content);
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in fase deserializzazione rawTransfJson{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // // se ho qualcosa da processare...
+ // if (receivedData != null)
+ // {
+ // try
+ // {
+ // foreach (var item in receivedData)
+ // {
+ // // per ora salvo su REDIS ultimo x tipo
+ // DataLayerObj.lastRawTrasfData = JsonConvert.SerializeObject(item.mesContent);
+
+ // // !!! FixMe ToDo fare deserializzazione e salvataggio su MongoDB
+ // // salvataggio su tab RawTrasf su DB IS
+
+ // // in base al tipo processo...
+ // switch (item.mesType)
+ // {
+ // case rawTransfType.IcoelBatch:
+ // break;
+
+ // case rawTransfType.IcoelVarInfo:
+ // break;
+
+ // case rawTransfType.RegGiacenze:
+ // // elenco ODL da svuotare preventivamente x insert...
+ // List listOdl = new List();
+ // // processo scrittura giacenze... processo 1:1 record di RegGiacenze
+ // List recData = new List();
+ // foreach (var singleRow in item.mesContent)
+ // {
+ // var listGiac = JsonConvert.DeserializeObject(singleRow.Value.ToString());
+ // recData.Add(listGiac);
+ // if (!listOdl.Contains(listGiac.IdxODL))
+ // {
+ // listOdl.Add(listGiac.IdxODL);
+ // }
+ // }
+ // // svuoto le giacenze degli ODL oggetto di import...
+ // bool fatto = DataLayerMagObj.resetRegGiacByOdl(listOdl);
+ // if (fatto)
+ // {
+ // // invio x salvare
+ // fatto = DataLayerMagObj.salvaRegGiac(recData);
+ // }
+ // break;
+
+ // case rawTransfType.ND:
+ // default:
+ // break;
+ // }
+ // insDone++;
+ // }
+ // // se vuoto --> OK!
+ // if (string.IsNullOrEmpty(answ))
+ // {
+ // answ = $"OK {insDone} processed";
+ // }
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in fase invio valori rawTransfJson{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // }
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// ELIMINA TASK richiesto x macchina:
+ /////
+ ///// GET: IOB/remOptPar/SIMUL_03?pName=PZREQ
+ /////
+ /////
+ /////
+ //public string remOptPar(string id, string pName)
+ //{
+ // string answ = "";
+ // // scrivo keep alive!!! (se necessario, altrimenti è in cache...)
+ // MapoDb.MapoDb connDb = new MapoDb.MapoDb();
+ // DataLayer DataLayerObj = new DataLayer();
+ // connDb.scriviKeepAlive(id, DateTime.Now);
+ // try
+ // {
+ // DataLayerObj.remOptPar4Machine(id, pName);
+ // answ = getOptPar(id);
+ // }
+ // catch
+ // { }
+ // return answ;
+ //}
+
+ /////
+ ///// ELIMINA TASK richiesto x macchina:
+ /////
+ ///// GET: IOB/remTask2Exe/SIMUL_03?taskName=T180326160502
+ /////
+ /////
+ /////
+ //public string remTask2Exe(string id, string taskName)
+ //{
+ // string answ = "";
+ // // scrivo keep alive!!! (se necessario, altrimenti è in cache...)
+ // MapoDb.MapoDb connDb = new MapoDb.MapoDb();
+ // DataLayer DataLayerObj = new DataLayer();
+ // connDb.scriviKeepAlive(id, DateTime.Now);
+ // try
+ // {
+ // // converto stringa in tipo task...
+ // taskType tName = taskType.nihil;
+ // bool fatto = Enum.TryParse(taskName, out tName);
+ // if (fatto)
+ // {
+ // DataLayerObj.remTask4Machine(id, tName);
+ // }
+ // else
+ // {
+ // logger.lg.scriviLog($"remTask2Exe: impossibile riconoscere il comando {taskName} come uno dei tipi ammessi, NON rimosso", tipoLog.ERROR);
+ // }
+ // answ = getTask2Exe(id);
+ // }
+ // catch
+ // { }
+ // return answ;
+ //}
+
+ /////
+ ///// Effettua RESET dell'ODL corrente x macchina:
+ /////
+ ///// GET: IOB/resetCurrODL/5
+ /////
+ /////
+ /////
+ //public string resetCurrODL(string id)
+ //{
+ // DataLayer DataLayerObj = new DataLayer();
+ // return DataLayerObj.emptyCurrODL(id);
+ //}
+
+ /////
+ ///// Processa una chiamata POST per l'invio di un array Json di oggetti plcMemConf
+ ///// PUT: IOB/saveConf/SIMUL_03
+ /////
+ ///// ID dell'IOB
+ /////
+ //[HttpPost]
+ //public string saveConf(string id)
+ //{
+ // string answ = "";
+ // if (string.IsNullOrWhiteSpace(id))
+ // {
+ // answ = "Missing IOB";
+ // }
+ // else
+ // {
+ // // questa classe è derivata da Controller.Response... x cui recupero lo stream in
+ // // altro modo...
+ // string content = "";
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // using (var reader = new StreamReader(Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true))
+ // {
+ // content = reader.ReadToEnd();
+ // }
+ // //Rest
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // // procedo a deserializzare in blocco l'oggetto...
+ // plcMemMap currMemMap = null;
+ // try
+ // {
+ // // deserializzo.
+ // currMemMap = JsonConvert.DeserializeObject(content);
+ // // se != null --> salvo!
+ // if (currMemMap != null)
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // DataLayerObj.setIobMemMap(id, currMemMap);
+ // answ = "OK";
+ // }
+ // }
+ // catch
+ // { }
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Processa una chiamata POST per l'invio di un array Json di oggetti di conf DataItems (es
+ ///// per MTC)
+ ///// PUT: IOB/saveDataItems/SIMUL_03
+ /////
+ ///// ID dell'IOB
+ /////
+ //[HttpPost]
+ //public string saveDataItems(string id)
+ //{
+ // string answ = "";
+ // logger.lg.scriviLog($"Richiesta saveDataItems per id {id}");
+ // if (string.IsNullOrWhiteSpace(id))
+ // {
+ // answ = "Missing IOB";
+ // }
+ // else
+ // {
+ // // questa classe è derivata da Controller.Response... x cui recupero lo stream in
+ // // altro modo...
+ // string content = "";
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // using (var reader = new StreamReader(Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true))
+ // {
+ // content = reader.ReadToEnd();
+ // }
+ // // Rest
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+
+ // // procedo a deserializzare in blocco l'oggetto...
+ // List dataItems = null;
+ // try
+ // {
+ // logger.lg.scriviLog($"Ricevuto payload di {content.Length} chars");
+ // // deserializzo.
+ // dataItems = JsonConvert.DeserializeObject>(content);
+ // // se != null --> salvo!
+ // if (dataItems != null)
+ // {
+ // // chiamo metodo update direttamente!
+ // MtcDataModelArchive.man.saveMachineDataItems(id, dataItems);
+ // answ = "OK";
+ // logger.lg.scriviLog($"Effettuato salvataggio saveDataItems per id {id}:{Environment.NewLine}{content}");
+ // }
+ // }
+ // catch
+ // { }
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// SALVA in blocco un incremento pezzi x macchina restituendo il valore appena inviato o,
+ ///// se mancasse chaive redis, del valore da DB
+ /////
+ ///// GET: IOB/savePzCountInc/5?qty=10
+ /////
+ ///// codice macchina
+ ///// num peziz da salvare in blocco
+ /////
+ //public string savePzCountInc(string id, string qty)
+ //{
+ // string answ = "";
+ // DateTime dataOraEvento = DateTime.Now;
+ // // salvo SEMPRE log x questo tipo di dati!
+ // logger.lg.scriviLog($"Salvataggio incremento contapezzi | idxMacchina: {id} | pezzi: {qty}", tipoLog.INFO);
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // answ = DataLayerObj.saveCaricoPezzi(id, qty);
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in savePzCountInc{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Registrazione variazione allarmi
+ /////
+ ///// GET: IOB/sendAlarmBankUpdate/SIMUL_03
+ /////
+ /////
+ /////
+ //[HttpPost]
+ //public string sendAlarmBankUpdate(string id, string memAddr, int index, int currStatus)
+ //{
+ // DataLayer DataLayerObj = new DataLayer();
+ // // esempio valido x MAPO
+ // string answ = "";
+ // logger.lg.scriviLog($"Richiesta sendAlarmBankUpdate per id {id}");
+ // if (string.IsNullOrWhiteSpace(id))
+ // {
+ // answ = "Missing IOB";
+ // }
+ // else
+ // {
+ // // questa classe è derivata da Controller.Response... x cui recupero lo stream in
+ // // altro modo...
+ // string content = "";
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // using (var reader = new StreamReader(Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true))
+ // {
+ // content = reader.ReadToEnd();
+ // }
+ // // Rest
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+
+ // // procedo a deserializzare in blocco l'oggetto...
+ // List ActiveAlarms = null;
+ // try
+ // {
+ // logger.lg.scriviLog($"Ricevuto payload di {content.Length} chars");
+ // // deserializzo.
+ // ActiveAlarms = JsonConvert.DeserializeObject>(content);
+ // // se != null --> salvo!
+ // if (ActiveAlarms != null)
+ // {
+ // string alarmDecoded = "-";
+ // if (ActiveAlarms != null && ActiveAlarms.Count > 0)
+ // {
+ // alarmDecoded = String.Join(" | ", ActiveAlarms);
+ // }
+ // DataLayerObj.taAlarmLog.insertQuery(DateTime.Now, id, memAddr, index, currStatus, alarmDecoded);
+ // answ = "OK";
+ // }
+ // }
+ // catch
+ // { }
+ // }
+ // return answ;
+
+ // // esempio GWMS
+ //}
+
+ ///// Salva MAC adress + IP dopo il reboot
+ ///// GET: IOB/sendReboot?idxMacchina=5&mac=18:C0:4D:37:3C:8C IP
+ ///// del Gateway
+ //public string sendReboot(string idxMacchina, string mac)
+ //{
+ // string answ = "NO";
+ // string IPv4 = "";
+ // string agent = "";
+ // try
+ // {
+ // // recupero IP del client remoto
+ // IPv4 = Request.UserHostName;
+ // agent = Request.UserAgent;
+ // }
+ // catch
+ // { }
+ // try
+ // {
+ // // ora salvo che la macchina è stata (ri)avviata...
+ // MapoDb.MapoDb MapoDbObj = new MapoDb.MapoDb();
+ // MapoDbObj.registraStartup(idxMacchina, IPv4, agent, mac);
+ // answ = "OK";
+ // }
+ // catch (Exception exc)
+ // {
+ // if (memLayer.ML.CRI("_logLevel") > 5)
+ // {
+ // string errore = string.Format("Errore: {0}{1}", Environment.NewLine, exc);
+ // logger.lg.scriviLog(errore, tipoLog.EXCEPTION);
+ // }
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Salva IP del gateway dopo il reboot
+ /////
+ ///// IP del Gateway
+ /////
+ //public string sendRebootGateway(string GWIP)
+ //{
+ // string answ = "OK";
+
+ // // !!!FARE!!! deve salvare il riavvio dell'applicazione GATEWAY multiclient
+
+ // return answ;
+ //}
+
+ /////
+ ///// SALVA Counter x macchina restituendo il valore appena inviato o, se mancasse chiave
+ ///// redis, del valore da DB
+ /////
+ ///// GET: IOB/setCounter/5?counter=10
+ /////
+ ///// cod macchina
+ ///// contapezzi da salvare
+ /////
+ //public string setCounter(string id, string counter)
+ //{
+ // string answ = "-1";
+ // DateTime dataOraEvento = DateTime.Now;
+ // if (memLayer.ML.CRI("_logLevel") > 6)
+ // {
+ // logger.lg.scriviLog($"Salvataggio counter | idxMacchina: {id}", tipoLog.INFO);
+ // }
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // answ = DataLayerObj.saveCounter(id, counter);
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog(string.Format("Errore in counter (set){0}{1}", Environment.NewLine, exc));
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Salva associazione tra macchina, device IOB chiamante e sue info
+ /////
+ ///// Id della macchina
+ ///// Nome dell'IOB di acquisizione della macchina
+ /////
+ //public string setM2IOB(string id, string IOB_name)
+ //{
+ // string answ = "";
+ // try
+ // {
+ // // recupero IP del client remoto
+ // string IPv4 = Request.UserHostName;
+ // string agent = Request.UserAgent;
+ // // creo oggetto IOB_data...
+ // IOB_data m2IOB = new IOB_data
+ // {
+ // name = IOB_name,
+ // IP = IPv4,
+ // iType = IobType.ND,
+ // typeCss = "fa fa-question-circle-o",
+ // CNC_Counter = false
+ // };
+ // // imposto tipo ed icona come windows/linux secondo UserAgent...
+ // if (agent.IndexOf("WIN") >= 0)
+ // {
+ // m2IOB.iType = IobType.WIN;
+ // m2IOB.typeCss = "fa fa-windows";
+ // m2IOB.CNC_Counter = true;
+ // }
+ // else if (agent.IndexOf("Python") >= 0)
+ // {
+ // m2IOB.iType = IobType.rPi;
+ // m2IOB.typeCss = "fa fa-linux";
+ // }
+ // // serializzo...
+ // string dataSer = JsonConvert.SerializeObject(m2IOB);
+ // // salvo in redis...
+ // string hM2IOB = DataLayer.hM2IOB(id);
+ // memLayer.ML.setRSV(hM2IOB, dataSer);
+ // // salvo tutto OK
+ // answ = "OK";
+ // }
+ // catch
+ // {
+ // answ = "KO";
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Processa una chiamata POST per l'invio di una List Json di oggetti objItem
+ ///// POST: IOB/setObjItems/SIMUL_03
+ /////
+ ///// ID dell'IOB
+ /////
+ //[HttpPost]
+ //public string setObjItems(string id)
+ //{
+ // string answ = "";
+ // if (string.IsNullOrWhiteSpace(id))
+ // {
+ // answ = "Missing IOB";
+ // }
+ // else
+ // {
+ // // questa classe è derivata da Controller.Response... x cui recupero lo stream in
+ // // altro modo...
+ // string content = "";
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // using (var reader = new StreamReader(Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true))
+ // {
+ // content = reader.ReadToEnd();
+ // }
+ // //Rest
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // // procedo a deserializzare in blocco l'oggetto...
+ // List currParams = new List();
+ // try
+ // {
+ // // deserializzo.
+ // currParams = JsonConvert.DeserializeObject>(content);
+ // // se != null --> salvo!
+ // if (currParams != null)
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // bool fatto = DataLayerObj.setCurrObjItems(id, currParams);
+ // answ = fatto ? "OK" : "KO";
+ // }
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in setCurrParams{Environment.NewLine}{exc}");
+ // answ = "EXC";
+ // }
+ // }
+ // return answ;
+ //}
+
+ //// GET: IOB/slog/SIMUL_03
+ //public string slog(string id)
+ //{
+ // string answ = "ND";
+ // // se id nullo --> KO!
+ // if (id == null)
+ // {
+ // answ = "KO";
+ // }
+ // else
+ // {
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // // salvo risposta
+ // answ = DataLayerObj.sLogEnab(id) ? "OK" : "NO";
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog(string.Format("Errore in sLog{0}{1}", Environment.NewLine, exc));
+ // answ = "NO";
+ // }
+ // }
+ // return answ;
+ //}
+
+ //// GET: IOB/takeFlogSnapshot/SIMUL_03
+ //public string takeFlogSnapshot(string id)
+ //{
+ // string answ = "";
+ // string caller = $"takeFlogSnapshot({id})";
+
+ // DateTime adesso = DateTime.Now;
+ // DateTime dtEnd = adesso;
+ // DateTime dtStart = adesso.AddDays(-1);
+ // //effettuo chiamata!
+ // answ = doSaveFLSnapshot(id, dtStart, dtEnd, caller);
+ // return answ;
+ //}
+
+ //// GET: IOB/ulog/SIMUL_03?flux=PROG&valore=P0001&dtEve=20161223180600000&dtCurr=20161223180600000&cnt=999&matrOpr=0=0&label=&valNum
+ //public string ulog(string id, string flux, string valore, string dtEve, string dtCurr, string cnt, string matrOpr, string label, string valNum)
+ //{
+ // string answ = "";
+ // // formato yyyymmddHHMMSSnnn ovvero da anno a millisecondi
+ // if (cnt == null)
+ // {
+ // cnt = "0";
+ // }
+
+ // DateTime dataOraEvento = DateTime.Now;
+ // if (memLayer.ML.CRI("_logLevel") > 6)
+ // {
+ // logger.lg.scriviLog($"ulog | Valori letti: idxMacchina: {id} | flux: {flux} valore: {valore} | matrOpr: {matrOpr} | label: {label} | valNum: {valNum}", tipoLog.INFO);
+ // }
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // int count = 0;
+ // int nMatrOpr = 0;
+ // int nValNum = 0;
+ // Int32.TryParse(cnt, out count);
+ // Int32.TryParse(matrOpr, out nMatrOpr);
+ // Int32.TryParse(valNum, out nValNum);
+ // answ = DataLayerObj.processUserLog(id, flux, valore, dtEve, dtCurr, count, nMatrOpr, label, nValNum);
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in ulog{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Processa una chiamata POST per l'invio di una List Json 1+ UserAction (contiene
+ ///// controlli, scarti, dichiarazioni)
+ ///// POST: IOB/ulogJson/SIMUL_03
+ /////
+ ///// ID dell'IOB
+ /////
+ //[HttpPost]
+ //public string ulogJson(string id)
+ //{
+ // int insDone = 0;
+ // string answ = "-";
+ // // questa classe è derivata da Controller.Response... x cui recupero lo stream in altro modo...
+ // string content = "";
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // using (var reader = new StreamReader(
+ // Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true))
+ // {
+ // content = reader.ReadToEnd();
+ // }
+ // //Rest
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // // se ho dati...
+ // if (content != "")
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // // procedo a deserializzare in blocco l'oggetto...
+ // ulogJsonPayload receivedData = new ulogJsonPayload();
+ // try
+ // {
+ // // deserializzo.
+ // receivedData = JsonConvert.DeserializeObject(content);
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in fase deserializzazione ulogJson{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // // se ho qualcosa da processare...
+ // if (receivedData != null)
+ // {
+ // // per ogni valore --> salvo!
+ // try
+ // {
+ // foreach (var item in receivedData.fluxData)
+ // {
+ // // formato datetime come yyyyMMddHHmmssfff -->es: 20181223180600000
+ // answ = DataLayerObj.processUserLog(id, item.flux, item.valore, item.dtEve.ToString("yyyyMMddHHmmssfff"), item.dtCurr.ToString("yyyyMMddHHmmssfff"), item.cnt, item.matrOpr, item.label, item.valNum);
+ // }
+ // // se vuoto --> OK!
+ // if (string.IsNullOrEmpty(answ))
+ // {
+ // answ = $"OK {insDone} processed";
+ // }
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in fase invio valori ulogJson{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // }
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Processa una chiamata POST per l'invio di un SET di file "a nome" di un IOB, formato MapoSDK.fileEmbed
+ ///// PUT: IOB/uploadFile/SIMUL_03
+ /////
+ ///// ID dell'IOB
+ /////
+ //[HttpPost]
+ //public string uploadFile(string id)
+ //{
+ // string answ = "";
+ // // questa classe è derivata da Controller.Response... x cui recupero lo stream in altro modo...
+ // string content = "";
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // using (var reader = new StreamReader(Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true))
+ // {
+ // content = reader.ReadToEnd();
+ // }
+ // //Rest
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // // procedo a deserializzare in blocco l'oggetto...
+ // try
+ // {
+ // // deserializzo.
+ // fileEmbed receivedData = JsonConvert.DeserializeObject(content);
+ // // salvo nella cartella di Upload...
+ // string basePath = Server.MapPath(memLayer.ML.CRS("uploadFileDir"));
+ // string dirPath = $"{basePath}\\{id}";
+ // // fix directory...
+ // Directory.CreateDirectory(dirPath);
+ // foreach (var item in receivedData.fileList)
+ // {
+ // // scrivo!
+ // System.IO.File.WriteAllText($"{dirPath}\\{item.fileName}", item.content);
+ // }
+ // answ = "OK";
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in uploadFile{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Processa una chiamata POST per l'invio di una List Json di UNO O PIU' oggetti objItem
+ ///// POST: IOB/upsertObjItems/SIMUL_03
+ /////
+ ///// ID dell'IOB
+ /////
+ //[HttpPost]
+ //public string upsertObjItems(string id)
+ //{
+ // string answ = "";
+ // if (string.IsNullOrWhiteSpace(id))
+ // {
+ // answ = "Missing IOB";
+ // }
+ // else
+ // {
+ // // questa classe è derivata da Controller.Response... x cui recupero lo stream in
+ // // altro modo...
+ // string content = "";
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // using (var reader = new StreamReader(Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true))
+ // {
+ // content = reader.ReadToEnd();
+ // }
+ // //Rest
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // // procedo a deserializzare in blocco l'oggetto...
+ // List innovazioni = new List();
+ // try
+ // {
+ // // deserializzo.
+ // innovazioni = JsonConvert.DeserializeObject>(content);
+ // // se != null --> salvo!
+ // if (innovazioni != null)
+ // {
+ // // salvo
+ // DataLayer DataLayerObj = new DataLayer();
+ // DataLayerObj.upsertCurrObjItems(id, innovazioni);
+ // answ = "OK";
+ // }
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in upsertObjItems{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // }
+ // return answ;
+ //}
+
+ #endregion Public Methods
+
+ #region Private Methods
+
+ /////
+ ///// Effettua vera chiamata x salvataggio snapshot dati FluxLog
+ /////
+ /////
+ /////
+ /////
+ /////
+ //private static string doSaveFLSnapshot(string id, DateTime dtStart, DateTime dtEnd, string caller)
+ //{
+ // string answ;
+ // DateTime dataOraEvento = DateTime.Now;
+ // if (memLayer.ML.CRI("_logLevel") > 6)
+ // {
+ // logger.lg.scriviLog($"{caller} | Richiesta snapshot dati FluxLog macchina: idxMacchina: {id} | periodo: {dtStart} - {dtEnd}", tipoLog.INFO);
+ // }
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // answ = DataLayerObj.takeFlogSnapshotLast(id, dtStart, dtEnd);
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in {caller}{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+
+ // return answ;
+ //}
+
+ #endregion Private Methods
+ }
+}
diff --git a/MP.IOC/Controllers/RecipeController.cs b/MP.IOC/Controllers/RecipeController.cs
new file mode 100644
index 00000000..e245c688
--- /dev/null
+++ b/MP.IOC/Controllers/RecipeController.cs
@@ -0,0 +1,73 @@
+using Microsoft.AspNetCore.Mvc;
+using MP.IOC.Data;
+using Newtonsoft.Json;
+using NLog;
+using System.Xml;
+
+namespace MP.IOC.Controllers
+{
+ [Route("api/[controller]")]
+ [ApiController]
+ public class RecipeController : ControllerBase
+ {
+ #region Public Constructors
+
+ public RecipeController(IConfiguration configuration, MpDataService DataService)
+ {
+ Log.Info("Starting RecipeController");
+ _configuration = configuration;
+ DService = DataService;
+ Log.Info("Avviata RecipeController");
+ }
+
+ #endregion Public Constructors
+
+ #region Public Methods
+
+ [HttpGet("GetRecipe")]
+ public async Task GetRecipe(int idxPODL)
+ {
+ string answ = "";
+ var reqRecipe = await DService.RecipeGetByPODL(idxPODL);
+ if (reqRecipe != null)
+ {
+ answ = DService.CalcRecipe(reqRecipe);
+ }
+ return answ;
+ }
+
+ [HttpGet("GetRecipeXML")]
+ public async Task GetRecipeXML(int idxPODL)
+ {
+ // aggiungo root node?
+ string answ = "";
+ // recupero versione json
+ string rawData = await GetRecipe(idxPODL);
+ if (!string.IsNullOrEmpty(rawData))
+ {
+ XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(rawData);
+ answ += doc.InnerXml;
+ }
+ return answ;
+ }
+
+ #endregion Public Methods
+
+ #region Protected Properties
+
+ ///
+ /// Dataservice x accesso DB
+ ///
+ protected MpDataService DService { get; set; }
+
+ #endregion Protected Properties
+
+ #region Private Fields
+
+ private static IConfiguration _configuration = null!;
+
+ private static Logger Log = LogManager.GetCurrentClassLogger();
+
+ #endregion Private Fields
+ }
+}
\ No newline at end of file
diff --git a/MP.IOC/Data/MpDataService.cs b/MP.IOC/Data/MpDataService.cs
new file mode 100644
index 00000000..a9cb16bf
--- /dev/null
+++ b/MP.IOC/Data/MpDataService.cs
@@ -0,0 +1,2131 @@
+using MP.Data;
+using MP.Data.Conf;
+using MP.Data.DatabaseModels;
+using MP.Data.DTO;
+using MP.Data.MgModels;
+using Newtonsoft.Json;
+using NLog;
+using StackExchange.Redis;
+using System.Data;
+using System.Diagnostics;
+
+namespace MP.IOC.Data
+{
+ public class MpDataService : IDisposable
+ {
+ #region Public Constructors
+
+ public MpDataService(IConfiguration configuration, ILogger logger)
+ {
+ _logger = logger;
+ _logger.LogInformation("Starting MpDataService INIT");
+ _configuration = configuration;
+
+ // setup compoenti REDIS
+ redisConn = ConnectionMultiplexer.Connect(_configuration.GetConnectionString("Redis"));
+ redisConnAdmin = ConnectionMultiplexer.Connect(_configuration.GetConnectionString("RedisAdmin"));
+ redisDb = redisConn.GetDatabase();
+ BroadastMsgPipe = new MessagePipe(redisConn, Constants.BROADCAST_M_PIPE);
+ // leggo cache lungo periodo
+ int.TryParse(_configuration.GetValue("ServerConf:redisLongTimeCache"), out redisLongTimeCache);
+
+ _logger.LogInformation("Redis INIT");
+
+ // conf DB
+ string connStr = _configuration.GetConnectionString("Mp.Data");
+ if (string.IsNullOrEmpty(connStr))
+ {
+ _logger.LogError("DbController: ConnString empty!");
+ }
+ else
+ {
+ SpecDbController = new MP.Data.Controllers.MpSpecController(configuration);
+ IocDbController = new MP.Data.Controllers.MpIocController(configuration);
+ _logger.LogInformation("DbControllers INIT OK");
+ }
+
+ // conf mongo...
+ connStr = _configuration.GetConnectionString("MongoConnect");
+ if (string.IsNullOrEmpty(connStr))
+ {
+ _logger.LogError("MongoController: ConnString empty!");
+ }
+ else
+ {
+ mongoController = new MP.Data.Controllers.MpMongoController(configuration);
+ _logger.LogInformation("MongoController INIT OK");
+ }
+ }
+
+ #endregion Public Constructors
+
+ #region Public Properties
+
+ public static MP.Data.Controllers.MpIocController IocDbController { get; set; } = null!;
+
+ public static MP.Data.Controllers.MpMongoController mongoController { get; set; } = null!;
+
+ public static MP.Data.Controllers.MpSpecController SpecDbController { get; set; } = null!;
+
+ public MessagePipe BroadastMsgPipe { get; set; } = null!;
+
+ ///
+ /// Dizionario dei tag configurati per IOB
+ ///
+ public Dictionary> currTagConf { get; set; } = new Dictionary>();
+
+ #endregion Public Properties
+
+ #region Public Methods
+
+ ///
+ /// Recupera eventuali azioni richieste
+ ///
+ ///
+ public async Task ActionGetReq()
+ {
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ DisplayAction? result = null;
+ // cerco in redis...
+ RedisValue rawData = await redisDb.StringGetAsync(Utils.redisActionReq);
+ if (!string.IsNullOrEmpty($"{rawData}"))
+ {
+ result = JsonConvert.DeserializeObject($"{rawData}");
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"ActionGetReq Read from REDIS: {ts.TotalMilliseconds}ms");
+ }
+ if (result == null)
+ {
+ result = new DisplayAction();
+ }
+ return result;
+ }
+
+ ///
+ /// Salva richiesta azione
+ ///
+ ///
+ ///
+ public bool ActionSetReq(DisplayAction? act2save)
+ {
+ bool fatto = false;
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ // cerco in redis...
+ string rawData = JsonConvert.SerializeObject(act2save);
+ // invio broadcast + salvo in redis
+ BroadastMsgPipe.saveAndSendMessage(Utils.redisActionReq, rawData);
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"ActionSetReq REDIS send to broadcast + Write cache: {ts.TotalMilliseconds}ms");
+ return fatto;
+ }
+
+ ///
+ /// Aggiunge un PARAMETRO OPZIONALE all'elenco di quelli salvati (in modalità upsert)
+ ///
+ ///
+ ///
+ ///
+ ///
+ public bool AddOptPar4Machine(string idxMacchina, string taskKey, string taskVal)
+ {
+ bool answ = false;
+ RedisKey currHash = Utils.OptParHash(idxMacchina);
+ try
+ {
+ // leggo task attuali...
+ var currVal = mOptParMacchina(idxMacchina);
+ currVal[taskKey] = taskVal;
+ answ = RedisSetHashDict(currHash, currVal);
+ }
+ catch (Exception exc)
+ {
+ Log.Error($"Eccezione in addOptPar4Machine{Environment.NewLine}{exc}");
+ }
+ return answ;
+ }
+
+ public async Task> AnagStatiComm()
+ {
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ List? result = new List();
+ // cerco in redis...
+ RedisValue rawData = await redisDb.StringGetAsync(Utils.redisStatoCom);
+ if (!string.IsNullOrEmpty($"{rawData}"))
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"AnagStatiComm Read from REDIS: {ts.TotalMilliseconds}ms");
+ }
+ else
+ {
+ result = await Task.FromResult(SpecDbController.AnagStatiComm());
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ await redisDb.StringSetAsync(Utils.redisStatoCom, rawData, getRandTOut(redisLongTimeCache));
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"AnagStatiComm Read from DB: {ts.TotalMilliseconds}ms");
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ return result;
+ }
+
+ public async Task> AnagTipoArtLV()
+ {
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string source = "DB";
+ List? result = new List();
+ // cerco in redis...
+ RedisValue rawData = await redisDb.StringGetAsync(Utils.redisTipoArt);
+ if (!string.IsNullOrEmpty($"{rawData}"))
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ source = "REDIS";
+ }
+ else
+ {
+ result = await Task.FromResult(SpecDbController.AnagTipoArtLV());
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ await redisDb.StringSetAsync(Utils.redisTipoArt, rawData, getRandTOut(redisLongTimeCache));
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"AnagTipoArtLV Read from {source}: {ts.TotalMilliseconds}ms");
+ if (result == null)
+ {
+ result = new List();
+ }
+ return result;
+ }
+
+ ///
+ /// Elenco Codice articolo con dati dossier gestiti
+ ///
+ ///
+ public async Task> ArticleWithDossier()
+ {
+ List? result = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = Utils.redisArtByDossier;
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ readType = "REDIS";
+ }
+ else
+ {
+ result = await Task.FromResult(SpecDbController.ArticleWithDossier());
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, getRandTOut(redisLongTimeCache));
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"ArticleWithDossier | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Eliminazione record selezionato
+ ///
+ ///
+ ///
+ public async Task ArticoliDeleteRecord(AnagArticoli currRec)
+ {
+ bool fatto = await SpecDbController.ArticoliDeleteRecord(currRec);
+ await resetCacheArticoli();
+ return fatto;
+ }
+
+ ///
+ /// Restitusice elenco articoli cercati
+ ///
+ ///
+ ///
+ ///
+ public async Task> ArticoliGetSearch(int numRecord, string azienda, string searchVal)
+ {
+ List? result = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string sKey = string.IsNullOrEmpty(searchVal) ? "***" : searchVal;
+ string currKey = $"{Utils.redisArtList}:{azienda}:{sKey}";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ readType = "REDIS";
+ }
+ else
+ {
+ result = await Task.FromResult(SpecDbController.ArticoliGetSearch(numRecord, azienda, searchVal));
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, getRandTOut(redisLongTimeCache / 5));
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"ArticoliGetSearch | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Aggiornamento record selezionato
+ ///
+ ///
+ ///
+ public async Task ArticoliUpdateRecord(AnagArticoli currRec)
+ {
+ bool fatto = await SpecDbController.ArticoliUpdateRecord(currRec);
+ await resetCacheArticoli();
+ return fatto;
+ }
+
+ ///
+ /// Verifica se sia possiubile cancellare articolo dato suo CodArt cercando su redis o su
+ /// tab veto da DB
+ ///
+ ///
+ ///
+ public bool ArticoloDelEnabled(object CodArt)
+ {
+ bool answ = false;
+ string codArticolo = $"{CodArt}";
+ int cacheCheckArtUsato = 1;
+ int.TryParse(_configuration.GetValue("ServerConf:cacheCheckArtUsato"), out cacheCheckArtUsato);
+ TimeSpan TTLCache = getRandTOut(cacheCheckArtUsato);
+ // cerco in cache redis...
+ string redKeyArtUsed = $"{Utils.redKeyArtUsed}:{codArticolo}";
+ string redKeyTabCheckArt = Utils.redKeyTabCheckArt;
+ string rawData = redisDb.StringGet(redKeyArtUsed);
+ if (!string.IsNullOrEmpty(rawData))
+ {
+ bool.TryParse(rawData, out answ);
+ }
+ else
+ {
+ // controllo non sia stato mai prodotto sennò non posso cancellare...
+ try
+ {
+ // cerco in cache se ci sia la tabella con gli articoli impiegati...
+ string rawTable = redisDb.StringGet(redKeyTabCheckArt);
+ List? artList = new List();
+ if (!string.IsNullOrEmpty(rawTable))
+ {
+ artList = JsonConvert.DeserializeObject>(rawTable);
+ }
+ // rileggo...
+ if (artList == null || artList.Count == 0)
+ {
+ artList = new List();
+ var tabArticoli = SpecDbController.ArticoliGetUsed();
+ var codList = tabArticoli.Select(x => x.CodArticolo);
+ foreach (string cod in codList)
+ {
+ artList.Add(cod);
+ }
+ // SE fosse vuoto aggiungo comunque il cado "ND"...
+ if (artList.Count == 0)
+ {
+ artList.Add("ND");
+ }
+ // salvo
+ rawTable = JsonConvert.SerializeObject(artList);
+ redisDb.StringSet(redKeyTabCheckArt, rawTable, TTLCache);
+ }
+ // cerco nella tabella: se ci fosse --> disabilitato delete
+ bool usato = false;
+ if (artList != null && artList.Count > 0)
+ {
+ usato = artList.Contains(codArticolo);
+ }
+ answ = !usato;
+ redisDb.StringSet(redKeyArtUsed, $"{answ}", TTLCache);
+ }
+ catch
+ { }
+ }
+ return answ;
+ }
+
+ public string CalcRecipe(RecipeModel currRecipe)
+ {
+ return mongoController.CalcRecipe(currRecipe);
+ }
+
+ public async Task> ConfigGetAll()
+ {
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ List? result = new List();
+ // cerco in redis...
+ RedisValue rawData = await redisDb.StringGetAsync(Utils.redisConfKey);
+ if (!string.IsNullOrEmpty($"{rawData}"))
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"ConfigGetAll Read from REDIS: {ts.TotalMilliseconds}ms");
+ }
+ else
+ {
+ result = await Task.FromResult(SpecDbController.ConfigGetAll());
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ await redisDb.StringSetAsync(Utils.redisConfKey, rawData, getRandTOut(redisLongTimeCache));
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"ConfigGetAll Read from DB: {ts.TotalMilliseconds}ms");
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ return result;
+ }
+
+ ///
+ /// Reset dati cache config
+ ///
+ ///
+ public async Task ConfigResetCache()
+ {
+ await redisDb.StringSetAsync(Utils.redisConfKey, "");
+ }
+
+ ///
+ /// Update chiave config
+ ///
+ ///
+ public async Task ConfigUpdate(ConfigModel updRec)
+ {
+ return await Task.FromResult(SpecDbController.ConfigUpdate(updRec));
+ }
+
+ ///
+ /// Elenco completo valori DatiMacchine
+ ///
+ ///
+ public async Task> DatiMacchineGetAll()
+ {
+ List? result = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = $"{Utils.redisBaseAddr}:TabDatiMacchine:ALL";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ readType = "REDIS";
+ }
+ else
+ {
+ result = await Task.FromResult(SpecDbController.DatiMacchineGetAll());
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, getRandTOut(redisLongTimeCache));
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"DatiMacchineGetAll | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Dispose del connettore ai dati
+ ///
+ public void Dispose()
+ {
+ // Clear database controller
+ SpecDbController.Dispose();
+ mongoController.Dispose();
+ redisConn.Dispose();
+ }
+
+ ///
+ /// Eliminazione di un dossier
+ ///
+ /// record dossier da eliminare
+ ///
+ public async Task DossiersDeleteRecord(DossierModel selRecord)
+ {
+ bool result = false;
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ result = await SpecDbController.DossiersDeleteRecord(selRecord);
+ // elimino cache redis...
+ RedisValue pattern = new RedisValue($"{Utils.redisDossByMac}:*");
+ bool answ = await RedisFlushPatternAsync(pattern);
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"DossiersDeleteRecord | IdxMacchina {selRecord.IdxMacchina} | DtRif {selRecord.DtRif} | IdxODL {selRecord.IdxODL} | {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Elenco ultimi n record DOssiers (che contengono ad esempio "salvataggi" di FLuxLog) dato
+ /// macchina (ordinato x data registrazione)
+ ///
+ /// * = tutte, altrimenti solo x una data macchina
+ /// Data minima per estrazione records
+ /// Data Massima per estrazione records
+ ///
+ public async Task> DossiersGetLastFilt(string IdxMacchina, string CodArticolo, DateTime DtStart, DateTime DtEnd)
+ {
+ List? result = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = $"{Utils.redisDossByMac}:{IdxMacchina}:{CodArticolo}:{DtStart:yyyyMMddHHmm}:{DtEnd:yyyyMMddHHmm}";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ readType = "REDIS";
+ }
+ else
+ {
+ result = await Task.FromResult(SpecDbController.DossiersGetLastFilt(IdxMacchina, CodArticolo, DtStart, DtEnd));
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, getRandTOut(redisLongTimeCache / 5));
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"DossiersGetLastFilt | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Inserimento nuovo record dossier
+ ///
+ ///
+ ///
+ public async Task DossiersInsert(DossierModel currDoss)
+ {
+ // aggiorno record sul DB
+ bool answ = await SpecDbController.DossiersInsert(currDoss);
+
+ return answ;
+ }
+
+ ///
+ /// Effettua salvataggio snapshot parametri (con stored) + svuota eventuale cache redis
+ ///
+ /// macchina
+ /// NUm massimo secondi per recuperare dati correnti
+ /// DataOra riferimento x cui prendere valori antecedenti
+ ///
+ public async Task DossiersTakeParamsSnapshotLast(string IdxMacchina, DateTime dtMin, DateTime dtMax)
+ {
+ bool answ = false;
+ await Task.Delay(1);
+ Log.Info($"Richiesta snapshot per macchina {IdxMacchina} | periodo {dtMin} --> {dtMax}");
+ // chiamo stored x salvare parametri
+ SpecDbController.DossiersTakeParamsSnapshotLast(IdxMacchina, dtMin, dtMax);
+ // elimino cache redis...
+ RedisValue pattern = new RedisValue($"{Utils.redisDossByMac}:*");
+ answ = await RedisFlushPatternAsync(pattern);
+ Log.Info($"Svuotata cache dossier | {pattern}");
+ return answ;
+ }
+
+ ///
+ /// Update valore dossier
+ ///
+ ///
+ ///
+ public async Task DossiersUpdateValore(DossierModel currDoss)
+ {
+ // aggiorno record sul DB
+ bool answ = await SpecDbController.DossiersUpdateValore(currDoss);
+
+ return answ;
+ }
+
+ ///
+ /// Restitusice elenco aziende
+ ///
+ ///
+ public Task> ElencoAziende()
+ {
+ return Task.FromResult(SpecDbController.AnagGruppiAziende());
+ }
+
+ ///
+ /// Restitusice elenco fasi
+ ///
+ ///
+ public Task> ElencoGruppiFase()
+ {
+ List result = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = $"{Utils.redisAnagGruppi}";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ var rawResult = JsonConvert.DeserializeObject>($"{rawData}");
+ if (rawResult != null)
+ {
+ result = rawResult;
+ }
+ readType = "REDIS";
+ }
+ else
+ {
+ result = SpecDbController.AnagGruppiFase();
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, getRandTOut(redisLongTimeCache / 5));
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"ElencoGruppiFase | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return Task.FromResult(result);
+ }
+
+ public Task> ElencoLink()
+ {
+ return Task.FromResult(SpecDbController.ElencoLink());
+ }
+
+ ///
+ /// Aggiunta record EventList
+ ///
+ ///
+ ///
+ public async Task EvListInsert(EventListModel newRec)
+ {
+ return await SpecDbController.EvListInsert(newRec);
+ }
+
+ ///
+ /// Imposta in redis la scadenza della pagina x il reload
+ ///
+ ///
+ ///
+ public DateTime ExpiryReloadParamGet()
+ {
+ DateTime dtRif = DateTime.Now;
+ string currKey = $"{Utils.redisParamPageExp}";
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ dtRif = JsonConvert.DeserializeObject($"{rawData}");
+ }
+ return dtRif;
+ }
+
+ ///
+ /// Imposta in redis la scadenza della pagina x il reload
+ ///
+ ///
+ ///
+ public bool ExpiryReloadParamSet(DateTime expTime)
+ {
+ bool fatto = false;
+ string currKey = $"{Utils.redisParamPageExp}";
+ string rawData = JsonConvert.SerializeObject(expTime);
+ fatto = redisDb.StringSet(currKey, rawData);
+ return fatto;
+ }
+
+ public async Task FlushRedisCache()
+ {
+ await Task.Delay(1);
+ RedisValue pattern = Utils.RedValue("*");
+ bool answ = await RedisFlushPatternAsync(pattern);
+ // rileggo vocabolario.,..
+ ObjVocabolario = VocabolarioGetAll();
+ return answ;
+ }
+
+ public async Task FlushRedisKey(string redKey)
+ {
+ await Task.Delay(1);
+ RedisValue pattern = Utils.RedValue(redKey);
+ bool answ = await RedisFlushPatternAsync(pattern);
+ return answ;
+ }
+
+ public List FluxLogDtoGetByFlux(string Valore)
+ {
+ List answ = new List();
+ DossierFluxLogDTO? result = JsonConvert.DeserializeObject(Valore);
+ if (result != null)
+ {
+ if (result.ODL != null)
+ {
+ answ = result
+ .ODL
+ .OrderBy(x => x.CodFlux)
+ .ToList();
+ // inizializzo SE necessario
+ foreach (var item in answ)
+ {
+ item.ValoreEdit = String.IsNullOrEmpty(item.ValoreEdit) ? item.Valore : item.ValoreEdit;
+ }
+ }
+ }
+ return answ;
+ }
+
+ ///
+ /// Elenco ultimi n record flux log dato macchina e flusso (ordinato x data registrazione)
+ ///
+ /// Data massima x eventi
+ /// Data minima x eventi
+ /// * = tutte, altrimenti solo x una data macchina
+ /// *=tutti, altrimenti solo selezionato
+ /// numero massimo record da restituire
+ ///
+ public async Task> FluxLogGetLastFilt(DateTime DtMax, DateTime DtMin, string IdxMacchina, string CodFlux, int MaxRec, double redisCacheSec)
+ {
+ List? result = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = $"{Utils.redisFluxLogFilt}:{IdxMacchina}:{CodFlux}:{MaxRec}:{DtMax:yyyyMMddHHmm}:{DtMin:yyyyMMddHHmm}";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ readType = "REDIS";
+ }
+ else
+ {
+ result = await Task.FromResult(SpecDbController.FluxLogGetLastFilt(DtMax, DtMin, IdxMacchina, CodFlux, MaxRec));
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ if (string.IsNullOrEmpty(canCacheParametri))
+ {
+ canCacheParametri = await tryGetConfig("SPEC_ParametriEnableRedisCache");
+ }
+ if (canCacheParametri != "false")
+ {
+ redisDb.StringSet(currKey, rawData, TimeSpan.FromSeconds(redisCacheSec));
+ }
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"FluxLogGetLastFilt | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Init ricetta
+ ///
+ ///
+ ///
+ ///
+ ///
+ public RecipeModel InitRecipe(string confPath, int idxPODL, Dictionary CalcArgs)
+ {
+ return mongoController.InitRecipe(confPath, idxPODL, CalcArgs);
+ }
+
+ ///
+ /// Restituisce il valore booleano se la macchina sia abilitata all'input
+ ///
+ ///
+ ///
+ public bool IobInsEnab(string idxMacchina)
+ {
+ bool answ = Convert.ToBoolean(mDatiMacchinaVal(idxMacchina, "insEnabled"));
+ return answ;
+ }
+
+ ///
+ ///
+ /// id odl da cercare
+ ///
+ public async Task> ListGiacenze(int IdxOdl)
+ {
+ List? result = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = $"{Utils.redisGiacenzaList}:{IdxOdl}";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ readType = "REDIS";
+ }
+ else
+ {
+ result = await Task.FromResult(SpecDbController.ListGiacenze(IdxOdl));
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, TimeSpan.FromSeconds(redisShortTimeCache));
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"ListGiacenze | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// elenco TUTTI gli ODL
+ ///
+ ///
+ ///
+ public List ListOdlAll()
+ {
+ List? result = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ result = SpecDbController.ListOdlAll();
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"ListOdlAll | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Elenco ODL filtrati x stato, articolo, KeyRich (che contiene stato)
+ ///
+ /// Stato ODL: true=in corso/completato
+ /// Cod articolo
+ /// KeyRich (parziale) da cercare (es cod stato x yacht)
+ /// Reparto selezionato
+ /// Macchina selezionata
+ /// Data inizio
+ /// Data fine
+ ///
+ public async Task> ListODLFilt(bool inCorso, string codArt, string keyRichPart, string Reparto, string IdxMacchina, DateTime startDate, DateTime endDate)
+ {
+ List? result = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = $"{Utils.redisOdlList}:{inCorso}:{codArt}:{keyRichPart}:{Reparto}:{IdxMacchina}:{startDate:yyyyMMdd_HHmmss}:{endDate:yyyyMMdd_HHmmss}";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ readType = "REDIS";
+ }
+ else
+ {
+ result = await Task.FromResult(SpecDbController.ListODLFilt(inCorso, codArt, keyRichPart, Reparto, IdxMacchina, startDate, endDate));
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, TimeSpan.FromSeconds(redisShortTimeCache));
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"ListODLFilt | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+
+ //return await Task.FromResult(SpecDbController.ListODLFilt(inCorso, codArt, keyRichPart, Reparto, IdxMacchina, startDate, endDate));
+ }
+
+ ///
+ /// Elenco PODL non avviati filtrati x articolo, KeyRich (che contiene stato)
+ ///
+ /// Solo lanciati (1) o ancora disponibili (0)
+ /// KeyRich (parziale) da cercare (es cod stato x yacht)
+ /// Macchina
+ /// Gruppo
+ /// Data inizio
+ /// Data fine
+ ///
+ public async Task> ListPODLFilt(bool lanciato, string keyRichPart, string idxMacchina, string codGruppo, DateTime startDate, DateTime endDate)
+ {
+ List? result = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = $"{Utils.redisPOdlList}:{codGruppo}:{idxMacchina}:{keyRichPart}:{lanciato}:{startDate:yyyyMMdd_HHmmss}:{endDate:yyyyMMdd_HHmmss}";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ readType = "REDIS";
+ }
+ else
+ {
+ result = await Task.FromResult(SpecDbController.ListPODLFilt(lanciato, keyRichPart, idxMacchina, codGruppo, startDate, endDate));
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, TimeSpan.FromSeconds(redisShortTimeCache));
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"ListPODLFilt | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Elenco completo valori Macchine 2 Slave
+ ///
+ ///
+ public List Macchine2SlaveGetAll()
+ {
+ List? result = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = $"{Utils.redisBaseAddr}:M2STab";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ readType = "REDIS";
+ }
+ else
+ {
+ result = IocDbController.Macchine2Slave();
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, getRandTOut(redisLongTimeCache));
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"Macchine2SlaveGetAll | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Elenco di tutte le macchine gestite
+ ///
+ ///
+ ///
+ public async Task> MacchineGetFilt(string codGruppo)
+ {
+ List? result = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string keyGrp = codGruppo != "*" ? codGruppo : "ALL";
+ string currKey = $"{Utils.redisMacList}:{keyGrp}";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ readType = "REDIS";
+ }
+ else
+ {
+ result = await Task.FromResult(SpecDbController.MacchineGetFilt(codGruppo));
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, getRandTOut(redisLongTimeCache));
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"MacchineGetAll | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Verifica se la macchina abbia un codice ricetta associato
+ ///
+ ///
+ ///
+ public async Task MacchineRecipe(string idxMacchina)
+ {
+ string? result = "";
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = $"{Utils.redisMacRecipe}:{idxMacchina}";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ result = JsonConvert.DeserializeObject($"{rawData}");
+ readType = "REDIS";
+ }
+ else
+ {
+ //recupero elenco macchine...
+ var machineList = await MacchineGetFilt("*");
+ var currMach = machineList.Where(x => x.IdxMacchina == idxMacchina).FirstOrDefault();
+ result = currMach != null ? currMach.RecipePath : null;
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, getRandTOut(redisLongTimeCache));
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"MacchineRecipe | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result ?? "";
+ }
+
+ ///
+ /// Elenco id Macchine che abbiano dati FLuxLog, nel periodo indicato
+ ///
+ ///
+ ///
+ ///
+ public async Task> MacchineWithFlux(DateTime dtStart, DateTime dtEnd)
+ {
+ List? result = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = $"{Utils.redisMacByFlux}:{dtStart:yyyyMMddHHmm}:{dtEnd:yyyyMMddHHmm}";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ readType = "REDIS";
+ }
+ else
+ {
+ result = await SpecDbController.MacchineWithFlux(dtStart, dtEnd);
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, getRandTOut(redisLongTimeCache));
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"MacchineWithFlux | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Restituisce valore di una singola chiave del dizionario DatiMacchina
+ ///
+ ///
+ ///
+ ///
+ public string mDatiMacchinaVal(string idxMacchina, string chiave)
+ {
+ string answ = "";
+ try
+ {
+ answ = mDatiMacchine(idxMacchina)[chiave];
+ }
+ catch { }
+ return answ;
+ }
+
+ ///
+ /// Restitusice elenco KVP dei campi DatiMacchine + StatoMacchine per l'impianto indicato
+ ///
+ ///
+ ///
+ public Dictionary mDatiMacchine(string idxMacchina)
+ {
+ // hard coded dimensione vettore DatiMacchine
+ Dictionary answ = new Dictionary();
+ // ORA recupero da memoria redis...
+ try
+ {
+ var currHash = Utils.dtMaccHash(idxMacchina);
+ answ = RedisGetHashDict(currHash);
+ // se è vuoto... leggo da DB e popolo!
+ if (answ.Count == 0)
+ {
+ answ = ResetDatiMacchina(idxMacchina);
+ }
+ }
+ catch (Exception exc)
+ {
+ Log.Error($"Errore in compilazione dati Macchine x Redis - idxMacchina {idxMacchina}:{Environment.NewLine}{exc}");
+ }
+ return answ;
+ }
+
+ ///
+ /// Restitusice elenco KVP dei TASK (da passare a IOB-WIN) per l'impianto indicato
+ ///
+ ///
+ ///
+ public Dictionary mOptParMacchina(string idxMacchina)
+ {
+ // hard coded dimensione vettore DatiMacchine
+ Dictionary answ = new Dictionary();
+ // ORA recupero da memoria redis...
+ try
+ {
+ RedisKey currHash = Utils.OptParHash(idxMacchina);
+ answ = RedisGetHashDict(currHash);
+ }
+ catch (Exception exc)
+ {
+ Log.Error($"Errore in compilazione dati OPT PARAM x Redis - idxMacchina {idxMacchina}{Environment.NewLine}{exc}");
+ }
+ return answ;
+ }
+
+ ///
+ /// Elenco ODL dato batch selezionato
+ ///
+ /// Batch richiesto
+ ///
+ public async Task> OdlByBatch(string BatchSel)
+ {
+ List? result = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = Utils.redisOdlByBatch;
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ readType = "REDIS";
+ }
+ else
+ {
+ result = await Task.FromResult(SpecDbController.OdlByBatch(BatchSel));
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, getRandTOut(redisLongTimeCache));
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"OdlByBatch | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// ODL da chiave
+ ///
+ ///
+ ///
+ public ODLExpModel OdlByKey(int IdxOdl)
+ {
+ ODLExpModel? result = new ODLExpModel();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ result = SpecDbController.OdlByKey(IdxOdl);
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"OdlByKey | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Effettua chiusura dell'ODL indicato, andand
+ ///
+ /// idx odl da chiudere
+ /// idx macchina
+ /// matricola operatore
+ /// indica se confermare i pezzi priam di chiudere ODL
+ public async Task ODLClose(int idxOdl, string idxMacchina, int matrOpr, bool confPezzi)
+ {
+ bool fatto = false;
+ await Task.Delay(1);
+ // recupero dati x conf modalità conferma
+ var configData = await ConfigGetAll();
+ if (configData != null)
+ {
+ bool confRett = false;
+ var currRec = configData.FirstOrDefault(x => x.Chiave == "confRett");
+ if (currRec != null)
+ {
+ bool.TryParse(currRec.Valore, out confRett);
+ }
+ int modoConfProd = 0;
+ currRec = configData.FirstOrDefault(x => x.Chiave == "modoConfProd");
+ if (currRec != null)
+ {
+ int.TryParse(currRec.Valore, out modoConfProd);
+ }
+ // chiamo metodo conferma!
+ fatto = await SpecDbController.ODLClose(idxOdl, idxMacchina, matrOpr, confPezzi, confRett, modoConfProd);
+ }
+
+ return fatto;
+ }
+
+ ///
+ /// Record ODL da chaive
+ ///
+ ///
+ public async Task OdlGetByKey(int IdxOdl)
+ {
+ await Task.Delay(1);
+ var dbResult = SpecDbController.OdlGetByKey(IdxOdl);
+ return dbResult;
+ }
+
+ ///
+ /// ODL correnti (tutti)
+ ///
+ ///
+ ///
+ public List OdlGetCurrent()
+ {
+ List? dbResult = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = $"{Utils.redisOdlCurrByMac}";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ try
+ {
+ dbResult = JsonConvert.DeserializeObject>($"{rawData}");
+ }
+ catch
+ { }
+ readType = "REDIS";
+ }
+ else
+ {
+ dbResult = SpecDbController.OdlGetCurrent().Select(x => x.IdxMacchina).Distinct().ToList();
+ rawData = JsonConvert.SerializeObject(dbResult);
+ redisDb.StringSet(currKey, rawData, TimeSpan.FromSeconds(3));
+ }
+ if (dbResult == null)
+ {
+ dbResult = new List();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"OdlGetCurrent | Read from {readType}: {ts.TotalMilliseconds}ms");
+
+ return dbResult;
+ }
+
+ ///
+ /// Elenco di tutti i parametri filtrati x macchina
+ ///
+ /// * = tutte, altrimenti solo x una data macchina
+ ///
+ public async Task> ParametriGetFilt(string IdxMacchina)
+ {
+ List? result = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = $"{Utils.redisFluxByMac}:{IdxMacchina}";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ readType = "REDIS";
+ }
+ else
+ {
+ result = await Task.FromResult(SpecDbController.ParametriGetFilt(IdxMacchina));
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, getRandTOut(redisLongTimeCache));
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"ParametriGetFilt | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Recupero PODL da chiave
+ ///
+ ///
+ ///
+ public async Task PODL_getByKey(int idxPODL)
+ {
+ PODLModel result = new PODLModel();
+ if (idxPODL != 0)
+ {
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = $"{Utils.redisPOdlByPOdl}:{idxPODL}";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ var rawResult = JsonConvert.DeserializeObject($"{rawData}");
+ if (rawResult != null)
+ {
+ result = rawResult;
+ readType = "REDIS";
+ }
+ }
+ else
+ {
+ result = await SpecDbController.PODL_getByKey(idxPODL);
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, getRandTOut(redisLongTimeCache));
+ }
+ if (result == null)
+ {
+ result = new PODLModel();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Trace($"PODL_getByKey | Read from {readType}: {ts.TotalMilliseconds}ms");
+ }
+ else
+ {
+ Log.Debug("Errore IdxPODL = 0");
+ }
+ return result;
+ }
+
+ ///
+ /// Recupero PODL da IdxODL
+ ///
+ ///
+ ///
+ public PODLModel PODL_getByOdl(int idxODL)
+ {
+ PODLModel result = new PODLModel();
+ if (idxODL != 0)
+ {
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = $"{Utils.redisPOdlByOdl}:{idxODL}";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ var rawResult = JsonConvert.DeserializeObject($"{rawData}");
+ if (rawResult != null)
+ {
+ result = rawResult;
+ }
+ readType = "REDIS";
+ }
+ else
+ {
+ result = SpecDbController.PODL_getByOdl(idxODL);
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, getRandTOut(redisLongTimeCache));
+ }
+ if (result == null)
+ {
+ result = new PODLModel();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Trace($"PODL_getByOdl | Read from {readType}: {ts.TotalMilliseconds}ms");
+ }
+ else
+ {
+ Log.Debug("Errore IdxODL = 0");
+ }
+ return result;
+ }
+
+ ///
+ /// Eliminazione record selezionato
+ ///
+ ///
+ ///
+ public async Task PODLDeleteRecord(PODLExpModel currRec)
+ {
+ var dbResult = await SpecDbController.PODLDeleteRecord(currRec);
+ // elimino cache redis...
+ RedisValue pattern = new RedisValue($"{Utils.redisXdlData}:*");
+ bool answ = await RedisFlushPatternAsync(pattern);
+ await Task.Delay(1);
+ return dbResult;
+ }
+
+ ///
+ /// Avvio fase setup per il record selezionato
+ ///
+ ///
+ ///
+ public async Task POdlDoSetup(PODLExpModel currRec)
+ {
+ var dbResult = await SpecDbController.PODL_startSetup(currRec, 0, 1, 1, "");
+ // elimino cache redis...
+ RedisValue pattern = new RedisValue($"{Utils.redisXdlData}:*");
+ bool answ = await RedisFlushPatternAsync(pattern);
+ await Task.Delay(1);
+ return dbResult;
+ }
+
+ ///
+ /// Aggiornamento record selezionato
+ ///
+ ///
+ ///
+ public async Task POdlUpdateRecord(PODLModel currRec)
+ {
+ var dbResult = await SpecDbController.PODLUpdateRecord(currRec);
+ // elimino cache redis...
+ RedisValue pattern = new RedisValue($"{Utils.redisXdlData}:*");
+ bool answ = await RedisFlushPatternAsync(pattern);
+ await Task.Delay(1);
+ return dbResult;
+ }
+
+ ///
+ /// Ricerca ricetta su MongoDB dato PODL
+ ///
+ ///
+ ///
+ public async Task RecipeGetByPODL(int idxPODL)
+ {
+ RecipeModel? result = null;
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "MongoDB";
+ result = await mongoController.RecipeGetByPODL(idxPODL);
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"RecipeGetByPODL | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Salva ricetta su MongoDB
+ ///
+ ///
+ ///
+ public async Task RecipeSetByPODL(RecipeModel currRecord)
+ {
+ bool answ = false;
+ answ = await mongoController.RecipeSetByPODL(currRecord);
+ return answ;
+ }
+
+ ///
+ /// Effettua conteggio chaivi REDIS dato pattern ricerca
+ ///
+ ///
+ ///
+ public int RedisCountKey(string keyPattern)
+ {
+ int num = 0;
+ keyPattern = (string.IsNullOrEmpty(keyPattern) ? "**" : keyPattern);
+ try
+ {
+ var listEndpoints = redisConnAdmin.GetEndPoints();
+ foreach (var endPoint in listEndpoints)
+ {
+ var server = redisConnAdmin.GetServer(endPoint);
+ foreach (RedisKey item in server.Keys(pattern: keyPattern, database: redisDb.Database, pageSize: 250, cursor: 0L))
+ {
+ num++;
+ }
+ }
+ }
+ catch (Exception arg)
+ {
+ Log.Error($"Eccezione in RedisCountKey{Environment.NewLine}{arg}");
+ }
+
+ return num;
+ }
+
+ ///
+ /// Esegue eliminazione memoria redis keyVal
+ ///
+ ///
+ ///
+ public bool RedisDelKey(string keyVal)
+ {
+ bool answ = false;
+ var listEndpoints = redisConnAdmin.GetEndPoints();
+ foreach (var endPoint in listEndpoints)
+ {
+ var server = redisConnAdmin.GetServer(endPoint);
+ if (server != null)
+ {
+ redisDb.KeyDelete((RedisKey)keyVal);
+ answ = true;
+ }
+ }
+ return answ;
+ }
+
+ ///
+ /// Esegue flush memoria redis dato keyVal
+ ///
+ ///
+ ///
+ public bool RedisFlushPattern(string pattern)
+ {
+ bool answ = false;
+ var listEndpoints = redisConnAdmin.GetEndPoints();
+ foreach (var endPoint in listEndpoints)
+ {
+ //var server = redisConnAdmin.GetServer(listEndpoints[0]);
+ var server = redisConnAdmin.GetServer(endPoint);
+ if (server != null)
+ {
+ var keyList = server.Keys(redisDb.Database, pattern);
+ foreach (var item in keyList)
+ {
+ redisDb.KeyDelete(item);
+ }
+ answ = true;
+ }
+ }
+ return answ;
+ }
+
+ ///
+ /// Esegue flush memoria redis dato keyVal, async
+ ///
+ ///
+ ///
+ public async Task RedisFlushPatternAsync(RedisValue pattern)
+ {
+ bool answ = false;
+ var listEndpoints = redisConnAdmin.GetEndPoints();
+ foreach (var endPoint in listEndpoints)
+ {
+ var server = redisConnAdmin.GetServer(endPoint);
+ if (server != null)
+ {
+ var keyList = server.Keys(redisDb.Database, pattern);
+ foreach (var item in keyList)
+ {
+ await redisDb.KeyDeleteAsync(item);
+ }
+ answ = true;
+ }
+ }
+ return answ;
+ }
+
+ public KeyValuePair[] RedisGetHash(RedisKey redKey)
+ {
+ HashEntry[] rawData = redisDb.HashGetAll(redKey);
+ var result = rawData.Where(x => !x.Name.IsNull).Select(x => new KeyValuePair(x.Name, x.Value)).ToArray();
+ return result;
+ }
+
+ public async Task[]> RedisGetHashAsync(string redKey)
+ {
+ HashEntry[] rawData = await redisDb.HashGetAllAsync(redKey);
+ var result = rawData.Where(x => !x.Name.IsNull).Select(x => new KeyValuePair(x.Name, x.Value)).ToArray();
+ return result;
+ }
+
+ public Dictionary RedisGetHashDict(RedisKey hashKey)
+ {
+ HashEntry[] rawData = redisDb.HashGetAll(hashKey);
+ var result = rawData.Where(x => !x.Name.IsNull).ToDictionary(x => x.Name.ToString(), x => x.Value.ToString());
+ return result;
+ }
+
+ public string RedisGetHashField(RedisKey key, string hashField)
+ {
+ string result = "";
+ try
+ {
+ RedisValue hashField2 = hashField;
+ result = redisDb.HashGet(key, hashField2).ToString();
+ }
+ catch (Exception exc)
+ {
+ Log.Error($"Errore in RedisGetHashField{Environment.NewLine}{exc}");
+ }
+
+ return result;
+ }
+
+ public bool RedisHashPresent(RedisKey key)
+ {
+ bool result = false;
+ try
+ {
+ result = redisDb.HashGetAll(key).Length != 0;
+ }
+ catch (Exception arg)
+ {
+ Log.Error($"Errore in redHashPresent per la key {key}{Environment.NewLine}{arg}");
+ }
+
+ return result;
+ }
+
+ public bool RedisHashPresentSz(string key)
+ {
+ return RedisHashPresent((RedisKey)key);
+ }
+
+ public bool RedisKeyPresent(RedisKey key)
+ {
+ bool result = false;
+ try
+ {
+ result = redisDb.KeyExists(key);
+ }
+ catch (Exception arg)
+ {
+ Log.Error($"Errore in redKeyPresent per la key {key}:{Environment.NewLine}{arg}");
+ }
+
+ return result;
+ }
+
+ public bool RedisKeyPresentSz(string key)
+ {
+ bool result = false;
+ try
+ {
+ RedisKey key2 = key;
+ result = RedisKeyPresent(key2);
+ }
+ catch
+ {
+ }
+
+ return result;
+ }
+
+ public bool RedisSetHash(RedisKey redKey, KeyValuePair[] valori, double expireSeconds = -1.0)
+ {
+ bool answ = false;
+ answ = RedisSetHash(redKey, valori);
+ if (expireSeconds > 0.0)
+ {
+ redisDb.KeyExpire(redKey, DateTime.Now.AddSeconds(expireSeconds));
+ }
+ return answ;
+ }
+
+ public bool RedisSetHash(RedisKey redKey, KeyValuePair[] valori)
+ {
+ bool answ = false;
+ HashEntry[] redHash = valori.Select(x => new HashEntry(x.Key, x.Value)).ToArray();
+ redisDb.HashSet(redKey, redHash);
+ answ = true;
+ return answ;
+ }
+
+ public bool RedisSetHashDict(RedisKey redKey, Dictionary valori, double expireSeconds = -1.0)
+ {
+ bool answ = false;
+ answ = RedisSetHashDict(redKey, valori);
+ if (expireSeconds > 0.0)
+ {
+ redisDb.KeyExpire(redKey, DateTime.Now.AddSeconds(expireSeconds));
+ }
+ return answ;
+ }
+
+ public bool RedisSetHashDict(RedisKey redKey, Dictionary valori)
+ {
+ bool answ = false;
+ HashEntry[] redHash = valori.Select(x => new HashEntry(x.Key, x.Value)).ToArray();
+ redisDb.HashSet(redKey, redHash);
+ answ = true;
+ return answ;
+ }
+
+ public bool RedisSetKey(string valKey, string redVal)
+ {
+ bool answ = redisDb.StringSet(Utils.RedKeyHash(valKey), redVal);
+ return answ;
+ }
+
+ public bool RedisSetKey(RedisKey valKey, string redVal, int TTL_sec)
+ {
+ bool answ = redisDb.StringSet(Utils.RedKeyHash(valKey), redVal, TimeSpan.FromSeconds(TTL_sec));
+ return answ;
+ }
+
+ ///
+ /// Restitusice elenco KVP dei campi DatiMacchine + StatoMacchine per l'impianto indicato
+ ///
+ ///
+ ///
+ public Dictionary ResetDatiMacchina(string idxMacc)
+ {
+ var currHash = Utils.dtMaccHash(idxMacc);
+ // inizio con un bel reset...
+ RedisFlushPattern($"{currHash}");
+ Dictionary? result = new Dictionary();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ var dbResults = IocDbController.VMSFDGetByMacc(idxMacc);
+ // converto in formato dizionario...
+ if (dbResults != null && dbResults.Count > 0)
+ {
+ var rowResult = dbResults[0];
+ // salvo 1:1 i valori... STATO
+ result.Add("IdxMicroStato", $"{rowResult.IdxMicroStato}");
+ result.Add("IdxStato", $"{rowResult.IdxStato}");
+ result.Add("CodArticolo", $"{rowResult.CodArticolo}");
+ result.Add("insEnabled", $"{rowResult.InsEnabled}");
+ result.Add("sLogEnabled", $"{rowResult.SLogEnabled}");
+ result.Add("pallet", $"{rowResult.Pallet}");
+ result.Add("CodArticolo_A", $"{rowResult.CodArticoloA}");
+ result.Add("CodArticolo_B", $"{rowResult.CodArticoloB}");
+ result.Add("TempoCicloBase", $"{rowResult.TempoCicloBase}");
+ result.Add("PzPalletProd", $"{rowResult.PzPalletProd}");
+ result.Add("MatrOpr", $"{rowResult.MatrOpr}");
+ result.Add("lastVal", $"{rowResult.LastVal}");
+ result.Add("TCBase", $"{rowResult.TempoCicloBase}");
+
+ //...e SETUP
+ result.Add("CodMacc", $"{rowResult.Codmacchina}");
+ result.Add("IdxFamIn", $"{rowResult.IdxFamigliaIngresso}");
+ result.Add("Multi", $"{rowResult.Multi}");
+ result.Add("BitFilt", $"{rowResult.BitFilt}");
+ result.Add("MaxVal", $"{rowResult.MaxVal}");
+ result.Add("BSR", $"{rowResult.Bsr}");
+ result.Add("ExplodeBit", $"{rowResult.ExplodeBit}");
+ result.Add("NumBit", $"{rowResult.NumBit}");
+ result.Add("IdxFamMacc", $"{rowResult.IdxFamiglia}");
+ result.Add("simplePallet", $"{rowResult.SimplePallet}");
+ result.Add("palletChange", $"{rowResult.PalletChange}");
+ }
+ // cerco info Master/slave...
+ var m2sTab = Macchine2SlaveGetAll();
+ string isMaster = m2sTab.Where(x => x.IdxMacchina == idxMacc).Count() > 0 ? "1" : "0";
+ string isSlave = m2sTab.Where(x => x.IdxMacchinaSlave == idxMacc).Count() > 0 ? "1" : "0";
+ result.Add("Master", isMaster);
+ result.Add("Slave", isSlave);
+
+ // durata cache in secondi dal valore insEnabled...
+ double numSecCache = 60 * ((result["insEnabled"].ToLower() == "true") ? redisShortTimeCache / 4 : redisShortTimeCache);
+ // ...e salvo...
+ RedisSetHashDict(currHash, result, numSecCache);
+
+ if (result == null)
+ {
+ result = new Dictionary();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"GetCurrMSFDMacc | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Resetta (rileggendo) i dati della State Machine ingressi nel formato
+ /// key: cState_nVal (current MICRO-STATE + "_" + new Value)
+ /// value: iTipoEv_nState (IdxTipoEv da trasmettere + New MICRO-STATE)
+ ///
+ ///
+ ///
+ public KeyValuePair[] resetSMI(int idxFamIn)
+ {
+ var currHash = Utils.hSMI(idxFamIn);
+ // leggo da DB...
+ var tabSMI = IocDbController.StateMachineIngressi(idxFamIn);
+
+ KeyValuePair