From 843bc5444081b862f190b17373dbf8f648f95740 Mon Sep 17 00:00:00 2001 From: Angel Ivan Date: Wed, 27 May 2026 10:27:35 -0600 Subject: [PATCH] =?UTF-8?q?Modificaciones=20en=20el=20proceso=20de=20respa?= =?UTF-8?q?ldo,=20mdificaci=C3=B3n=20y=20restauraci=C3=B3n=20de=20la=20con?= =?UTF-8?q?figuraci=C3=B3n=20del=20lector?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- LecturaDM/Program.cs | 203 ++++++++++++++++++++++++++++--------------- 1 file changed, 133 insertions(+), 70 deletions(-) diff --git a/LecturaDM/Program.cs b/LecturaDM/Program.cs index 3d1d223..d16c9fa 100644 --- a/LecturaDM/Program.cs +++ b/LecturaDM/Program.cs @@ -20,10 +20,14 @@ class Program private static volatile bool _triggerEnviado = false; - // ARREGLOS PARA EL RESPALDO + // Respaldo por perfil private static string[] _backupStandard = new string[4]; private static string[] _backupToken = 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; static void Main(string[] args) @@ -85,31 +89,84 @@ class Program Console.WriteLine("[OK] Conectado con éxito."); Console.ResetColor(); + // ========================================================================= + // FASE 1: LIMPIEZA INICIAL + // ========================================================================= try { myDevice.SendCommand("TRIGGER OFF"); } catch { } Thread.Sleep(100); try { myDevice.SendCommand("SET TRIGGER.TYPE 0"); } catch { } - // ===================================================================== - // FASE DE RESPALDO Y MODIFICACIÓN - // ===================================================================== - Console.WriteLine("[SISTEMA] Respaldando y preparando perfiles..."); + // ========================================================================= + // FASE 2: RESPALDO + // Guardamos el perfil activo ANTES de tocar nada, para restaurarlo al final. + // 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; for (int i = 0; i <= 3; i++) { - try { myDevice.SendCommand($"SET FORMAT.PROG-TARG {i}"); } - catch { continue; } + if (!_perfilRespadado[i]) continue; // No tocar lo que no pudimos respaldar - try { _backupStandard[i] = myDevice.SendCommand("GET FORMAT.STANDARD").PayLoad.Trim(); } catch { } - try { _backupToken[i] = myDevice.SendCommand("GET FORMAT.TOKEN").PayLoad.Trim(' ', '"'); } catch { } - try { _backupDelimiter[i] = myDevice.SendCommand("GET FORMAT.DELIMITER").PayLoad.Trim(); } catch { } - - // INYECTAMOS EL TOKEN COMPLETO PARA OBLIGARLA A DARNOS EL XML - try { myDevice.SendCommand("SET FORMAT.STANDARD ON"); } catch { } - try { myDevice.SendCommand("SET FORMAT.TOKEN \"\""); } catch { } - try { myDevice.SendCommand("SET FORMAT.DELIMITER 5"); } catch { } + try + { + myDevice.SendCommand($"SET FORMAT.PROG-TARG {i}"); + myDevice.SendCommand("SET FORMAT.STANDARD ON"); + myDevice.SendCommand("SET FORMAT.TOKEN \"\""); + myDevice.SendCommand("SET FORMAT.DELIMITER 5"); + // Console.WriteLine($"[SISTEMA] Perfil {i} modificado OK."); + } + 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.XmlResultArrived += (sender, e) => @@ -119,7 +176,6 @@ class Program lock (_lock) { if (_lecturaExitosa) return; - if (string.IsNullOrEmpty(e.XmlResult)) return; try @@ -131,39 +187,24 @@ class Program if (statusNode == null || !statusNode.InnerText.ToUpper().Contains("GOOD READ")) return; - // ======= DIAGNÓSTICO TEMPORAL - BORRAR DESPUÉS ======= - /*Console.WriteLine("=== XML EXTERIOR COMPLETO ==="); - Console.WriteLine(e.XmlResult); - Console.WriteLine("=== FIN XML EXTERIOR ==="); + // Leer el código desde full_string (puede ser base64) + XmlNode? fullStringNode = doc.SelectSingleNode("//general/full_string"); + string innerXmlText = ""; - XmlNode? outerFullString_diag = doc.SelectSingleNode("//general/full_string"); - - if (outerFullString_diag != null) + if (fullStringNode != null) { - Console.WriteLine("=== CONTENIDO FULL_STRING EXTERIOR ==="); - 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 ==="); - } - */ + innerXmlText = fullStringNode.InnerText; - // El full_string exterior contiene otro XML completo como texto - 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") - { - try + string? enc = fullStringNode.Attributes?["encoding"]?.Value; + if (enc != null && enc.ToLower() == "base64") { - byte[] bytes = Convert.FromBase64String(innerXmlText); - innerXmlText = System.Text.Encoding.UTF8.GetString(bytes); + try + { + byte[] bytes = Convert.FromBase64String(innerXmlText); + innerXmlText = System.Text.Encoding.UTF8.GetString(bytes); + } + catch { } } - catch { } } string posX = "0"; @@ -173,21 +214,23 @@ class Program try { - // CDATA: extraer el código real + // Código real dentro del CDATA var matchCdata = Regex.Match(innerXmlText, @""); if (matchCdata.Success) codigoFinal = matchCdata.Groups[1].Value.Trim(); - // Primer punto de code_position = posición del código - var matchX = Regex.Match(innerXmlText, @"\s*\s*([\d]+)\s*([\d]+)"); - if (matchX.Success) + // Posición: primer de + var matchPos = Regex.Match(innerXmlText, + @"\s*\s*([\d]+)\s*([\d]+)"); + if (matchPos.Success) { - posX = matchX.Groups[1].Value; - posY = matchX.Groups[2].Value; + posX = matchPos.Groups[1].Value; + posY = matchPos.Groups[2].Value; } // Ángulo - var matchAng = Regex.Match(innerXmlText, @"([\d]+)"); + var matchAng = Regex.Match(innerXmlText, + @"([\d]+)"); if (matchAng.Success) angulo = matchAng.Groups[1].Value; } @@ -203,10 +246,10 @@ class Program Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine($"\n[ÉXITO]"); - Console.WriteLine($"-> Lectura: {codigoFinal}"); + Console.WriteLine($"-> Lectura: {codigoFinal}"); Console.WriteLine($"-> Posición X: {posX}"); Console.WriteLine($"-> Posición Y: {posY}"); - Console.WriteLine($"-> Ángulo: {angulo}°"); + Console.WriteLine($"-> Ángulo: {angulo}°"); Console.ResetColor(); _lecturaExitosa = true; @@ -249,32 +292,56 @@ class Program } 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 { } Thread.Sleep(100); 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++) { - try { myDevice.SendCommand($"SET FORMAT.PROG-TARG {i}"); } catch { continue; } + if (!_perfilRespadado[i]) continue; - if (!string.IsNullOrEmpty(_backupStandard[i])) - try { myDevice.SendCommand($"SET FORMAT.STANDARD {_backupStandard[i]}"); } catch { } + try + { + myDevice.SendCommand($"SET FORMAT.PROG-TARG {i}"); - if (!string.IsNullOrEmpty(_backupDelimiter[i])) - try { myDevice.SendCommand($"SET FORMAT.DELIMITER {_backupDelimiter[i]}"); } catch { } + myDevice.SendCommand($"SET FORMAT.STANDARD {_backupStandard[i]}"); + myDevice.SendCommand($"SET FORMAT.DELIMITER {_backupDelimiter[i]}"); - if (!string.IsNullOrEmpty(_backupToken[i])) - try { myDevice.SendCommand($"SET FORMAT.TOKEN \"{_backupToken[i]}\""); } catch { } - else - try { myDevice.SendCommand("SET FORMAT.TOKEN \"\""); } catch { } + // El token puede ser vacío si LabVIEW no usaba ninguno + string tokenRestaurar = string.IsNullOrEmpty(_backupToken[i]) + ? "\"\"" + : $"\"{_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 { } } @@ -291,7 +358,6 @@ class Program { try { - // Paso 1: Escribir en la carpeta local del .exe string localResultPath = "ResultLectura.txt"; string localCopiaPath = "ResultLectura_Copia.txt"; @@ -306,7 +372,6 @@ class Program File.Move(localCopiaPath, localResultPath); Console.WriteLine("[SISTEMA] ResultLectura.txt actualizado localmente con estado: " + estado); - // Paso 2: Copiar al configDirectory Thread.Sleep(100); string configCopiaPath = Path.Combine(_configDirectory, "ResultLectura_Copia.txt"); File.Copy(localResultPath, configCopiaPath, true); @@ -332,7 +397,6 @@ class Program { try { - // Paso 1: Escribir en la carpeta local del .exe string localLecturaPath = "Lectura.txt"; string localCopiaPath = "Lectura_Copia.txt"; string[] lineas = new string[] { resultado, x, y, angle }; @@ -348,7 +412,6 @@ class Program File.Move(localCopiaPath, localLecturaPath); Console.WriteLine("[SISTEMA] Lectura.txt actualizado localmente."); - // Paso 2: Copiar al configDirectory Thread.Sleep(100); string configCopiaPath = Path.Combine(_configDirectory, "Lectura_Copia.txt"); File.Copy(localLecturaPath, configCopiaPath, true);