1387 lines
58 KiB
Python
1387 lines
58 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
|
|
|
|
# --- process_edge_detector MODIFICADA ---
|
|
def process_edge_detector(instruction, network_id, scl_map, access_map):
|
|
"""Genera SCL para PBox (P_TRIG) o NBox (N_TRIG).
|
|
Guarda la expresión del pulso en scl_map['out'] y la actualización
|
|
de memoria en un campo temporal '_edge_mem_update_scl'.
|
|
El campo 'scl' principal se deja casi vacío.
|
|
"""
|
|
instr_uid = instruction["instruction_uid"]
|
|
instr_type_original = instruction["type"] # PBox o NBox
|
|
|
|
if instr_type_original.endswith(SCL_SUFFIX) or "_error" in instr_type_original:
|
|
return False
|
|
|
|
# 1. Obtener CLK y MemBit original
|
|
clk_input = instruction["inputs"].get("in")
|
|
mem_bit_input = instruction["inputs"].get("bit")
|
|
clk_scl = get_scl_representation(clk_input, network_id, scl_map, access_map)
|
|
mem_bit_scl_original = get_scl_representation(mem_bit_input, network_id, scl_map, access_map)
|
|
|
|
# 2. Verificar dependencias y tipo de MemBit
|
|
if clk_scl is None or mem_bit_scl_original is None: return False
|
|
if not (mem_bit_input and mem_bit_input.get("type") == "variable"):
|
|
instruction["scl"] = f"// ERROR: {instr_type_original} {instr_uid} 'bit' no es variable."
|
|
instruction["type"] = instr_type_original + "_error"
|
|
return True
|
|
|
|
# 3. Formatear CLK
|
|
clk_scl_formatted = clk_scl
|
|
if clk_scl not in ["TRUE", "FALSE"] and \
|
|
(' ' in clk_scl or 'AND' in clk_scl or 'OR' in clk_scl or ':=' in clk_scl) and \
|
|
not (clk_scl.startswith('(') and clk_scl.endswith(')')):
|
|
clk_scl_formatted = f"({clk_scl})"
|
|
|
|
# 4. Generar Lógica SCL del *pulso*
|
|
result_pulse_expression = "FALSE"
|
|
scl_comment = ""
|
|
if instr_type_original == "PBox": # P_TRIG
|
|
result_pulse_expression = f"{clk_scl_formatted} AND NOT {mem_bit_scl_original}"
|
|
scl_comment = f"// P_TRIG({clk_scl_formatted})"
|
|
elif instr_type_original == "NBox": # N_TRIG
|
|
result_pulse_expression = f"NOT {clk_scl_formatted} AND {mem_bit_scl_original}"
|
|
scl_comment = f"// N_TRIG({clk_scl_formatted})"
|
|
else: # Error
|
|
instruction["scl"] = f"// ERROR: Tipo de flanco inesperado {instr_type_original}"
|
|
instruction["type"] = instr_type_original + "_error"
|
|
return True
|
|
|
|
# 5. Generar la actualización del bit de memoria
|
|
scl_mem_update = f"{mem_bit_scl_original} := {clk_scl_formatted};"
|
|
|
|
# 6. Almacenar Resultados
|
|
map_key_out = (network_id, instr_uid, "out")
|
|
scl_map[map_key_out] = result_pulse_expression # Guardar EXPRESIÓN del pulso
|
|
|
|
instruction['_edge_mem_update_scl'] = scl_mem_update # Guardar UPDATE en campo temporal
|
|
instruction['scl'] = f"{scl_comment} (Mem update handled by consumer)" # Dejar SCL principal vacío/comentario
|
|
instruction["type"] = instr_type_original + SCL_SUFFIX
|
|
|
|
# 7. Propagar ENO
|
|
map_key_eno = (network_id, instr_uid, "eno")
|
|
scl_map[map_key_eno] = clk_scl
|
|
|
|
return True
|
|
|
|
# --- process_coil MODIFICADA ---
|
|
def process_coil(instruction, network_id, scl_map, access_map):
|
|
"""Genera la asignación para Coil. Si la entrada viene de PBox/NBox,
|
|
añade la actualización de memoria del flanco DESPUÉS de la asignación."""
|
|
instr_uid = instruction["instruction_uid"]
|
|
instr_type = instruction["type"]
|
|
if instr_type.endswith(SCL_SUFFIX) or "_error" in instr_type:
|
|
return False
|
|
|
|
coil_input_info = instruction["inputs"].get("in")
|
|
operand_info = instruction["inputs"].get("operand")
|
|
|
|
in_rlo_scl = get_scl_representation(coil_input_info, network_id, scl_map, access_map)
|
|
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
|
|
|
|
if not (operand_info and operand_info.get("type") == "variable"):
|
|
instruction["scl"] = f"// ERROR: Coil {instr_uid} operando no es variable o falta info"
|
|
instruction["type"] = instr_type + "_error"
|
|
return True
|
|
|
|
operand_scl_formatted = format_variable_name(operand_scl)
|
|
if in_rlo_scl == "(TRUE)": in_rlo_scl = "TRUE"
|
|
elif in_rlo_scl == "(FALSE)": in_rlo_scl = "FALSE"
|
|
|
|
# Generar la asignación SCL principal
|
|
scl_assignment = f"{operand_scl_formatted} := {in_rlo_scl};"
|
|
scl_final = scl_assignment # Inicializar SCL final
|
|
|
|
# --- Lógica para añadir actualización de memoria de flancos ---
|
|
mem_update_scl = None
|
|
if isinstance(coil_input_info, dict) and coil_input_info.get("type") == "connection":
|
|
source_uid = coil_input_info.get("source_instruction_uid")
|
|
source_pin = coil_input_info.get("source_pin")
|
|
# Buscar la instrucción fuente en la lógica de la red actual
|
|
source_instruction = None
|
|
network_logic = next((net["logic"] for net in data["networks"] if net["id"] == network_id), [])
|
|
for instr in network_logic:
|
|
if instr.get("instruction_uid") == source_uid:
|
|
source_instruction = instr
|
|
break
|
|
|
|
if source_instruction:
|
|
source_type = source_instruction.get("type","").replace('_scl','').replace('_error','')
|
|
# Si la fuente es PBox o NBox y tiene el campo temporal con la actualización
|
|
if source_type in ["PBox", "NBox"] and '_edge_mem_update_scl' in source_instruction:
|
|
mem_update_scl = source_instruction['_edge_mem_update_scl']
|
|
# Añadir la actualización DESPUÉS de la asignación de la bobina
|
|
scl_final = f"{scl_assignment}\\n{mem_update_scl} {source_instruction.get('scl', '')}" # Añadir también comentario original del PBox/NBox
|
|
# Marcar la instrucción PBox/NBox para que x3 no escriba su SCL (que ahora está vacío/comentario)
|
|
source_instruction['scl'] = f"// Logic moved to Coil {instr_uid}"
|
|
|
|
instruction["scl"] = scl_final
|
|
instruction["type"] = instr_type + SCL_SUFFIX
|
|
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
|
|
|
|
|
|
# --- FUNCIÓN UNIFICADA CORREGIDA para PBox y NBox ---
|
|
|
|
"""Genera SCL para PBox (P_TRIG) o NBox (N_TRIG)."""
|
|
instr_uid = instruction["instruction_uid"]
|
|
instr_type_original = instruction["type"] # PBox o NBox
|
|
# print(f"DEBUG Edge: Intentando procesar {instr_type_original} UID {instr_uid} en Red {network_id}") # Debug
|
|
|
|
if instr_type_original.endswith(SCL_SUFFIX) or "_error" in instr_type_original:
|
|
return False # Ya procesado o error
|
|
|
|
# 1. Obtener representaciones SCL de las entradas CLK y MemBit
|
|
clk_input = instruction["inputs"].get("in")
|
|
mem_bit_input = instruction["inputs"].get("bit")
|
|
|
|
clk_scl = get_scl_representation(clk_input, network_id, scl_map, access_map)
|
|
mem_bit_scl_original = get_scl_representation(mem_bit_input, network_id, scl_map, access_map)
|
|
|
|
# 2. Verificar si las dependencias están listas
|
|
if clk_scl is None:
|
|
# print(f"DEBUG Edge: CLK no resuelto para {instr_type_original} UID {instr_uid}. Esperando.")
|
|
return False # Dependencia CLK no lista
|
|
if mem_bit_scl_original is None:
|
|
# Esto es menos probable, pero por seguridad
|
|
print(f"Error: No se pudo resolver MemBit para {instr_type_original} UID {instr_uid}.")
|
|
instruction["scl"] = f"// ERROR: {instr_type_original} {instr_uid} MemBit no resuelto."
|
|
instruction["type"] = instr_type_original + "_error"
|
|
return True # Marcar como error
|
|
|
|
# 3. Validar que el bit de memoria sea una variable
|
|
if not (mem_bit_input and mem_bit_input.get("type") == "variable"):
|
|
print(f"Error: {instr_type_original} {instr_uid} 'bit' no es variable o falta información.")
|
|
instruction["scl"] = f"// ERROR: {instr_type_original} {instr_uid} 'bit' no es variable."
|
|
instruction["type"] = instr_type_original + "_error"
|
|
return True # Procesado con error
|
|
|
|
# 4. Renombrar bit de memoria para VAR_STAT y formatear CLK
|
|
mem_bit_name_clean = mem_bit_scl_original.strip('"')
|
|
stat_mem_bit_scl = f'"stat_{mem_bit_name_clean}"' if not mem_bit_name_clean.startswith("stat_") else mem_bit_scl_original
|
|
|
|
clk_scl_formatted = clk_scl
|
|
# Añadir paréntesis si es necesario (expresión compleja) - No a TRUE/FALSE
|
|
if clk_scl not in ["TRUE", "FALSE"] and \
|
|
(' ' in clk_scl or 'AND' in clk_scl or 'OR' in clk_scl or ':=' in clk_scl) and \
|
|
not (clk_scl.startswith('(') and clk_scl.endswith(')')):
|
|
clk_scl_formatted = f"({clk_scl})"
|
|
|
|
# 5. Generar Lógica SCL específica para PBox o NBox
|
|
result_pulse_scl = "FALSE" # SCL para la salida del flanco (pin 'out')
|
|
scl_comment = ""
|
|
|
|
if instr_type_original == "PBox": # Flanco Positivo (P_TRIG)
|
|
# Pulso = CLK actual Y NO Memoria anterior
|
|
result_pulse_scl = f"{clk_scl_formatted} AND NOT {stat_mem_bit_scl}"
|
|
scl_comment = f"// P_TRIG({clk_scl_formatted})"
|
|
elif instr_type_original == "NBox": # Flanco Negativo (N_TRIG)
|
|
# Pulso = NO CLK actual Y Memoria anterior
|
|
result_pulse_scl = f"NOT {clk_scl_formatted} AND {stat_mem_bit_scl}"
|
|
scl_comment = f"// N_TRIG({clk_scl_formatted})"
|
|
else:
|
|
print(f"Error interno: process_edge_detector llamado para tipo inesperado {instr_type_original}")
|
|
instruction["scl"] = f"// ERROR: Tipo de flanco inesperado {instr_type_original}"
|
|
instruction["type"] = instr_type_original + "_error"
|
|
return True
|
|
|
|
# 6. Generar la actualización del bit de memoria (siempre se actualiza con el estado actual de CLK)
|
|
scl_mem_update = f"{stat_mem_bit_scl} := {clk_scl_formatted};"
|
|
|
|
# 7. Almacenar Resultados
|
|
# - El *pulso* resultante se almacena en el mapa para la salida 'out'.
|
|
# - La *actualización de memoria* se almacena en el campo 'scl' de la instrucción.
|
|
map_key_out = (network_id, instr_uid, "out")
|
|
scl_map[map_key_out] = result_pulse_scl
|
|
# print(f"DEBUG Edge: {instr_type_original} UID {instr_uid} -> map['out'] = {result_pulse_scl}") # Debug
|
|
|
|
instruction["scl"] = f"{scl_mem_update} {scl_comment}" # Incluye la acción principal y un comentario
|
|
instruction["type"] = instr_type_original + SCL_SUFFIX
|
|
# print(f"DEBUG Edge: {instr_type_original} UID {instr_uid} -> instruction['scl'] = {instruction['scl']}") # Debug
|
|
|
|
# 8. Propagar ENO (generalmente sigue al CLK)
|
|
map_key_eno = (network_id, instr_uid, "eno")
|
|
scl_map[map_key_eno] = clk_scl # Usar el clk_scl original sin formato extra
|
|
|
|
# print(f"DEBUG Edge: {instr_type_original} UID {instr_uid} procesado exitosamente.") # Debug
|
|
return True # Indicar que se procesó
|
|
|
|
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_edge_detector, # Usar la nueva función unificada
|
|
process_add,
|
|
process_move,
|
|
process_call,
|
|
process_coil,
|
|
# ... otros procesadores base ...
|
|
]
|
|
# Crear mapa por nombre de tipo original (en minúsculas)
|
|
processor_map = {}
|
|
for func in base_processors:
|
|
match = re.match(r"process_(\w+)", func.__name__)
|
|
if match:
|
|
type_name = match.group(1).lower()
|
|
if type_name == "call":
|
|
processor_map["call_fc"] = func
|
|
processor_map["call_fb"] = func
|
|
processor_map["call"] = func
|
|
elif type_name == "edge_detector": # Mapear PBox y NBox a la nueva función
|
|
processor_map["pbox"] = func
|
|
processor_map["nbox"] = func
|
|
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:
|
|
# Pasar la lista de lógica completa solo si es necesario (PBox)
|
|
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 = "BlenderRun_ProdTime" # 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)
|