Files
Mapo-IOB-WIN/IOB-WIN/IobFanuc.cs
T
2017-12-19 14:54:21 +01:00

656 lines
22 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IOB_UT;
using CncLib.CNC;
using System.Net.NetworkInformation;
using System.Net;
namespace IOB_WIN
{
public class IobFanuc : IobGeneric
{
protected byte[] MemBlockF = new byte[2];
protected byte[] MemBlockG = new byte[44];
protected byte[] MemBlockF_pre = new byte[2];
/// <summary>
/// wrapper chiamata lettura/scrittura SINGOLO BYTE...
/// </summary>
/// <param name="bWrite"></param>
/// <param name="MemType"></param>
/// <param name="memIndex"></param>
/// <param name="Value"></param>
/// <returns></returns>
public bool FanucMemRW(bool bWrite, FANUC.MemType MemType, Int32 memIndex, ref byte Value)
{
bool answ = false;
if (FANUC_ref.Connected)
{
try
{
parentForm.commPlcActive = true;
answ = FANUC_ref.F_RW_Byte(bWrite, MemType, memIndex, ref Value);
}
catch
{ }
}
parentForm.commPlcActive = false;
return answ;
}
/// <summary>
/// wrapper chiamata lettura/scrittura MULTI BYTE...
/// </summary>
/// <param name="bWrite"></param>
/// <param name="MemType"></param>
/// <param name="memIndex"></param>
/// <param name="MATRICE Value"></param>
/// <returns></returns>
public bool FanucMemRW(bool bWrite, FANUC.MemType MemType, Int32 memIndex, ref byte[] Value)
{
bool answ = false;
if (FANUC_ref.Connected)
{
try
{
parentForm.commPlcActive = true;
answ = FANUC_ref.F_RW_Byte(bWrite, MemType, memIndex, ref Value);
}
catch
{ }
}
parentForm.commPlcActive = false;
return answ;
}
/// <summary>
/// Oggetto MAIN x connessione FANUC
/// </summary>
protected FANUC FANUC_ref;
/// <summary>
/// estende l'init della classe base...
/// </summary>
/// <param name="caller"></param>
/// <param name="adpConf"></param>
public IobFanuc(AdapterForm caller, IobConfiguration IOBConf) : base(caller, IOBConf)
{
// i dati RAW principali sono 6 byte...
RawInput = new byte[6];
// è little endian (NON serve conversione)
hasBigEndian = false;
lg.Info("Start init Adapter FANUC all'IP {0}:{1} per IOB {2}", IOBConf.cncIpAddr, IOBConf.cncPort, IOBConf.codIOB);
// Creo oggetto connessione NC
parentForm.commPlcActive = true;
Runtime.CreateNC(CNC.NcType.FANUC, IOBConf.cncIpAddr, IOBConf.cncPort);
parentForm.commPlcActive = false;
// aggiungo referenza obj FANUC
FANUC_ref = (FANUC)Runtime.NC;
if (utils.CRB("verbose")) lg.Info("FANUC_ref da CncLib");
// disconnetto e connetto...
if (utils.CRB("verbose")) lg.Info("FANUC: tryDisconnect");
tryDisconnect();
lg.Info("FANUC: tryConnect");
tryConnect();
lg.Info("End init Adapter FANUC");
}
/// <summary>
/// Override disconnessione
/// </summary>
public override void tryDisconnect()
{
if (connectionOk)
{
string szStatusConnection = "";
try
{
FANUC_ref.Disconnect(ref szStatusConnection);
connectionOk = false;
lg.Info(szStatusConnection);
lg.Info("Effettuata disconnessione adapter FANUC!");
}
catch (Exception exc)
{
lg.Fatal(exc, "Errore nella disconnessione dall'adapter FANUC");
}
}
else
{
lg.Error("IMPOSSIBILE effettuare disconnessione: Connessione non disponibile...");
}
}
/// <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) lg.Info("ConnKO - tryConnect");
// in primis salvo data ping...
lastPING = DateTime.Now;
// ora PING!!!
Ping pingSender = new Ping();
IPAddress address = IPAddress.Loopback;
IPAddress.TryParse(currIobConf.cncIpAddr, out address);
PingReply reply = pingSender.Send(address, 100);
// se passa il ping faccio il resto...
if (reply.Status == IPStatus.Success)
{
string szStatusConnection = "";
try
{
// ora provo connessione...
parentForm.commPlcActive = true;
FANUC_ref.Connect(ref szStatusConnection);
parentForm.commPlcActive = false;
lg.Info("szStatusConnection: " + szStatusConnection);
connectionOk = true;
// refresh stato allarmi!!!
if (connectionOk)
{
if (adpRunning)
{
// carico status allarmi (completo)
lg.Info("Inizio refresh completo stato allarmi...");
forceAlarmCheck();
lg.Info("Completato refresh completo stato allarmi!");
}
else
{
lg.Info("Connessione OK");
}
}
else
{
lg.Error("Impossibile procedere, connessione mancante...");
}
}
catch (Exception exc)
{
lg.Fatal(string.Format("Errore nella connessione all'adapter FANUC: {0}{1}{2}", szStatusConnection, Environment.NewLine, exc));
connectionOk = false;
lg.Info(string.Format("Eccezione in TryConnect, Adapter NON running, pausa di {0} msec prima di ulteriori tentativi di riconnessione", utils.CRI("waitRecMSec")));
}
}
else
{
// loggo no risposta ping ...
connectionOk = false;
if (verboseLog || periodicLog) lg.Info(string.Format("Attenzione: controllo PING fallito per IP {0} - {1}", currIobConf.cncIpAddr, reply.Status));
}
}
}
// se non è ancora connesso faccio procesisng memoria caso disconnesso...
if (!connectionOk)
{
// processo semafori ed invio...
processMemoryDiscon();
}
}
public override void readSemafori()
{
base.readSemafori();
if (verboseLog) lg.Info("inizio read semafori");
parentForm.sIN = Semaforo.SV;
// leggo SEMAFORI, leggo da Y8 ...leggo 3 bit in Y8..Y10 HARD CODED, rendere parametrico!!!
byte[] MemBlock = new byte[4];
// Red: Y8.4 | Yellow: Y8.5 | Green Y8.6 | WrkZone Y8.7 | All DoorsClosed: Y10.5
int memIndex = 8;
inizio = DateTime.Now;
FanucMemRW(R, FANUC.MemType.Y, memIndex, ref MemBlock);
if (utils.CRB("recTime")) TimingData.addResult(string.Format("R{0}-Y", MemBlock.Length), DateTime.Now.Subtract(inizio).Ticks);
// riporto!
Buffer.BlockCopy(MemBlock, 0, RawInput, 0, 4);
// ora mi leggo 2 byte in area X... HARD CODED, rendere parametrico...
MemBlock = new byte[2];
// GESTIONE memoria endcycle
// la variabile X7.0 (da 1 a 0) oppure la X7.1 (da 0 a 1) indica il CONTAPEZZI --> copio 2 byte!
inizio = DateTime.Now;
FanucMemRW(R, FANUC.MemType.X, 6, ref MemBlock);
if (utils.CRB("recTime")) TimingData.addResult(string.Format("R{0}-X", MemBlockF.Length), DateTime.Now.Subtract(inizio).Ticks);
// riporto!
Buffer.BlockCopy(MemBlock, 0, RawInput, 4, 2);
if (verboseLog) lg.Info(string.Format("RawInput: {0}", utils.binaryForm((int)RawInput[0])));
// salvo il solo BYTE dell'input decifrando il semaforo...
decodeToBitmap();
}
/// <summary>
/// Effettua decodifica aree memoria alla bitmap usata x MAPO
/// </summary>
private void decodeToBitmap()
{
// init a zero...
B_input = 0;
// !!!FARE!!! generalizzazione... x ora usa dati "hard coded"...
//Red: Y8.4 | Yellow: Y8.5 | Green Y8.6
// leggo i byte interessati...
int byteSem = RawInput[0];
int byteCount = RawInput[5];
if (verboseLog) lg.Info(string.Format("PrimoByte: {0}", byteSem));
if (utils.CRB("macOnFromConn"))
{
// SE SI E' CONNESSO al FANUC allora è 1...
if (FANUC_ref.Connected)
{
B_input += 1 << 0;
}
}
else
{
// B0: facio un OR tra i 3 semafori...
if ((byteSem & 112) > 0)
{
B_input += 1 << 0;
}
}
// B1: verde! Y8.6
if ((byteSem & 64) > 0)
{
B_input += 1 << 1;
}
// B2: contapezzi da area X
if ((byteCount & 2) > 0)
{
B_input += 1 << 2;
}
// B3: Rosso! Y8.4
if ((byteSem & 16) > 0)
{
B_input += 1 << 3;
}
// B4: giallo! Y8.5
if ((byteSem & 32) > 0)
{
B_input += 1 << 4;
}
// log opzionale!
if (verboseLog) lg.Info(string.Format("Trasformazione B_input: {0}", B_input));
}
/// <summary>
/// Recupero programma in lavorazione
/// </summary>
/// <returns></returns>
public override string getPrgName()
{
string prgName = "";
// recupero NUOVO prgName...
try
{
// recupero nome programma MAIN
prgName = utils.purgedChar2String(FANUC_ref.getPrgNameMain());
// trimmo path del programma, ovvero "CNCMEMUSERPATH1"
prgName = prgName.Replace(utils.CRS("basePrgMemPath"), "");
}
catch (Exception exc)
{
lg.Error(string.Format("Eccezione in recupero PRG NAME MAIN:{0}{1}", Environment.NewLine, exc));
}
return prgName;
}
/// <summary>
/// Recupero programma in lavorazione come Dictionary FANUC...
/// - SYSINFO: (prima KEY globale) TUTTI i valori separati da # (x fare check modifica)
/// - altre stringhe: ogni singolo parametro / valore
/// </summary>
/// <returns></returns>
public override Dictionary<string, string> getSysInfo()
{
Dictionary<string, string> outVal = new Dictionary<string, string>();
inizio = DateTime.Now;
CncLib.Focas1.ODBSYS answ = FANUC_ref.getSysInfo();
if (utils.CRB("recTime")) TimingData.addResult(string.Format("SYS-INFO"), DateTime.Now.Subtract(inizio).Ticks);
try
{
string cnc_type = new string(answ.cnc_type);
string mt_type = new string(answ.mt_type);
string series = new string(answ.series);
string version = new string(answ.version);
string axes = new string(answ.axes);
//short addInfo = answ.addinfo;
short max_axis = answ.max_axis;
// preparo i singoli valori dell'array...
outVal.Add("SYSINFO", string.Format("{0}#{1}#{2}#{3}#{4}#{5}", cnc_type, mt_type, series, version, axes, max_axis));
outVal.Add("CNC", cnc_type);
outVal.Add("MTT", mt_type);
outVal.Add("SER", series);
outVal.Add("VER", version);
outVal.Add("AXS", string.Format("{0}|{1}", axes, max_axis));
}
catch (Exception exc)
{
lg.Error(exc, "Errore in getSysInfo");
}
return outVal;
}
/// <summary>
/// Effettua vero processing contapezzi
/// </summary>
public override void processContapezzi()
{
if (utils.CRB("enableContapezzi"))
{
try
{
// verifico quale modalità sia richiesta: STD (6711) oppure BIT (CUstom, con indicazione area)
if (currIobConf.optPar.Count > 0 && currIobConf.optPar["PZCOUNT_MODE"] != "")
{
if (currIobConf.optPar["PZCOUNT_MODE"] == "STD")
{
object output = new object();
// deve usare F_RW_Param_Integer
FANUC_ref.F_RW_Param_Integer(false, 6711, 3, ref output);
lg.Info(string.Format("Contapezzi 6711: {0}", output));
FANUC_ref.F_RW_Param_Integer(false, 6712, 3, ref output);
lg.Info(string.Format("Contapezzi 6712: {0}", output));
FANUC_ref.F_RW_Param_Integer(false, 6713, 3, ref output);
lg.Info(string.Format("Contapezzi 6713: {0}", output));
// !!!FARE!!! salvo numero!!!
// 6711: pezzi lavorati
// 6712: pezzi lavorati totali
// 6713: pezzi richiesti
// output!
}
else if (currIobConf.optPar["PZCOUNT_MODE"] == "BIT")
{
// posizioni DWord
//1602:543809: NUM PEZZI x ciclo (6408..6411)
//1603:5300: NUM PEZZI RICHIESTI (6412..6415)
//1604:5007: NUM PEZZI FATTI (6416..6419)
//1605:543809: NUM PEZZI TOTALI (6420..6423)
//[OPTPAR]
//ENDCYCLE_MADDR=X7.1
//PZ_CAD_MADDR=1602
//PZ_REQ_MADDR=1603
//PZ_DONE_MADDR=1604
//PZ_GTOT_MADDR=1605
// LEGGO le memorie DW dei vari contatori
// salvo in area locale e confronto con precedenti, dove cambiato INVIO come dato aggiuntivo
}
}
}
catch (Exception exc)
{
lg.Error(exc, "Errore in contapezzi FANUC");
}
}
}
/// <summary>
/// Esegue processing MODE (e nel contempo recupera altri dati dell'area G)
/// </summary>
public override void processMode()
{
if (utils.CRB("enableMode"))
{
try
{
inizio = DateTime.Now;
// leggo tutto da 0 a 43...
int memIndex = 0;
FanucMemRW(R, FANUC.MemType.G, memIndex, ref MemBlockG);
if (utils.CRB("recTime")) TimingData.addResult(string.Format("R{0}-G-AREA", MemBlockG.Length), DateTime.Now.Subtract(inizio).Ticks);
// verifico modo con valore corrente, se cambia aggiorno...
CNC_MODE newMode = decodeG43(MemBlockG[43]);
if (newMode != currMode)
{
// aggiorno!
currMode = newMode;
// conversione NUM MODE in descrizione da ENUM
string descrMode = Enum.GetName(typeof(CNC_MODE), currMode);
// accodo x invio
string sVal = string.Format("[CNC_MODE]{0}", descrMode);
// chiamo accodamento...
accodaFLog(sVal, qEncodeFLog("CNC_MODE", descrMode));
}
}
catch (Exception exc)
{
lg.Error(exc, "Errore in process Mode G43");
}
}
}
/// <summary>
/// decodifica il modo dai valori del byte G43
/// </summary>
/// <param name="currVal"></param>
/// <returns></returns>
protected CNC_MODE decodeG43(byte currVal)
{
// hard coded da valori tabellari a MODI definiti in CNC_MODE...
CNC_MODE answ = CNC_MODE.ND;
switch (currVal)
{
case 0:
answ = CNC_MODE.MDI;
break;
case 1:
answ = CNC_MODE.MEN;
break;
case 3:
answ = CNC_MODE.EDIT;
break;
case 4:
answ = CNC_MODE.HANDLE_INC;
break;
case 5:
answ = CNC_MODE.JOG;
break;
case 6:
answ = CNC_MODE.TJOG;
break;
case 7:
answ = CNC_MODE.THND;
break;
case 33:
answ = CNC_MODE.RMT;
break;
case 133:
answ = CNC_MODE.REF;
break;
default:
answ = CNC_MODE.ND;
break;
}
return answ;
}
/// <summary>
/// Recupero dati dinamici...
/// </summary>
public override Dictionary<string, string> getDynData()
{
Dictionary<string, string> outVal = new Dictionary<string, string>();
inizio = DateTime.Now;
CncLib.Focas1.ODBDY2_1 answ = FANUC_ref.getAllDynData();
if (utils.CRB("recTime")) TimingData.addResult(string.Format("PROC-DYN-DATA"), DateTime.Now.Subtract(inizio).Ticks);
try
{
string actf = answ.actf.ToString();
string acts = answ.acts.ToString();
//string numAlarm = answ.alarm.ToString();
// preparo i singoli valori dell'array...
//outVal.Add("DYNDATA", string.Format("{0}#{1}#{2}", actf, acts, numAlarm));
outVal.Add("DYNDATA", string.Format("FEED {0}#SPEED_RPM {1}", actf, acts));
if (utils.CRB("SendFeedSpeed"))
{
outVal.Add("FEED", actf);
outVal.Add("SPEED_RPM", acts);
//outVal.Add("NUM_ALARM", numAlarm);
}
if (utils.CRB("SendAxPos"))
{
// salvo le posizioni...
CncLib.Focas1.FAXIS posAx = answ.pos;
int[] currPosAbs = posAx.absolute;
int i = 0;
foreach (var item in currPosAbs)
{
i++;
outVal.Add(string.Format("POS_{0:00}", i), item.ToString());
}
}
}
catch (Exception exc)
{
lg.Error(exc, "Errore in getDynData");
}
return outVal;
}
/// <summary>
/// Recupero dati override (da area G che è già stata letta...)
/// </summary>
/// <returns></returns>
public override Dictionary<string, string> getOverrides()
{
Dictionary<string, string> outVal = new Dictionary<string, string>();
outVal.Add("FEED_OVER", MemBlockG[30].ToString());
outVal.Add("RAPID_OVER", MemBlockG[12].ToString());
return outVal;
}
/// <summary>
/// Override salvataggio valori in memoria...
/// </summary>
public override void saveMemDump()
{
dump_MemAreaD();
dump_MemAreaY();
}
public override void sampleMemDump()
{
dump_MemAreaD(6400, 400);
}
/// <summary>
/// Dump PERIODICO area D della memoria
/// </summary>
/// <param name="memIndex">area memoria di partenza</param>
/// <param name="memSyzeByte"></param>
private void dump_MemAreaD(int memIndex, int memSyzeByte)
{
// leggo TUTTI i 9999 byte della memoria D...
byte[] MemBlockD = new byte[memSyzeByte];
inizio = DateTime.Now;
if (verboseLog) lg.Info("START MemDump AreaD");
FanucMemRW(R, FANUC.MemType.D, memIndex, ref MemBlockD);
if (verboseLog) lg.Info("END MemDump AreaD");
if (utils.CRB("recTime")) TimingData.addResult(string.Format("R{0}-MemDumpD", MemBlockD.Length), DateTime.Now.Subtract(inizio).Ticks);
// file out!
string nomeFile = "";
Dictionary<string, string> mappaValori = new Dictionary<string, string>();
// salvo in file i dati letti come DWord (4byte)
nomeFile = string.Format(@"{0}\SAMPLES\MemDump_D_DW_{1:yyyyMMdd_HHmmss}.dat", utils.dataDatDir, DateTime.Now);
for (int i = 0; i < MemBlockD.Length / 4; i++)
{
mappaValori.Add(i.ToString("0000"), BitConverter.ToUInt32(MemBlockD, i * 4).ToString());
}
utils.WritePlain(mappaValori, nomeFile);
}
/// <summary>
/// Dump area D della memoria
/// </summary>
private void dump_MemAreaD()
{
// faccio chaimate e salvo in file dump...
int memIndex = 0;
// leggo TUTTI i 9999 byte della memoria D...
byte[] MemBlockD = new byte[9999];
inizio = DateTime.Now;
if (verboseLog) lg.Info("START MemDump AreaD");
FanucMemRW(R, FANUC.MemType.D, memIndex, ref MemBlockD);
if (verboseLog) lg.Info("END MemDump AreaD");
if (utils.CRB("recTime")) TimingData.addResult(string.Format("R{0}-MemDumpD", MemBlockD.Length), DateTime.Now.Subtract(inizio).Ticks);
//
string nomeFile = "";
// salvo in file i dati letti come BYTE
nomeFile = string.Format(@"{0}\MemDump_D_Byte.dat", utils.dataDatDir);
Dictionary<string, string> mappaValori = new Dictionary<string, string>();
for (int i = 0; i < MemBlockD.Length; i++)
{
mappaValori.Add(i.ToString("0000"), MemBlockD[i].ToString());
}
utils.WritePlain(mappaValori, nomeFile);
// salvo in file i dati letti come DWord (4byte)
nomeFile = string.Format(@"{0}\MemDump_D_DW.dat", utils.dataDatDir);
mappaValori = new Dictionary<string, string>();
for (int i = 0; i < MemBlockD.Length / 4; i++)
{
mappaValori.Add(i.ToString("0000"), BitConverter.ToUInt32(MemBlockD, i * 4).ToString());
}
utils.WritePlain(mappaValori, nomeFile);
// salvo in file i dati letti come DWord (4byte)
nomeFile = string.Format(@"{0}\MemDump_D_W.dat", utils.dataDatDir);
mappaValori = new Dictionary<string, string>();
for (int i = 0; i < MemBlockD.Length / 2; i++)
{
mappaValori.Add(i.ToString("0000"), BitConverter.ToUInt16(MemBlockD, i * 2).ToString());
}
utils.WritePlain(mappaValori, nomeFile);
}
/// <summary>
/// Dump area Y della memoria
/// </summary>
private void dump_MemAreaY()
{
// faccio chaimate e salvo in file dump...
int memIndex = 0;
// leggo TUTTI i 9999 byte della memoria Y...
byte[] MemBlockY = new byte[10];
inizio = DateTime.Now;
if (verboseLog) lg.Info("START MemDump AreaY");
FanucMemRW(R, FANUC.MemType.Y, memIndex, ref MemBlockY);
if (verboseLog) lg.Info("END MemDump AreaY");
if (utils.CRB("recTime")) TimingData.addResult(string.Format("R{0}-MemDumpY", MemBlockY.Length), DateTime.Now.Subtract(inizio).Ticks);
//
string nomeFile = "";
// salvo in file i dati letti come BYTE
nomeFile = string.Format(@"{0}\MemDump_Y_Byte.dat", utils.dataDatDir);
Dictionary<string, string> mappaValori = new Dictionary<string, string>();
for (int i = 0; i < MemBlockY.Length; i++)
{
mappaValori.Add(i.ToString("0000"), MemBlockY[i].ToString());
}
utils.WritePlain(mappaValori, nomeFile);
// salvo in file i dati letti come DWord (4byte)
nomeFile = string.Format(@"{0}\MemDump_Y_DW.dat", utils.dataDatDir);
mappaValori = new Dictionary<string, string>();
for (int i = 0; i < MemBlockY.Length / 4; i++)
{
mappaValori.Add(i.ToString("0000"), BitConverter.ToUInt32(MemBlockY, i * 4).ToString());
}
utils.WritePlain(mappaValori, nomeFile);
// salvo in file i dati letti come DWord (4byte)
nomeFile = string.Format(@"{0}\MemDump_Y_W.dat", utils.dataDatDir);
mappaValori = new Dictionary<string, string>();
for (int i = 0; i < MemBlockY.Length / 2; i++)
{
mappaValori.Add(i.ToString("0000"), BitConverter.ToUInt16(MemBlockY, i * 2).ToString());
}
utils.WritePlain(mappaValori, nomeFile);
}
}
}