Compare commits

1 Commits

View File

@@ -20,10 +20,14 @@ class Program
private static volatile bool _triggerEnviado = false; private static volatile bool _triggerEnviado = false;
// ARREGLOS PARA EL RESPALDO // Respaldo por perfil
private static string[] _backupStandard = new string[4]; private static string[] _backupStandard = new string[4];
private static string[] _backupToken = new string[4]; private static string[] _backupToken = new string[4];
private static string[] _backupDelimiter = new string[4]; private static string[] _backupDelimiter = new string[4];
private static bool[] _perfilRespadado = new bool[4]; // true solo si el respaldo fue exitoso
// Perfil activo cuando nos conectamos (para restaurarlo al final)
private static int _perfilActivoOriginal = 0;
private static bool _configModificada = false; private static bool _configModificada = false;
static void Main(string[] args) static void Main(string[] args)
@@ -85,31 +89,84 @@ class Program
Console.WriteLine("[OK] Conectado con éxito."); Console.WriteLine("[OK] Conectado con éxito.");
Console.ResetColor(); Console.ResetColor();
// =========================================================================
// FASE 1: LIMPIEZA INICIAL
// =========================================================================
try { myDevice.SendCommand("TRIGGER OFF"); } catch { } try { myDevice.SendCommand("TRIGGER OFF"); } catch { }
Thread.Sleep(100); Thread.Sleep(100);
try { myDevice.SendCommand("SET TRIGGER.TYPE 0"); } catch { } try { myDevice.SendCommand("SET TRIGGER.TYPE 0"); } catch { }
// ===================================================================== // =========================================================================
// FASE DE RESPALDO Y MODIFICACIÓN // FASE 2: RESPALDO
// ===================================================================== // Guardamos el perfil activo ANTES de tocar nada, para restaurarlo al final.
Console.WriteLine("[SISTEMA] Respaldando y preparando perfiles..."); // Solo marcamos _perfilRespadado[i] = true si el respaldo fue completo.
// =========================================================================
Console.WriteLine("[SISTEMA] Respaldando configuración de perfiles...");
try
{
// Leer qué perfil está activo actualmente
string perfilActualStr = myDevice.SendCommand("GET FORMAT.PROG-TARG").PayLoad.Trim();
if (!int.TryParse(perfilActualStr, out _perfilActivoOriginal))
_perfilActivoOriginal = 0;
Console.WriteLine($"[SISTEMA] Perfil activo al conectar: {_perfilActivoOriginal}");
}
catch
{
_perfilActivoOriginal = 0;
Console.WriteLine("[AVISO] No se pudo leer el perfil activo. Se asumirá perfil 0.");
}
for (int i = 0; i <= 3; i++)
{
try
{
// Seleccionar el perfil explícitamente y verificar que responde
DmccResponse respPerfil = myDevice.SendCommand($"SET FORMAT.PROG-TARG {i}");
_backupStandard[i] = myDevice.SendCommand("GET FORMAT.STANDARD").PayLoad.Trim();
_backupToken[i] = myDevice.SendCommand("GET FORMAT.TOKEN").PayLoad.Trim(' ', '"');
_backupDelimiter[i] = myDevice.SendCommand("GET FORMAT.DELIMITER").PayLoad.Trim();
_perfilRespadado[i] = true; // Solo marcamos si todos los GET tuvieron éxito
// Console.WriteLine($"[SISTEMA] Perfil {i} respaldado OK.");
}
catch (Exception ex)
{
_perfilRespadado[i] = false;
Console.WriteLine($"[AVISO] No se pudo respaldar perfil {i}: {ex.Message}");
}
}
// =========================================================================
// FASE 3: MODIFICACIÓN
// Solo modificamos los perfiles que se respaldaron correctamente.
// =========================================================================
Console.WriteLine("[SISTEMA] Inyectando token de geometría...");
_configModificada = true; _configModificada = true;
for (int i = 0; i <= 3; i++) for (int i = 0; i <= 3; i++)
{ {
try { myDevice.SendCommand($"SET FORMAT.PROG-TARG {i}"); } if (!_perfilRespadado[i]) continue; // No tocar lo que no pudimos respaldar
catch { continue; }
try { _backupStandard[i] = myDevice.SendCommand("GET FORMAT.STANDARD").PayLoad.Trim(); } catch { } try
try { _backupToken[i] = myDevice.SendCommand("GET FORMAT.TOKEN").PayLoad.Trim(' ', '"'); } catch { } {
try { _backupDelimiter[i] = myDevice.SendCommand("GET FORMAT.DELIMITER").PayLoad.Trim(); } catch { } myDevice.SendCommand($"SET FORMAT.PROG-TARG {i}");
myDevice.SendCommand("SET FORMAT.STANDARD ON");
// INYECTAMOS EL TOKEN COMPLETO PARA OBLIGARLA A DARNOS EL XML myDevice.SendCommand("SET FORMAT.TOKEN \"<DATA><CPOS><CANG>\"");
try { myDevice.SendCommand("SET FORMAT.STANDARD ON"); } catch { } myDevice.SendCommand("SET FORMAT.DELIMITER 5");
try { myDevice.SendCommand("SET FORMAT.TOKEN \"<DATA><CPOS><CANG>\""); } catch { } // Console.WriteLine($"[SISTEMA] Perfil {i} modificado OK.");
try { myDevice.SendCommand("SET FORMAT.DELIMITER 5"); } catch { } }
catch (Exception ex)
{
Console.WriteLine($"[AVISO] No se pudo modificar perfil {i}: {ex.Message}");
}
} }
// =========================================================================
// FASE 4: SUSCRIPCIÓN Y DISPARO
// =========================================================================
myDevice.SetResultTypes(ResultTypes.ReadString | ResultTypes.ReadXml); myDevice.SetResultTypes(ResultTypes.ReadString | ResultTypes.ReadXml);
myDevice.XmlResultArrived += (sender, e) => myDevice.XmlResultArrived += (sender, e) =>
@@ -119,7 +176,6 @@ class Program
lock (_lock) lock (_lock)
{ {
if (_lecturaExitosa) return; if (_lecturaExitosa) return;
if (string.IsNullOrEmpty(e.XmlResult)) return; if (string.IsNullOrEmpty(e.XmlResult)) return;
try try
@@ -131,31 +187,15 @@ class Program
if (statusNode == null || !statusNode.InnerText.ToUpper().Contains("GOOD READ")) if (statusNode == null || !statusNode.InnerText.ToUpper().Contains("GOOD READ"))
return; return;
// ======= DIAGNÓSTICO TEMPORAL - BORRAR DESPUÉS ======= // Leer el código desde full_string (puede ser base64)
/*Console.WriteLine("=== XML EXTERIOR COMPLETO ==="); XmlNode? fullStringNode = doc.SelectSingleNode("//general/full_string");
Console.WriteLine(e.XmlResult); string innerXmlText = "";
Console.WriteLine("=== FIN XML EXTERIOR ===");
XmlNode? outerFullString_diag = doc.SelectSingleNode("//general/full_string"); if (fullStringNode != null)
if (outerFullString_diag != null)
{ {
Console.WriteLine("=== CONTENIDO FULL_STRING EXTERIOR ==="); innerXmlText = fullStringNode.InnerText;
Console.WriteLine($"InnerText: [{outerFullString_diag.InnerText}]");
Console.WriteLine($"InnerXml: [{outerFullString_diag.InnerXml}]");
Console.WriteLine($"Encoding attr: [{outerFullString_diag.Attributes?["encoding"]?.Value ?? "ninguno"}]");
Console.WriteLine("=== FIN FULL_STRING ===");
}
*/
// El full_string exterior contiene otro XML completo como texto string? enc = fullStringNode.Attributes?["encoding"]?.Value;
XmlNode? outerFullString = doc.SelectSingleNode("//general/full_string");
if (outerFullString == null) return;
string innerXmlText = outerFullString.InnerText;
// Si está en base64, decodificar
string? enc = outerFullString.Attributes?["encoding"]?.Value;
if (enc != null && enc.ToLower() == "base64") if (enc != null && enc.ToLower() == "base64")
{ {
try try
@@ -165,6 +205,7 @@ class Program
} }
catch { } catch { }
} }
}
string posX = "0"; string posX = "0";
string posY = "0"; string posY = "0";
@@ -173,21 +214,23 @@ class Program
try try
{ {
// CDATA: extraer el código real // Código real dentro del CDATA
var matchCdata = Regex.Match(innerXmlText, @"<!\[CDATA\[([\s\S]*?)\]\]>"); var matchCdata = Regex.Match(innerXmlText, @"<!\[CDATA\[([\s\S]*?)\]\]>");
if (matchCdata.Success) if (matchCdata.Success)
codigoFinal = matchCdata.Groups[1].Value.Trim(); codigoFinal = matchCdata.Groups[1].Value.Trim();
// Primer punto de code_position = posición del código // Posición: primer <point> de <code_position>
var matchX = Regex.Match(innerXmlText, @"<code_position>\s*<point>\s*<x>([\d]+)</x>\s*<y>([\d]+)</y>"); var matchPos = Regex.Match(innerXmlText,
if (matchX.Success) @"<code_position>\s*<point>\s*<x>([\d]+)</x>\s*<y>([\d]+)</y>");
if (matchPos.Success)
{ {
posX = matchX.Groups[1].Value; posX = matchPos.Groups[1].Value;
posY = matchX.Groups[2].Value; posY = matchPos.Groups[2].Value;
} }
// Ángulo // Ángulo
var matchAng = Regex.Match(innerXmlText, @"<code_orientation>([\d]+)</code_orientation>"); var matchAng = Regex.Match(innerXmlText,
@"<code_orientation>([\d]+)</code_orientation>");
if (matchAng.Success) if (matchAng.Success)
angulo = matchAng.Groups[1].Value; angulo = matchAng.Groups[1].Value;
} }
@@ -249,32 +292,56 @@ class Program
} }
finally finally
{ {
// ===================================================================== // =========================================================================
// FASE DE RESTAURACIÓN // FASE 5: RESTAURACIÓN Y CIERRE
// ===================================================================== // Solo restauramos perfiles que fueron respaldados exitosamente.
// Al final, dejamos activo el mismo perfil que estaba al conectar.
// =========================================================================
try { myDevice.SendCommand("TRIGGER OFF"); } catch { } try { myDevice.SendCommand("TRIGGER OFF"); } catch { }
Thread.Sleep(100); Thread.Sleep(100);
if (_configModificada) if (_configModificada)
{ {
Console.WriteLine("[SISTEMA] Restaurando formato de salida original de la cámara..."); Console.WriteLine("[SISTEMA] Restaurando configuración original...");
for (int i = 0; i <= 3; i++) for (int i = 0; i <= 3; i++)
{ {
try { myDevice.SendCommand($"SET FORMAT.PROG-TARG {i}"); } catch { continue; } if (!_perfilRespadado[i]) continue;
if (!string.IsNullOrEmpty(_backupStandard[i])) try
try { myDevice.SendCommand($"SET FORMAT.STANDARD {_backupStandard[i]}"); } catch { } {
myDevice.SendCommand($"SET FORMAT.PROG-TARG {i}");
if (!string.IsNullOrEmpty(_backupDelimiter[i])) myDevice.SendCommand($"SET FORMAT.STANDARD {_backupStandard[i]}");
try { myDevice.SendCommand($"SET FORMAT.DELIMITER {_backupDelimiter[i]}"); } catch { } myDevice.SendCommand($"SET FORMAT.DELIMITER {_backupDelimiter[i]}");
if (!string.IsNullOrEmpty(_backupToken[i])) // El token puede ser vacío si LabVIEW no usaba ninguno
try { myDevice.SendCommand($"SET FORMAT.TOKEN \"{_backupToken[i]}\""); } catch { } string tokenRestaurar = string.IsNullOrEmpty(_backupToken[i])
else ? "\"\""
try { myDevice.SendCommand("SET FORMAT.TOKEN \"\""); } catch { } : $"\"{_backupToken[i]}\"";
myDevice.SendCommand($"SET FORMAT.TOKEN {tokenRestaurar}");
// Console.WriteLine($"[SISTEMA] Perfil {i} restaurado OK.");
}
catch (Exception ex)
{
Console.WriteLine($"[AVISO] No se pudo restaurar perfil {i}: {ex.Message}");
} }
} }
// Restaurar el perfil que estaba activo originalmente
try
{
myDevice.SendCommand($"SET FORMAT.PROG-TARG {_perfilActivoOriginal}");
Console.WriteLine($"[SISTEMA] Perfil activo restaurado a: {_perfilActivoOriginal}");
}
catch (Exception ex)
{
Console.WriteLine($"[AVISO] No se pudo restaurar perfil activo: {ex.Message}");
}
}
Thread.Sleep(300);
try { myDevice.Disconnect(); } catch { } try { myDevice.Disconnect(); } catch { }
} }
@@ -291,7 +358,6 @@ class Program
{ {
try try
{ {
// Paso 1: Escribir en la carpeta local del .exe
string localResultPath = "ResultLectura.txt"; string localResultPath = "ResultLectura.txt";
string localCopiaPath = "ResultLectura_Copia.txt"; string localCopiaPath = "ResultLectura_Copia.txt";
@@ -306,7 +372,6 @@ class Program
File.Move(localCopiaPath, localResultPath); File.Move(localCopiaPath, localResultPath);
Console.WriteLine("[SISTEMA] ResultLectura.txt actualizado localmente con estado: " + estado); Console.WriteLine("[SISTEMA] ResultLectura.txt actualizado localmente con estado: " + estado);
// Paso 2: Copiar al configDirectory
Thread.Sleep(100); Thread.Sleep(100);
string configCopiaPath = Path.Combine(_configDirectory, "ResultLectura_Copia.txt"); string configCopiaPath = Path.Combine(_configDirectory, "ResultLectura_Copia.txt");
File.Copy(localResultPath, configCopiaPath, true); File.Copy(localResultPath, configCopiaPath, true);
@@ -332,7 +397,6 @@ class Program
{ {
try try
{ {
// Paso 1: Escribir en la carpeta local del .exe
string localLecturaPath = "Lectura.txt"; string localLecturaPath = "Lectura.txt";
string localCopiaPath = "Lectura_Copia.txt"; string localCopiaPath = "Lectura_Copia.txt";
string[] lineas = new string[] { resultado, x, y, angle }; string[] lineas = new string[] { resultado, x, y, angle };
@@ -348,7 +412,6 @@ class Program
File.Move(localCopiaPath, localLecturaPath); File.Move(localCopiaPath, localLecturaPath);
Console.WriteLine("[SISTEMA] Lectura.txt actualizado localmente."); Console.WriteLine("[SISTEMA] Lectura.txt actualizado localmente.");
// Paso 2: Copiar al configDirectory
Thread.Sleep(100); Thread.Sleep(100);
string configCopiaPath = Path.Combine(_configDirectory, "Lectura_Copia.txt"); string configCopiaPath = Path.Combine(_configDirectory, "Lectura_Copia.txt");
File.Copy(localLecturaPath, configCopiaPath, true); File.Copy(localLecturaPath, configCopiaPath, true);