Files
Mapo-IOB-WIN/IOB-WIN-NEXT/IobModbusTCPHam.cs
T
2021-11-04 16:45:04 +01:00

254 lines
9.0 KiB
C#

using EasyModbus;
using IOB_UT_NEXT;
using MapoSDK;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
namespace IOB_WIN_NEXT
{
/* --------------------------------------------------------------------------------
* Controlli ModBusTCP COMECA
* - protocollo ModBus TCP HAM
* - specifico comportamento impianti HAM Pizzaferri
*
* STRUTTURA MEMORIA a banchi di byte, convertiti successivamente in bit/int/real:
* lettura: xxx byte,
* scrittura yyy byte
* G:\Drive condivisi\30_Clienti\Pizzaferri\Impianti\HAM
*
* -------------------------------------------------------------------------------- */
public class IobModbusTCPHam : IobModbusTCP
{
#region Public Constructors
/// Classe base con i metodi x ModBusTCP
/// </summary>
/// <param name="caller"></param>
/// <param name="adpConf"></param>
public IobModbusTCPHam(AdapterForm caller, IobConfiguration IOBConf) : base(caller, IOBConf)
{
lgInfo("NEW IOB ModBus TCP HAM");
// provo lettura una prima volta i dati DYN
if (currPLC != null && currPLC.Connected)
{
try
{
processDynData();
}
catch (Exception exc)
{
lgError($"Eccezione in processDynData iniziale x ModBus TCP HAM:{Environment.NewLine}{exc}");
}
}
}
#endregion Public Constructors
#region Private Methods
private void testBlockRead(int baseAddr, int numByte)
{
int baseHold = 40001;
int[] readTestFull = new int[2];
lgInfo($"-------------------- Inizio test lettura {baseAddr} --------------------");
try
{
stopwatch.Restart();
readTestFull = currPLC.ReadHoldingRegisters(baseAddr - baseHold, numByte);
stopwatch.Stop();
lgInfo($"Stats lettura | {readTestFull.Length} val | {stopwatch.ElapsedMilliseconds}ms");
}
catch
{ }
for (int i = 0; i < readTestFull.Length / 2; i++)
{
int[] thisSet = new int[2];
Array.Copy(readTestFull, i * 2, thisSet, 0, 2);
lgInfo($"{baseAddr + i * 2:000} | HoldingRegisters: {thisSet[0]} / {thisSet[1]} | Val Real: {ModbusClient.ConvertRegistersToFloat(thisSet):N6}");
}
lgInfo("-------------------- Completato test lettura {baseAddr} --------------------");
}
private void testRead()
{
//Ip-Address and Port of Modbus-TCP-Server
//currPLC = new ModbusClient(cIobConf.cncIpAddr, 502);
////Connect to Server
//currPLC.Connect();
//modbusClient.WriteMultipleCoils(4, new bool[] { true, true, true, true, true, true, true, true, true, true }); //Write Coils starting with Address 5
//bool[] readCoils = modbusClient.ReadCoils(9, 10); //Read 10 Coils from Server, starting with address 10
//int[] readHoldingRegisters = currPLC.ReadHoldingRegisters(0, 34); //Read 10 Holding Registers from Server, starting with Address 1
foreach (var item in memSetR)
{
testBlockRead(item.Key, item.Value);
}
}
#endregion Private Methods
#region Protected Methods
/// <summary>
/// Effettua decodifica aree memoria alla bitmap usata x MAPO/GWMS
/// - per lo scopo specifico IN REALTA' non conta lo stato macchina.... ma lo inviamo lo stesso
/// </summary>
protected override void decodeToBaseBitmap()
{
// init a zero...
B_input = 0;
/* -----------------------------------------------------
* bitmap MAPO STANDARD
* B0: POWER_ON
* B1: RUN
* B2: pzCount
* B3: allarme
*
----------------------------------------------------- */
var MemInt = new byte[2];
int byteSignals = 0;
// bit 0 (poweron) imposto a 1 SE connected...
if (currPLC.Connected)
{
byteSignals += (1 << 0);
}
// processo dagli stati + gravi...
if (hasAlarms)
{
byteSignals += (1 << 3);
}
else
{
byteSignals += (1 << 1);
}
// salvo!
B_input = byteSignals;
}
#endregion Protected Methods
#region Public Methods
/// <summary>
/// Override connessione
/// </summary>
public override void tryConnect()
{
bool doLog = (verboseLog || periodicLog);
lgInfo("ModBus TCP HAM: tryConnect step 01");
if (!connectionOk)
{
// SE è necessario refresh...
if (needRefresh)
{
lgInfo("ModBus TCP HAM: tryConnect step 02");
// reimporto parametri PLC se necessario...
setParamPlc();
}
lgInfo("ModBus TCP HAM: tryConnect step 03");
// controllo che il ping sia stato tentato almeno pingTestSec fa...
if (DateTime.Now.Subtract(lastPING).TotalSeconds > utils.CRI("pingTestSec"))
{
if (doLog)
{
lgInfo("ModBus TCP HAM: ConnKO - tryConnect");
}
lgInfo("ModBus TCP HAM: tryConnect step 04");
// in primis salvo data ping...
lastPING = DateTime.Now;
// se passa il ping faccio il resto...
if (testPingMachine == IPStatus.Success)
{
string szStatusConnection = "ND";
try
{
// ora provo connessione...
parentForm.commPlcActive = true;
currPLC.Connect();
szStatusConnection = "OPEN";
parentForm.commPlcActive = false;
connectionOk = currPLC.Connected;
lgInfo($"StatusConnection: {szStatusConnection}");
// refresh stato allarmi!!!
if (connectionOk)
{
if (adpRunning)
{
lgInfo($"Connessione OK: {connectionOk} | adpRunning: {adpRunning}");
}
}
else
{
lgError("Impossibile procedere, connessione mancante...");
}
}
catch (Exception exc)
{
lgFatal($"Errore in TryConnect adapter ModBusTCP | szStatusConnection {szStatusConnection}{Environment.NewLine}{exc}");
connectionOk = false;
needRefresh = true;
}
}
else
{
// loggo no risposta ping ...
connectionOk = false;
if (doLog)
{
lgInfo($"Attenzione: ModBusTCP controllo PING fallito per IP {cIobConf.cncIpAddr}");
}
}
}
}
// 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
{
currPLC.Disconnect();
connectionOk = false;
lgInfo(szStatusConnection);
lgInfo("Effettuata disconnessione adapter ModBusTCP!");
}
catch (Exception exc)
{
lgFatal(exc, "Errore nella disconnessione dall'adapter ModBusTCP");
}
}
else
{
lgError("IMPOSSIBILE effettuare disconnessione ModBusTCP: Connessione non disponibile...");
}
}
#endregion Public Methods
}
}