Simatic_XML_Parser_to_SCL/processors/process_se.py

92 lines
4.4 KiB
Python

# -*- coding: utf-8 -*-
from .processor_utils import get_scl_representation, format_variable_name,get_target_scl_name
# TODO: Import necessary functions from processor_utils
# Example: from .processor_utils import get_scl_representation, format_variable_name
# Or: import processors.processor_utils as utils
# TODO: Define constants if needed (e.g., SCL_SUFFIX) or import them
SCL_SUFFIX = "_scl"
# --- Function code starts ---
def process_se(instruction, network_id, scl_map, access_map, data):
"""
Genera SCL para Temporizador de Pulso (Se -> TP).
Requiere datos de instancia (DB o STAT/TEMP).
"""
instr_uid = instruction["instruction_uid"]
instr_type = "Se" # Tipo original LAD
if instruction["type"].endswith(SCL_SUFFIX) or "_error" in instruction["type"]:
return False
# 1. Obtener Inputs: s (start), tv (time value)
# El pin 'r' (reset) no tiene equivalente directo en TP, se ignora aquí.
s_info = instruction["inputs"].get("s")
tv_info = instruction["inputs"].get("tv")
timer_instance_info = instruction["inputs"].get("timer") # Esperando que x1 lo extraiga
scl_s = get_scl_representation(s_info, network_id, scl_map, access_map)
scl_tv = get_scl_representation(tv_info, network_id, scl_map, access_map)
# Obtenemos el nombre de la variable instancia, crucial!
scl_instance_name = get_scl_representation(timer_instance_info, network_id, scl_map, access_map)
if scl_s is None or scl_tv is None:
return False # Dependencias no listas
# 2. Validar y obtener Nombre de Instancia
instance_name = None
if timer_instance_info and timer_instance_info.get("type") == "variable":
instance_name = scl_instance_name # Ya debería estar formateado por get_scl_repr
elif timer_instance_info: # Si está conectado pero no es variable directa? Raro.
print(f"Advertencia: Pin 'timer' de {instr_type} UID {instr_uid} conectado a algo inesperado: {timer_instance_info.get('type')}")
instance_name = f"#TP_INSTANCE_{instr_uid}" # Usar placeholder
else: # Si no hay pin 'timer' conectado (no debería pasar si x1 funciona)
instance_name = f"#TP_INSTANCE_{instr_uid}" # Usar placeholder
print(f"Advertencia: No se encontró conexión al pin 'timer' para {instr_type} UID {instr_uid}. Usando placeholder '{instance_name}'. ¡Revisar x1.py y XML!")
# 3. Formatear entradas si son variables (aunque get_scl_representation ya debería hacerlo)
scl_s_formatted = format_variable_name(scl_s) if s_info and s_info.get("type") == "variable" else scl_s
scl_tv_formatted = format_variable_name(scl_tv) if tv_info and tv_info.get("type") == "variable" else scl_tv
# 4. Generar la llamada SCL (TP usa IN, PT, Q, ET)
scl_call = f"{instance_name}(IN := {scl_s_formatted}, PT := {scl_tv_formatted}); // TODO: Declarar {instance_name} : TP; en VAR_STAT o VAR"
instruction["scl"] = scl_call
instruction["type"] = instr_type + SCL_SUFFIX
# 5. Actualizar scl_map usando los nombres de pin ORIGINALES mapeados si existen
output_pin_mapping_reverse = {v: k for k, v in instruction.get("_output_pin_mapping", {}).items()} # Necesitaríamos guardar el mapeo en x1
q_original_pin = "q" # Default
rt_original_pin = "rt" # Default
# Intentar encontrar los pines originales si x1 guardó el mapeo (MEJORA NECESARIA en x1)
# Por ahora, para SdCoil que mapeaba out->q, usaremos 'out' directamente
if instruction.get("type") == "Se_scl" and instruction.get("original_type") == "SdCoil": # Necesitamos guardar original_type en x1
q_original_pin = "out"
# rt no existe en SdCoil
map_key_q = (network_id, instr_uid, q_original_pin)
scl_map[map_key_q] = f"{instance_name}.Q"
if rt_original_pin: # Solo añadir rt si corresponde
map_key_rt = (network_id, instr_uid, rt_original_pin)
scl_map[map_key_rt] = f"{instance_name}.ET"
return True
# --- Procesador para Sd (On-Delay Timer -> TON SCL) ---
# --- Function code ends ---
# --- Processor Information Function ---
def get_processor_info():
"""Devuelve la información para el temporizador de Pulso (Se -> TP) y maneja SdCoil."""
# Asumiendo que el tipo en el JSON es 'Se'
# Y que SdCoil también se mapea aquí según el análisis previo
return [
{'type_name': 'se', 'processor_func': process_se, 'priority': 5},
{'type_name': 'sdcoil', 'processor_func': process_se, 'priority': 5} # SdCoil también se procesa como TP
]