Simatic_XML_Parser_to_SCL/x2_process.py

1462 lines
60 KiB
Python

# -*- coding: utf-8 -*-
import json
import os
import copy
import traceback
import re
# --- Constantes y Configuración ---
SCL_SUFFIX = "_scl"
GROUPED_COMMENT = "// Logic included in grouped IF"
# Global data variable
data = {}
# --- Helper Functions ---
# (get_scl_representation, format_variable_name, generate_temp_var_name, get_target_scl_name - sin cambios)
def get_scl_representation(source_info, network_id, scl_map, access_map):
if not source_info:
return None
if isinstance(source_info, list):
scl_parts = []
all_resolved = True
for sub_source in source_info:
sub_scl = get_scl_representation(
sub_source, network_id, scl_map, access_map
)
if sub_scl is None:
all_resolved = False
break
if (
sub_scl in ["TRUE", "FALSE"]
or (sub_scl.startswith('"') and sub_scl.endswith('"'))
or sub_scl.isdigit()
or (sub_scl.startswith("(") and sub_scl.endswith(")"))
):
scl_parts.append(sub_scl)
else:
scl_parts.append(f"({sub_scl})")
return (
" OR ".join(scl_parts)
if len(scl_parts) > 1
else (scl_parts[0] if scl_parts else "FALSE") if all_resolved else None
)
source_type = source_info.get("type")
if source_type == "powerrail":
return "TRUE"
elif source_type == "variable":
name = source_info.get("name")
# Asegurar que los nombres de variables se formatean correctamente aquí también
return (
format_variable_name(name)
if name
else f"_ERR_VAR_NO_NAME_{source_info.get('uid')}_"
)
elif source_type == "constant":
dtype = str(source_info.get("datatype", "")).upper()
value = source_info.get("value")
try:
if dtype == "BOOL":
return str(value).upper()
elif dtype in [
"INT",
"DINT",
"SINT",
"USINT",
"UINT",
"UDINT",
"LINT",
"ULINT",
"WORD",
"DWORD",
"LWORD",
"BYTE",
]:
return str(value)
elif dtype in ["REAL", "LREAL"]:
s_val = str(value)
return s_val if "." in s_val or "e" in s_val.lower() else s_val + ".0"
elif dtype == "STRING":
# Escapar comillas simples dentro del string si es necesario
str_val = str(value).replace("'", "''")
return f"'{str_val}'"
elif dtype == "TYPEDCONSTANT":
# Podría necesitar formateo específico basado en el tipo real
return str(value)
else:
# Otros tipos (TIME, DATE, etc.) - devolver como string por ahora
str_val = str(value).replace("'", "''")
return f"'{str_val}'"
except Exception as e:
print(f"Advertencia: Error formateando constante {source_info}: {e}")
return f"_ERR_CONST_FORMAT_{source_info.get('uid')}_"
elif source_type == "connection":
map_key = (
network_id,
source_info.get("source_instruction_uid"),
source_info.get("source_pin"),
)
return scl_map.get(map_key)
elif source_type == "unknown_source":
print(
f"Advertencia: Refiriendo a fuente desconocida UID: {source_info.get('uid')}"
)
return f"_ERR_UNKNOWN_SRC_{source_info.get('uid')}_"
else:
print(f"Advertencia: Tipo de fuente desconocido: {source_info}")
return f"_ERR_INVALID_SRC_TYPE_"
def format_variable_name(name):
"""Limpia el nombre de la variable para SCL."""
if not name:
return "_INVALID_NAME_"
# Si ya está entre comillas dobles, asumimos que es un nombre complejo (ej. "DB"."Variable")
# y lo devolvemos tal cual para SCL.
if name.startswith('"') and name.endswith('"'):
# Podríamos añadir validación extra aquí si fuera necesario
return name
# Si no tiene comillas, es un nombre simple (ej. Tag_1, #tempVar)
# Reemplazar caracteres no válidos (excepto '_') por '_'
# Permitir '#' al inicio para variables temporales
prefix = ""
if name.startswith("#"):
prefix = "#"
name = name[1:]
# Permitir letras, números y guiones bajos. Reemplazar el resto.
# Asegurarse de que no empiece con número (después del # si existe)
if name and name[0].isdigit():
name = "_" + name
# Reemplazar caracteres no válidos
name = re.sub(r"[^a-zA-Z0-9_]", "_", name)
return prefix + name
def generate_temp_var_name(network_id, instr_uid, pin_name):
net_id_clean = str(network_id).replace("-", "_")
instr_uid_clean = str(instr_uid).replace("-", "_")
pin_name_clean = str(pin_name).replace("-", "_").lower()
# Usar # para variables temporales SCL estándar
return f"#_temp_{net_id_clean}_{instr_uid_clean}_{pin_name_clean}"
def get_target_scl_name(instruction, output_pin_name, network_id, default_to_temp=True):
instr_uid = instruction["instruction_uid"]
output_pin_data = instruction["outputs"].get(output_pin_name)
target_scl = None
if (
output_pin_data
and isinstance(output_pin_data, list)
and len(output_pin_data) == 1
):
dest_access = output_pin_data[0]
if dest_access.get("type") == "variable":
target_scl = dest_access.get("name")
if target_scl:
target_scl = format_variable_name(target_scl) # Formatear nombre
else:
print(
f"Error: Var destino {instr_uid}.{output_pin_name} sin nombre (UID: {dest_access.get('uid')}). {'Usando temp.' if default_to_temp else 'Ignorando.'}"
)
target_scl = (
generate_temp_var_name(network_id, instr_uid, output_pin_name)
if default_to_temp
else None
)
elif dest_access.get("type") == "constant":
print(
f"Advertencia: Instr {instr_uid} escribe en const UID {dest_access.get('uid')}. {'Usando temp.' if default_to_temp else 'Ignorando.'}"
)
target_scl = (
generate_temp_var_name(network_id, instr_uid, output_pin_name)
if default_to_temp
else None
)
else:
print(
f"Advertencia: Destino {instr_uid}.{output_pin_name} no es var/const: {dest_access.get('type')}. {'Usando temp.' if default_to_temp else 'Ignorando.'}"
)
target_scl = (
generate_temp_var_name(network_id, instr_uid, output_pin_name)
if default_to_temp
else None
)
elif default_to_temp:
target_scl = generate_temp_var_name(network_id, instr_uid, output_pin_name)
# Si target_scl sigue siendo None y no se debe usar temp, devolver None
if target_scl is None and not default_to_temp:
return None
# Si target_scl es None pero sí se permite temp, generar uno ahora
if target_scl is None and default_to_temp:
target_scl = generate_temp_var_name(network_id, instr_uid, output_pin_name)
return target_scl
# --- Procesadores de Instrucciones ---
# (process_contact, process_eq, process_coil, process_convert, process_mod,
# process_add, process_move, process_pbox, process_o, process_call - sin cambios significativos,
# solo asegurar que usan format_variable_name donde sea necesario para operandos/destinos)
# ... (código de los procesadores aquí, asumiendo que ya usan format_variable_name) ...
def process_contact(instruction, network_id, scl_map, access_map):
"""Traduce Contact (normal o negado) a una expresión booleana SCL."""
instr_uid = instruction["instruction_uid"]
instr_type = instruction["type"]
if instr_type.endswith(SCL_SUFFIX) or "_error" in instr_type:
return False
# --- INICIO LEER NEGACIÓN ---
# Verificar si el pin 'operand' está marcado como negado en el JSON
is_negated = instruction.get("negated_pins", {}).get("operand", False)
# --- FIN LEER NEGACIÓN ---
# print(f"DEBUG: Intentando procesar CONTACT{' (N)' if is_negated else ''} - UID: {instr_uid} en Red: {network_id}")
in_input = instruction["inputs"].get("in")
in_rlo_scl = (
"TRUE"
if in_input is None
else get_scl_representation(in_input, network_id, scl_map, access_map)
)
operand_scl = get_scl_representation(
instruction["inputs"].get("operand"), network_id, scl_map, access_map
)
if in_rlo_scl is None or operand_scl is None:
return False
# Usar is_negated para aplicar NOT
term = f"NOT {operand_scl}" if is_negated else operand_scl
if not (term.startswith('"') and term.endswith('"')):
# Añadir paréntesis si es NOT o si contiene espacios/operadores
if is_negated or (
" " in term and not (term.startswith("(") and term.endswith(")"))
):
term = f"({term})"
new_rlo_scl = (
term
if in_rlo_scl == "TRUE"
else (
f"({in_rlo_scl}) AND {term}"
if ("AND" in in_rlo_scl or "OR" in in_rlo_scl)
and not (in_rlo_scl.startswith("(") and in_rlo_scl.endswith(")"))
else f"{in_rlo_scl} AND {term}"
)
)
map_key = (network_id, instr_uid, "out")
scl_map[map_key] = new_rlo_scl
instruction["scl"] = f"// RLO: {new_rlo_scl}"
instruction["type"] = instr_type + SCL_SUFFIX
return True
def process_eq(instruction, network_id, scl_map, access_map):
instr_uid = instruction["instruction_uid"]
instr_type = instruction["type"]
if instr_type.endswith(SCL_SUFFIX) or "_error" in instr_type:
return False
in1_info = instruction["inputs"].get("in1")
in2_info = instruction["inputs"].get("in2")
in1_scl = get_scl_representation(in1_info, network_id, scl_map, access_map)
in2_scl = get_scl_representation(in2_info, network_id, scl_map, access_map)
if in1_scl is None or in2_scl is None:
return False # Dependencias no listas
# Formatear operandos si son variables
op1 = (
format_variable_name(in1_scl)
if in1_info and in1_info.get("type") == "variable"
else in1_scl
)
op2 = (
format_variable_name(in2_scl)
if in2_info and in2_info.get("type") == "variable"
else in2_scl
)
# Añadir paréntesis si los operandos contienen espacios (poco probable después de formatear)
op1 = f"({op1})" if " " in op1 and not op1.startswith("(") else op1
op2 = f"({op2})" if " " in op2 and not op2.startswith("(") else op2
comparison_scl = f"{op1} = {op2}"
# Guardar el resultado booleano de la comparación en el mapa SCL para la salida 'out'
map_key_out = (network_id, instr_uid, "out")
scl_map[map_key_out] = comparison_scl
# Procesar la entrada 'pre' (RLO anterior) para determinar ENO
pre_input = instruction["inputs"].get("pre")
pre_scl = (
"TRUE"
if pre_input is None
else get_scl_representation(pre_input, network_id, scl_map, access_map)
)
if pre_scl is None:
return False # Dependencia 'pre' no lista
# Guardar el estado de 'pre' como ENO
map_key_eno = (network_id, instr_uid, "eno")
scl_map[map_key_eno] = pre_scl
# El SCL generado es solo un comentario indicando la condición,
# ya que la lógica se propaga a través de scl_map['out']
instruction["scl"] = f"// Comparison Eq {instr_uid}: {comparison_scl}"
instruction["type"] = instr_type + SCL_SUFFIX
return True
def process_coil(instruction, network_id, scl_map, access_map):
instr_uid = instruction["instruction_uid"]
instr_type = instruction["type"]
if instr_type.endswith(SCL_SUFFIX) or "_error" in instr_type:
return False
in_rlo_scl = get_scl_representation(
instruction["inputs"].get("in"), network_id, scl_map, access_map
)
operand_info = instruction["inputs"].get("operand")
operand_scl = get_scl_representation(operand_info, network_id, scl_map, access_map)
if in_rlo_scl is None or operand_scl is None:
return False # Dependencias no listas
# Validar y formatear operando
if not (operand_info and operand_info.get("type") == "variable"):
print(f"Error: Operando COIL {instr_uid} no es variable o falta información.")
instruction["scl"] = (
f"// ERROR: Coil {instr_uid} operando no es variable o falta info"
)
instruction["type"] = instr_type + "_error"
return True # Marcar como procesado (con error)
operand_scl_formatted = format_variable_name(operand_scl)
# Simplificar RLO si es posible
if in_rlo_scl == "(TRUE)":
in_rlo_scl = "TRUE"
elif in_rlo_scl == "(FALSE)":
in_rlo_scl = "FALSE"
# Generar la asignación SCL
scl_final = f"{operand_scl_formatted} := {in_rlo_scl};"
instruction["scl"] = scl_final
instruction["type"] = instr_type + SCL_SUFFIX
# Las bobinas no suelen tener salida ENO explícita en este contexto,
# pero podríamos propagar el RLO de entrada si fuera necesario para alguna lógica posterior.
# map_key_eno = (network_id, instr_uid, "eno")
# scl_map[map_key_eno] = in_rlo_scl
return True
def process_convert(instruction, network_id, scl_map, access_map):
instr_uid = instruction["instruction_uid"]
instr_type = instruction["type"]
if instr_type.endswith(SCL_SUFFIX) or "_error" in instr_type:
return False
en_input = instruction["inputs"].get("en")
en_scl = (
get_scl_representation(en_input, network_id, scl_map, access_map)
if en_input
else "TRUE"
)
in_info = instruction["inputs"].get("in")
in_scl = get_scl_representation(in_info, network_id, scl_map, access_map)
if en_scl is None or in_scl is None:
return False # Esperar si dependencias no listas
target_scl = get_target_scl_name(
instruction, "out", network_id, default_to_temp=True
)
if target_scl is None:
print(f"Error: Sin destino claro para CONVERT {instr_uid}")
instruction["scl"] = f"// ERROR: Convert {instr_uid} sin destino"
instruction["type"] += "_error"
return True # Procesado con error
# Formatear entrada si es variable
in_scl_formatted = (
format_variable_name(in_scl)
if in_info and in_info.get("type") == "variable"
else in_scl
)
# Determinar el tipo de destino (simplificado, necesitaría info del XML original)
# Asumimos que el tipo está en TemplateValues o inferirlo del nombre/contexto
target_type = instruction.get("template_values", {}).get(
"destType", "VARIANT"
) # Ejemplo, ajustar según XML real
conversion_func = f"{target_type}_TO_" # Necesita el tipo de origen también
# Esta parte es compleja sin saber los tipos exactos. Usaremos una conversión genérica o MOVE.
# Para una conversión real, necesitaríamos algo como:
# conversion_expr = f"CONVERT(IN := {in_scl_formatted}, OUT => {target_scl})" # Sintaxis inventada
# O usar funciones específicas: INT_TO_REAL, etc.
# Simplificación: Usar asignación directa (MOVE implícito) o función genérica si existe
# Asumiremos asignación directa por ahora.
conversion_expr = in_scl_formatted
scl_core = f"{target_scl} := {conversion_expr};"
# Añadir IF EN si es necesario
scl_final = (
f"IF {en_scl} THEN\n {scl_core}\nEND_IF;" if en_scl != "TRUE" else scl_core
)
instruction["scl"] = scl_final
instruction["type"] = instr_type + SCL_SUFFIX
map_key_out = (network_id, instr_uid, "out")
scl_map[map_key_out] = target_scl # El valor de salida es el contenido del destino
map_key_eno = (network_id, instr_uid, "eno")
scl_map[map_key_eno] = en_scl # ENO sigue a EN
return True
def process_mod(instruction, network_id, scl_map, access_map):
instr_uid = instruction["instruction_uid"]
instr_type = instruction["type"]
if instr_type.endswith(SCL_SUFFIX) or "_error" in instr_type:
return False
en_input = instruction["inputs"].get("en")
en_scl = (
get_scl_representation(en_input, network_id, scl_map, access_map)
if en_input
else "TRUE"
)
in1_info = instruction["inputs"].get("in1")
in2_info = instruction["inputs"].get("in2")
in1_scl = get_scl_representation(in1_info, network_id, scl_map, access_map)
in2_scl = get_scl_representation(in2_info, network_id, scl_map, access_map)
if en_scl is None or in1_scl is None or in2_scl is None:
return False
target_scl = get_target_scl_name(
instruction, "out", network_id, default_to_temp=True
)
if target_scl is None:
print(f"Error: Sin destino MOD {instr_uid}")
instruction["scl"] = f"// ERROR: Mod {instr_uid} sin destino"
instruction["type"] += "_error"
return True
# Formatear operandos si son variables
op1 = (
format_variable_name(in1_scl)
if in1_info and in1_info.get("type") == "variable"
else in1_scl
)
op2 = (
format_variable_name(in2_scl)
if in2_info and in2_info.get("type") == "variable"
else in2_scl
)
# Añadir paréntesis si es necesario (poco probable tras formatear)
op1 = f"({op1})" if " " in op1 and not op1.startswith("(") else op1
op2 = f"({op2})" if " " in op2 and not op2.startswith("(") else op2
scl_core = f"{target_scl} := {op1} MOD {op2};"
scl_final = (
f"IF {en_scl} THEN\n {scl_core}\nEND_IF;" if en_scl != "TRUE" else scl_core
)
instruction["scl"] = scl_final
instruction["type"] = instr_type + SCL_SUFFIX
map_key_out = (network_id, instr_uid, "out")
scl_map[map_key_out] = target_scl
map_key_eno = (network_id, instr_uid, "eno")
scl_map[map_key_eno] = en_scl
return True
def process_add(instruction, network_id, scl_map, access_map):
instr_uid = instruction["instruction_uid"]
instr_type = instruction["type"]
if instr_type.endswith(SCL_SUFFIX) or "_error" in instr_type:
return False
en_input = instruction["inputs"].get("en")
en_scl = (
get_scl_representation(en_input, network_id, scl_map, access_map)
if en_input
else "TRUE"
)
in1_info = instruction["inputs"].get("in1")
in2_info = instruction["inputs"].get("in2")
in1_scl = get_scl_representation(in1_info, network_id, scl_map, access_map)
in2_scl = get_scl_representation(in2_info, network_id, scl_map, access_map)
if en_scl is None or in1_scl is None or in2_scl is None:
return False
target_scl = get_target_scl_name(
instruction, "out", network_id, default_to_temp=True
)
if target_scl is None:
print(f"Error: Sin destino ADD {instr_uid}")
instruction["scl"] = f"// ERROR: Add {instr_uid} sin destino"
instruction["type"] += "_error"
return True
# Formatear operandos si son variables
op1 = (
format_variable_name(in1_scl)
if in1_info and in1_info.get("type") == "variable"
else in1_scl
)
op2 = (
format_variable_name(in2_scl)
if in2_info and in2_info.get("type") == "variable"
else in2_scl
)
# Añadir paréntesis si es necesario
op1 = f"({op1})" if " " in op1 and not op1.startswith("(") else op1
op2 = f"({op2})" if " " in op2 and not op2.startswith("(") else op2
scl_core = f"{target_scl} := {op1} + {op2};"
scl_final = (
f"IF {en_scl} THEN\n {scl_core}\nEND_IF;" if en_scl != "TRUE" else scl_core
)
instruction["scl"] = scl_final
instruction["type"] = instr_type + SCL_SUFFIX
map_key_out = (network_id, instr_uid, "out")
scl_map[map_key_out] = target_scl
map_key_eno = (network_id, instr_uid, "eno")
scl_map[map_key_eno] = en_scl
return True
def process_move(instruction, network_id, scl_map, access_map):
instr_uid = instruction["instruction_uid"]
instr_type = instruction["type"]
if instr_type.endswith(SCL_SUFFIX) or "_error" in instr_type:
return False
en_input = instruction["inputs"].get("en")
en_scl = (
get_scl_representation(en_input, network_id, scl_map, access_map)
if en_input
else "TRUE"
)
in_info = instruction["inputs"].get("in")
in_scl = get_scl_representation(in_info, network_id, scl_map, access_map)
if en_scl is None or in_scl is None:
return False
# Intentar obtener el destino de 'out1' (o 'out' si es el estándar)
target_scl = get_target_scl_name(
instruction, "out1", network_id, default_to_temp=False
)
if target_scl is None:
target_scl = get_target_scl_name(
instruction, "out", network_id, default_to_temp=False
)
if target_scl is None:
# Si no hay destino explícito, podríamos usar una temp si la lógica lo requiere,
# pero MOVE generalmente necesita un destino claro. Marcar como advertencia/error.
print(
f"Advertencia/Error: MOVE {instr_uid} sin destino claro en 'out' o 'out1'. Se requiere destino explícito."
)
# Decidir si generar error o simplemente no hacer nada. No hacer nada es más seguro.
# instruction["scl"] = f"// ERROR: MOVE {instr_uid} sin destino"
# instruction["type"] += "_error"
# return True
return False # No procesar si no hay destino claro
# Formatear entrada si es variable
in_scl_formatted = (
format_variable_name(in_scl)
if in_info and in_info.get("type") == "variable"
else in_scl
)
scl_core = f"{target_scl} := {in_scl_formatted};"
scl_final = (
f"IF {en_scl} THEN\n {scl_core}\nEND_IF;" if en_scl != "TRUE" else scl_core
)
instruction["scl"] = scl_final
instruction["type"] = instr_type + SCL_SUFFIX
# Propagar el valor movido a través de scl_map si se usa 'out' o 'out1' como fuente
map_key_out = (network_id, instr_uid, "out") # Asumir 'out' como estándar
scl_map[map_key_out] = target_scl # El valor es lo que está en el destino
map_key_out1 = (network_id, instr_uid, "out1") # Si existe out1
scl_map[map_key_out1] = target_scl
map_key_eno = (network_id, instr_uid, "eno")
scl_map[map_key_eno] = en_scl
return True
def process_pbox(instruction, network_id, scl_map, access_map, network_logic_list):
instr_uid = instruction["instruction_uid"]
instr_type = instruction["type"]
if instr_type.endswith(SCL_SUFFIX) or "_error" in instr_type:
return False
mem_bit_input = instruction["inputs"].get("bit")
mem_bit_scl = get_scl_representation(mem_bit_input, network_id, scl_map, access_map)
if mem_bit_scl is None:
return False # Dependencia no lista
# Validar y formatear el bit de memoria
if not (mem_bit_input and mem_bit_input.get("type") == "variable"):
print(f"Error: PBOX {instr_uid} 'bit' no es variable o falta información.")
instruction["scl"] = (
f"// ERROR: PBox {instr_uid} 'bit' no es variable o falta info"
)
instruction["type"] += "_error"
return True # Procesado con error
mem_bit_scl_formatted = format_variable_name(mem_bit_scl)
# --- Lógica para inferir CLK (similar a la versión anterior) ---
# Determinar si es P_TRIG (conectado a una bobina)
is_likely_p_trig = False
consuming_coil_uid = None
for potential_consumer in network_logic_list:
coil_input_signal = potential_consumer.get("inputs", {}).get("in")
if (
isinstance(coil_input_signal, dict)
and coil_input_signal.get("type") == "connection"
and coil_input_signal.get("source_instruction_uid") == instr_uid
and coil_input_signal.get("source_pin")
== "out" # PBox output alimenta la bobina
):
consumer_type_original = (
potential_consumer.get("type", "")
.replace("_scl", "")
.replace("_error", "")
)
if consumer_type_original == "Coil":
is_likely_p_trig = True
consuming_coil_uid = potential_consumer.get("instruction_uid")
break # Encontrado consumidor de bobina
rlo_scl = None # Este será el CLK inferido
if is_likely_p_trig:
# Buscar hacia atrás la fuente del RLO que alimenta este PBox
clk_source_found = False
current_instr_index = -1
for i, instr in enumerate(network_logic_list):
if instr["instruction_uid"] == instr_uid:
current_instr_index = i
break
if current_instr_index != -1:
# Buscar la entrada 'in' del PBox si existe explícitamente
pbox_in_signal = instruction.get("inputs", {}).get("in")
if pbox_in_signal:
rlo_scl = get_scl_representation(
pbox_in_signal, network_id, scl_map, access_map
)
if rlo_scl is not None:
clk_source_found = True
# print(f"DEBUG: PBox {instr_uid} CLK encontrado por pin 'in': {rlo_scl}")
# Si no hay pin 'in' explícito, buscar hacia atrás (lógica LAD clásica)
if not clk_source_found:
# print(f"DEBUG: PBox {instr_uid} buscando CLK hacia atrás...")
for i in range(current_instr_index - 1, -1, -1):
prev_instr = network_logic_list[i]
prev_instr_uid = prev_instr["instruction_uid"]
prev_instr_type_original = (
prev_instr.get("type", "")
.replace(SCL_SUFFIX, "")
.replace("_error", "")
)
# ¿Es una instrucción que genera RLO booleano?
if prev_instr_type_original in [
"Contact",
"Eq",
"O",
"PBox",
"And",
"Xor",
"Ne",
"Gt",
"Lt",
"Ge",
"Le",
]:
map_key_prev_out = (network_id, prev_instr_uid, "out")
potential_clk_scl = scl_map.get(map_key_prev_out)
if potential_clk_scl is not None:
rlo_scl = potential_clk_scl
clk_source_found = True
# print(f"DEBUG: PBox {instr_uid} CLK encontrado de {prev_instr_type_original} {prev_instr_uid} (out): {rlo_scl}")
break
# ¿Es un bloque funcional cuya salida ENO podría ser el RLO?
elif prev_instr_type_original in [
"Move",
"Add",
"Convert",
"Mod",
"Call",
]: # Añadir otros bloques funcionales
map_key_prev_eno = (network_id, prev_instr_uid, "eno")
potential_clk_scl = scl_map.get(map_key_prev_eno)
if potential_clk_scl is not None:
rlo_scl = potential_clk_scl
clk_source_found = True
# print(f"DEBUG: PBox {instr_uid} CLK encontrado de {prev_instr_type_original} {prev_instr_uid} (eno): {rlo_scl}")
break
# Si encontramos una bobina, el RLO se detiene ahí
elif prev_instr_type_original == "Coil":
# print(f"DEBUG: PBox {instr_uid} búsqueda CLK detenida por Coil {prev_instr_uid}")
break
if not clk_source_found:
print(f"Error: No se pudo inferir CLK para P_TRIG PBOX {instr_uid}")
instruction["scl"] = f"// ERROR: PBox {instr_uid} (P_TRIG) sin CLK inferido"
instruction["type"] += "_error"
return True # Procesado con error
if rlo_scl is None:
# print(f"DEBUG: PBox {instr_uid} CLK encontrado pero valor es None, esperando...")
return False # Dependencia (CLK) no resuelta aún
# --- Generar SCL ---
scl_comment = ""
result_scl = "" # El valor que PBox pone en scl_map['out']
if is_likely_p_trig:
# Formatear CLK si es variable (poco probable, suele ser resultado lógico)
# clk_signal_formatted = format_variable_name(rlo_scl) if ... else rlo_scl
clk_signal_formatted = (
rlo_scl # Asumir que ya está bien formateado o es una expresión
)
# Añadir paréntesis si CLK es complejo
if (
" " in clk_signal_formatted
or "AND" in clk_signal_formatted
or "OR" in clk_signal_formatted
) and not (
clk_signal_formatted.startswith("(") and clk_signal_formatted.endswith(")")
):
clk_signal_formatted = f"({clk_signal_formatted})"
# Generar llamada a función de flanco (asumimos P_TRIG)
# Necesitamos un nombre para la instancia del flanco, usualmente una variable STAT
# Podríamos generarla automáticamente o requerirla en el XML.
# Generación automática:
stat_var_name = f"stat_{network_id}_{instr_uid}_ptrig"
stat_var_name_scl = format_variable_name(f'"{stat_var_name}"') # Poner comillas
# La generación SCL real depende de si usamos una función o lógica explícita.
# Usando función estándar (requiere declarar la instancia 'stat_var_name_scl' como P_TRIG en VAR_STAT):
# result_scl = f"{stat_var_name_scl}(CLK := {clk_signal_formatted})" # La función devuelve Q
# scl_comment = f"// P_TRIG {instr_uid}: {result_scl}"
# instruction["scl"] = f"{stat_var_name_scl}(CLK := {clk_signal_formatted}); // Generates edge pulse" # La llamada en sí
# result_scl = f"{stat_var_name_scl}.Q" # La salida es el pin Q de la instancia
# Usando lógica explícita (más portable si no se declaran instancias):
result_scl = f"{clk_signal_formatted} AND NOT {mem_bit_scl_formatted}"
scl_comment = f"// P_TRIG Logic {instr_uid}: {result_scl}"
# La actualización del bit de memoria se hace aparte
instruction["scl"] = (
f"{mem_bit_scl_formatted} := {clk_signal_formatted}; // Update edge memory bit"
)
else: # Si no es P_TRIG (ej. N_TRIG o simplemente pasando el bit)
# Aquí asumimos que es N_TRIG si tiene TemplateValue "Negated" o similar
is_negated_pbox = (
instruction.get("template_values", {}).get("Negated") == "true"
)
if is_negated_pbox:
# Lógica N_TRIG explícita
clk_signal_formatted = rlo_scl # Asumimos que CLK se infiere igual
if clk_signal_formatted is None:
return False # Esperar CLK
if (
" " in clk_signal_formatted
or "AND" in clk_signal_formatted
or "OR" in clk_signal_formatted
) and not (
clk_signal_formatted.startswith("(")
and clk_signal_formatted.endswith(")")
):
clk_signal_formatted = f"({clk_signal_formatted})"
result_scl = f"NOT {clk_signal_formatted} AND {mem_bit_scl_formatted}"
scl_comment = f"// N_TRIG Logic {instr_uid}: {result_scl}"
instruction["scl"] = (
f"{mem_bit_scl_formatted} := {clk_signal_formatted}; // Update edge memory bit"
)
else:
# Comportamiento por defecto: pasar el bit de memoria (raro para PBox)
print(
f"Advertencia: PBox {instr_uid} no parece ser P_TRIG ni N_TRIG. Pasando bit de memoria."
)
result_scl = mem_bit_scl_formatted
scl_comment = f"// PBox {instr_uid} - Passing memory bit: {result_scl}"
instruction["scl"] = f"// {scl_comment}" # Solo comentario
# Actualizar el mapa SCL con el resultado booleano del flanco/paso
map_key_out = (network_id, instr_uid, "out")
scl_map[map_key_out] = result_scl
# ENO sigue al CLK (si existe) o es TRUE por defecto? Asumimos que sigue al CLK si es P/N_TRIG
map_key_eno = (network_id, instr_uid, "eno")
scl_map[map_key_eno] = rlo_scl if rlo_scl is not None else "TRUE"
instruction["type"] = instr_type + SCL_SUFFIX
return True
def process_o(instruction, network_id, scl_map, access_map):
instr_uid = instruction["instruction_uid"]
instr_type = instruction["type"]
if instr_type.endswith(SCL_SUFFIX) or "_error" in instr_type:
return False
# Buscar todas las entradas 'in', 'in1', 'in2', ...
input_pins = sorted([pin for pin in instruction["inputs"] if pin.startswith("in")])
if not input_pins:
print(f"Error: O {instr_uid} sin pines de entrada (inX).")
instruction["scl"] = f"// ERROR: O {instr_uid} sin pines inX"
instruction["type"] += "_error"
return True # Procesado con error
scl_parts = []
all_resolved = True
for pin in input_pins:
in_scl = get_scl_representation(
instruction["inputs"][pin], network_id, scl_map, access_map
)
if in_scl is None:
all_resolved = False
# print(f"DEBUG: O {instr_uid} esperando pin {pin}")
break # Salir del bucle for si una entrada no está lista
# Formatear término (añadir paréntesis si es necesario)
term = in_scl
if (" " in term or "AND" in term) and not (
term.startswith("(") and term.endswith(")")
):
term = f"({term})"
scl_parts.append(term)
if not all_resolved:
return False # Esperar a que todas las entradas estén resueltas
# Construir la expresión OR
result_scl = "FALSE" # Valor por defecto si no hay entradas válidas (raro)
if scl_parts:
result_scl = " OR ".join(scl_parts)
# Simplificar si solo hay un término
if len(scl_parts) == 1:
result_scl = scl_parts[0]
# Quitar paréntesis redundantes si solo hay un término y está entre paréntesis
if result_scl.startswith("(") and result_scl.endswith(")"):
# Comprobar si los paréntesis son necesarios (contienen operadores de menor precedencia)
# Simplificación: quitar siempre si solo hay un término. Podría ser incorrecto en casos complejos.
# result_scl = result_scl[1:-1] # Comentado por seguridad
pass
# Actualizar mapa SCL y la instrucción
map_key_out = (network_id, instr_uid, "out")
scl_map[map_key_out] = result_scl
instruction["scl"] = (
f"// Logic O {instr_uid}: {result_scl}" # Comentario informativo
)
instruction["type"] = instr_type + SCL_SUFFIX
# La instrucción 'O' no tiene ENO propio, propaga el resultado por 'out'
return True
def process_call(instruction, network_id, scl_map, access_map):
instr_uid = instruction["instruction_uid"]
instr_type = instruction.get("type", "") # Usar get con default
if instr_type.endswith(SCL_SUFFIX) or "_error" in instr_type:
return False
block_name = instruction.get("block_name", f"UnknownCall_{instr_uid}")
block_type = instruction.get("block_type") # FC, FB
instance_db = instruction.get("instance_db") # Nombre del DB de instancia (para FB)
# Formatear nombres
block_name_scl = format_variable_name(block_name)
instance_db_scl = format_variable_name(instance_db) if instance_db else None
# --- Manejo de EN ---
en_input = instruction["inputs"].get("en")
en_scl = (
get_scl_representation(en_input, network_id, scl_map, access_map)
if en_input
else "TRUE"
)
if en_scl is None:
return False # Dependencia EN no resuelta
# --- Procesar Parámetros de Entrada/Salida ---
# Necesitamos iterar sobre los pines definidos en la interfaz del bloque llamado.
# Esta información no está directamente en la instrucción 'Call' del JSON simplificado.
# ¡Limitación! Sin la interfaz del bloque llamado, solo podemos manejar EN/ENO
# y asumir una llamada sin parámetros o con parámetros conectados implícitamente.
# Solución temporal: Buscar conexiones en 'inputs' y 'outputs' que NO sean 'en'/'eno'
# y construir la llamada basándose en eso. Esto es muy heurístico.
scl_call_params = []
processed_inputs = {"en"} # Marcar 'en' como ya procesado
for pin_name, source_info in instruction.get("inputs", {}).items():
if pin_name not in processed_inputs:
param_scl = get_scl_representation(
source_info, network_id, scl_map, access_map
)
if param_scl is None:
# print(f"DEBUG: Call {instr_uid} esperando parámetro de entrada {pin_name}")
return False # Dependencia de parámetro no resuelta
# Formatear si es variable
param_scl_formatted = (
format_variable_name(param_scl)
if source_info.get("type") == "variable"
else param_scl
)
scl_call_params.append(
f"{format_variable_name(pin_name)} := {param_scl_formatted}"
)
processed_inputs.add(pin_name)
# Procesar parámetros de salida (asignaciones después de la llamada o pasados como VAR_IN_OUT/VAR_OUTPUT)
# Esto es aún más complejo. SCL normalmente asigna salidas después o usa punteros/referencias.
# Simplificación: Asumir que las salidas se manejan por asignación posterior si es necesario,
# o que son VAR_OUTPUT y se acceden como instancia.salida.
# Por ahora, no generamos asignaciones explícitas para las salidas aquí.
# --- Construcción de la Llamada SCL ---
scl_call_body = ""
param_string = ", ".join(scl_call_params)
if block_type == "FB":
if not instance_db_scl:
print(
f"Error: Llamada a FB '{block_name_scl}' (UID {instr_uid}) sin DB de instancia especificado."
)
instruction["scl"] = f"// ERROR: FB Call {block_name_scl} sin instancia"
instruction["type"] = "Call_FB_error"
return True # Procesado con error
# Llamada a FB con DB de instancia
scl_call_body = f"{instance_db_scl}({param_string});"
elif block_type == "FC":
# Llamada a FC
scl_call_body = f"{block_name_scl}({param_string});"
else:
print(
f"Advertencia: Tipo de bloque no soportado para Call UID {instr_uid}: {block_type}"
)
scl_call_body = f"// ERROR: Call a bloque tipo '{block_type}' no soportado: {block_name_scl}"
instruction["type"] = f"Call_{block_type}_error" # Marcar como error parcial
# --- Aplicar Condición EN ---
scl_final = ""
if en_scl != "TRUE":
# Indentar la llamada dentro del IF
indented_call = "\n".join([f" {line}" for line in scl_call_body.splitlines()])
scl_final = f"IF {en_scl} THEN\n{indented_call}\nEND_IF;"
else:
scl_final = scl_call_body
# --- Actualizar JSON y Mapa SCL ---
instruction["scl"] = scl_final
instruction["type"] = (
f"Call_{block_type}_scl"
if "_error" not in instruction["type"]
else instruction["type"]
)
# Actualizar scl_map con el estado ENO (igual a EN para llamadas simples sin manejo explícito de ENO)
map_key_eno = (network_id, instr_uid, "eno")
scl_map[map_key_eno] = en_scl
# Propagar valores de salida (si pudiéramos determinarlos)
# Ejemplo: Si supiéramos que hay una salida 'Out1' de tipo INT
# map_key_out1 = (network_id, instr_uid, "Out1")
# if block_type == "FB" and instance_db_scl:
# scl_map[map_key_out1] = f"{instance_db_scl}.Out1" # Acceso a salida de instancia
# else:
# # Para FCs, necesitaríamos una variable temporal o asignación explícita
# temp_out1 = generate_temp_var_name(network_id, instr_uid, "Out1")
# # Modificar scl_call_body para incluir la asignación: Out1 => temp_out1
# scl_map[map_key_out1] = temp_out1
return True
# --- NUEVO: Procesador de Agrupación (Refinado) ---
def process_group_ifs(instruction, network_id, scl_map, access_map):
"""
Busca instrucciones que generan condiciones (Contact, O, Eq, PBox, etc.) ya procesadas
y, si habilitan un grupo (>1) de bloques funcionales (Move, Add, Call, etc.),
construye el bloque IF agrupado.
Modifica el campo 'scl' de la instrucción generadora de condición.
"""
instr_uid = instruction["instruction_uid"]
instr_type = instruction["type"]
instr_type_original = instr_type.replace("_scl", "").replace("_error", "")
made_change = False
# Solo actuar sobre generadores de condición ya procesados (_scl)
# y que no sean ellos mismos errores o ya agrupados por otro IF
if (
not instr_type.endswith("_scl")
or "_error" in instr_type
or instruction.get("grouped", False)
or instr_type_original
not in [
"Contact",
"O",
"Eq",
"Ne",
"Gt",
"Lt",
"Ge",
"Le",
"PBox",
"And",
"Xor",
]
): # Añadir más si es necesario
return False
# Evitar reagrupar si ya se hizo (comprobando si SCL ya es un IF complejo)
current_scl = instruction.get("scl", "")
if current_scl.strip().startswith("IF") and "END_IF;" in current_scl:
# print(f"DEBUG Group: {instr_uid} ya tiene IF complejo, saltando agrupación.")
return False
# Ignorar comentarios simples que empiezan por IF
if current_scl.strip().startswith("//") and "IF" in current_scl:
return False
# Obtener la condición generada por esta instrucción (debería estar en scl_map['out'])
map_key_out = (network_id, instr_uid, "out")
condition_scl = scl_map.get(map_key_out)
# No agrupar para condiciones triviales, no encontradas o ya agrupadas
if condition_scl is None or condition_scl in ["TRUE", "FALSE"]:
return False
# Encontrar todos los bloques funcionales habilitados DIRECTAMENTE por esta condición
grouped_instructions_cores = [] # Lista de SCL 'core' de los consumidores
consumer_instr_list = [] # Lista de instrucciones consumidoras
network_logic = next(
(net["logic"] for net in data["networks"] if net["id"] == network_id), []
)
if not network_logic:
return False
# Identificar los tipos de instrucciones que queremos agrupar (bloques funcionales)
groupable_types = [
"Move",
"Add",
"Sub",
"Mul",
"Div",
"Mod",
"Convert",
"Call_FC",
"Call_FB",
] # Añadir más si es necesario
for consumer_instr in network_logic:
consumer_uid = consumer_instr["instruction_uid"]
# Saltar si ya está agrupado por otra condición o es él mismo
if consumer_instr.get("grouped", False) or consumer_uid == instr_uid:
continue
consumer_en = consumer_instr.get("inputs", {}).get("en")
consumer_type = consumer_instr.get("type", "") # Tipo actual (_scl o no)
consumer_type_original = consumer_type.replace("_scl", "").replace("_error", "")
# ¿Está la entrada 'en' del consumidor conectada a nuestra salida 'out'?
is_enabled_by_us = False
if (
isinstance(consumer_en, dict)
and consumer_en.get("type") == "connection"
and consumer_en.get("source_instruction_uid") == instr_uid
and consumer_en.get("source_pin")
== "out" # Condición viene de 'out' del generador
):
is_enabled_by_us = True
# ¿Es un tipo de instrucción agrupable y ya procesado (tiene SCL)?
if (
is_enabled_by_us
and consumer_type.endswith("_scl")
and consumer_type_original in groupable_types
):
consumer_scl = consumer_instr.get("scl", "")
# Extraer el SCL core (la parte DENTRO del IF o la línea única si no había IF)
core_scl = None
if consumer_scl.strip().startswith("IF"):
# Extraer todo entre THEN y END_IF;
match = re.search(
r"IF\s+.*\s+THEN\s*(.*?)\s*END_IF;",
consumer_scl,
re.DOTALL | re.IGNORECASE,
)
if match:
core_scl = match.group(1).strip()
elif consumer_scl and not consumer_scl.strip().startswith("//"):
# Si no es IF y no es solo comentario, es el core
core_scl = consumer_scl.strip()
if core_scl:
grouped_instructions_cores.append(core_scl)
consumer_instr_list.append(consumer_instr) # Guardar referencia
# else: # Debug
# print(f"DEBUG Group: Consumidor {consumer_uid} ({consumer_type}) habilitado por {instr_uid} no tenía SCL core extraíble. SCL: '{consumer_scl}'")
# Si encontramos más de un consumidor agrupable
if len(grouped_instructions_cores) > 1:
print(
f"INFO: Agrupando {len(grouped_instructions_cores)} instrucciones bajo condición de {instr_type_original} UID {instr_uid} (Cond: {condition_scl})"
)
# Construir el bloque IF agrupado
scl_grouped = [f"IF {condition_scl} THEN"]
for core_line in grouped_instructions_cores:
# Añadir indentación adecuada (2 espacios)
indented_core = "\n".join(
[f" {line.strip()}" for line in core_line.splitlines()]
)
scl_grouped.append(indented_core)
scl_grouped.append("END_IF;")
final_grouped_scl = "\n".join(scl_grouped)
# Sobrescribir 'scl' de la instrucción generadora de condición
instruction["scl"] = final_grouped_scl
# Marcar los consumidores como agrupados y limpiar su SCL original
for consumer_instr in consumer_instr_list:
consumer_instr["scl"] = f"{GROUPED_COMMENT} (by UID {instr_uid})"
consumer_instr["grouped"] = True # Marcar como agrupado
made_change = True
# else: # Debug
# if len(grouped_instructions_cores) == 1:
# print(f"DEBUG Group: Solo 1 consumidor ({consumer_instr_list[0]['instruction_uid']}) para {instr_uid}. No se agrupa.")
# elif len(grouped_instructions_cores) == 0 and condition_scl not in ['TRUE', 'FALSE']:
# # Solo mostrar si la condición no era trivial
# pass # print(f"DEBUG Group: Ningún consumidor agrupable encontrado para {instr_uid} (Cond: {condition_scl}).")
return made_change
# --- Bucle Principal de Procesamiento ---
def process_json_to_scl(json_filepath):
"""Lee el JSON, aplica los procesadores iterativamente y guarda el resultado."""
if not os.path.exists(json_filepath):
print(f"Error: JSON no encontrado: {json_filepath}")
return
print(f"Cargando JSON desde: {json_filepath}")
try:
with open(json_filepath, "r", encoding="utf-8") as f:
global data # Modificar la variable global
data = json.load(f)
except Exception as e:
print(f"Error al cargar JSON: {e}")
traceback.print_exc()
return
# Crear mapas de acceso por red (para resolver UIDs de variables/constantes rápidamente)
network_access_maps = {}
# print("Creando mapas de acceso por red...") # Comentado para brevedad
for network in data.get("networks", []):
net_id = network["id"]
current_access_map = {}
# Extraer todos los 'Access' (variables/constantes) usados en esta red
# Esta información ya está dentro de inputs/outputs en el JSON simplificado
for instr in network.get("logic", []):
# Revisar Inputs
for _, source in instr.get("inputs", {}).items():
sources_to_check = (
source
if isinstance(source, list)
else ([source] if isinstance(source, dict) else [])
)
for src in sources_to_check:
if (
isinstance(src, dict)
and src.get("uid")
and src.get("type") in ["variable", "constant"]
):
current_access_map[src["uid"]] = (
src # Guardar info del Access por UID
)
# Revisar Outputs
for _, dest_list in instr.get("outputs", {}).items():
if isinstance(dest_list, list):
for dest in dest_list:
if (
isinstance(dest, dict)
and dest.get("uid")
and dest.get("type") in ["variable", "constant"]
):
current_access_map[dest["uid"]] = (
dest # Guardar info del Access por UID
)
network_access_maps[net_id] = current_access_map
# Mapa global para almacenar el SCL generado para cada salida de instrucción (pin)
# Clave: (network_id, instruction_uid, pin_name) -> Valor: SCL string
scl_map = {}
# --- Bucle Iterativo ---
max_passes = 30 # Aumentar por si hay dependencias largas o agrupaciones complejas
passes = 0
processing_complete = False
# Lista y mapa de procesadores base
base_processors = [
process_convert,
process_mod,
process_eq,
process_contact,
process_o,
process_pbox,
process_add,
process_move,
process_call,
process_coil,
# Añadir aquí nuevos procesadores base para otros tipos de instrucciones
]
# Crear mapa por nombre de tipo original (en minúsculas)
processor_map = {}
for func in base_processors:
# Extraer tipo del nombre de la función (p.ej., 'process_contact' -> 'contact')
match = re.match(r"process_(\w+)", func.__name__)
if match:
type_name = match.group(1).lower()
# Manejar casos especiales como 'call' que puede ser FC o FB
if type_name == "call":
processor_map["call_fc"] = func
processor_map["call_fb"] = func
processor_map["call"] = func # Genérico por si acaso
else:
processor_map[type_name] = func
print("\n--- Iniciando Bucle de Procesamiento Iterativo ---")
while passes < max_passes and not processing_complete:
passes += 1
made_change_in_base_pass = False
made_change_in_group_pass = False
print(f"\n--- Pase {passes} ---")
num_processed_this_pass = 0
num_grouped_this_pass = 0
# --- FASE 1: Procesadores Base ---
for network in data.get("networks", []):
network_id = network["id"]
access_map = network_access_maps.get(network_id, {})
network_logic = network.get(
"logic", []
) # Obtener referencia a la lista de lógica
# Crear una copia de la lista de instrucciones para iterar,
# ya que modificaremos la original (al añadir _scl al tipo)
# logic_to_process = list(network_logic) # No necesario si solo modificamos in-place
for instruction in network_logic: # Iterar sobre la lista original
instr_uid = instruction.get("instruction_uid")
instr_type_original = instruction.get("type", "Unknown")
# Saltar si ya procesado, es un error, o está agrupado
if (
instr_type_original.endswith(SCL_SUFFIX)
or "_error" in instr_type_original
or instruction.get("grouped", False)
):
continue
# Buscar el procesador adecuado
# Para 'Call', necesitamos distinguir FC/FB si es posible
lookup_key = instr_type_original.lower()
if instr_type_original == "Call":
block_type = instruction.get("block_type", "").upper()
if block_type == "FC":
lookup_key = "call_fc"
elif block_type == "FB":
lookup_key = "call_fb"
# else: se usará 'call' genérico si existe
func_to_call = processor_map.get(lookup_key)
if func_to_call:
try:
changed = False
# Pasar la lista de lógica completa solo si es necesario (PBox)
if func_to_call == process_pbox:
changed = func_to_call(
instruction,
network_id,
scl_map,
access_map,
network_logic,
)
else:
changed = func_to_call(
instruction, network_id, scl_map, access_map
)
if changed:
made_change_in_base_pass = True
num_processed_this_pass += 1
# print(f"DEBUG: Procesado {instr_type_original} UID {instr_uid}") # Debug detallado
except Exception as e:
print(
f"ERROR(Base) al procesar {instr_type_original} UID {instr_uid} con {func_to_call.__name__}: {e}"
)
traceback.print_exc()
# Marcar como error para no reintentar
instruction["scl"] = f"// ERROR en procesador base: {e}"
instruction["type"] = instr_type_original + "_error"
made_change_in_base_pass = True # Considerar error como cambio para evitar bucles infinitos
# else: # Debug para tipos no encontrados
# if lookup_key not in ['unknown', 'unknown_structure', 'error_parsing_symbol', 'error_parsing_constant', 'error_no_name']:
# print(f"DEBUG: No se encontró procesador base para el tipo '{instr_type_original}' (lookup: '{lookup_key}') UID {instr_uid}")
# pass
# --- FASE 2: Procesador de Agrupación ---
# Ejecutar solo si hubo cambios en la fase base (o en el primer pase) para optimizar
if made_change_in_base_pass or passes == 1:
# print(f"DEBUG: Iniciando Fase 2 (Agrupación IF) - Pase {passes}") # Debug
for network in data.get("networks", []):
network_id = network["id"]
access_map = network_access_maps.get(network_id, {})
network_logic = network.get("logic", [])
# Iterar sobre generadores de condición ya procesados
for instruction in network_logic:
# Solo intentar agrupar si es un generador de condición procesado y no agrupado
if instruction["type"].endswith("_scl") and not instruction.get(
"grouped", False
):
try:
group_changed = process_group_ifs(
instruction, network_id, scl_map, access_map
)
if group_changed:
made_change_in_group_pass = True
num_grouped_this_pass += 1
except Exception as e:
print(
f"ERROR(Group) al intentar agrupar desde UID {instruction.get('instruction_uid')}: {e}"
)
traceback.print_exc()
# No marcar la instrucción generadora como error, solo falló la agrupación
# --- Comprobar si se completó el procesamiento ---
if not made_change_in_base_pass and not made_change_in_group_pass:
print(
f"\n--- No se hicieron más cambios en el pase {passes}. Proceso iterativo completado. ---"
)
processing_complete = True
else:
print(
f"--- Fin Pase {passes}: {num_processed_this_pass} procesados, {num_grouped_this_pass} agrupados. Continuando..."
)
if passes == max_passes and not processing_complete:
print(
f"\n--- ADVERTENCIA: Límite de {max_passes} pases alcanzado. Puede haber dependencias no resueltas. ---"
)
# --- FIN BUCLE ITERATIVO ---
# --- NUEVO: Verificación de Instrucciones No Procesadas ---
print("\n--- Verificación Final de Instrucciones No Procesadas ---")
unprocessed_count = 0
unprocessed_details = [] # Lista para guardar detalles
for network in data.get("networks", []):
network_id = network.get("id", "Unknown ID")
network_title = network.get("title", f"Network {network_id}")
for instruction in network.get("logic", []):
instr_uid = instruction.get("instruction_uid", "Unknown UID")
instr_type = instruction.get("type", "Unknown Type")
is_grouped = instruction.get("grouped", False)
# Comprobar si NO está procesada (sin _scl), NO es error, y NO está agrupada
if (
not instr_type.endswith(SCL_SUFFIX)
and "_error" not in instr_type
and not is_grouped
):
unprocessed_count += 1
# Añadir detalle formateado a la lista
unprocessed_details.append(
f" - Red '{network_title}' (ID: {network_id}), "
f"Instrucción UID: {instr_uid}, Tipo Original: '{instr_type}'"
)
# Imprimir el resumen de no procesadas
if unprocessed_count > 0:
print(
f"ADVERTENCIA: Se encontraron {unprocessed_count} instrucciones que no pudieron ser procesadas a SCL:"
)
# Imprimir cada detalle de la lista
for detail in unprocessed_details:
print(detail)
print(
">>> Estos tipos de instrucción podrían necesitar un procesador específico en 'x2_process.py'."
)
else:
print(
"INFO: Todas las instrucciones fueron procesadas a SCL, marcadas como error o agrupadas exitosamente."
)
# --- FIN Verificación ---
# --- Guardar JSON Final ---
output_filename = json_filepath.replace(
"_simplified.json", "_simplified_processed.json"
)
print(f"\nGuardando JSON procesado en: {output_filename}")
try:
with open(output_filename, "w", encoding="utf-8") as f:
json.dump(data, f, indent=4, ensure_ascii=False)
print("Guardado completado.")
except Exception as e:
print(f"Error Crítico al guardar JSON procesado: {e}")
traceback.print_exc()
# --- Ejecución ---
if __name__ == "__main__":
# Asegúrate de que el nombre base del archivo XML sea correcto
xml_filename_base = "TestLAD" # Cambia esto si tu XML se llama diferente
input_json_file = f"{xml_filename_base}_simplified.json"
if not os.path.exists(input_json_file):
print(
f"Error Fatal: El archivo de entrada JSON simplificado no existe: '{input_json_file}'"
)
print(
"Asegúrate de haber ejecutado 'x1_to_json.py' primero sobre el archivo XML correcto."
)
else:
process_json_to_scl(input_json_file)