""" Gestor de configuración para guardar y cargar ajustes """ import json import os class ConfigManager: def __init__(self, config_file="maselli_simulator_config.json"): self.config_file = config_file self.default_config = { 'connection_type': 'TCP', 'com_port': 'COM8', 'baud_rate': '115200', 'ip_address': '10.1.33.18', 'port': '8899', 'adam_address': '01', 'function_type': 'Sinusoidal', 'min_brix_map': '0', 'max_brix_map': '80', 'cycle_time': '0.5', 'manual_input_type': 'Brix', # Nuevo: 'Brix', 'mA', 'Voltaje' 'manual_value': '10.0', # Nuevo: valor correspondiente al manual_input_type # Configuración para NetCom 'netcom_com_port': 'COM3', 'netcom_baud_rate': '115200', 'netcom_bytesize': 8, # Data bits (5, 6, 7, 8) 'netcom_parity': 'N', # Parity ('N', 'E', 'O', 'M', 'S') 'netcom_stopbits': 1, # Stop bits (1, 1.5, 2) 'netcom_rtscts': False, # Hardware flow control RTS/CTS 'netcom_dsrdtr': False, # Hardware flow control DSR/DTR 'netcom_xonxoff': False, # Software flow control XON/XOFF 'netcom_bridge_delay': 0.001 # Delay in seconds for the bridge polling loop } def save_config(self, config_data): """Guarda la configuración en archivo JSON""" try: with open(self.config_file, 'w') as f: json.dump(config_data, f, indent=4) return True except Exception as e: print(f"Error al guardar configuración: {e}") return False def load_config(self): """Carga la configuración desde archivo JSON""" if not os.path.exists(self.config_file): return self.default_config.copy() try: with open(self.config_file, 'r') as f: config = json.load(f) # Asegurarse de que todas las claves necesarias estén presentes for key, value in self.default_config.items(): if key not in config: config[key] = value # Migrar 'period' a 'cycle_time' si existe if 'period' in config and 'cycle_time' not in config: config['cycle_time'] = config['period'] del config['period'] # Migrar 'manual_brix' a 'manual_input_type' y 'manual_value' if 'manual_brix' in config and 'manual_value' not in config: config['manual_value'] = config['manual_brix'] config['manual_input_type'] = config.get('manual_input_type', 'Brix') # Asumir Brix si no existe del config['manual_brix'] return config except Exception as e: print(f"Error al cargar configuración: {e}") return self.default_config.copy() def get_connection_params(self, config, use_netcom_port=False): """Extrae los parámetros de conexión de la configuración""" conn_type = config.get('connection_type', 'Serial') if conn_type == "Serial": if use_netcom_port: # Para NetCom, usar el puerto COM físico dedicado return { 'port': config.get('netcom_com_port', 'COM3'), 'baud': int(config.get('netcom_baud_rate', '115200')) } else: return { 'port': config.get('com_port', 'COM3'), 'baud': int(config.get('baud_rate', '115200')) } elif conn_type == "TCP-Server": # Para TCP-Server, la IP es implícitamente '0.0.0.0' (escuchar en todas las interfaces) # Solo necesitamos el puerto para el bind. return { 'port': int(config.get('port', '8899')) # Usa el mismo campo de puerto } else: return { 'ip': config.get('ip_address', '192.168.1.100'), 'port': int(config.get('port', '502')) } def validate_config(self, config): """Valida que la configuración tenga valores correctos""" errors = [] # Validar dirección ADAM adam_address = config.get('adam_address', '') if len(adam_address) != 2: errors.append("La dirección ADAM debe tener exactamente 2 caracteres") # Validar rango de Brix try: min_brix = float(config.get('min_brix_map', '0')) max_brix = float(config.get('max_brix_map', '80')) if min_brix >= max_brix: errors.append("El valor mínimo de Brix debe ser menor que el máximo") except ValueError: errors.append("Los valores de Brix deben ser números válidos") # Validar tiempo de ciclo try: cycle_time = float(config.get('cycle_time', '1.0')) if cycle_time <= 0: errors.append("El tiempo de ciclo debe ser mayor que 0") except ValueError: errors.append("El tiempo de ciclo debe ser un número válido") # Validar valor manual try: manual_value = float(config.get('manual_value', '0')) # Aquí se podrían añadir validaciones de rango según el manual_input_type except ValueError: errors.append("El valor manual debe ser un número válido") # Validar puerto serie if config.get('connection_type') == 'Serial': com_port = config.get('com_port', '') if not com_port.upper().startswith('COM'): errors.append("El puerto COM debe tener formato 'COMx'") try: baud_rate = int(config.get('baud_rate', '9600')) if baud_rate <= 0: errors.append("La velocidad de baudios debe ser mayor que 0") except ValueError: errors.append("La velocidad de baudios debe ser un número entero") # Validar configuración TCP/UDP/TCP-Server else: try: port = int(config.get('port', '502')) if port <= 0 or port > 65535: errors.append("El puerto debe estar entre 1 y 65535") except ValueError: errors.append("El puerto debe ser un número entero") return errors