Files
activestep/Step.Core/ThreadsFunctions.cs
2020-09-12 16:11:43 +02:00

1393 lines
49 KiB
C#

using CMS_CORE_Library.Models;
using Step.Config;
using Step.Core;
using Step.Database.Controllers;
using Step.Model.DTOModels;
using Step.Model.DTOModels.AlarmModels;
using Step.Model.DTOModels.MaintenanceModels;
using Step.Model.DTOModels.Scada;
using Step.Model.DTOModels.ToolModels;
using Step.NC;
using Step.Utils;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using TeamDev.SDK.MVVM;
using static CMS_CORE_Library.Models.DataStructures;
using static Step.Config.ServerConfig;
using static Step.Model.Constants;
using static Step.Utils.ExceptionManager;
public static class ThreadsFunctions
{
public static bool reconnectionIsRunning = false;
private static ConcurrentDictionary<string, long> Timers = new ConcurrentDictionary<string, long>();
private static ConcurrentDictionary<string, long> Counter = new ConcurrentDictionary<string, long>();
private static Thread ConnThread;
#region Functions
public static void ManageWatchdog()
{
NcAdapter ncAdapter = new NcAdapter();
Stopwatch sw = new Stopwatch();
int errorCounter = 0;
try
{
CmsError libraryError = ncAdapter.Connect();
if (libraryError.errorCode != 0)
ManageLibraryError(libraryError);
while (true)
{
sw.Restart();
//if(errorCounter == MAX_NUM_OF_WATCHDOG_ERROR)
//{
//}
// Check if client is connected
if (ncAdapter.numericalControl.NC_IsConnected())
{
// Manage watchdog
libraryError = ncAdapter.ManageWatchdog();
if (libraryError == PLC_NOT_RUNNING_ERROR)
{
if (errorCounter < MAX_NUM_OF_WATCHDOG_ERROR)
errorCounter++;
}
else if (libraryError == NO_ERROR)
errorCounter = 0;
}
else
RestoreConnection();
sw.Stop();
//Update thread timer
UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds);
// Wait
Thread.Sleep(CalcSleepTime(500, (int)sw.ElapsedMilliseconds));
}
}
catch (ThreadAbortException ex)
{
ncAdapter.Dispose();
}
}
public static void ReadAlarms()
{
NcAdapter ncAdapter = new NcAdapter();
Stopwatch sw = new Stopwatch();
try
{
CmsError libraryError = ncAdapter.Connect();
if (libraryError.errorCode != 0)
ManageLibraryError(libraryError);
while (true)
{
sw.Restart();
// Check if client is connected
if (ncAdapter.numericalControl.NC_IsConnected())
{
// Get Alarms from NC
libraryError = ncAdapter.GetNcAlarms(out DTOAlarmsModel alarms);
if (libraryError.errorCode != 0)
{
ManageLibraryError(libraryError);
}
else
// Send through signalR
MessageServices.Current.Publish(SEND_ALARMS, null, alarms);
}
else
RestoreConnection();
sw.Stop();
//Update thread timer
UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds);
// Wait
Thread.Sleep(CalcSleepTime(200, (int)sw.ElapsedMilliseconds));
}
}
catch (ThreadAbortException)
{
ncAdapter.Dispose();
}
}
public static void ReadPowerOnData()
{
NcAdapter ncAdapter = new NcAdapter();
Stopwatch sw = new Stopwatch();
try
{
CmsError libraryError = ncAdapter.Connect();
if (libraryError.errorCode != 0)
ManageLibraryError(libraryError);
while (true)
{
sw.Restart();
// Check if client is connected
if (ncAdapter.numericalControl.NC_IsConnected())
{
// Get Data from NC
libraryError = ncAdapter.GetPowerOnData(out DTOPowerOnDataModel powerOnData);
if (libraryError.errorCode != 0)
ManageLibraryError(libraryError);
else
// Send through signalR
MessageServices.Current.Publish(SEND_POWER_ON_DATA, null, powerOnData);
}
else
RestoreConnection();
sw.Stop();
//Update thread timer
UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds);
// Wait
Thread.Sleep(CalcSleepTime(400, (int)sw.ElapsedMilliseconds));
}
}
catch (ThreadAbortException)
{
ncAdapter.Dispose();
}
}
public static void ReadProcessesPPStatus()
{
NcAdapter ncAdapter = new NcAdapter();
Stopwatch sw = new Stopwatch();
try
{
// Try connection
CmsError libraryError = ncAdapter.Connect();
if (libraryError.errorCode != 0)
ManageLibraryError(libraryError);
while (true)
{
sw.Restart();
if (ncAdapter.numericalControl.NC_IsConnected())
{
// Get Data from NC
libraryError = ncAdapter.GetProcessesData(out DTOProcessesDataModel processesPPData);
if (libraryError.errorCode != 0)
ManageLibraryError(libraryError);
else
{
// Get softkey data from config and PLC
libraryError = ncAdapter.GetNcSoftKeys(out List<DTONcSoftKeyModel> ncSoftKeys);
if (libraryError.errorCode != 0)
ManageLibraryError(libraryError);
else
{
// Send processes through signalR
MessageServices.Current.Publish(SEND_PROCESSES_DATA, null, processesPPData);
// Send ncSoftKeys through signalR
MessageServices.Current.Publish(SEND_NC_SOFTKEYS_DATA, null, ncSoftKeys);
}
}
}
else
RestoreConnection();
sw.Stop();
//Update thread timer
UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds);
// Wait
Thread.Sleep(CalcSleepTime(200, (int)sw.ElapsedMilliseconds));
}
}
catch (ThreadAbortException)
{
ncAdapter.Dispose();
}
}
public static void ReadMComandsData()
{
NcAdapter ncAdapter = new NcAdapter();
Stopwatch sw = new Stopwatch();
try
{
// Try connection
CmsError libraryError = ncAdapter.Connect();
if (libraryError.errorCode != 0)
ManageLibraryError(libraryError);
while (true)
{
sw.Restart();
if (ncAdapter.numericalControl.NC_IsConnected())
{
libraryError = ncAdapter.GetM155Data(out List<DTOM155InputModel> m155Data);
if (libraryError.errorCode != 0)
ManageLibraryError(libraryError);
else
{
// Send m155 through signalR
MessageServices.Current.Publish(SEND_M155_DATA, null, m155Data);
if(NcConfig.NcVendor != NC_VENDOR.SIEMENS)
{
libraryError = ncAdapter.GetM156Data(out List<DTOM156InputModel> m156Data);
if (libraryError.IsError())
ManageLibraryError(libraryError);
else
MessageServices.Current.Publish(SEND_M156_DATA, null, m156Data);
}
// Read & send M157 data
//libraryError = ncAdapter.GetM157Data(out List<DTOM157DataModel> m157Data);
//if (libraryError.IsError())
// ManageLibraryError(libraryError);
//else
// MessageServices.Current.Publish(SEND_M157_DATA, null, m157Data);
}
}
else
RestoreConnection();
sw.Stop();
//Update thread timer
UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds);
// Wait
Thread.Sleep(CalcSleepTime(200, (int)sw.ElapsedMilliseconds));
}
}
catch (ThreadAbortException)
{
ncAdapter.Dispose();
}
}
public static void ReadEnabledFunctionality()
{
NcAdapter ncAdapter = new NcAdapter();
Stopwatch sw = new Stopwatch();
try
{
// Try connection
CmsError libraryError = ncAdapter.Connect();
if (libraryError.errorCode != 0)
ManageLibraryError(libraryError);
while (true)
{
sw.Restart();
if (ncAdapter.numericalControl.NC_IsConnected())
{
// Get Data from NC
libraryError = ncAdapter.GetFunctionsMappedWithNC(out List<DTORuntimeFunctionalityModel> functionsAccessList);
if (libraryError.errorCode != 0)
ManageLibraryError(libraryError);
else
// Send through signalR
MessageServices.Current.Publish(SEND_FUNCTIONALITY_DATA, null, functionsAccessList);
}
else
RestoreConnection();
sw.Stop();
//Update thread timer
UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds);
// Wait
Thread.Sleep(CalcSleepTime(200, (int)sw.ElapsedMilliseconds));
}
}
catch (ThreadAbortException)
{
ncAdapter.Dispose();
}
}
public static void ReadExpiredMaintenances()
{
NcAdapter ncAdapter = new NcAdapter();
Stopwatch sw = new Stopwatch();
try
{
// Try connection
CmsError libraryError = ncAdapter.Connect();
if (libraryError.errorCode != 0)
ManageLibraryError(libraryError);
while (true)
{
sw.Restart();
if (ncAdapter.numericalControl.NC_IsConnected())
{
libraryError = ncAdapter.GetMaintenancesWithPermissions(out List<DTOMaintenanceModel> dtoMaintenance, 1);
if (libraryError.IsError())
ManageLibraryError(libraryError);
foreach(var maint in dtoMaintenance)
{
if (maint.CreatedByCms)
{
var config = MaintenancesConfig.Where(x => x.Id == maint.Id).FirstOrDefault();
RedisController.WriteMaintenance(maint.Id, config.LocalizedName["en"], maint.PercentageOfCompletion, config.LocalizedDescription["en"]);
}
else
{
RedisController.WriteMaintenance(maint.Id, maint.Title, maint.PercentageOfCompletion, maint.Description);
}
}
// Get Data from database and PLC
libraryError = ncAdapter.GetExpiredMaintenances(out List<DTOExpiredMaintenanceModel> expiredMaintenances);
if (libraryError.errorCode != 0)
ManageLibraryError(libraryError);
else
// Send through signalR
MessageServices.Current.Publish(SEND_EXPIRED_MAINTENANCES_DATA, null, expiredMaintenances);
//Manage Candies
libraryError = ncAdapter.ManageCandies();
if (libraryError.errorCode != 0)
ManageLibraryError(libraryError);
}
else
RestoreConnection();
sw.Stop();
//Update thread timer
UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds);
// Wait
Thread.Sleep(30000);
}
}
catch (ThreadAbortException)
{
ncAdapter.Dispose();
}
catch (Exception ex)
{
}
}
public static void ReadUserSoftKeysData()
{
NcAdapter ncAdapter = new NcAdapter();
Stopwatch sw = new Stopwatch();
try
{
// Try connection
CmsError libraryError = ncAdapter.Connect();
if (libraryError.errorCode != 0)
ManageLibraryError(libraryError);
while (true)
{
sw.Restart();
if (ncAdapter.numericalControl.NC_IsConnected())
{
// Get softkey data from config and PLC
libraryError = ncAdapter.GetUserSoftKeys(out List<DTOUserSoftKeyModel> softKeys);
if (libraryError.errorCode != 0)
ManageLibraryError(libraryError);
else
// Send through signalR
MessageServices.Current.Publish(SEND_USER_SOFTKEYS_DATA, null, softKeys);
}
else
RestoreConnection();
sw.Stop();
//Update thread timer
UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds);
// Wait
Thread.Sleep(CalcSleepTime(200, (int)sw.ElapsedMilliseconds));
}
}
catch (ThreadAbortException)
{
ncAdapter.Dispose();
}
}
public static void ReadHeadsData()
{
NcAdapter ncAdapter = new NcAdapter();
Stopwatch sw = new Stopwatch();
try
{
// Try connection
CmsError libraryError = ncAdapter.Connect();
if (libraryError.errorCode != 0)
ManageLibraryError(libraryError);
while (true)
{
sw.Restart();
if (ncAdapter.numericalControl.NC_IsConnected())
{
// Get Data from config and PLC
libraryError = ncAdapter.GetHeadsData(out List<DTOHeadModel> heads);
if (libraryError.errorCode != 0)
ManageLibraryError(libraryError);
else
// Send through signalR
MessageServices.Current.Publish(SEND_HEADS_DATA, null, heads);
}
else
RestoreConnection();
sw.Stop();
//Update thread timer
UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds);
// Wait
Thread.Sleep(CalcSleepTime(500, (int)sw.ElapsedMilliseconds));
}
}
catch (ThreadAbortException)
{
ncAdapter.Dispose();
}
}
public static void ReadAxesNamesData()
{
NcAdapter ncAdapter = new NcAdapter();
Stopwatch sw = new Stopwatch();
try
{
// Try connection
CmsError libraryError = ncAdapter.Connect();
if (libraryError.errorCode != 0)
ManageLibraryError(libraryError);
while (true)
{
sw.Restart();
if (ncAdapter.numericalControl.NC_IsConnected())
{
// Get Data from config and PLC
libraryError = ncAdapter.ReadAxisData(out List<DTOAxisNameModel> axes);
if (libraryError.errorCode != 0)
ManageLibraryError(libraryError);
else
// Send through signalR
MessageServices.Current.Publish(SEND_AXIS_NAMES_DATA, null, axes);
}
else
RestoreConnection();
sw.Stop();
//Update thread timer
UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds);
// Wait
Thread.Sleep(CalcSleepTime(800, (int)sw.ElapsedMilliseconds));
}
}
catch (ThreadAbortException)
{
ncAdapter.Dispose();
}
}
public static void ReadAxesPositionsData()
{
NcAdapter ncAdapter = new NcAdapter();
Stopwatch sw = new Stopwatch();
try
{
// Try connection
CmsError libraryError = ncAdapter.Connect();
if (libraryError.errorCode != 0)
ManageLibraryError(libraryError);
while (true)
{
sw.Restart();
if (ncAdapter.numericalControl.NC_IsConnected())
{
// Get Data from NC
libraryError = ncAdapter.GetAxesPositionsBySelectedProcess(out DTOAxesModel axesPositions);
if (libraryError.errorCode != 0)
ManageLibraryError(libraryError);
else
// Send through signalR
MessageServices.Current.Publish(SEND_AXES, null, axesPositions);
}
else
RestoreConnection();
sw.Stop();
//Update thread timer
UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds);
// Wait
Thread.Sleep(CalcSleepTime(100, (int)sw.ElapsedMilliseconds));
}
}
catch (ThreadAbortException)
{
ncAdapter.Dispose();
}
}
public static void ReadMagazinesStatus()
{
SiemensToolTableAdapter ncAdapter = new SiemensToolTableAdapter();
Stopwatch sw = new Stopwatch();
try
{
// Try connection
CmsError libraryError = ncAdapter.Connect();
if (libraryError.errorCode != 0)
ManageLibraryError(libraryError);
while (true)
{
sw.Restart();
if (ncAdapter.numericalControl.NC_IsConnected())
{
// Get Data from config and PLC
libraryError = ncAdapter.GetMagazineStatus(out DTOMagazineActionModel magazineStatus);
if (libraryError.errorCode != 0)
ManageLibraryError(libraryError);
else
// Send through signalR
MessageServices.Current.Publish(SEND_MAGAZINES_STATUS, null, magazineStatus);
}
else
RestoreConnection();
sw.Stop();
//Update thread timer
UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds);
// Wait
Thread.Sleep(CalcSleepTime(1000, (int)sw.ElapsedMilliseconds));
}
}
catch (ThreadAbortException)
{
ncAdapter.Dispose();
}
}
public static void ReadActiveProgramData()
{
NcFileAdapter ncAdapter = new NcFileAdapter();
Stopwatch sw = new Stopwatch();
try
{
// Try connection
CmsError libraryError = ncAdapter.Connect();
if (libraryError.errorCode != 0)
ManageLibraryError(libraryError);
while (true)
{
sw.Restart();
if (ncAdapter.numericalControl.NC_IsConnected())
{
// Get Data from config and PLC
libraryError = ncAdapter.GetActiveProgramInfo(out DTOActiveProgramDataModel active);
if (libraryError.IsError())
ManageLibraryError(libraryError);
else
// Send through signalR
MessageServices.Current.Publish(SEND_ACTIVE_PROGRAM_DATA, null, active);
}
else
RestoreConnection();
sw.Stop();
//Update thread timer
UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds);
// Wait
Thread.Sleep(CalcSleepTime(400, (int)sw.ElapsedMilliseconds));
}
}
catch (ThreadAbortException)
{
ncAdapter.Dispose();
}
}
public static void UpdateToolsData()
{
NcToolTableAdapter ncAdapter = new NcToolTableAdapter();
Stopwatch sw = new Stopwatch();
if(NcConfig.NcVendor != NC_VENDOR.SIEMENS)
{
try
{
// Try connection
CmsError libraryError = ncAdapter.Connect();
if (libraryError.errorCode != 0)
ManageLibraryError(libraryError);
while (true)
{
sw.Restart();
// Check if client is connected
if (ncAdapter.numericalControl.NC_IsConnected())
{
// Get new data from PLC
libraryError = ncAdapter.GetUpdatedToolsData(out Dictionary<int, byte> updatedStatus, out Dictionary<int, uint> updatedLives);
if (libraryError.IsError())
ManageLibraryError(libraryError);
MessageServices.Current.Publish(UPDATE_TOOLS_DATA, null,
new DTONewToolDataModel
{
UpdatedStatus = updatedStatus,
UpdatedLives = updatedLives
});
}
else
RestoreConnection();
sw.Stop();
//Update thread timer
UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds);
// Wait
Thread.Sleep(CalcSleepTime(1000, (int)sw.ElapsedMilliseconds));
}
}
catch (ThreadAbortException)
{
ncAdapter.Dispose();
}
}
}
public static void ReadNcMagazineActive()
{
if (NcConfig.NcVendor != NC_VENDOR.SIEMENS)
{
NcToolTableAdapter ncAdapter = new NcToolTableAdapter();
Stopwatch sw = new Stopwatch();
try
{
// Try connection
CmsError libraryError = ncAdapter.Connect();
if (libraryError.errorCode != 0)
ManageLibraryError(libraryError);
while (true)
{
sw.Restart();
// Check if client is connected
if (ncAdapter.numericalControl.NC_IsConnected())
{
// Get new data from PLC
libraryError = ncAdapter.GetNcMagazineStatus(out Dictionary<int, bool> status);
if (libraryError.IsError())
ManageLibraryError(libraryError);
MessageServices.Current.Publish(NC_MAGAZINE_IS_ACTIVE, null, status);
// Read assisted tooling data
libraryError = ncAdapter.ReadAssistedToolingProcedure(out DTOAssistedToolingEndValueModel data);
if (libraryError.IsError())
ManageLibraryError(libraryError);
// Send assisted tooling data
MessageServices.Current.Publish(ASSISTED_TOOLING_DATA, null, data);
// Read if there are changes between magazines
libraryError = ncAdapter.ReadMovementBetweenMagazines(out DTOMovementBetweenMagazinesModel movementData);
if (libraryError.IsError())
ManageLibraryError(libraryError);
// Send data
MessageServices.Current.Publish(MOVEMENT_TOOLING_DATA, null, movementData);
}
else
RestoreConnection();
sw.Stop();
//Update thread timer
UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds);
// Wait
Thread.Sleep(CalcSleepTime(500, (int)sw.ElapsedMilliseconds));
}
}
catch (ThreadAbortException)
{
ncAdapter.Dispose();
}
}
}
public static void ReadPartProgramQueueData()
{
NcFileAdapter ncAdapter = new NcFileAdapter();
Stopwatch sw = new Stopwatch();
try
{
// Try connection
CmsError libraryError = ncAdapter.Connect();
if (libraryError.errorCode != 0)
ManageLibraryError(libraryError);
while (true)
{
sw.Restart();
// Check if client is connected
if (ncAdapter.numericalControl.NC_IsConnected())
{
// Read data
libraryError = ncAdapter.UpdateQueue();
if (libraryError.IsError())
ManageLibraryError(libraryError);
libraryError = ncAdapter.GetSelectedProcessQueue(out List<DTOQueueModel> queue);
if (libraryError.IsError())
ManageLibraryError(libraryError);
MessageServices.Current.Publish(SEND_QUEUE_DATA, null, queue);
}
else
RestoreConnection();
sw.Stop();
//Update thread timer
UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds);
// Wait
Thread.Sleep(CalcSleepTime(500, (int)sw.ElapsedMilliseconds));
}
}
catch (ThreadAbortException)
{
ncAdapter.Dispose();
}
}
public static void ReadScadaData()
{
NcAdapter ncAdapter = new NcAdapter();
Stopwatch sw = new Stopwatch();
try
{
// Try connection
CmsError libraryError = ncAdapter.Connect();
if (libraryError.errorCode != 0)
ManageLibraryError(libraryError);
while (true)
{
sw.Restart();
// Check if client is connected
if (ncAdapter.numericalControl.NC_IsConnected())
{
List<ScadaSchemaModel> scadaToRead = ProductionScadaSchema.Concat(SubscribedScada).ToList();
// Get new data from PLC
libraryError = ncAdapter.ReadScadasData(scadaToRead, out List<DTOScadaModel> scadas);
if (libraryError.IsError())
ManageLibraryError(libraryError);
MessageServices.Current.Publish(SEND_SCADA_DATA, null, scadas);
}
else
RestoreConnection();
sw.Stop();
//Update thread timer
UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds);
// Wait
Thread.Sleep(CalcSleepTime(500, (int)sw.ElapsedMilliseconds));
}
}
catch (ThreadAbortException)
{
ncAdapter.Dispose();
}
}
public static void ReadM154Data()
{
NcAdapter ncAdapter = new NcAdapter();
Stopwatch sw = new Stopwatch();
try
{
// Try connection
CmsError libraryError = ncAdapter.Connect();
if (libraryError.errorCode != 0)
ManageLibraryError(libraryError);
string ApplicationPath = ServerStartupConfig.MTCFolderPath + "\\" + ServerStartupConfig.MTCApplicationName + ".exe";
while (true)
{
sw.Restart();
// Check if client is connected
if (ncAdapter.numericalControl.NC_IsConnected())
{
libraryError = ncAdapter.GetM154Data(out List<M154DataModel> data, out bool MTCStatus);
if (libraryError.IsError())
ManageLibraryError(libraryError);
if (ServerStartupConfig.MTCFolderPath != "")
{
// Check if process exists
Process[] processes = Process.GetProcessesByName(ServerStartupConfig.MTCApplicationName);
if (!MTCStatus)
{
// Kill if is running
if (processes.Count() > 0)
processes[0].Kill();
}
else
{
// if is already running ignore
if (processes.Count() == 0)
if (File.Exists(ApplicationPath))
{
ProcessStartInfo PSI = new ProcessStartInfo(ApplicationPath);
var directory = new FileInfo(ApplicationPath).Directory;
if (directory != null)
{
PSI.WorkingDirectory = directory.FullName;
Process.Start(PSI);
}
}
}
}
foreach (M154DataModel m154 in data)
{
//if (CmsConnectConfig.Enabled)
if(ServerStartupConfig.CmsConnectReady)
{
if (m154.Parameters.Count() >= 2 && m154.Parameters[0] == "SOUR")
{
// Convert tag string in Pascal Case and add to result string
switch (m154.Parameters[1].ToLower().Trim())
{
case "currprog":
if (m154.Parameters.Count() < 3)
return;
RedisController.WriteProductionName(m154.Process, m154.Parameters[2]);
break;
case "repstarget":
if (m154.Parameters.Count() < 3)
return;
RedisController.WriteProductionRepsTarget(m154.Process, m154.Parameters[2]);
break;
case "repsdone":
if (m154.Parameters.Count() < 3)
return;
RedisController.WriteProductionRepsDone(m154.Process, m154.Parameters[2]);
break;
case "startprog":
RedisController.WriteStartProgram(m154.Process);
break;
case "endprog":
RedisController.WriteEndProgram(m154.Process);
break;
case "fixture":
if (m154.Parameters.Count() < 3)
return;
RedisController.WriteNotification(m154.Process, m154.Parameters[2]);
break;
case "partid":
if (m154.Parameters.Count() < 3)
return;
RedisController.WritePartId(m154.Process, m154.Parameters[2]);
break;
default:
string notif = m154.Parameters[1];
if (m154.Parameters.Count() > 2)
notif += m154.Parameters[2];
RedisController.WriteProductionNotification(m154.Process, notif);
break;
}
}
// Write ack
libraryError = ncAdapter.WriteM154Ack((int)m154.Process);
if (libraryError.IsError())
ManageLibraryError(libraryError);
}
else // MT CONNECT
{
string stringVal = "Path_0" + m154.Process + "_";
string val = "";
// Check if command is MTC
if (m154.Parameters[0] == "MTC")
{
// Convert tag string in Pascal Case and add to result string
switch (m154.Parameters[1].ToLower())
{
case "currprog":
stringVal += "CurrProg";
break;
case "partid":
stringVal += "PartId";
break;
default:
stringVal += m154.Parameters[1];
break;
}
// Set value
if (m154.Parameters.Count() > 2)
val = m154.Parameters[2];
// Create MTC Directory if not exist
if (!Directory.Exists(ServerStartupConfig.MTCFolderPath))
Directory.CreateDirectory(ServerStartupConfig.MTCFolderPath);
string outputFileName = ServerStartupConfig.MTCFolderPath + "\\DATA\\CmsGeneralStatus.mtc";
// Create file if not exits
if (!File.Exists(outputFileName))
using (var f = File.Create(outputFileName)) { };
// Read file
List<string> fileLines = File.ReadAllLines(outputFileName).ToList();
string[] parametersInLine;
bool found = false;
for (int i = 0; i < fileLines.Count() && !found; i++)
{
// Get tag & value from row
parametersInLine = fileLines[i].Split('|');
if (parametersInLine[0] == stringVal)
{
found = true;
fileLines[i] = stringVal + "|" + val;
}
}
// If tag doesn't exists, append new line
if (!found)
fileLines.Add(stringVal + "|" + val);
// Write file
File.WriteAllLines(outputFileName, fileLines.ToArray());
// Write ack
libraryError = ncAdapter.WriteM154Ack((int)m154.Process);
if (libraryError.IsError())
ManageLibraryError(libraryError);
}
}
}
}
else
RestoreConnection();
sw.Stop();
//Update thread timer
UpdateStat(MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds);
// Wait
Thread.Sleep(CalcSleepTime(500, (int)sw.ElapsedMilliseconds));
}
}
catch (ThreadAbortException)
{
ncAdapter.Dispose();
}
}
public static void SetupCmsConnect()
{
NcAdapter ncAdapter = new NcAdapter();
try
{
List<DTOLanguageModel> availableLanguages = LanguageController.GetLanguageListFromDirectory();
if (availableLanguages == null)
return ;
ICollection<CultureInfo> cultureInfos = new List<CultureInfo>();
// Get nc available language
CmsError cmsError = ncAdapter.numericalControl.NC_GetAvailableLanguages(ref cultureInfos);
if (cmsError.IsError())
ManageLibraryError(cmsError);
// Filter available language with
availableLanguages = availableLanguages.Where(x => cultureInfos.Any(y => y.TwoLetterISOLanguageName == x.IsoId)).ToList();
// Fill redis DB
int count = 1;
Dictionary<string, string> defAlarmsNamesEn = null;
Dictionary<string, string> defAlarmsNamesIt = null;
foreach (DTOLanguageModel lang in availableLanguages)
{
Dictionary<string, string> alarmsNames = GetPlcAlarmsTranslations(lang.IsoId);
if(lang.IsoId.ToLower() == "en")
{
defAlarmsNamesEn = alarmsNames;
if(!RedisController.WriteAlarmsConfigEn(alarmsNames))
ManageError(ERROR_LEVEL.FATAL, CMS_CONNECT_SETUP_ALARM_MESSAGE);
}
else if (lang.IsoId.ToLower() == "it")
{
defAlarmsNamesIt = alarmsNames;
if (!RedisController.WriteAlarmsConfigIt(alarmsNames))
ManageError(ERROR_LEVEL.FATAL, CMS_CONNECT_SETUP_ALARM_MESSAGE);
}
else
if (!RedisController.WriteAlarmsConfigCurr(alarmsNames))
ManageError(ERROR_LEVEL.FATAL, CMS_CONNECT_SETUP_ALARM_MESSAGE);
if (count == 3)
break;
else
count++;
}
if (availableLanguages.Count < 3 && defAlarmsNamesEn != null)
if (!RedisController.WriteAlarmsConfigCurr(defAlarmsNamesEn))
ManageError(ERROR_LEVEL.FATAL, CMS_CONNECT_SETUP_ALARM_MESSAGE);
else if (availableLanguages.Count < 3 && defAlarmsNamesIt != null)
if (!RedisController.WriteAlarmsConfigCurr(defAlarmsNamesIt))
ManageError(ERROR_LEVEL.FATAL, CMS_CONNECT_SETUP_ALARM_MESSAGE);
}
catch (ThreadAbortException)
{
ncAdapter.Dispose();
}
}
#endregion Functions
#region SupportFunctions
private static void TryNcConnection()
{
// Stop all the NC threads
ThreadsHandler.Stop();
StatReset();
NcAdapter ncAdapter = new NcAdapter();
CmsError cmsError = NO_ERROR;
// Run loop until NC is connected
while (!ncAdapter.numericalControl.NC_IsConnected())
{
// Try reconnection
cmsError = ncAdapter.Connect();
if (cmsError.errorCode == CMS_ERROR_CODES.SIEMENS_ENVIRONMENT_NOT_FOUND || cmsError.errorCode == CMS_ERROR_CODES.SIEMENS_HMI_NOT_RUNNING || cmsError.errorCode == CMS_ERROR_CODES.OSAI_TT_FOLDER_NOT_FOUND)
ManageLibraryError(cmsError);
else if (cmsError.errorCode != CMS_ERROR_CODES.OK)
{
ncAdapter.Dispose();
}
if (cmsError.errorCode == CMS_ERROR_CODES.SIEMENS_TOOL_TABLE_ERROR)
ManageLibraryError(cmsError);
// Send status to UI
var isConnected = ncAdapter.numericalControl.NC_IsConnected();
MessageServices.Current.Publish(SEND_NC_STATUS, null, isConnected);
MessageServices.Current.Publish(SEND_NC_STATUS_TO_UI, null, isConnected);
Thread.Sleep(1000);
}
if (NcConfig.NcVendor == NC_VENDOR.FANUC || NcConfig.NcVendor == NC_VENDOR.OSAI)
{
using (NcToolTableAdapter toolTable = new NcToolTableAdapter())
{
toolTable.Connect();
// After reconecction write option
cmsError = toolTable.SetupNcToolManager();
if (cmsError.IsError())
ManageLibraryError(cmsError);
// cmsError = toolTable.RestoreTableLock();
}
}
if (!cmsError.IsError())
{
if (ServerStartupConfig.AutoOpenCmsClient)
StartCMSClient();
// Start/Restart NC threads
ThreadsHandler.StartWorkers();
reconnectionIsRunning = false;
MessageServices.Current.Publish(SEND_NC_STATUS, null, true);
MessageServices.Current.Publish(SEND_NC_STATUS_TO_UI, null, true);
}
}
public static void RestoreConnection()
{
if (reconnectionIsRunning == false)
{ // Set thread as running state
reconnectionIsRunning = true;
// Start reconnection thread
ConnThread = new Thread(() =>
TryNcConnection()
);
ConnThread.Start();
}
}
public static void AbortNcConnection()
{
if (ConnThread != null && ConnThread.IsAlive)
ConnThread.Abort();
}
public static void ManageLibraryError(CmsError cmsError)
{
switch (cmsError.errorCode)
{
case CMS_ERROR_CODES.NC_PROD_ERROR:
ManageError(ERROR_LEVEL.WARNING, cmsError.localizationKey);
break;
case CMS_ERROR_CODES.NOT_CONNECTED:
RestoreConnection(); // If not connected try reconnection
break;
case CMS_ERROR_CODES.SIEMENS_ENVIRONMENT_NOT_FOUND:
case CMS_ERROR_CODES.OSAI_TT_FOLDER_NOT_FOUND:
case CMS_ERROR_CODES.OPTION_NOT_CONSISTENT:
case CMS_ERROR_CODES.SIEMENS_TOOL_TABLE_ERROR:
ManageError(ERROR_LEVEL.FATAL, cmsError.localizationKey);
break;
case CMS_ERROR_CODES.SIEMENS_HMI_NOT_RUNNING:
ManageError(ERROR_LEVEL.FATAL, "SIEMENS HMI NOT RUNNING");
break;
case CMS_ERROR_CODES.SELECTED_PROCESS:
ManageError(ERROR_LEVEL.WARNING, cmsError.localizationKey);
break;
case CMS_ERROR_CODES.INTERNAL_ERROR:
ManageException(ERROR_LEVEL.FATAL, cmsError.exception);
break;
}
}
internal static void UpdateStat(string functionName, long timer)
{
if (!Timers.ContainsKey(functionName))
Timers.TryAdd(functionName, timer);
else
Timers[functionName] += timer;
if (!Counter.ContainsKey(functionName))
Counter.TryAdd(functionName, 1);
else
Counter[functionName]++;
}
internal static void StatThread()
{
while (true)
{
foreach(var value in Counter)
{
if(ThreadsHandler.RunningThreadStatus.ContainsKey(value.Key) && Counter[value.Key] != 0)
{
ThreadsHandler.RunningThreadStatus[value.Key] = (Timers[value.Key] / Counter[value.Key]) + " mS";
Timers[value.Key] = 0;
Counter[value.Key] = 0;
}
}
MessageServices.Current.Publish(SEND_THREADS_STATUS, null, ThreadsHandler.RunningThreadStatus);
Thread.Sleep(2000);
}
}
private static void StatReset()
{
foreach (var value in Counter)
{
Timers[value.Key] = 0;
Counter[value.Key] = 0;
}
}
private static int CalcSleepTime(int maxSleep, int execTime)
{
int sleep = 0;
// Check if the execution time is greater than the half of the max sleep time
if (maxSleep - execTime < maxSleep / 2)
{
sleep = maxSleep;
}
else
{
sleep = maxSleep - execTime;
}
return sleep;
}
public static void StartCMSClient()
{
//Setup the Path Variable
if (!ClientIsRunning())
{
ThreadsHandler.StartClient = new Thread(() => clientProcess());
ThreadsHandler.StartClient.Start();
}
}
private static void clientProcess()
{
string CMSClientPath = "";
// Check if the system is 64/32 bit
if (Environment.Is64BitOperatingSystem && File.Exists(CLIENT_PATH_64))
CMSClientPath = CLIENT_PATH_64;
else if (File.Exists(CLIENT_PATH_86))
CMSClientPath = CLIENT_PATH_86;
if (!String.IsNullOrEmpty(CMSClientPath))
{
Process pr = Process.Start(CMSClientPath, null);
if (ServerStartupConfig.AutoOpenCmsClient)
{
pr.WaitForExit();
MessageServices.Current.Publish(SEND_STOP_SERVER);
}
}
}
private static bool ClientIsRunning()
{
Process[] p = Process.GetProcessesByName(CLIENT_EXE_NAME_NOEXT);
foreach (Process pr in p)
{
if (pr.MainWindowHandle != IntPtr.Zero)
{
ShowWindow(pr.MainWindowHandle, 9);
SetForegroundWindow(pr.MainWindowHandle);
return true;
}
}
return false;
}
private static Dictionary<string, string> GetPlcAlarmsTranslations(string language)
{
using (NcAdapter ncAdapter = new NcAdapter())
{
Dictionary<string, string> returnValue = new Dictionary<string, string>();
Dictionary<int, string> messages = new Dictionary<int, string>();
// Read data from CN
ncAdapter.numericalControl.NC_GetTranslatedPlcMessages(language, ref messages); // Avoid checking error because in the worst case "messages" is empty
// Id start from 1
for (int i = 1; i <= 1024; i++)
{
// Get configurated alarms
var tmpAlarmConfig = InitialAlarmsConfig.Where(x => x.PlcId == i).FirstOrDefault();
// Default string
string message = string.Format(NOT_CONFIGURATED_ALARM_MESSAGE, i);
// If is configurated
if (tmpAlarmConfig != null)
{
// Find translated string
message = messages.Where(x => x.Key == tmpAlarmConfig.AlarmId).FirstOrDefault().Value;
if (message == null)
message = string.Format(NOT_FOUND_ALARM_MESSAGE, i);
}
// Add to dictionary
returnValue.Add(i.ToString("D6") + "|900",message);
}
return returnValue;
}
}
[DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
#endregion SupportFunctions
}