Spostamento adapter in ADAPTER.OLD

This commit is contained in:
Samuele Locatelli
2022-06-14 10:51:02 +02:00
parent 9857de0f1a
commit a623b4f2db
18 changed files with 3896 additions and 0 deletions
+631
View File
@@ -0,0 +1,631 @@
using Microsoft.Extensions.Configuration;
using MP.MONO.Core;
using MP.MONO.Core.CONF;
using Newtonsoft.Json;
using NLog;
using System.Net;
using System.Net.NetworkInformation;
using static MP.MONO.Core.CONF.OpcUaParamConf;
using static MP.MONO.Core.Enums;
namespace MP.MONO.ADAPTER
{
public class IobGeneric
{
#region Public Fields
/// <summary>
/// Data/ora ultimo avvio adapter
/// </summary>
public DateTime dtAvvioAdp = DateTime.Now;
/// <summary>
/// Data/ora ultimo spegnimento adapter
/// </summary>
public DateTime dtStopAdp = DateTime.Now;
/// <summary>
/// dataOra ultimo log periodico...
/// </summary>
public DateTime lastPeriodicLog;
/// <summary>
/// dataOra ultimo PING inviato verso il PLC...
/// </summary>
public DateTime lastPING = DateTime.Now.AddHours(-1);
/// <summary>
/// Struttura memoria PLC x lettura/scrittura da JSON file
/// </summary>
public plcMemMap memMap;
#endregion Public Fields
#region Public Constructors
/// <summary>
/// Avvia generico IOB
/// </summary>
/// <param name="confPath"></param>
/// <param name="config"></param>
public IobGeneric(string confPath, IConfigurationRoot? config)
{
lg = LogManager.GetCurrentClassLogger();
connectionOk = false;
configPath = confPath;
confMan = config;
if (confMan != null)
{
var selection = confMan.GetSection("Endpoint");
if (selection.Exists())
{
// recupero dati endpoint
cIobConf = selection.Get<EndpointData>();
}
}
}
#endregion Public Constructors
#region Public Properties
/// <summary>
/// Salva verifica stato connessione OK
/// </summary>
/// <returns></returns>
public virtual bool connectionOk
{
get
{
return _connOk;
}
set
{
_connOk = value;
}
}
/// <summary>
/// Verifica SE si debba fare log verboso (verboso + ogni tot letture IN)
/// </summary>
public bool verboseLog
{
get
{
bool answ = false;
int logEvery = confMan.GetValue<int>("logEvery");
if (logEvery < 1)
{
logEvery = 10;
}
answ = confMan.GetValue<bool>("verbose") && (nReadIN % logEvery == 0);
return answ;
}
}
#endregion Public Properties
#region Public Methods
/// <summary>
/// Esecuzione dei task richiesti e pulizia coda richieste eseguite
/// </summary>
/// <param name="task2exe"></param>
public virtual Dictionary<string, string> executeTasks(Dictionary<string, string> task2exe)
{
// Verificare il protocollo: dovrebbe togliere SOLO i task eseguiti...
Dictionary<string, string> taskDone = new Dictionary<string, string>();
if (task2exe != null)
{
// controllo se memMap != null...
if (memMap != null)
{
bool taskOk = false;
string taskVal = "";
// cerco task specifici: se ho startSetup --> imposto bit DBB701.DBB0.4
foreach (var item in task2exe)
{
taskOk = false;
taskVal = "";
// converto richiesta in enum...
taskType tName = taskType.nihil;
Enum.TryParse(item.Key, out tName);
// controllo sulla KEY...
switch (tName)
{
case taskType.setArt:
case taskType.setComm:
case taskType.setProg:
case taskType.setPzComm:
// recupero dati da memMap...
if (memMap != null && memMap.mMapWrite != null)
{
if (memMap.mMapWrite.ContainsKey(item.Key))
{
dataConf currMem = memMap.mMapWrite[item.Key];
string addr = currMem.memAddr;
taskVal = $"SET task: {item.Key} --> {item.Value} | mem: {currMem.memAddr} - {currMem.size} byte";
// salvo il nuovo valore nella memoria... così prox invio lo trasmetterà
memMap.mMapWrite[item.Key].value = item.Value;
}
else
{
taskVal = $"NO DATA MEM, SET task: {item.Key} --> {item.Value}";
}
}
else
{
taskVal = $"NO MemMap found, SET task: {item.Key} --> {item.Value}";
}
// salvo in currProd..
saveProdData(new KeyValuePair<string, string>(item.Key, item.Value));
break;
case taskType.forceResetPzCount:
// reset contapezzi inizio setup
taskOk = resetcontapezziPLC();
taskVal = taskOk ? "RESET PZ COUNT OK" : "PZ RESET DISABLED | NO EXEC";
lgInfo($"Chiamata forceResetPzCount: taskOk: {taskOk} | taskVal: {taskVal}");
break;
case taskType.startSetup:
// reset contapezzi inizio setup
taskOk = resetcontapezziPLC();
taskVal = taskOk ? "RESET: SETUP START" : "PZ RESET DISABLED | NO EXEC";
lgInfo($"Chiamata startSetup: taskOk: {taskOk} | taskVal: {taskVal}");
break;
case taskType.stopSetup:
// reset contapezzi fine setup SE ESPLICITAMENTE IMPOSTATO
if (confMan.GetValue<bool>("ENABLE_PZ_RESET_stopSetup"))
{
taskOk = resetcontapezziPLC();
}
taskVal = taskOk ? "RESET: SETUP END" : "PZ RESET DISABLED | NO EXEC";
lgInfo($"Chiamata stopSetup: taskOk: {taskOk} | taskVal: {taskVal}");
break;
case taskType.setParameter:
// richiedo da URL i parametri WRITE da popolare
lgInfo("Chiamata setParameter --> processMemWriteRequests");
taskVal = processMemWriteRequests();
// se restituiscce "" faccio altra prova...
if (string.IsNullOrEmpty(taskVal))
{
// i parametri me li aspetto come stringa composta paramName|paramvalue
if (item.Value.Contains("|"))
{
string[] paramsJob = item.Value.Split('|');
taskVal = $"REQUEST SET PARAMETERS: {paramsJob[0]} --> {paramsJob[1]}";
}
else
{
taskVal = $"WRONG REQUEST FOR SET PARAMETERS: {item.Value} doesnt contain pipe for splitting key/value";
}
}
break;
default:
taskVal = $"taskReq: {tName} | key: {item.Key} | val: {item.Value} | SKIPPED | NO EXEC";
lgInfo($"Chiamata senza processing: taskOk: {taskOk} | taskVal: {taskVal}");
break;
}
// aggiungo task!
taskDone.Add(item.Key, taskVal);
}
}
else
{
lgError($"Attenzione! memMap è nullo, non posso eseguire task2exe!");
}
}
return taskDone;
}
/// <summary>
/// Metodo generico di reset contapezzi...
/// </summary>
/// <returns></returns>
public virtual bool resetcontapezziPLC()
{
return false;
}
/// <summary>
/// Salva valori indicati in prod data
/// </summary>
/// <param name="item">Item KVP di cui salvare i dati in currProdData come chiave/valore</param>
/// <returns></returns>
public void saveProdData(KeyValuePair<string, string> item)
{
// imposto i valori...
if (currProdData.ContainsKey(item.Key))
{
currProdData[item.Key] = item.Value;
}
else
{
currProdData.Add(item.Key, item.Value);
}
}
/// <summary>
/// Metodo base connessione...
/// </summary>
public virtual void tryConnect()
{
dtAvvioAdp = DateTime.Now;
}
#endregion Public Methods
#region Protected Fields
/// <summary>
/// wrapper di log
/// </summary>
protected static Logger lg;
protected bool _connOk = false;
/// <summary>
/// Dizionario valori impostati x produzione
/// </summary>
protected Dictionary<string, string> currProdData = new Dictionary<string, string>();
/// <summary>
/// Dizionario ultimi valori (double) delle TSVC
/// </summary>
protected Dictionary<string, double> LastTSVC = new Dictionary<string, double>();
/// <summary>
/// Dizionario di VC da trattare come TimeSeries (con conf decodificata + processing successivo...)
/// </summary>
protected Dictionary<string, VCData> TSVC_Data = new Dictionary<string, VCData>();
#endregion Protected Fields
#region Protected Properties
/// <summary>
/// Numero letture IN da avvio
/// </summary>
protected int nReadIN { get; set; }
/// <summary>
/// COnfiguraizone Endpoint corrente
/// </summary>
private EndpointData cIobConf { get; set; } = new EndpointData();
/// <summary>
/// test ping all'indirizzo PLC/CNC impostato nei parametri
/// </summary>
/// <returns></returns>
protected IPStatus testPingMachine
{
get
{
IPStatus answ = IPStatus.Unknown;
// se disabilitato salto...
if (pingDisabled)
{
answ = IPStatus.Success;
}
else
{
IPAddress address;
PingReply reply;
using (Ping pingSender = new Ping())
{
address = IPAddress.Loopback;
int pingMsTimeout = cIobConf.PingMsTimeout;
IPAddress.TryParse(cIobConf.IpAddress, out address);
try
{
// se != null --> uso address...
if (address != null)
{
reply = pingSender.Send(address, pingMsTimeout);
}
else
{
reply = pingSender.Send(cIobConf.IpAddress, pingMsTimeout);
}
}
catch
{
reply = pingSender.Send(IPAddress.Loopback, pingMsTimeout);
}
answ = reply.Status;
}
}
return answ;
}
}
/// <summary>
/// indica se ping disabilitato da optPar
/// </summary>
public bool pingDisabled
{
get
{
bool answ = false;
bool.TryParse(confMan.GetValue<string>("NO_PING"), out answ);
return answ;
}
}
#endregion Protected Properties
#region Protected Methods
/// <summary>
/// Stringa raw dei parametri da scrivere...
/// </summary>
/// <returns></returns>
protected string getParams2write()
{
string answ = "";
// recuperare da una apposita area REDIS...
#if false
string url2call = $"{urlGetParams2Write}";
if (verboseLog)
{
lgInfo("chiamata URL " + url2call);
}
answ = utils.callUrlNow(url2call);
// se vuoto faccio seconda prova...
if (string.IsNullOrEmpty(answ))
{
answ = utils.callUrlNow(url2call);
}
#endif
return answ;
}
/// <summary>
/// Effettua logging DEBUG corretto impostanto anche la variabile IOB prima di scrivere...
/// </summary>
/// <param name="message"></param>
protected void lgDebug(string message)
{
lg.Debug(message);
}
/// <summary>
/// Effettua logging DEBUG corretto impostanto anche la variabile IOB prima di scrivere...
/// </summary>
/// <param name="message"></param>
/// <param name="args"></param>
protected void lgDebug(string message, params object[] args)
{
lg.Debug(message, args);
}
/// <summary>
/// Effettua logging ERROR corretto impostanto anche la variabile IOB prima di scrivere...
/// </summary>
/// <param name="message"></param>
protected void lgError(string message)
{
lg.Error(message);
}
/// <summary>
/// Effettua logging ERROR corretto impostanto anche la variabile IOB prima di scrivere...
/// </summary>
/// <param name="message"></param>
/// <param name="args"></param>
protected void lgError(string message, params object[] args)
{
lg.Error(message, args);
}
/// <summary>
/// Effettua logging ERROR corretto impostanto anche la variabile IOB prima di scrivere...
/// </summary>
/// <param name="exception"></param>
/// <param name="message"></param>
/// <param name="args"></param>
protected void lgError(Exception exception, string message, params object[] args)
{
lg.Error(exception, message, args);
}
/// <summary>
/// Effettua logging FATAL corretto impostanto anche la variabile IOB prima di scrivere...
/// </summary>
/// <param name="message"></param>
protected void lgFatal(string message)
{
lg.Fatal(message);
}
/// <summary>
/// Effettua logging FATAL corretto impostanto anche la variabile IOB prima di scrivere...
/// </summary>
/// <param name="message"></param>
/// <param name="args"></param>
protected void lgFatal(string message, params object[] args)
{
lg.Fatal(message, args);
}
/// <summary>
/// Effettua logging FATAL corretto impostanto anche la variabile IOB prima di scrivere...
/// </summary>
/// <param name="exception"></param>
/// <param name="message"></param>
/// <param name="args"></param>
protected void lgFatal(Exception exception, string message, params object[] args)
{
lg.Fatal(exception, message, args);
}
/// <summary>
/// Effettua logging INFO corretto impostanto anche la variabile IOB prima di scrivere...
/// </summary>
/// <param name="message"></param>
protected void lgInfo(string message)
{
lg.Info(message);
}
/// <summary>
/// Effettua logging INFO corretto impostanto anche la variabile IOB prima di scrivere...
/// </summary>
/// <param name="message"></param>
/// <param name="args"></param>
protected void lgInfo(string message, params object[] args)
{
lg.Info(message, args);
}
/// <summary>
/// Effettua logging INFO corretto impostanto anche la variabile IOB prima di scrivere...
/// </summary>
/// <param name="message"></param>
protected void lgTrace(string message)
{
lg.Trace(message);
}
/// <summary>
/// Effettua logging INFO corretto impostanto anche la variabile IOB prima di scrivere...
/// </summary>
/// <param name="message"></param>
/// <param name="args"></param>
protected void lgTrace(string message, params object[] args)
{
lg.Trace(message, args);
}
/// <summary>
/// Metodo da overridare x scrivere DAVVERO i parametri sul PLC
/// </summary>
/// <param name="updatedPar"></param>
protected virtual void plcWriteParams(ref List<objItem> updatedPar)
{
// non faccio nulla di base...
}
/// <summary>
/// Processa le richieste di scrittura memoria
/// </summary>
/// <returns></returns>
protected string processMemWriteRequests()
{
string answ = "";
// li salvo nei parametri in memoria locale (ogni adapter DOVREBBE salvare POI sul VERO PLC)
List<objItem> writeList = new List<objItem>();
List<objItem> updatedPar = new List<objItem>();
// recupero elenco delle cose da fare
string resp = getParams2write();
if (!string.IsNullOrEmpty(resp))
{
try
{
writeList = JsonConvert.DeserializeObject<List<objItem>>(resp);
// se ho da fare chiamo esecuzione..
if (writeList.Count > 0)
{
foreach (var item in writeList)
{
// scrivo in memoria
if (memMap.mMapWrite.ContainsKey(item.uid))
{
memMap.mMapWrite[item.uid].value = item.reqValue;
// accodo in stringa taskVal...
answ += $" | Parameter {item.uid} --> {item.reqValue}";
// sistemo valori
item.value = item.reqValue;
lgInfo($"Richiesta update parametro {item.uid} | actVal = {item.value} | reqVal = {item.reqValue}");
item.reqValue = "";
// salvo in lista da ritrasmettere
updatedPar.Add(item);
}
else
{
answ += $" | Error: parameter {item.uid} not found";
}
}
// richiamo scrittura parametri su PLC
plcWriteParams(ref updatedPar);
// invio su cloud parametri!
string rawData = JsonConvert.SerializeObject(updatedPar);
lgInfo("Notifica a server scrittura parametri");
#if false
utils.callUrl($"{urlUpdateWriteParams}", rawData);
#endif
}
}
catch (Exception exc)
{
lgError($"Eccezione in processMemWriteRequests:{Environment.NewLine}{exc}");
}
}
else
{
lgError("Non è stata ricevuta risposta x task da eseguire");
}
return answ;
}
/// <summary>
/// setup parametri da file di conf
/// </summary>
protected void setupMemMap()
{
lgInfo($"setupMemMap | trovati {memMap.mMapRead.Count} parametri Read (TSVC)");
lgInfo($"setupMemMap | trovati {memMap.mMapWrite.Count} parametri Write");
if (confMan.GetValue<bool>("verbose"))
{
string rawMemConf = JsonConvert.SerializeObject(memMap, Formatting.Indented);
lgDebug($"setupMemMap | configurazione memoria R/W:{Environment.NewLine}{rawMemConf}");
}
// se ho variabili read --> genero dati TSVC...
if (memMap.mMapRead.Count > 0)
{
TSVC_Data.Clear();
LastTSVC.Clear();
VCData currConf;
int periodo = 0;
VC_func funz = VC_func.POINT;
// accodo nella conf...
foreach (var item in memMap.mMapRead)
{
funz = item.Value.func;
periodo = item.Value.period;
currConf = new VCData()
{
Funzione = funz,
Period = periodo,
DTStart = DateTime.Now.AddHours(-1),
dataArray = new List<double>()
};
TSVC_Data.Add(item.Key, currConf);
}
// documento...
foreach (var item in TSVC_Data)
{
lgTrace($"TSVC: {item.Key} | periodo: {item.Value.Period} | funz: {item.Value.Funzione}");
// salvo i valori PREC...
LastTSVC.Add(item.Key, 0);
}
}
}
#endregion Protected Methods
#region Private Properties
internal string configPath { get; set; } = "";
internal IConfigurationRoot? confMan { get; set; } = null!;
#endregion Private Properties
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,59 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Version>1.12206.1410</Version>
</PropertyGroup>
<ItemGroup>
<None Remove="appsettings.json" />
</ItemGroup>
<ItemGroup>
<Content Include="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="NLog" Version="5.0.1" />
<PackageReference Include="OPCFoundation.NetStandard.Opc.Ua.Client" Version="1.4.368.58" />
<PackageReference Include="OPCFoundation.NetStandard.Opc.Ua.Configuration" Version="1.4.368.58" />
<PackageReference Include="OPCFoundation.NetStandard.Opc.Ua.Core" Version="1.4.368.58" />
<PackageReference Include="OPCFoundation.NetStandard.Opc.Ua.Security.Certificates" Version="1.4.368.58" />
<PackageReference Include="StackExchange.Redis" Version="2.5.43" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MP.MONO.Core\MP.MONO.Core.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="conf\ModeList.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="conf\AlarmList.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="conf\ParamList.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="conf\StatusList.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="powershell.exe -ExecutionPolicy Unrestricted -NoProfile -NonInteractive -File $(ProjectDir)\post-build.ps1 -ProjectDir $(ProjectDir) -ProjectPath $(ProjectPath)" />
</Target>
</Project>
+291
View File
@@ -0,0 +1,291 @@
using Microsoft.Extensions.Configuration;
using MP.MONO.ADAPTER;
using MP.MONO.Core;
using MP.MONO.Core.CONF;
using MP.MONO.Core.DTO;
using Newtonsoft.Json;
using NLog;
using StackExchange.Redis;
// init parte config, vedere https://blog.hildenco.com/2020/05/configuration-in-net-core-console.html
var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var builder = new ConfigurationBuilder()
.AddJsonFile($"appsettings.json", true, true)
.AddJsonFile($"appsettings.{env}.json", true, true)
.AddEnvironmentVariables();
var config = builder.Build();
// imposto variabili di base
string lineSep = "---------------------------------------------";
string redisConf = config.GetConnectionString("Redis");
string confPath = Path.Combine(Directory.GetCurrentDirectory(), "conf");
#if false
string alarmSimMode = config.GetValue<string>("AlarmSimMode");
#endif
Logger Log = LogManager.GetCurrentClassLogger();
Random rand = new Random();
List<MachineStatus>? statusList = new List<MachineStatus>();
List<MachineMode>? modeList = new List<MachineMode>();
// fix numero minimo dei thread pool x evitare collasso chiamate redis
ThreadPool.SetMinThreads(10, 10);
Dictionary<string, int> LogSimulator = new Dictionary<string, int>();
Dictionary<string, DateTime> LastSend = new Dictionary<string, DateTime>();
DateTime lastLog = DateTime.Now.AddMinutes(-1);
bool verboseLog = false;
bool logWriting = false;
logInfo(lineSep, true, true);
logInfo($"Starting Machine ADAPTER", true, true);
logInfo($"Redis server param: {redisConf.Substring(0, 20)}...", false, true);
logInfo(lineSep, true, true);
logInfo("", true, true);
logInfo("Running - press CTRL-C to stop SIM", false, true);
logInfo("", false, true);
// Setup REDIS
ConnectionMultiplexer.SetFeatureFlag("preventthreadtheft", true);
ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(redisConf);
ISubscriber sub = redis.GetSubscriber();
IDatabase? redisDb = redis.GetDatabase();
// salvo configurazioni in redis
setupConf();
// avvio il vero e proprio programma di comunicaizone OPC-UA
var currIob = new IobOpcUa(confPath, config);
#if false
var currSimGen = new Simulator(confPath, modeList.Count, statusList.Count);
// preparo la lista dei contatori invio...
LogSimulator.Add(Constants.ACT_LOG_M_QUEUE, 0);
LogSimulator.Add(Constants.ALARM_M_QUEUE, 0);
LogSimulator.Add(Constants.EVENT_LOG_M_QUEUE, 0);
LogSimulator.Add(Constants.PARAMS_M_QUEUE, 0);
LogSimulator.Add(Constants.PROD_M_QUEUE, 0);
LogSimulator.Add(Constants.MACH_STATS_M_QUEUE, 0);
LogSimulator.Add(Constants.MAINT_STATS_M_QUEUE, 0);
LogSimulator.Add(Constants.TOOLS_M_QUEUE, 0);
// avvio tutti i thread...
Thread threadStatus = new Thread(simStatus);
Thread threadAlarms = new Thread(simAlarms);
Thread threadParams = new Thread(simParameters);
Thread threadProd = new Thread(simProd);
Thread threadMachStat = new Thread(simMachStat);
Thread threadMaint = new Thread(simMaint);
Thread threadTools = new Thread(simTools);
Thread threadEvHistory = new Thread(simEvents);
Thread threadActLog = new Thread(simActivityLog);
threadStatus.Start();
threadAlarms.Start();
threadParams.Start();
threadProd.Start();
threadMachStat.Start();
threadMaint.Start();
threadTools.Start();
threadEvHistory.Start();
threadActLog.Start();
#endif
// Ciclo infinito x attesa chiusura con CTRL-C
do
{
// se non fosse connesso... riprovo la connessione...
if (!currIob.connectionOk)
{
currIob.tryConnect();
}
// attesa...
Thread.Sleep(100);
} while (true);
/// <summary>
/// verifica esistenza file oppure lo crea...
/// </summary>
void checkFilePresent(string filePath)
{
// verific presenza file log...
if (!File.Exists(filePath))
{
File.WriteAllText(filePath, $"{filePath} created!");
}
}
/// <summary>
/// Setup e salvataggio redis delle conf (es modi/stati)
/// </summary>
void setupConf()
{
#if false
// leggo e salvo conf stati
string fullPath = Path.Combine(confPath, "StatusList.json");
if (File.Exists(fullPath))
{
var rawData = File.ReadAllText(fullPath);
if (!string.IsNullOrEmpty(rawData))
{
List<MachineStatus>? statusList = JsonConvert.DeserializeObject<List<MachineStatus>>(rawData);
// salvo in redis!
redisDb.StringSetAsync(Constants.STATUS_CONF_KEY, JsonConvert.SerializeObject(statusList));
}
}
// leggo e salvo conf modi
fullPath = Path.Combine(confPath, "ModeList.json");
if (File.Exists(fullPath))
{
var rawData = File.ReadAllText(fullPath);
if (!string.IsNullOrEmpty(rawData))
{
var localObj = JsonConvert.DeserializeObject<List<MachineMode>>(rawData);
// salvo in redis!
redisDb.StringSetAsync(Constants.MODE_CONF_KEY, JsonConvert.SerializeObject(localObj));
}
}
// leggo e salvo conf allarmi
fullPath = Path.Combine(confPath, "AlarmList.json");
if (File.Exists(fullPath))
{
var rawData = File.ReadAllText(fullPath);
if (!string.IsNullOrEmpty(rawData))
{
var localObj = JsonConvert.DeserializeObject<List<BaseAlarmConf>>(rawData);
if (localObj != null)
{
// sistemo allarmi
foreach (var item in localObj)
{
item.setupData();
// loggo
logInfo($"Decodifica aree alarmMap: {item.description} | {item.memAddr} x {item.size} byte | {item.messages.Count} messaggi allarme", true, true);
}
}
// salvo in redis!
redisDb.StringSetAsync(Constants.ALARMS_CONF_KEY, JsonConvert.SerializeObject(localObj));
}
}
// leggo e salvo conf parametri
fullPath = Path.Combine(confPath, "ParamList.json");
if (File.Exists(fullPath))
{
var rawData = File.ReadAllText(fullPath);
if (!string.IsNullOrEmpty(rawData))
{
var localObj = JsonConvert.DeserializeObject<List<DisplayDataDTO>>(rawData);
// salvo in redis!
redisDb.StringSetAsync(Constants.PARAMS_CONF_KEY, JsonConvert.SerializeObject(localObj));
}
}
#endif
ConfigManager configManager = new ConfigManager(redisConf, confPath);
_ = configManager.getAlarmsConf();
_ = configManager.getMachineModeConf();
_ = configManager.getMachineStatusConf();
_ = configManager.getParamsConf();
}
/// <summary>
/// Effettua log INFO su file e se richiesto su console
/// </summary>
void logInfo(string msg, bool log2file = true, bool log2console = false)
{
if (log2console)
{
Console.WriteLine(msg);
}
if (log2file)
{
Log.Info(msg);
}
}
/// <summary>
/// Effettua log ERROR su file e se richiesto su console
/// </summary>
void logError(string msg, bool log2file = true, bool log2console = false)
{
if (log2console)
{
Console.WriteLine(msg);
}
if (log2file)
{
Log.Error(msg);
}
}
void saveAndSendMessage(string memKey, string value, string notifyChannel, string message)
{
// effettuo la scrittura nell'area di memoria indicata SE passato intervallo minimo
bool doSend = true;
if (LastSend.ContainsKey(memKey))
{
if (DateTime.Now.Subtract(LastSend[memKey]).TotalSeconds < 60)
{
doSend = false;
}
}
else
{
LastSend.Add(memKey, DateTime.Now);
}
if (doSend)
{
redisDb.StringSetAsync(memKey, value);
LastSend[memKey] = DateTime.Now;
logInfo($"Redis Cache Key: {memKey}");
}
//redisDb.SetAdd(memKey, value);
// invio notifica tramite il canale richiesto
sub.Publish(notifyChannel, message);
if (verboseLog)
{
logInfo($"[{notifyChannel}] key: {memKey} | val: {value} | message: {message}");
}
else
{
try
{
if (!logWriting)
{
if (LogSimulator.ContainsKey(notifyChannel))
{
LogSimulator[notifyChannel]++;
}
else
{
LogSimulator.Add(notifyChannel, 1);
}
logWriting = true;
// vedo se loggare...
DateTime adesso = DateTime.Now;
if (adesso.Subtract(lastLog).TotalSeconds > 15)
{
lastLog = adesso;
logInfo(lineSep);
// lavoro su copia...
var LogSimulatorCopy = new Dictionary<string, int>(LogSimulator);
foreach (var item in LogSimulatorCopy)
{
logInfo($"Redis mQueue {item.Key,-20}{item.Value,12}");
}
logInfo(lineSep);
}
logWriting = false;
}
}
catch (Exception ex)
{
logError($"ERROR{Environment.NewLine}{ex}");
}
}
}
@@ -0,0 +1,26 @@
<body>
<i>MAPO-MONO</i>
<h4>Version: {{CURRENT-REL}}</h4>
<br /> Release Note:
<ul>
<li>
<b>Last changes:</b>
<ul>{{LAST-CHANGES}}</ul>
</li>
<li>
<b>v.1.0.* &rarr;</b>
<ul>
<li>Current CORE version</li>
<li>Release dotnet6</li>
</ul>
</li>
</ul>
<div>
<div style="float: left;">
<img src="logoSteamware.png" />
</div>
<div style="float: right;">
<a href="https://www.steamware.net/MAPO" target="_blank">&copy; Egalware 2006-2022</a>
</div>
</div>
</body>
@@ -0,0 +1,26 @@
<body>
<i>MAPO-MONO</i>
<h4>Version: 1.12206.1410</h4>
<br /> Release Note:
<ul>
<li>
<b>Last changes:</b>
<ul>{{LAST-CHANGES}}</ul>
</li>
<li>
<b>v.1.0.* &rarr;</b>
<ul>
<li>Current CORE version</li>
<li>Release dotnet6</li>
</ul>
</li>
</ul>
<div>
<div style="float: left;">
<img src="logoSteamware.png" />
</div>
<div style="float: right;">
<a href="https://www.steamware.net/MAPO" target="_blank">&copy; Egalware 2006-2022</a>
</div>
</div>
</body>
@@ -0,0 +1 @@
1.12206.1410
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<item>
<version>1.0.0.0</version>
<url>http://nexus.steamware.net/repository/SWS/{{DIRNAME}}/{{BRANCHNAME}}/{{PACKNAME}}.zip</url>
<changelog>http://nexus.steamware.net/repository/SWS/{{DIRNAME}}/{{BRANCHNAME}}/ChangeLog.html</changelog>
<mandatory>false</mandatory>
</item>
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<item>
<version>1.12206.1410</version>
<url>http://nexus.steamware.net/repository/SWS/MP.MONO.ADAPTER/stable/LAST/MP.Mon.zip</url>
<changelog>http://nexus.steamware.net/repository/SWS/MP.MONO.ADAPTER/stable/LAST/ChangeLog.html</changelog>
<mandatory>false</mandatory>
</item>
File diff suppressed because it is too large Load Diff
+47
View File
@@ -0,0 +1,47 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"Redis": "nkcredis.steamware.net:6379,DefaultDatabase=7,connectTimeout=5000,syncTimeout=5000,asyncTimeout=5000,abortConnect=false,ssl=false,password=nkc.password",
"AuthConnection": "Server=localhost;port=3306;database=GWMS;user=GWMS;pwd=GWMS_secret_pwd;sslmode=None;",
"DefaultConnection": "Server=localhost;port=3306;database=MAPO.MONO;user=GWMS;pwd=GWMS_secret_pwd;sslmode=None;",
"AdminConnection": "Server=localhost;port=3306;database=MAPO.MONO;user=root;pwd=Egalware_24068!;sslmode=None;",
"MP.MONO.Data": "Server=localhost;port=3306;database=MAPO.MONO;user=GWMS;pwd=GWMS_secret_pwd;sslmode=None;"
},
"DbConfig": {
"Server": "10.74.82.230",
"nKey": "MONO",
"sKey": "Calcium0xide-CaO"
},
"MachineId": 1,
"maxRecord": 15,
"ExternalProviders": {
"MailKit": {
"SMTP": {
"Address": "smtp.gmail.com",
"Port": "465",
"Account": "steamwarebot@gmail.com",
"Password": "drmfsls16",
"SenderEmail": "steamwarebot@gmail.com",
"SenderName": "Steamware Email BOT"
}
}
},
"Endpoint": {
"IpAddress": "192.168.0.2",
"Port": "4840",
"PingMsTimeout": 1500
},
"ENABLE_DATA_FILTER": true,
"ENABLE_CLI_RESTART": true,
"logEvery": 10,
"OPC_PARAM_CONF": "MULTIAX.json",
"pingTestSec": 5,
"verbose": false,
"verboseLogTOut": 60
}
+52
View File
@@ -0,0 +1,52 @@
[
{
"description": "General Alarm",
"tipoMem": "DInt",
"memAddr": "40901",
"index": 901,
"size": 2,
"messages": [
"Alarm 001",
"Alarm 002",
"Alarm 003",
"Alarm 004",
"Alarm 005",
"Alarm 006",
"Alarm 007",
"Alarm 008",
"Alarm 009",
"Alarm 010",
"Alarm 011",
"Alarm 012",
"##Alarm 013",
"##Alarm 014",
"##Alarm 015",
"##Alarm 016"
]
},
{
"description": "Secondary Alarm",
"tipoMem": "DInt",
"memAddr": "40907",
"index": 907,
"size": 2,
"messages": [
"Warning 001",
"Warning 002",
"Warning 003",
"Warning 004",
"Warning 005",
"Warning 006",
"Warning 007",
"Warning 008",
"##Warning 009",
"##Warning 010",
"##Warning 011",
"##Warning 012",
"Warning 013",
"Warning 014",
"Warning 015",
"Warning 016"
]
}
]
+129
View File
@@ -0,0 +1,129 @@
{
"BrowseFullVal": "ns=1;s=OSAI-PLC",
"BrowseNSIndex": 4,
"BrowseValue": 5001,
"keyPartCount": "50_2_COUNTER CYCLE",
"keyPartReq": "",
"keyPartId": "",
"keyProgName": "",
"keyRunMode": "51_1_MODE",
"pingAsPowerOn": true,
"condWork": [
{
"keyName": "1_1_MACHINE STATUS",
"targetValue": "ON"
}
],
"condPowerOn": {
"checkMode": "AND",
"checkList": [
{
"keyName": "1_1_MACHINE STATUS",
"targetValue": "ON"
},
{
"keyName": "51_1_MODE",
"targetValue": "AUTO"
},
{
"keyName": "50_1_STATUS",
"targetValue": "RUN"
}
]
},
"condReady": {
"checkMode": "AND",
"checkList": [
{
"keyName": "51_1_MODE",
"targetValue": "AUTO"
}
]
},
"condManual": {
"checkMode": "AND",
"checkList": [
{
"keyName": "51_1_MODE",
"targetValue": "HOLD"
}
]
},
"condEStop": {
"checkMode": "AND",
"checkList": [
{
"keyName": "IO_121.02",
"targetValue": "True"
}
]
},
"condError": {
"checkMode": "AND",
"checkList": [
{
"keyName": "IO_120.08",
"targetValue": "True"
}
]
},
"condCountEnabled": {
"checkMode": "AND",
"checkList": []
},
"condWarmUpCoolDown": {
"checkMode": "OR",
"checkList": [
{
"keyName": "IO_120.04",
"targetValue": "True"
},
{
"keyName": "IO_120.05",
"targetValue": "True"
}
]
},
"fluxLogVeto": [
"L2p1CommonVariable"
],
"itemTranslation": {
"avail": "Machine Available",
"rstat": "Execution Mode",
"mode": "Controller Mode",
"ncprog": "Program Name",
"IO_150": "Qta Prodotta (metri)",
"lpremain": "Qta Richiesta",
"fdovrd": "PATH FEED OVERRIDE",
"rovrd": "PATH RAPID OVERRIDE"
},
"paramsEndThresh": {
"InvDDone": 50
},
"mMapWrite": {
"setPzComm": {
"name": "setPzComm",
"description": "Qty",
"tipoMem": "Int",
"memAddr": "ns=4;s=IO_153",
"index": 0,
"size": -1
},
"setComm": {
"name": "setComm",
"description": "Commessa",
"tipoMem": "String",
"memAddr": "ns=4;s=ST80",
"index": 0,
"size": 20
},
"setArt": {
"name": "setArt",
"description": "Articolo",
"tipoMem": "String",
"memAddr": "ns=4;s=ST80",
"index": 20,
"size": 20
}
}
}
+58
View File
@@ -0,0 +1,58 @@
[
{
"MModeID": 0,
"Description": "UNDEFINED",
"Css": "bg-dark text-light",
"Priority": 1,
"Group": "POWEROFF"
},
{
"MModeID": 1,
"Description": "EXE",
"Css": "bg-success text-light",
"Priority": 2,
"Group": "RUN"
},
{
"MModeID": 2,
"Description": "READY",
"Css": "bg-primary text-light",
"Priority": 3,
"Group": "MANUAL"
},
{
"MModeID": 3,
"Description": "HOLD",
"Css": "bg-warning text-light",
"Priority": 3,
"Group": "MANUAL"
},
{
"MModeID": 4,
"Description": "FEED_HOLD",
"Css": "bg-warning text-light",
"Priority": 3,
"Group": "MANUAL"
},
{
"MModeID": 5,
"Description": "OPTIONAL_STOP",
"Css": "bg-danger text-warning",
"Priority": 3,
"Group": "ERROR"
},
{
"MModeID": 6,
"Description": "PROGRAM_STOPPED",
"Css": "bg-warning text-light",
"Priority": 3,
"Group": "MANUAL"
},
{
"MModeID": 7,
"Description": "DONE",
"Css": "bg-primary text-light",
"Priority": 3,
"Group": "MANUAL"
}
]
+125
View File
@@ -0,0 +1,125 @@
[
{
"Order": 3,
"Type": "SPEED-5000-10000",
"Title": "SPEED",
"Value": "4000",
"ValueNum": 4000,
"MinVal": 1000,
"MaxVal": 10000,
"DisplFormat": "N0",
"IsNumeric": true,
"EnablePlot": true,
"ShowBar": true,
"CssIcon": "fa-solid fa-gauge-high",
"SamplePeriod": 180,
"VcFunc": "MEDIAN"
},
{
"Order": 2,
"Type": "FEED-3000-5000",
"Title": "FEED",
"Value": "2500",
"ValueNum": 2500,
"MinVal": 1000,
"MaxVal": 5000,
"DisplFormat": "N0",
"IsNumeric": true,
"EnablePlot": true,
"ShowBar": true,
"CssIcon": "fa-solid fa-gauge-high",
"SamplePeriod": 180,
"VcFunc": "MEDIAN"
},
{
"Order": 1,
"Type": "LOAD",
"Title": "SPINDLE LOAD",
"Value": "30",
"ValueNum": 30,
"MinVal": 0,
"MaxVal": 100,
"DisplFormat": "N1",
"IsNumeric": true,
"EnablePlot": true,
"ShowBar": true,
"CssIcon": "fa-solid fa-bolt",
"SamplePeriod": 180,
"VcFunc": "MEDIAN"
},
{
"Order": 4,
"Type": "POS",
"Title": "X POS",
"Value": "1500",
"ValueNum": 1500,
"MinVal": 0,
"MaxVal": 5000,
"DisplFormat": "N2",
"IsNumeric": true,
"EnablePlot": true,
"CssIcon": "fa-solid fa-ruler-horizontal",
"SamplePeriod": 180,
"VcFunc": "MEDIAN"
},
{
"Order": 5,
"Type": "POS",
"Title": "Y POS",
"Value": "5000",
"ValueNum": 5000,
"MinVal": 0,
"MaxVal": 10000,
"DisplFormat": "N2",
"IsNumeric": true,
"EnablePlot": true,
"CssIcon": "fa-solid fa-ruler-horizontal",
"SamplePeriod": 180,
"VcFunc": "MEDIAN"
},
{
"Order": 6,
"Type": "POS",
"Title": "Z POS",
"Value": "-1500",
"ValueNum": -1500,
"MinVal": -3000,
"MaxVal": 0,
"DisplFormat": "N2",
"IsNumeric": true,
"EnablePlot": true,
"CssIcon": "fa-solid fa-ruler-horizontal",
"SamplePeriod": 180,
"VcFunc": "MEDIAN"
},
{
"Order": 7,
"Type": "POS",
"Title": "A POS",
"Value": "150",
"ValueNum": 150,
"MinVal": 0,
"MaxVal": 360,
"DisplFormat": "N3",
"IsNumeric": true,
"EnablePlot": true,
"CssIcon": "fa-solid fa-rotate-right",
"SamplePeriod": 180,
"VcFunc": "MEDIAN"
},
{
"Order": 8,
"Type": "POS",
"Title": "B POS",
"Value": "150",
"ValueNum": 150,
"MinVal": 0,
"MaxVal": 360,
"DisplFormat": "N3",
"IsNumeric": true,
"EnablePlot": true,
"CssIcon": "fa-solid fa-rotate-right",
"SamplePeriod": 180,
"VcFunc": "MEDIAN"
}
]
+58
View File
@@ -0,0 +1,58 @@
[
{
"MStatusID": 0,
"Description": "UNDEFINED",
"Css": "bg-dark text-light",
"Priority": 1,
"Group": "POWEROFF"
},
{
"MStatusID": 1,
"Description": "POWEROFF",
"Css": "bg-secondary text-light",
"Priority": 1,
"Group": "POWEROFF"
},
{
"MStatusID": 2,
"Description": "AUTOMATIC",
"Css": "bg-success text-light",
"Priority": 2,
"Group": "RUN"
},
{
"MStatusID": 3,
"Description": "EDIT",
"Css": "bg-warning text-light",
"Priority": 3,
"Group": "MANUAL"
},
{
"MStatusID": 4,
"Description": "SEMIAUTOMATIC",
"Css": "bg-warning text-light",
"Priority": 3,
"Group": "MANUAL"
},
{
"MStatusID": 5,
"Description": "MANUAL_JOG",
"Css": "bg-warning text-light",
"Priority": 3,
"Group": "MANUAL"
},
{
"MStatusID": 6,
"Description": "ALARM",
"Css": "bg-danger text-warning",
"Priority": 3,
"Group": "ERROR"
},
{
"MStatusID": 7,
"Description": "ESTOP",
"Css": "bg-danger text-light",
"Priority": 3,
"Group": "ERROR"
}
]
+32
View File
@@ -0,0 +1,32 @@
param([string]$ProjectDir, [string]$ProjectPath);
$FileMajMin = "..\MajMin.vers"
$FileVers = "Resources\VersNum.txt"
$FileManIn = "Resources\manifest-original.xml"
$FileManOut = "Resources\manifest.xml"
$FileCLogIn = "Resources\ChangeLog-original.html"
$FileCLogOut = "Resources\ChangeLog.html"
$MajMin = Get-Content $FileMajMin
$currentDate = get-date -format yyMM;
$currentTime = get-date -format dHH;
$find = "<Version>(.|\n)*?</Version>";
$currRelNum = $MajMin + $currentDate +"." + $currentTime
$replace = "<Version>" + $MajMin + $currentDate +"." + $currentTime + "</Version>";
$csproj = Get-Content $ProjectPath
$csprojUpdated = $csproj -replace $find, $replace
Set-Content -Path $ProjectPath -Value $csprojUpdated
Set-Content -Path $FileVers -Value $currRelNum
# replace x manifest
$manData = Get-Content $FileManIn
$manData = $manData -replace "1.0.0.0", $currRelNum
$manData = $manData -replace "{{DIRNAME}}", "MP.MONO.ADAPTER"
$manData = $manData -replace "{{BRANCHNAME}}", "stable/LAST"
$manData = $manData -replace "{{PACKNAME}}", "MP.Mon"
Set-Content -Path $FileManOut -Value $manData
# replace x ChangeLog
$clogData = Get-Content $FileCLogIn
$clogData = $clogData -replace "{{CURRENT-REL}}", $currRelNum
Set-Content -Path $FileCLogOut -Value $clogData