Compare commits

...

7 Commits

Author SHA1 Message Date
Angel Ivan
deba5d7e96 Se agregó un timer para obtener el tiempo de ejecución del programa. 2026-05-15 10:59:31 -06:00
Angel Ivan
5ad683d52a Cambios relacionados con las rutas de los archivos de configuración y respaldo 2026-05-14 12:04:12 -06:00
Angel Ivan
3cf3ac6c40 Cambios menores 2026-05-14 11:01:47 -06:00
Angel Ivan
a535cbe5fe Creación de archivo resultbackup.txt.
Soporte para LabVIEW y nuevo formato de configuración

Se cambia el archivo de configuración a configbackup.txt, ahora con tres líneas (IP, ruta .dmb y MAC). Se añade la función ActualizarEstadoLabVIEW para comunicar el estado del proceso a LabVIEW mediante un archivo bandera. Se eliminan mensajes innecesarios y se automatiza el cierre de la app. Mejoras menores en manejo de errores y formato del archivo de ejemplo.
2026-05-14 10:50:14 -06:00
Angel Ivan
d88c796ec5 Version actualizada. 2026-05-13 08:34:24 -06:00
Angel Ivan
757ff3cf4f Merge branch 'master' of https://gitea.giat.synology.me/AngelJurado/BackupCognex 2026-05-13 08:33:48 -06:00
Angel Ivan
c95923051f Version actualizada. 2026-05-13 08:30:16 -06:00
3 changed files with 219 additions and 0 deletions

View File

@@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Reference Include="Cognex.DataMan.CogNamer.PC">
<HintPath>..\..\..\..\Cognex\DataMan SDK 5.6.3\Binaries\PC\Cognex.DataMan.CogNamer.PC.dll</HintPath>
</Reference>
<Reference Include="Cognex.DataMan.SDK.Discovery.PC">
<HintPath>..\..\..\..\Cognex\DataMan SDK 5.6.3\Binaries\PC\Cognex.DataMan.SDK.Discovery.PC.dll</HintPath>
</Reference>
<Reference Include="Cognex.DataMan.SDK.PC">
<HintPath>..\..\..\..\Cognex\DataMan SDK 5.6.3\Binaries\PC\Cognex.DataMan.SDK.PC.dll</HintPath>
</Reference>
<Reference Include="Cognex.DataMan.SDK.Utils.PC">
<HintPath>..\..\..\..\Cognex\DataMan SDK 5.6.3\Binaries\PC\Cognex.DataMan.SDK.Utils.PC.dll</HintPath>
</Reference>
</ItemGroup>
</Project>

192
BackupCognex/Program.cs Normal file
View File

@@ -0,0 +1,192 @@
using System;
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Threading;
using Cognex.DataMan.SDK;
class Program
{
static void Main(string[] args)
{
// Iniciar cronómetro para medir tiempo de ejecución
Stopwatch timer = Stopwatch.StartNew();
// 1. Leer configuración desde config.txt
string exeDirectory = AppDomain.CurrentDomain.BaseDirectory;
string configDirectory = "C:\\Jabil DM Config Station\\Files\\";
string configPath = Path.Combine(configDirectory, "ConfigBackUP.txt");
if (!File.Exists(configPath))
{
Console.WriteLine($"No se encontró el archivo de configuración: {configPath}");
Console.ReadKey();
return;
}
string[] configLines = File.ReadAllLines(configPath);
if (configLines.Length < 2)
{
Console.WriteLine("El archivo ConfigBackUP.txt debe tener 2 líneas: IP y Ruta .dmb");
Console.ReadKey();
return;
}
string ipString = configLines[0].Trim();
string originalDmbPath = configLines[1].Trim().Trim('"');
string labviewFolder = "C:\\Jabil DM Config Station\\Files\\"; //TODO: Actualizar ruta
if (!File.Exists(originalDmbPath))
{
Console.WriteLine($"No se encontró el archivo .dmb original en la ruta: {originalDmbPath}");
Console.ReadKey();
return;
}
// 2. Preparar el entorno
string tempFolder = Path.Combine(Path.GetTempPath(), "DMBackup_" + Guid.NewGuid().ToString().Substring(0, 8));
EthSystemConnector connector = new EthSystemConnector(System.Net.IPAddress.Parse(ipString));
DataManSystem myDevice = new DataManSystem(connector);
// --- MARCAMOS INICIO DE PROCESO PARA LABVIEW (0) ---
ActualizarEstadoLabVIEW(0, exeDirectory, labviewFolder);
try
{
// --- FASE 1: MANEJO DE ARCHIVOS (Descomprimir) ---
Console.WriteLine("Extrayendo archivos del backup (.dmb)...");
Directory.CreateDirectory(tempFolder);
string zipPath = Path.Combine(tempFolder, "backup.zip");
File.Copy(originalDmbPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, tempFolder);
string[] cfgFiles = Directory.GetFiles(tempFolder, "*.cfg");
string[] cdcFiles = Directory.GetFiles(tempFolder, "*.cdc");
if (cfgFiles.Length == 0)
{
Console.WriteLine("\n[ERROR] El archivo .dmb no contenía un archivo de configuración (.cfg).");
ActualizarEstadoLabVIEW(2, exeDirectory, labviewFolder); // Error
return;
}
// --- FASE 2: CONEXIÓN Y CARGA AL DATAMAN ---
Console.WriteLine("\nConectando al lector...");
myDevice.Connect();
Console.WriteLine("Forzando al lector a modo Offline...");
try
{
myDevice.SendCommand("SET SYSTEM.ONLINE OFF");
Thread.Sleep(1000);
}
catch { /* Ignorar si ya está offline */ }
Console.WriteLine($"Cargando configuración: {Path.GetFileName(cfgFiles[0])}...");
myDevice.SetConfig(cfgFiles[0]);
Thread.Sleep(2000);
if (cdcFiles.Length > 0)
{
Console.WriteLine($"Cargando calibración: {Path.GetFileName(cdcFiles[0])}...");
myDevice.Restore(cdcFiles[0]);
Thread.Sleep(2000);
}
// --- FASE 3: GUARDADO Y REINICIO ---
Console.WriteLine("Guardando configuración en la memoria flash...");
myDevice.SendCommand("CONFIG.SAVE");
Thread.Sleep(1000);
Console.WriteLine("Reiniciando el lector...");
try { myDevice.SendCommand("REBOOT"); } catch { }
Console.WriteLine("\n------------------------------------------------");
Console.WriteLine("¡Restauración completada y lector reiniciado!");
Console.WriteLine("------------------------------------------------");
// --- MARCAMOS ÉXITO PARA LABVIEW (1) ---
ActualizarEstadoLabVIEW(1, exeDirectory, labviewFolder);
}
catch (Cognex.DataMan.SDK.UnknownErrorException ex)
{
timer.Stop();
Console.WriteLine("\n[ERROR COGNEX] El lector rechazó la operación.");
Console.WriteLine("Comando que falló: " + ex.Command);
Console.WriteLine("Detalle: " + ex.Message);
Console.WriteLine($"Tiempo transcurrido: {timer.Elapsed.TotalSeconds:F2} segundos");
ActualizarEstadoLabVIEW(2, exeDirectory, labviewFolder); // Error
}
catch (Exception ex)
{
timer.Stop();
Console.WriteLine("\n[ERROR GENERAL]: " + ex.Message);
Console.WriteLine($"Tiempo transcurrido: {timer.Elapsed.TotalSeconds:F2} segundos");
ActualizarEstadoLabVIEW(2, exeDirectory, labviewFolder); // Error
}
finally
{
// --- FASE 4: DESCONEXIÓN Y LIMPIEZA TOTAL ---
try { myDevice.Disconnect(); } catch { }
Console.WriteLine("\nLimpiando archivos temporales...");
try
{
if (Directory.Exists(tempFolder))
{
Directory.Delete(tempFolder, true);
Console.WriteLine("Basura eliminada correctamente.");
}
}
catch { Console.WriteLine("Aviso: No se pudieron eliminar algunos archivos temporales."); }
}
Console.WriteLine("\nEsperando 30 segundos hasta que se reinicie el lector");
Thread.Sleep(30000);
timer.Stop();
TimeSpan tiempoTotal = timer.Elapsed;
Console.WriteLine($"\n================================================");
Console.WriteLine($"Tiempo total de ejecución: {tiempoTotal.TotalSeconds:F2} segundos");
Console.WriteLine($"Desglose: {tiempoTotal.Hours}h {tiempoTotal.Minutes}m {tiempoTotal.Seconds}s {tiempoTotal.Milliseconds}ms");
Console.WriteLine($"================================================");
Console.WriteLine("\nLa aplicación se cerrará automáticamente en 5 segundos...");
Thread.Sleep(5000);
}
/// <summary>
/// Crea el archivo de resultado localmente, elimina el existente en la carpeta destino (para disparar el evento en LabVIEW)
/// y luego copia el nuevo archivo actualizado.
/// </summary>
static void ActualizarEstadoLabVIEW(int estado, string directorioLocal, string carpetaDestino)
{
try
{
// 1. Escribir el estado en el archivo local de la aplicación
string archivoLocal = Path.Combine(directorioLocal, "ResultBackUp.txt");
File.WriteAllText(archivoLocal, estado.ToString());
// 2. Ruta del archivo en la carpeta que monitorea LabVIEW
string archivoDestino = Path.Combine(carpetaDestino, "ResultBackUp.txt");
// 3. Eliminar el archivo destino si existe (Obligatorio para que LabVIEW detecte el cambio)
if (File.Exists(archivoDestino))
{
File.Delete(archivoDestino);
// Pequeña pausa para asegurar que el sistema de archivos registre la eliminación
Thread.Sleep(100);
}
// 4. Copiar el archivo actualizado a la carpeta destino
File.Copy(archivoLocal, archivoDestino);
Console.WriteLine($"[SISTEMA] Bandera LabVIEW actualizada a: {estado}");
}
catch (Exception ex)
{
Console.WriteLine($"\n[AVISO] Ocurrió un problema al intentar actualizar el archivo para LabVIEW: {ex.Message}");
}
}
}

2
BackupCognex/config.txt Normal file
View File

@@ -0,0 +1,2 @@
192.168.1.10
C:\Backups\mi_lector.dmb