643 lines
17 KiB
C#
643 lines
17 KiB
C#
using Newtonsoft.Json;
|
|
using NLog;
|
|
using S7.Net;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Net;
|
|
using System.Net.NetworkInformation;
|
|
using System.Reflection;
|
|
using System.Windows.Forms;
|
|
|
|
namespace IOB.WIN.FileExp
|
|
{
|
|
public partial class IOB_Exporter : Form
|
|
{
|
|
#region oggetti di base
|
|
|
|
/// <summary>
|
|
/// configurazione principale proxy
|
|
/// </summary>
|
|
protected dataProxy currDataProxy;
|
|
/// <summary>
|
|
/// Oggetto PLC da ri-utilizzare...
|
|
/// </summary>
|
|
protected Plc currPLC;
|
|
/// <summary>
|
|
/// parametri di connessione
|
|
/// </summary>
|
|
protected connParam parametri;
|
|
/// <summary>
|
|
/// oggetto logging
|
|
/// </summary>
|
|
public static Logger lg;
|
|
/// <summary>
|
|
/// oggetto uiTimer x gestione refresh UI
|
|
/// </summary>
|
|
protected Timer uiTimer = new Timer();
|
|
/// <summary>
|
|
/// oggetto uiTimer x sampling file testuale
|
|
/// </summary>
|
|
protected Timer sampleTimer = new Timer();
|
|
/// <summary>
|
|
/// oggetto uiTimer x verifiche
|
|
/// </summary>
|
|
protected Timer checkTimer = new Timer();
|
|
/// <summary>
|
|
/// Contatore per decidere quando loggare la lettura del file
|
|
/// </summary>
|
|
protected int loaderLogCounter = 30;
|
|
/// <summary>
|
|
/// Directory base delle risorse (virtuale)
|
|
/// </summary>
|
|
protected const string RESOURCE_DIRECTORY = @"IOB.WIN.FileExp.Config.";
|
|
/// <summary>
|
|
/// file delle conf attivo
|
|
/// </summary>
|
|
protected const string setupFile = RESOURCE_DIRECTORY + @"setup.json";
|
|
/// <summary>
|
|
/// File output x salvataggio
|
|
/// </summary>
|
|
protected string outFilePath = @"C:\TMP\OutFile.csv";
|
|
/// <summary>
|
|
/// Ultimi valori registrati da file
|
|
/// </summary>
|
|
protected Dictionary<string, string> prevValues;
|
|
/// <summary>
|
|
/// valori correntemente letti dal file
|
|
/// </summary>
|
|
protected Dictionary<string, string> currValues;
|
|
#endregion
|
|
|
|
#region inizializazione
|
|
|
|
public IOB_Exporter()
|
|
{
|
|
InitializeComponent();
|
|
myInit();
|
|
}
|
|
|
|
private void myInit()
|
|
{
|
|
lg = LogManager.GetCurrentClassLogger();
|
|
tsslApp.Text = $"{utils.CRS("appName")}";
|
|
fixVisibility();
|
|
prevValues = new Dictionary<string, string>();
|
|
currValues = new Dictionary<string, string>();
|
|
loadMemConf();
|
|
loadPlc();
|
|
startUiTimer();
|
|
#if false
|
|
startSampleTimer();
|
|
startCheckTimer();
|
|
#endif
|
|
}
|
|
|
|
private void fixVisibility()
|
|
{
|
|
bool showParams = false;
|
|
#if DEBUG
|
|
showParams = true;
|
|
#endif
|
|
lblPlcIp.Visible = showParams;
|
|
lblPlcCpu.Visible = showParams;
|
|
lblPlcRack.Visible = showParams;
|
|
lblPlcSlot.Visible = showParams;
|
|
txtIP.Visible = showParams;
|
|
txtCpuType.Visible = showParams;
|
|
txtRack.Visible = showParams;
|
|
txtSlot.Visible = showParams;
|
|
}
|
|
|
|
private void startUiTimer()
|
|
{
|
|
uiTimer.Interval = 20;
|
|
uiTimer.Tick += UiTimer_Tick;
|
|
uiTimer.Start();
|
|
}
|
|
private void startSampleTimer()
|
|
{
|
|
int sampleTimerMs = utils.CRI("sampleTimerMs");
|
|
sampleTimerMs = sampleTimerMs < 100 ? 100 : sampleTimerMs;
|
|
sampleTimer.Interval = sampleTimerMs;
|
|
sampleTimer.Tick += SampleTimer_Tick;
|
|
sampleTimer.Start();
|
|
}
|
|
private void startCheckTimer()
|
|
{
|
|
// ogni 5 minuti watchdog
|
|
checkTimer.Interval = sampleTimer.Interval * 60;
|
|
checkTimer.Tick += CheckTimer_Tick;
|
|
checkTimer.Start();
|
|
}
|
|
/// <summary>
|
|
/// init PLC
|
|
/// </summary>
|
|
private void loadPlc()
|
|
{
|
|
lgInfo("Refreshing connection...");
|
|
parametri = currDataProxy.confPLC;
|
|
// ora tento avvio PLC... SE PING OK...
|
|
if (testPing() == IPStatus.Success)
|
|
{
|
|
try
|
|
{
|
|
lgInfo($"PLC parameters: CPU {parametri.tipoCpu} | IP: {parametri.ipAdrr} | R/S: {parametri.rack}/{parametri.slot}");
|
|
currPLC = new Plc(parametri.tipoCpu, parametri.ipAdrr, parametri.rack, parametri.slot);
|
|
currPLC.Open();
|
|
if (currPLC.IsConnected)
|
|
{
|
|
lgInfo("PLC Connected!");
|
|
}
|
|
else
|
|
{
|
|
lgInfo("Connection error!");
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
lgError(exc, "Errore in INIT PLC");
|
|
}
|
|
}
|
|
}
|
|
/// <summary>
|
|
/// Init conf memoria
|
|
/// </summary>
|
|
protected void loadMemConf()
|
|
{
|
|
lgInfo("Starting loadMemConf");
|
|
|
|
// recupero conf da resources
|
|
Assembly myAssembly = Assembly.GetExecutingAssembly();
|
|
//var resNames = myAssembly.GetManifestResourceNames();
|
|
using (Stream confStream = myAssembly.GetManifestResourceStream(setupFile))
|
|
{
|
|
using (StreamReader fileReader = new StreamReader(confStream))
|
|
{
|
|
string jsonData = fileReader.ReadToEnd();
|
|
if (!string.IsNullOrEmpty(jsonData))
|
|
{
|
|
lgInfo("Setup File found!");
|
|
try
|
|
{
|
|
currDataProxy = JsonConvert.DeserializeObject<dataProxy>(jsonData);
|
|
// verifica num max variabili (MAX 8...)
|
|
if (currDataProxy.parametersList.Count > 8)
|
|
{
|
|
lgInfo("Invalid config, reduce params list");
|
|
while (currDataProxy.parametersList.Count > 8)
|
|
{
|
|
currDataProxy.parametersList.Remove(currDataProxy.parametersList.LastOrDefault().Key);
|
|
}
|
|
}
|
|
|
|
lgInfo("Completed data deserialization");
|
|
}
|
|
catch
|
|
{
|
|
currDataProxy = null;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if (currDataProxy == null)
|
|
{
|
|
lgInfo($"File NOT found: {setupFile} - creating new");
|
|
dataConf newParam = new dataConf()
|
|
{
|
|
Column = "Valore assoluto",
|
|
Index = 8,
|
|
MemConf = "DB701.DBD142",
|
|
DataType = "real"
|
|
};
|
|
Dictionary<string, dataConf> paramList = new Dictionary<string, dataConf>();
|
|
paramList.Add(newParam.MemConf, newParam);
|
|
// creo nuovo obj...
|
|
currDataProxy = new dataProxy()
|
|
{
|
|
TriggerMemConf = "DB700.DBB0",
|
|
confPLC = new connParam()
|
|
{
|
|
ipAdrr = "192.168.0.102",
|
|
tipoCpu = CpuType.S71500,
|
|
rack = 0,
|
|
slot = 1
|
|
},
|
|
parametersList = paramList
|
|
};
|
|
}
|
|
|
|
// adesso valorizzo tutti i parametri
|
|
outFilePath = utils.CRS("csvFilePath");
|
|
txtCsvPath.Text = outFilePath;
|
|
txtIP.Text = currDataProxy.confPLC.ipAdrr;
|
|
txtCpuType.Text = $"{currDataProxy.confPLC.tipoCpu}";
|
|
txtRack.Text = $"{currDataProxy.confPLC.rack}";
|
|
txtSlot.Text = $"{currDataProxy.confPLC.slot}";
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region metodi ricorrenti
|
|
|
|
/// <summary>
|
|
/// Esecuzione task UI
|
|
/// </summary>
|
|
/// <param name="sender"></param>
|
|
/// <param name="e"></param>
|
|
private void UiTimer_Tick(object sender, EventArgs e)
|
|
{
|
|
toolStripProgressBar1.ProgressBar.Value++;
|
|
if (toolStripProgressBar1.ProgressBar.Value >= toolStripProgressBar1.ProgressBar.Maximum)
|
|
{
|
|
toolStripProgressBar1.ProgressBar.Value = 0;
|
|
}
|
|
}
|
|
/// <summary>
|
|
/// Esecuzione task di verifica periodica
|
|
/// </summary>
|
|
/// <param name="sender"></param>
|
|
/// <param name="e"></param>
|
|
private void CheckTimer_Tick(object sender, EventArgs e)
|
|
{
|
|
// loggo!
|
|
lgInfo("Program Alive control...");
|
|
//verifico PLC
|
|
if (currPLC.IsConnected)
|
|
{
|
|
lgInfo("PLC Connected!");
|
|
}
|
|
else
|
|
{
|
|
lgInfo("Connection error!");
|
|
}
|
|
// verifico file
|
|
if(false)
|
|
{
|
|
// se non esiste --> creo con headers se richiesto!
|
|
}
|
|
}
|
|
/// <summary>
|
|
/// Esecuzione task di campionamento
|
|
/// </summary>
|
|
/// <param name="sender"></param>
|
|
/// <param name="e"></param>
|
|
private void SampleTimer_Tick(object sender, EventArgs e)
|
|
{
|
|
// rileggo il file
|
|
reloadTriggersFromPLC();
|
|
|
|
// verifico valore confrontando con i precedenti...
|
|
if (dataChanged())
|
|
{
|
|
// loggo!
|
|
lgInfo("Data Change on PLC");
|
|
//rileggo dal PLC
|
|
readDataFromPLC();
|
|
// invio a PLC
|
|
saveToFile();
|
|
}
|
|
}
|
|
|
|
|
|
|
|
#endregion
|
|
|
|
#region helper methods
|
|
|
|
/// <summary>
|
|
/// salva i dati sul FILE in append
|
|
/// </summary>
|
|
private void saveToFile()
|
|
{
|
|
// FIXME TODO salvare su file
|
|
#if false
|
|
// invio TUTTI i dati al PLC secondo configurazione...
|
|
if (testCncConn())
|
|
{
|
|
// decodifico memoria...
|
|
memAddress memoria = null;
|
|
double valore = -999;
|
|
foreach (var item in currValues)
|
|
{
|
|
memoria = new memAddress(item.Key);
|
|
double.TryParse(item.Value, out valore);
|
|
// hard coded REAL!!!
|
|
byte[] DB_Byte = new byte[4];
|
|
S7.Net.Types.Double.ToByteArray(valore).CopyTo(DB_Byte, 0);
|
|
currPLC.WriteBytes(DataType.DataBlock, memoria.DbNum, memoria.indiceMem, DB_Byte);
|
|
// loggo invio al PLC!
|
|
lgInfo($"Value sent to PLC: {item.Key} | {valore}");
|
|
}
|
|
}
|
|
#endif
|
|
}
|
|
/// <summary>
|
|
/// Effettua comparazioen dati vecchi/nuovi
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
private bool dataChanged()
|
|
{
|
|
bool answ = false;
|
|
// se i 2 vettori sono diversi
|
|
if (currValues.Count != prevValues.Count)
|
|
{
|
|
resetPrevVal();
|
|
return true;
|
|
}
|
|
// verifico ogni singolo valore...
|
|
foreach (var item in currValues)
|
|
{
|
|
// cerco...
|
|
if (prevValues.ContainsKey(item.Key))
|
|
{
|
|
// verifico se diversi --> trovato cambio!
|
|
answ = currValues[item.Key] != prevValues[item.Key];
|
|
}
|
|
else
|
|
{
|
|
answ = true;
|
|
}
|
|
// se ho cambiamenti --> esco!
|
|
if (answ)
|
|
{
|
|
// salvo ed esco subito
|
|
resetPrevVal();
|
|
return true;
|
|
}
|
|
}
|
|
return answ;
|
|
}
|
|
/// <summary>
|
|
/// Refresh oggetto valori precedenti
|
|
/// </summary>
|
|
private void resetPrevVal()
|
|
{
|
|
// salvo ed esco subito
|
|
prevValues = new Dictionary<string, string>();
|
|
foreach (var item in currValues)
|
|
{
|
|
prevValues.Add(item.Key, item.Value);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Effettua rilettura da PLC dei triggers data
|
|
/// </summary>
|
|
protected void reloadTriggersFromPLC()
|
|
{
|
|
#if false
|
|
if (File.Exists(currDataProxy.csvFilePath))
|
|
{
|
|
// leggo...
|
|
using (StreamReader sr = new StreamReader(currDataProxy.csvFilePath))
|
|
{
|
|
string currentLine;
|
|
//se ha header salto la prima riga...
|
|
if (currDataProxy.csvFileEnableWrite)
|
|
{
|
|
if ((currentLine = sr.ReadLine()) == null)
|
|
{
|
|
// vuoto: loggo ed esco!
|
|
lgError("Errore intestazione vuota!");
|
|
return;
|
|
}
|
|
}
|
|
// ora leggo la riga successiva... SE !=null
|
|
|
|
if ((currentLine = sr.ReadLine()) != null)
|
|
{
|
|
// splitto riga e cerco valore...
|
|
var valori = currentLine.Split(currDataProxy.csvSeparator);
|
|
// cerco parametri!
|
|
try
|
|
{
|
|
foreach (var item in currDataProxy.parametersList)
|
|
{
|
|
// cerco!
|
|
if (valori.Count() >= item.Value.Index)
|
|
{
|
|
upsertValue(item.Key, valori[item.Value.Index]);
|
|
}
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
lgError($"Eccezione i decodifica riga misura: {Environment.NewLine}{exc}");
|
|
}
|
|
loaderLogCounter--;
|
|
if (loaderLogCounter < 0)
|
|
{
|
|
// loggo che ho letto file e che contiene una certa riga...
|
|
lgInfo($"Verifica periodica riga file, contenuto:{Environment.NewLine}{currentLine}");
|
|
loaderLogCounter = 30;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
// vuoto: loggo ed esco!
|
|
lgError("Errore riga vuota!");
|
|
return;
|
|
}
|
|
loaderLogCounter--;
|
|
if (loaderLogCounter < 0)
|
|
{
|
|
// loggo che ho letto file e che contiene una certa riga...
|
|
lgInfo("Check periodico file presente OK");
|
|
loaderLogCounter = 30;
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
lgError($"Errore! file non trovato: {currDataProxy.csvFilePath}");
|
|
}
|
|
#endif
|
|
}
|
|
|
|
/// <summary>
|
|
/// Effettua rilettura da file
|
|
/// </summary>
|
|
protected void readDataFromPLC()
|
|
{
|
|
#if false
|
|
if (File.Exists(currDataProxy.csvFilePath))
|
|
{
|
|
// leggo...
|
|
using (StreamReader sr = new StreamReader(currDataProxy.csvFilePath))
|
|
{
|
|
string currentLine;
|
|
//se ha header salto la prima riga...
|
|
if (currDataProxy.csvFileEnableWrite)
|
|
{
|
|
if ((currentLine = sr.ReadLine()) == null)
|
|
{
|
|
// vuoto: loggo ed esco!
|
|
lgError("Errore intestazione vuota!");
|
|
return;
|
|
}
|
|
}
|
|
// ora leggo la riga successiva... SE !=null
|
|
|
|
if ((currentLine = sr.ReadLine()) != null)
|
|
{
|
|
// splitto riga e cerco valore...
|
|
var valori = currentLine.Split(currDataProxy.csvSeparator);
|
|
// cerco parametri!
|
|
try
|
|
{
|
|
foreach (var item in currDataProxy.parametersList)
|
|
{
|
|
// cerco!
|
|
if (valori.Count() >= item.Value.Index)
|
|
{
|
|
upsertValue(item.Key, valori[item.Value.Index]);
|
|
}
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
lgError($"Eccezione i decodifica riga misura: {Environment.NewLine}{exc}");
|
|
}
|
|
loaderLogCounter--;
|
|
if (loaderLogCounter < 0)
|
|
{
|
|
// loggo che ho letto file e che contiene una certa riga...
|
|
lgInfo($"Verifica periodica riga file, contenuto:{Environment.NewLine}{currentLine}");
|
|
loaderLogCounter = 30;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
// vuoto: loggo ed esco!
|
|
lgError("Errore riga vuota!");
|
|
return;
|
|
}
|
|
loaderLogCounter--;
|
|
if (loaderLogCounter < 0)
|
|
{
|
|
// loggo che ho letto file e che contiene una certa riga...
|
|
lgInfo("Check periodico file presente OK");
|
|
loaderLogCounter = 30;
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
lgError($"Errore! file non trovato: {currDataProxy.csvFilePath}");
|
|
}
|
|
#endif
|
|
}
|
|
|
|
protected void upsertValue(string key, string value)
|
|
{
|
|
// cerco se ci sia... aggiorno!
|
|
if (currValues.ContainsKey(key))
|
|
{
|
|
currValues[key] = value;
|
|
}
|
|
// altrimenti aggiungo
|
|
else
|
|
{
|
|
currValues.Add(key, value);
|
|
}
|
|
|
|
}
|
|
|
|
/// <summary>
|
|
/// test ping all'indirizzo impostato nei parametri
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
private IPStatus testPing()
|
|
{
|
|
IPStatus answ = IPStatus.Unknown; ;
|
|
IPAddress address;
|
|
PingReply reply;
|
|
Ping pingSender = new Ping();
|
|
address = IPAddress.Loopback;
|
|
IPAddress.TryParse(parametri.ipAdrr, out address);
|
|
reply = pingSender.Send(address, 100);
|
|
answ = reply.Status;
|
|
return answ;
|
|
}
|
|
/// <summary>
|
|
/// Test connessione CNC
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
private bool testCncConn()
|
|
{
|
|
bool answ = false;
|
|
IPStatus pingStatus = testPing();
|
|
// se passa il ping faccio il resto...
|
|
if (pingStatus != IPStatus.Success)
|
|
{
|
|
lgError("Errore ping");
|
|
}
|
|
else
|
|
{
|
|
if (!currPLC.IsConnected)
|
|
{
|
|
currPLC.Open();
|
|
}
|
|
|
|
if (!currPLC.IsConnected)
|
|
{
|
|
lgError("Errore connessione");
|
|
}
|
|
else
|
|
{
|
|
answ = true;
|
|
}
|
|
}
|
|
return answ;
|
|
}
|
|
private void appenRTLog(string contenuto)
|
|
{
|
|
// se troppe righe trimmo...
|
|
string fullLog = limitLine2show($"{contenuto}{Environment.NewLine}{txtLog.Text}");
|
|
// update
|
|
txtLog.Text = fullLog;
|
|
}
|
|
/// <summary>
|
|
/// Effettua un trim della stringa al numero max di linee da mostrare a video
|
|
/// </summary>
|
|
/// <param name="newString"></param>
|
|
/// <returns></returns>
|
|
public string limitLine2show(string newString)
|
|
{
|
|
if (!string.IsNullOrEmpty(newString))
|
|
{
|
|
// se num righe superiore a limite trimmo...
|
|
if (newString.Split('\n').Length > 50)
|
|
{
|
|
//int idx = newString.LastIndexOf('\r');
|
|
int idx = newString.LastIndexOf(Environment.NewLine);
|
|
newString = newString.Substring(0, idx);
|
|
}
|
|
}
|
|
return newString;
|
|
}
|
|
protected void lgInfo(string contenuto)
|
|
{
|
|
lg.Info(contenuto);
|
|
appenRTLog(contenuto);
|
|
}
|
|
|
|
|
|
protected void lgError(string contenuto)
|
|
{
|
|
lg.Error(contenuto);
|
|
appenRTLog(contenuto);
|
|
}
|
|
protected void lgError(Exception exc, string contenuto)
|
|
{
|
|
lg.Error(exc, contenuto);
|
|
appenRTLog(contenuto);
|
|
}
|
|
|
|
#endregion
|
|
}
|
|
}
|