1097 lines
42 KiB
C#
1097 lines
42 KiB
C#
using IOB_UT;
|
|
using MapoSDK;
|
|
using MTConnect.Clients;
|
|
using Newtonsoft.Json;
|
|
using System;
|
|
using System.Threading.Tasks;
|
|
using Opc.Ua;
|
|
using Opc.Ua.Configuration;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Net.NetworkInformation;
|
|
using System.Threading;
|
|
using System.Windows.Forms;
|
|
|
|
namespace IOB_WIN_NEXT
|
|
{
|
|
public class IobOpcUa : IobGeneric
|
|
{
|
|
#region Private Fields
|
|
|
|
/// <summary>
|
|
/// Struttura dove vengono memorizzati i dataitem ed i rispettivi valori x processing
|
|
/// </summary>
|
|
private Dictionary<string, OpcUaDataItemExt> dataItemMem = new Dictionary<string, OpcUaDataItemExt>();
|
|
|
|
/// <summary>
|
|
/// Elenco degli items da monitorare come risultato del browse iniziale
|
|
/// </summary>
|
|
private Dictionary<string, string> selectedItemList = new Dictionary<string, string>();
|
|
|
|
#endregion Private Fields
|
|
|
|
#region Protected Fields
|
|
|
|
/// <summary>
|
|
/// Abilitazione restart (da opt par...)
|
|
/// </summary>
|
|
protected bool enableCliRestart = false;
|
|
|
|
/// <summary>
|
|
/// Gestione filtraggio dati
|
|
/// </summary>
|
|
protected bool enableDataFilter = false;
|
|
|
|
/// <summary>
|
|
/// Determina se ha effettuata lettura items in memoria x confronto...
|
|
/// </summary>
|
|
protected bool hasReadItems = false;
|
|
|
|
/// <summary>
|
|
/// Ultimo current received x gestione update periodico...
|
|
/// </summary>
|
|
protected DateTime lastCurrent = DateTime.Now;
|
|
|
|
/// <summary>
|
|
/// Oggetto MAIN x connessione MTC
|
|
/// </summary>
|
|
protected UAClient UA_ref;
|
|
|
|
/// <summary>
|
|
/// Veto controllos tatus x log...
|
|
/// </summary>
|
|
protected DateTime vetoCheckStatus = DateTime.Now;
|
|
|
|
#endregion Protected Fields
|
|
|
|
#region Public Constructors
|
|
|
|
/// <summary>
|
|
/// Estende l'init della classe base, impiegando il pacchetto Nuget OPC-UA foundation
|
|
/// https://github.com/OPCFoundation/UA-.NETStandard
|
|
/// </summary>
|
|
/// <param name="caller"></param>
|
|
/// <param name="IOBConf"></param>
|
|
public IobOpcUa(AdapterForm caller, IobConfiguration IOBConf) : base(caller, IOBConf)
|
|
{
|
|
// gestione invio ritardato contapezzi
|
|
pzCountDelay = utils.CRI("pzCountDelay");
|
|
// gestione data filtering...
|
|
if (!string.IsNullOrEmpty(getOptPar("ENABLE_DATA_FILTER")))
|
|
{
|
|
bool.TryParse(getOptPar("ENABLE_DATA_FILTER"), out enableDataFilter);
|
|
}
|
|
// gestione restart MTC client...
|
|
if (!string.IsNullOrEmpty(getOptPar("ENABLE_CLI_RESTART")))
|
|
{
|
|
bool.TryParse(getOptPar("ENABLE_CLI_RESTART"), out enableCliRestart);
|
|
}
|
|
// init datetime counters
|
|
DateTime adesso = DateTime.Now;
|
|
lastPzCountSend = adesso;
|
|
lastWarnODL = adesso;
|
|
lastCurrent = adesso;
|
|
// ora leggo il file di conf specifico....
|
|
string jsonFileName = getOptPar("OPC_PARAM_CONF");
|
|
if (!string.IsNullOrEmpty(jsonFileName))
|
|
{
|
|
// leggo il file...
|
|
loadOpcUaConf(jsonFileName);
|
|
}
|
|
}
|
|
|
|
#endregion Public Constructors
|
|
|
|
#region Protected Properties
|
|
|
|
/// <summary>
|
|
/// Verifico se abbia ALMENO un errore...
|
|
/// </summary>
|
|
protected bool hasError
|
|
{
|
|
get
|
|
{
|
|
return checkMultiCondition(opcUaParams.condError);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Indica se abbia emergenza premuta
|
|
/// </summary>
|
|
protected bool hasEStopTriggered
|
|
{
|
|
get
|
|
{
|
|
return checkMultiCondition(opcUaParams.condEStop);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Parametri specifici MTC
|
|
/// </summary>
|
|
protected OpcUaParamConf opcUaParams { get; set; }
|
|
|
|
/// <summary>
|
|
/// URL x salvataggio elenco dataItems OpcUa
|
|
/// </summary>
|
|
protected string urlSaveDataItems
|
|
{
|
|
get
|
|
{
|
|
string answ = "";
|
|
try
|
|
{
|
|
string machineName = Environment.MachineName;
|
|
answ = $@"http://{cIobConf.serverData.MPIP}{cIobConf.serverData.MPURL}{cIobConf.serverData.CMDALIVE}/saveDataItems/{cIobConf.codIOB}";
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
lgError(exc, "Errore in composizione urlSaveDataItems");
|
|
}
|
|
return answ;
|
|
}
|
|
}
|
|
|
|
#endregion Protected Properties
|
|
|
|
#region Private Methods
|
|
|
|
/// <summary>
|
|
/// Verifica ed invia variazioni
|
|
/// </summary>
|
|
/// <param name="currChange"></param>
|
|
/// <param name="forceSend"></param>
|
|
private void checkAndSend(Opc.Ua.Client.MonitoredItem MonIt, MonitoredItemNotification Notify, bool forceSend)
|
|
{
|
|
if (document != null)
|
|
{
|
|
foreach (var deviceStream in document.DeviceStreams)
|
|
{
|
|
string sVal = "";
|
|
string descr = "";
|
|
DateTime locTStamp = DateTime.Now;
|
|
// check su Conditions
|
|
try
|
|
{
|
|
// check su dataItems (conditions + events + samples)
|
|
foreach (var dataItem in deviceStream.Conditions)
|
|
{
|
|
descr = itemTranslation("C", dataItem.DataItemId);
|
|
locTStamp = dataItem.Timestamp.ToLocalTime();
|
|
sVal = $"CONDITION: {locTStamp.ToString()} | Id: {dataItem.DataItemId} | | Name: {dataItem.Name} | descr: {descr} | Val: {dataItem.CDATA}";
|
|
// condizion verboso SEMPRE!
|
|
lgInfo(sVal);
|
|
DateTime tStamp = dataItem.Timestamp;
|
|
var time2 = tStamp.ToLocalTime();
|
|
// verifico se salvare
|
|
bool changed = checkSaveItem(dataItem);
|
|
if (changed || forceSend)
|
|
{
|
|
// accodare ed invia nella coda ALARMS (che POI salva in document MongoDB anche ultimi x minuti di FluxLog...)
|
|
accodaAlarmLog(sVal, qEncodeFLog(time2, descr, dataItem.CDATA));
|
|
}
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
lgError($"Eccezione in decodifica Conditions x StreamSuccesfull{Environment.NewLine}{exc}", false);
|
|
}
|
|
// check su events
|
|
try
|
|
{
|
|
// check su dataItems (conditions + events + samples)
|
|
foreach (var dataItem in deviceStream.Events)
|
|
{
|
|
descr = itemTranslation("E", dataItem.DataItemId);
|
|
locTStamp = dataItem.Timestamp.ToLocalTime();
|
|
sVal = $"EVENT: {locTStamp.ToString()} | descr: {descr} | Id: {dataItem.DataItemId} | Name: {dataItem.Name} | Val: {dataItem.CDATA}";
|
|
if (isVerboseLog)
|
|
{
|
|
lgInfo(sVal);
|
|
}
|
|
DateTime tStamp = dataItem.Timestamp;
|
|
var time2 = tStamp.ToLocalTime();
|
|
// verifico se salvare
|
|
bool changed = checkSaveItem(dataItem);
|
|
// cerco se non sia un dato filtrato in FLUXLOG...
|
|
|
|
if (changed || forceSend)
|
|
{
|
|
accodaFLog(sVal, qEncodeFLog(time2, descr, dataItem.CDATA));
|
|
}
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
lgError($"Eccezione in decodifica Events x StreamSuccesfull{Environment.NewLine}{exc}", false);
|
|
}
|
|
|
|
// check su samples
|
|
try
|
|
{
|
|
// check su dataItems (conditions + events + samples)
|
|
foreach (var dataItem in deviceStream.Samples)
|
|
{
|
|
descr = itemTranslation("S", dataItem.DataItemId);
|
|
locTStamp = dataItem.Timestamp.ToLocalTime();
|
|
sVal = $"SAMPLE: {locTStamp.ToString()} | descr: {descr} | Id: {dataItem.DataItemId} | | Name: {dataItem.Name} | Val: {dataItem.CDATA}";
|
|
if (isVerboseLog)
|
|
{
|
|
lgInfo(sVal);
|
|
}
|
|
DateTime tStamp = dataItem.Timestamp;
|
|
var time2 = tStamp.ToLocalTime();
|
|
// verifico se salvare
|
|
bool changed = checkSaveSample(dataItem);
|
|
// cerco se non sia un dato filtrato in FLUXLOG...
|
|
bool isFiltered = opcUaParams.fluxLogVeto.Contains(dataItem.DataItemId);
|
|
if (isFiltered)
|
|
{
|
|
if (isVerboseLog)
|
|
{
|
|
lgInfo($"NON ACCODATO sample per {dataItem.DataItemId} poiché trovato VETO in fluxLogVeto", false);
|
|
}
|
|
}
|
|
else
|
|
{
|
|
if (changed || forceSend)
|
|
{
|
|
accodaFLog(sVal, qEncodeFLog(time2, descr, dataItem.CDATA));
|
|
}
|
|
else
|
|
{
|
|
if (isVerboseLog)
|
|
{
|
|
lgInfo($"NON ACCODATO sample per {dataItem.DataItemId} poiché verifica variazione SAMPLE ha dato esito negativo", false);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
lgError($"Eccezione in decodifica Samples x StreamSuccesfull{Environment.NewLine}{exc}");
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
lgError("StreamsSuccessful ERROR: document è null");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Verifica condizione "multipla" secondo setup json
|
|
/// </summary>
|
|
/// <param name="checkList"></param>
|
|
/// <returns></returns>
|
|
private bool checkMultiCondition(List<diCheckCondition> checkList)
|
|
{
|
|
bool answ = false;
|
|
if (checkList != null && checkList.Count > 0)
|
|
{
|
|
int numCond = checkList.Count;
|
|
int numCondOk = 0;
|
|
// cerco nell'elenco delle condizioni che indicano lavora se sono ok faccio +1 conteggio......
|
|
foreach (var item in checkList)
|
|
{
|
|
if (getDataItemValue(item.keyName) == item.targetValue)
|
|
{
|
|
numCondOk++;
|
|
}
|
|
}
|
|
answ = (numCond == numCondOk);
|
|
}
|
|
return answ;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Effettua decodifica aree memoria alla bitmap usata x MAPO
|
|
/// </summary>
|
|
private void decodeToBaseBitmap()
|
|
{
|
|
// init a zero...
|
|
B_input = 0;
|
|
|
|
/* -----------------------------------------------------
|
|
* bitmap MAPO
|
|
* B0: POWER_ON
|
|
* B1: RUN
|
|
* B2: pzCount
|
|
* B3: allarme
|
|
* B4: manuale
|
|
* B5: emergenza
|
|
----------------------------------------------------- */
|
|
|
|
// Controllo booleano PING e POWERON...
|
|
string currPowerOn = getDataItemValue(opcUaParams.condPowerOn.keyName);
|
|
// se valido il check ping lo eseguo... altrimenti lo do x buono
|
|
bool checkPing = !opcUaParams.pingAsPowerOn;
|
|
if (!checkPing)
|
|
{
|
|
checkPing = (testPingMachine == IPStatus.Success);
|
|
}
|
|
// verifico da target value richiesto...
|
|
bool checkPowerOn = (currPowerOn == opcUaParams.condPowerOn.targetValue);
|
|
|
|
// bit 0 (poweron) imposto a 1 SE pingo o PowerOn=="ON"...
|
|
B_input = (checkPing || checkPowerOn) ? 1 : 0;
|
|
|
|
// variabili RUN...
|
|
string currRun = getDataItemValue(opcUaParams.keyRunMode);
|
|
|
|
// controllo RUN MODE preliminare... CABLATO poiché è GENERALE x MTC
|
|
if (currRun == "AUTOMATIC" || currRun == "SEMI_AUTO" || currRun == "SEMI_AUTOMATIC")
|
|
{
|
|
int numCond = opcUaParams.condWork.Count;
|
|
int numCondOk = 0;
|
|
// cerco nell'elenco delle condizioni che indicano lavora se sono ok faccio +1 conteggio......
|
|
foreach (var item in opcUaParams.condWork)
|
|
{
|
|
if (getDataItemValue(item.keyName) == item.targetValue)
|
|
{
|
|
numCondOk++;
|
|
}
|
|
}
|
|
// se tutte condizioni rispettate --> lavora!
|
|
if (numCond == numCondOk)
|
|
{
|
|
// RUN = LAVORA!
|
|
B_input += (1 << 1);
|
|
}
|
|
}
|
|
// se ho emergenza premuta --> emergenza!
|
|
else if (hasEStopTriggered)
|
|
{
|
|
B_input += (1 << 5);
|
|
}
|
|
// se ho almeno 1 allarme E NON SONO IN AUTO --> ALARM!
|
|
else if (hasError)
|
|
{
|
|
B_input += (1 << 3);
|
|
}
|
|
else
|
|
{
|
|
// se ho run mode != auto --> manual
|
|
B_input += (1 << 4);
|
|
}
|
|
|
|
DateTime adesso = DateTime.Now;
|
|
int vFactor = 1;
|
|
// controllo SE HO dati per fare verifiche...
|
|
if (string.IsNullOrEmpty(currRun))
|
|
{
|
|
// se ho parametro x gestione reset...
|
|
if (enableCliRestart)
|
|
{
|
|
// controllo se ho ricevuto il current da OLTRE 1 minuto...
|
|
if (lastCurrent.AddMinutes(3) < adesso)
|
|
{
|
|
lastCurrent = adesso;
|
|
// stop...
|
|
lgInfo("Fermato MTC_ref per mancanza dati current");
|
|
UA_ref.Stop();
|
|
Thread.Sleep(1000);
|
|
// restart
|
|
lgInfo("Riavviato MTC_ref per mancanza dati current");
|
|
UA_ref.Start();
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
vFactor = 6;
|
|
}
|
|
|
|
// solo se non ho veto check
|
|
if (vetoCheckStatus < adesso)
|
|
{
|
|
lgInfo($"Stato variabili: currRun: {currRun}");
|
|
// imposto veto per vetoSeconds...
|
|
vetoCheckStatus = adesso.AddSeconds(vetoSeconds * vFactor);
|
|
}
|
|
// log opzionale!
|
|
if (verboseLog)
|
|
{
|
|
lgInfo($"Trasformazione B_input: {B_input} | currRun = {currRun}");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Vera connessione ad MTC
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
private async Task<short> doConnect()
|
|
{
|
|
IOutput console = new ConsoleOutput();
|
|
short esitoLink = 0;
|
|
// reset memoria dataItem..
|
|
dataItemMem = new Dictionary<string, OpcUaDataItemExt>();
|
|
// predisposizione conf oggetto di comunicazione MTC
|
|
short port = 5000;
|
|
short.TryParse(cIobConf.cncPort, out port);
|
|
// ora avvio
|
|
try
|
|
{
|
|
lgInfo("Start init OpcUa Client");
|
|
// Define the UA Client application
|
|
ApplicationInstance application = new ApplicationInstance();
|
|
application.ApplicationName = "Steamware IOB-WIN Client";
|
|
application.ApplicationType = ApplicationType.Client;
|
|
|
|
// load the application configuration.
|
|
await application.LoadApplicationConfiguration("ConsoleReferenceClient.Config.xml", silent: false);
|
|
// check the application certificate.
|
|
await application.CheckApplicationInstanceCertificate(silent: false, minimumKeySize: 0);
|
|
|
|
lgInfo($"Chiamata UAClient con configurazione standard: {application.ApplicationConfiguration.ApplicationName}");
|
|
UA_ref = new UAClient(application.ApplicationConfiguration, console, ClientBase.ValidateResponse);
|
|
|
|
lgInfo($"Chiamata apertura OpcUa Client: {cIobConf.cncIpAddr}:{port}");
|
|
UA_ref.ServerUrl = $"opc.tcp://{cIobConf.cncIpAddr}:{port}";
|
|
bool connected = await UA_ref.ConnectAsync();
|
|
if (connected)
|
|
{
|
|
// faccio un primo browse dei dati...
|
|
selectedItemList = UA_ref.Browse(opcUaParams.BrowseNSIndex, opcUaParams.BrowseValue);
|
|
// sottoscrivo a rilevazione cambio dati
|
|
List<Opc.Ua.Client.MonitoredItem> subscribedItems = UA_ref.SubscribeToDataChanges(selectedItemList);
|
|
// aggiungo come DataItems
|
|
int dSamplePeriod = 0;
|
|
int threshDBand = 0;
|
|
string uuid = "";
|
|
foreach (var item in subscribedItems)
|
|
{
|
|
OpcUaDataItemExt newItem = formatDataItem(ref dSamplePeriod, ref threshDBand, ref uuid, item);
|
|
dataItemMem.Add(uuid, newItem);
|
|
}
|
|
// gestione eventi change
|
|
UA_ref.eh_MonItChange += UA_ref_eh_MonItChange;
|
|
}
|
|
|
|
esitoLink = 1;
|
|
|
|
// fix tempi!
|
|
DateTime adesso = DateTime.Now;
|
|
lastPzCountSend = adesso;
|
|
lastWarnODL = adesso;
|
|
lastCurrent = adesso;
|
|
}
|
|
catch
|
|
{ }
|
|
return esitoLink;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Formatta un dataitem x salvataggio in memoria locale
|
|
/// </summary>
|
|
/// <param name="dSamplePeriod"></param>
|
|
/// <param name="threshDBand"></param>
|
|
/// <param name="uuid"></param>
|
|
/// <param name="dataItem"></param>
|
|
/// <returns></returns>
|
|
private OpcUaDataItemExt formatDataItem(ref int dSamplePeriod, ref int threshDBand, ref string uuid, Opc.Ua.Client.MonitoredItem dataItem)
|
|
{
|
|
OpcUaDataItemExt currDataItem;
|
|
// calcolo parametri
|
|
uuid = $"OPC_{dataItem.StartNodeId}";
|
|
// SOLO SE è abilitato il datafiltering...
|
|
if (enableDataFilter)
|
|
{
|
|
threshDBand = 1;
|
|
// controllo SE ho conf x deadband...
|
|
if (opcUaParams.paramsEndThresh.Count > 0)
|
|
{
|
|
// ciclo su tutti i parametri indicati...
|
|
foreach (var item in opcUaParams.paramsEndThresh)
|
|
{
|
|
if (uuid.EndsWith(item.Key))
|
|
{
|
|
threshDBand = item.Value;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
threshDBand = 0;
|
|
}
|
|
dSamplePeriod = 60;
|
|
|
|
// salvo oggetto x "uso interno"
|
|
currDataItem = new OpcUaDataItemExt(dataItem)
|
|
{
|
|
uid = uuid,
|
|
thresholdDeadBand = threshDBand,
|
|
samplePeriod = dSamplePeriod
|
|
};
|
|
|
|
return currDataItem;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Effettua lettura file di conf specifico OPC-UA da oggetto serializzato json
|
|
/// <paramref name="fileName">Nome file da cui leggere i parametri json</paramref>
|
|
/// </summary>
|
|
private void loadOpcUaConf(string fileName)
|
|
{
|
|
string jsonFullPath = $"{Application.StartupPath}/DATA/CONF/{fileName}";
|
|
lgInfo($"Apertura file {jsonFullPath}");
|
|
StreamReader reader = new StreamReader(jsonFullPath);
|
|
string jsonData = reader.ReadToEnd().Replace("\n", "").Replace("\r", "");
|
|
if (!string.IsNullOrEmpty(jsonData))
|
|
{
|
|
lgInfo($"File json composto da {jsonData.Length} caratteri");
|
|
try
|
|
{
|
|
opcUaParams = JsonConvert.DeserializeObject<OpcUaParamConf>(jsonData);
|
|
lgInfo($"Decodifica aree OpcUaParamConf: trovati {opcUaParams.paramsEndThresh.Count} valori paramsEndThresh");
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
lgError($"Eccezione in decodifica conf json OPC-UA:{Environment.NewLine}{exc}");
|
|
}
|
|
}
|
|
else
|
|
{
|
|
lgError("Errore in loadOpcUaConf: file json vuoto!");
|
|
}
|
|
reader.Dispose();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Effettua invio a MP/IO dell'elenco serializzato dei dataItems
|
|
/// </summary>
|
|
/// <param name="dataItems"></param>
|
|
private void sendDataItemsList(List<machDataItem> dataItems)
|
|
{
|
|
string rawData = JsonConvert.SerializeObject(dataItems);
|
|
utils.callUrlNow($"{urlSaveDataItems}", rawData);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Evento rilevazione modifica valori --> chiamo checkSend
|
|
/// </summary>
|
|
/// <param name="sender"></param>
|
|
/// <param name="e"></param>
|
|
private void UA_ref_eh_MonItChange(object sender, opcUaMonitItemChange e)
|
|
{
|
|
checkAndSend(e.CurrMonitoredItem, e.CurrNotify, false);
|
|
}
|
|
|
|
#endregion Private Methods
|
|
|
|
#region Protected Methods
|
|
|
|
/// <summary>
|
|
/// Verifica un DataItem e se il valore corrisponde a quello indicato come "true value" restituisce true
|
|
/// </summary>
|
|
/// <param name="itemName"></param>
|
|
/// <param name="trueVal"></param>
|
|
/// <returns></returns>
|
|
protected bool checkDataItem(string itemName, string trueVal)
|
|
{
|
|
bool answ = false;
|
|
OpcUaDataItemExt currValue = null;
|
|
try
|
|
{
|
|
currValue = dataItemMem[itemName];
|
|
answ = (currValue.value.Equals(trueVal));
|
|
}
|
|
catch
|
|
{
|
|
lgError($"Errore in decodifica valore per {itemName} rispetto a {trueVal} | recuperato {currValue} / {currValue.value}");
|
|
}
|
|
return answ;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Verifica / Salva valore generico (NON SAMPLE)
|
|
/// </summary>
|
|
/// <param name="newValue"></param>
|
|
/// <returns></returns>
|
|
protected bool checkSaveItem(MTConnectStreams.DataItem newValue)
|
|
{
|
|
bool answ = !enableDataFilter;
|
|
|
|
if (newValue != null)
|
|
{
|
|
if (isVerboseLog)
|
|
{
|
|
lgInfo($"Richiesta checkSaveItem per {newValue} | id: {newValue.DataItemId} | CDATA: {newValue.CDATA}");
|
|
}
|
|
// verifico in memoria se ho l'oggetto condition ed il suo valore..
|
|
if (dataItemMem.ContainsKey(newValue.DataItemId))
|
|
{
|
|
// salvo sempre!
|
|
dataItemMem[newValue.DataItemId].value = newValue.CDATA;
|
|
dataItemMem[newValue.DataItemId].valueTimestamp = newValue.Timestamp;
|
|
answ = true;
|
|
}
|
|
else
|
|
{
|
|
// registro non trovato da aggiungere...
|
|
lgInfo($"DataItem non trovato in checkSaveItem: {newValue.DataItemId}");
|
|
try
|
|
{
|
|
// provo a creare oggetot in memoria...
|
|
List<machDataItem> elencoDataItems = new List<machDataItem>();
|
|
int dSamplePeriod = 0;
|
|
int threshDBand = 0;
|
|
string uuid = "";
|
|
var currDataItem = formatDataItem(ref dSamplePeriod, ref threshDBand, ref uuid, newValue);
|
|
// aggiungo
|
|
dataItemMem.Add(newValue.DataItemId, currDataItem);
|
|
// salvo oggetto x registrazione su server MP-IO
|
|
var currMapoDataItem = new machDataItem()
|
|
{
|
|
uuid = newValue.DataItemId,
|
|
Category = (DataItemCategory)newValue.Category,
|
|
Name = newValue.Name,
|
|
Type = newValue.Type,
|
|
SubType = newValue.SubType,
|
|
//Units = newValue.Units
|
|
};
|
|
// aggiungo
|
|
elencoDataItems.Add(currMapoDataItem);
|
|
// invio il dataItem serializzato...
|
|
sendDataItemsList(elencoDataItems);
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
lgError($"Eccezione in checkSaveSample{Environment.NewLine}{exc}");
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
lgError("Attenzione: checkSaveItem con newValue null!");
|
|
}
|
|
return answ;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Verifica / Salva valore SAMPLE e restitusice SE sia variato (e quindi da inviare...)
|
|
/// </summary>
|
|
/// <param name="newValue"></param>
|
|
/// <returns></returns>
|
|
protected bool checkSaveSample(MTConnectStreams.Sample newValue)
|
|
{
|
|
bool answ = !enableDataFilter;
|
|
double oldVal = 0;
|
|
double newVal = 0;
|
|
if (newValue != null)
|
|
{
|
|
if (isVerboseLog)
|
|
{
|
|
lgInfo($"Richiesta checkSaveSample per {newValue} | id: {newValue.DataItemId} | CDATA: {newValue.CDATA}");
|
|
}
|
|
// verifico in memoria se ho l'oggetto condition ed il suo valore..
|
|
if (dataItemMem.ContainsKey(newValue.DataItemId))
|
|
{
|
|
MtcDataItemExt currDataItemMem = dataItemMem[newValue.DataItemId];
|
|
// controllo SE SIA scaduto il tempo massimo...
|
|
if (Math.Abs(dataItemMem[newValue.DataItemId].valueTimestamp.Subtract(newValue.Timestamp).TotalSeconds) > currDataItemMem.samplePeriod)
|
|
{
|
|
answ = true;
|
|
}
|
|
else
|
|
{
|
|
// ALTRIMENTI controllo SE diverso
|
|
if (dataItemMem[newValue.DataItemId].value != newValue.CDATA)
|
|
{
|
|
// controllo SE ho DeadBand...
|
|
if (dataItemMem[newValue.DataItemId].thresholdDeadBand > 0)
|
|
{
|
|
if (isVerboseLog)
|
|
{
|
|
lgInfo($"Test deadband: oldVal: {oldVal} | newVal: {newVal}");
|
|
}
|
|
// recupero i valori e testo DeadBand...
|
|
double.TryParse(dataItemMem[newValue.DataItemId].value.Replace(".", ","), out oldVal);
|
|
double.TryParse(newValue.CDATA.Replace(".", ","), out newVal);
|
|
// test deadband!
|
|
if (Math.Abs(newVal - oldVal) > dataItemMem[newValue.DataItemId].thresholdDeadBand)
|
|
{
|
|
// indico da salvare..
|
|
answ = true;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if (answ)
|
|
{
|
|
// salvo!
|
|
dataItemMem[newValue.DataItemId].value = newValue.CDATA;
|
|
dataItemMem[newValue.DataItemId].valueTimestamp = newValue.Timestamp;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
// registro non trovato da aggiungere...
|
|
lgInfo($"DataItem non trovato in checkSaveSample: {newValue.DataItemId}");
|
|
// provo a creare oggetto in memoria...
|
|
try
|
|
{
|
|
List<machDataItem> elencoDataItems = new List<machDataItem>();
|
|
int dSamplePeriod = 0;
|
|
int threshDBand = 0;
|
|
string uuid = "";
|
|
var currDataItem = formatDataItem(ref dSamplePeriod, ref threshDBand, ref uuid, newValue);
|
|
// aggiungo
|
|
dataItemMem.Add(newValue.DataItemId, currDataItem);
|
|
// salvo oggetto x registrazione su server MP-IO
|
|
var currMapoDataItem = new machDataItem()
|
|
{
|
|
uuid = newValue.DataItemId,
|
|
Category = (DataItemCategory)newValue.Category,
|
|
Name = newValue.Name,
|
|
Type = newValue.Type,
|
|
SubType = newValue.SubType,
|
|
//Units = newValue.Units
|
|
};
|
|
// aggiungo
|
|
elencoDataItems.Add(currMapoDataItem);
|
|
// invio il dataItem serializzato...
|
|
sendDataItemsList(elencoDataItems);
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
lgError($"Eccezione in checkSaveSample{Environment.NewLine}{exc}");
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
lgError("Attenzione: checkSaveItem con newValue null!");
|
|
}
|
|
return answ;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Effettuata discovery iniziale valori CURRENT
|
|
/// </summary>
|
|
/// <param name="document"></param>
|
|
/// <param name="forceSend"></param>
|
|
protected void CurrentSuccessful(MTConnectStreams.Document document)
|
|
{
|
|
if (document != null)
|
|
{
|
|
lgInfo($"DiscoverySuccessful: discovery per {document.Url}");
|
|
if (document.DeviceStreams != null)
|
|
{
|
|
lgInfo($"DiscoverySuccessful: trovati {document.DeviceStreams.Count} streams");
|
|
}
|
|
checkAndSend(document, true);
|
|
}
|
|
else
|
|
{
|
|
lgError("StreamsSuccessful ERROR: document è null");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Effettua traduzione ITEM da LUT parametrica (key: tipo+id) del file di conf, se non trovo uso key
|
|
/// </summary>
|
|
/// <param name="tipo"></param>
|
|
/// <param name="id"></param>
|
|
/// <returns></returns>
|
|
protected string itemTranslation(string tipo, string id)
|
|
{
|
|
string answ = "";
|
|
string lemma = $"{tipo}_{id}";
|
|
// cerco nel dizionario delle traduzioni SE esiste un valore e prendo quello, altrimenti uso il lemma...
|
|
if (opcUaParams.itemTranslation.ContainsKey(lemma))
|
|
{
|
|
answ = opcUaParams.itemTranslation[lemma];
|
|
}
|
|
else
|
|
{
|
|
answ = lemma;
|
|
}
|
|
return answ;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Effettua log di un elenco componenti
|
|
/// </summary>
|
|
/// <param name="elencoComponenti"></param>
|
|
protected void logComponentsList(List<MTConnectDevices.Component> elencoComponenti)
|
|
{
|
|
if (elencoComponenti != null)
|
|
{
|
|
foreach (var item in elencoComponenti)
|
|
{
|
|
lgInfo($"Component data | ID: {item.Id} | Name: {item.Name} | Type: {item.Type} | # items: {item.DataItems.Count}");
|
|
// se ho sottocomponenti richiamo...
|
|
if (item.SubComponents != null)
|
|
{
|
|
if (item.SubComponents.Components.Count > 0)
|
|
{
|
|
logComponentsList(item.SubComponents.Components);
|
|
}
|
|
}
|
|
if (item.DataItems.Count > 0)
|
|
{
|
|
logDataItemList(item.DataItems);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Log elenco DataItems
|
|
/// </summary>
|
|
/// <param name="elencoItems"></param>
|
|
protected void logDataItemList(List<MTConnectDevices.DataItem> elencoItems)
|
|
{
|
|
if (elencoItems != null)
|
|
{
|
|
// loggo devices principali...
|
|
foreach (var item in elencoItems)
|
|
{
|
|
lgInfo($"Device data | ID: {item.Id} | Name: {item.Name} | Category: {item.Category} | # Type: {item.Type}");
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Effettua log di un devices (ed eventualmente dei sub-devices...
|
|
/// </summary>
|
|
/// <param name="elencoDevices"></param>
|
|
protected void logDevicesList(List<MTConnectDevices.Device> elencoDevices)
|
|
{
|
|
if (elencoDevices != null)
|
|
{
|
|
// loggo devices principali...
|
|
foreach (var item in elencoDevices)
|
|
{
|
|
lgInfo($"Device data | ID: {item.Id} | Name: {item.Name} | UUID: {item.Uuid} | # items: {item.DataItems.Count}");
|
|
// se ho subItems descrivo pure loro...
|
|
if (item.DataItems.Count > 0)
|
|
{
|
|
logDataItemList(item.DataItems);
|
|
}
|
|
if (item.Components.Components.Count > 0)
|
|
{
|
|
logComponentsList(item.Components.Components);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
#endregion Protected Methods
|
|
|
|
#region Public Methods
|
|
|
|
/// <summary>
|
|
/// Processo i task richiesti e li elimino dalla coda 1:1
|
|
/// </summary>
|
|
/// <param name="task2exe"></param>
|
|
public override Dictionary<string, string> executeTasks(Dictionary<string, string> task2exe)
|
|
{
|
|
// uso metodo base x ora
|
|
return base.executeTasks(task2exe);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Recupera uno specifico dataItem
|
|
/// </summary>
|
|
/// <param name="diKey"></param>
|
|
/// <returns></returns>
|
|
public string getDataItemValue(string diKey)
|
|
{
|
|
string answ = "";
|
|
try
|
|
{
|
|
var currDataItem = dataItemMem[diKey];
|
|
answ = currDataItem.value;
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
Logging.Instance.Error($"Errore in getDataItemValue per {diKey}{Environment.NewLine}{exc}");
|
|
}
|
|
return answ;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Recupero dati dinamici...
|
|
/// </summary>
|
|
public override Dictionary<string, string> getDynData()
|
|
{
|
|
Dictionary<string, string> outVal = new Dictionary<string, string>();
|
|
return outVal;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Effettua vero processing contapezzi
|
|
/// </summary>
|
|
public override void processContapezzi()
|
|
{
|
|
if (utils.CRB("enableContapezzi"))
|
|
{
|
|
// cerco parametro contapezzi...
|
|
string currPzCount = getDataItemValue(opcUaParams.keyPartCount);
|
|
|
|
// se ho un contapezzi... processo...
|
|
if (!string.IsNullOrEmpty(currPzCount))
|
|
{
|
|
int newVal = -1;
|
|
Int32.TryParse(currPzCount, out newVal);
|
|
contapezziPLC = newVal > -1 ? newVal : contapezziPLC;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Effettua lettura semafori principale
|
|
/// <paramref name="currDispData">Parametri da aggiornare x display in form</paramref>
|
|
/// </summary>
|
|
public override void readSemafori(ref newDisplayData currDispData)
|
|
{
|
|
base.readSemafori(ref currDispData);
|
|
try
|
|
{
|
|
if (verboseLog)
|
|
{
|
|
lgInfo("inizio read semafori");
|
|
}
|
|
|
|
currDispData.semIn = Semaforo.SV;
|
|
|
|
// decodifica e gestione
|
|
decodeToBaseBitmap();
|
|
reportRawInput(ref currDispData);
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
currDispData.semIn = Semaforo.SR;
|
|
lgError($"Eccezione in readSemafori:{Environment.NewLine}{exc}");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Effettua reset del contapezzi, NON POSSIBILE in questa versione
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
public override bool resetcontapezziPLC()
|
|
{
|
|
bool answ = false;
|
|
return answ;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Effettua IMPOSTAZIONE FORZATA del contapezzi, NON POSSIBILE in questa versione
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
public override bool setcontapezziPLC(int newPzCount)
|
|
{
|
|
bool answ = false;
|
|
return answ;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Override connessione
|
|
/// </summary>
|
|
public override void tryConnect()
|
|
{
|
|
if (!connectionOk)
|
|
{
|
|
// controllo che il ping sia stato tentato almeno pingTestSec fa...
|
|
if (DateTime.Now.Subtract(lastPING).TotalSeconds > utils.CRI("pingTestSec"))
|
|
{
|
|
if (verboseLog || periodicLog)
|
|
{
|
|
lgInfo("OpcUa: ConnKO - tryConnect");
|
|
}
|
|
// in primis salvo data ping...
|
|
lastPING = DateTime.Now;
|
|
// se passa il ping faccio il resto...
|
|
if (testPingMachine == IPStatus.Success)
|
|
{
|
|
string szStatusConnection = "";
|
|
try
|
|
{
|
|
// ora provo connessione...
|
|
parentForm.commPlcActive = true;
|
|
var task = Task.Run(async () =>
|
|
{
|
|
return await doConnect();
|
|
});
|
|
|
|
short esitoLink = task.Result; // use returned result from async method here
|
|
lgInfo($"szStatusConnection OpcUa, esitoLink: {esitoLink}");
|
|
parentForm.commPlcActive = false;
|
|
connectionOk = true;
|
|
// refresh stato allarmi!!!
|
|
if (connectionOk)
|
|
{
|
|
if (adpRunning)
|
|
{
|
|
lgInfo("Connessione OK");
|
|
}
|
|
}
|
|
else
|
|
{
|
|
lgError("Impossibile procedere, connessione mancante...");
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
lgFatal($"Errore nella connessione all'adapter OpcUa: {szStatusConnection}{Environment.NewLine}{exc}");
|
|
connectionOk = false;
|
|
lgInfo($"Eccezione in TryConnect, Adapter OpcUa NON running, pausa di {utils.CRI("waitRecMSec")} msec prima di ulteriori tentativi di riconnessione");
|
|
}
|
|
}
|
|
else
|
|
{
|
|
// loggo no risposta ping ...
|
|
connectionOk = false;
|
|
if (verboseLog || periodicLog)
|
|
{
|
|
lgInfo($"Attenzione: OpcUa controllo PING fallito per IP {cIobConf.cncIpAddr}");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
needRefresh = true;
|
|
}
|
|
// se non è ancora connesso faccio procesisng memoria caso disconnesso...
|
|
if (!connectionOk)
|
|
{
|
|
// processo semafori ed invio...
|
|
processMemoryDiscon();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Override disconnessione
|
|
/// </summary>
|
|
public override void tryDisconnect()
|
|
{
|
|
if (connectionOk)
|
|
{
|
|
string szStatusConnection = "";
|
|
try
|
|
{
|
|
UA_ref.Disconnect();
|
|
connectionOk = false;
|
|
lgInfo(szStatusConnection);
|
|
lgInfo("Effettuata disconnessione adapter OpcUa!");
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
lgFatal(exc, "Errore nella disconnessione dall'adapter OpcUa");
|
|
}
|
|
}
|
|
else
|
|
{
|
|
lgError("IMPOSSIBILE effettuare disconnessione OpcUa: Connessione non disponibile...");
|
|
}
|
|
}
|
|
|
|
#endregion Public Methods
|
|
}
|
|
} |