ParamManagerScripts/backend/script_groups/ObtainIOFromProjectTia/.doc/test_x2.py

229 lines
7.9 KiB
Python

"""
Verificar si las DLLs de TIA Portal V20 están disponibles para pythonnet
"""
import os
import clr
def check_v20_dlls():
"""Check if TIA Portal V20 DLLs are available."""
print("="*70)
print("VERIFICADOR DE DLL TIA PORTAL V20 PARA SIMATIC SD")
print("="*70)
# Possible paths for V20 DLLs
v20_paths = [
r"C:\Program Files\Siemens\Automation\Portal V20\PublicAPI\V20",
r"C:\Program Files (x86)\Siemens\Automation\Portal V20\PublicAPI\V20",
r"C:\Program Files\Siemens\Automation\Portal V20\bin\PublicAPI\V20"
]
print("🔍 Buscando instalación de TIA Portal V20...")
v20_path = None
for path in v20_paths:
if os.path.exists(path):
dll_path = os.path.join(path, "Siemens.Engineering.dll")
if os.path.exists(dll_path):
v20_path = path
print(f"✅ Encontrado TIA Portal V20 en: {path}")
break
else:
print(f"❌ Directorio existe pero falta Siemens.Engineering.dll: {path}")
else:
print(f"❌ Directorio no encontrado: {path}")
if not v20_path:
print("\n❌ TIA Portal V20 no encontrado")
print("\n📋 OPCIONES DISPONIBLES:")
print("1. 🔧 Instalar TIA Portal V20 completo con Openness")
print("2. 🔧 Usar C# en lugar de Python")
print("3. 🔧 Esperar a una versión más nueva del paquete Python")
return False
print(f"\n📁 Explorando DLLs en: {v20_path}")
# List all DLLs
try:
dlls = [f for f in os.listdir(v20_path) if f.endswith('.dll')]
print(f"DLLs encontradas: {len(dlls)}")
for dll in sorted(dlls):
print(f" - {dll}")
# Check for V20 specific DLLs
v20_dll = "Siemens.TiaPortal.OpennessApi20.dll"
if v20_dll in dlls:
print(f"\n✅ ¡{v20_dll} encontrada!")
print(" Esto significa que tienes API V20 disponible")
else:
print(f"\n{v20_dll} NO encontrada")
print(" Solo tienes APIs hasta V19 - sin SIMATIC SD")
# List available API versions
api_dlls = [dll for dll in dlls if "OpennessApi" in dll]
if api_dlls:
print(f" APIs disponibles: {api_dlls}")
except Exception as list_ex:
print(f"❌ Error listando DLLs: {list_ex}")
return False
# Try to load V20 DLLs with pythonnet
print(f"\n🔧 Probando carga con pythonnet...")
try:
import sys
sys.path.append(v20_path)
# Try to load main assembly
clr.AddReference("Siemens.Engineering")
print("✅ Siemens.Engineering cargada")
# Try to import V20-specific classes
try:
from Siemens.Engineering import TiaPortal, TiaPortalMode
print("✅ TiaPortal y TiaPortalMode importados")
# Try to connect
try:
portal = TiaPortal.Open(TiaPortalMode.WithoutUserInterface)
if portal:
print("✅ Portal V20 abierto exitosamente")
# This would be where you test ExportAsDocuments
print("🎯 Portal V20 funcional - SIMATIC SD potencialmente disponible")
portal.Close()
return True
else:
print("❌ No se pudo abrir portal")
except Exception as portal_ex:
print(f"❌ Error abriendo portal: {portal_ex}")
except Exception as import_ex:
print(f"❌ Error importando clases V20: {import_ex}")
except Exception as load_ex:
print(f"❌ Error cargando DLLs con pythonnet: {load_ex}")
return False
def create_c_sharp_alternative():
"""Create a C# script as alternative."""
print(f"\n🔧 CREANDO ALTERNATIVA EN C#...")
csharp_code = '''
using System;
using System.IO;
using Siemens.Engineering;
using Siemens.Engineering.HW.Features;
class SimaticSDExporter
{
static void Main(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine("Uso: SimaticSDExporter.exe <proyecto.ap20> <directorio_export>");
return;
}
string projectPath = args[0];
string exportDir = args[1];
TiaPortal portal = null;
Project project = null;
try
{
// Abrir TIA Portal V20
portal = TiaPortal.Open(TiaPortalMode.WithUserInterface);
Console.WriteLine("✅ TIA Portal V20 abierto");
// Abrir proyecto
project = portal.Projects.Open(projectPath);
Console.WriteLine($"✅ Proyecto abierto: {project.Name}");
// Buscar PLCs
foreach (Device device in project.Devices)
{
foreach (DeviceItem deviceItem in device.DeviceItems)
{
if (deviceItem.GetService<SoftwareContainer>() != null)
{
var sw = deviceItem.GetService<SoftwareContainer>().Software;
Console.WriteLine($"Procesando PLC: {deviceItem.Name}");
// Exportar bloques en SIMATIC SD
foreach (var block in sw.BlockGroup.Blocks)
{
try
{
string blockExportDir = Path.Combine(exportDir, deviceItem.Name, "SIMATIC_SD");
Directory.CreateDirectory(blockExportDir);
// ¡AQUÍ ESTÁ EL MÉTODO SIMATIC SD!
block.ExportAsDocuments(
new DirectoryInfo(blockExportDir),
block.Name
);
Console.WriteLine($"{block.Name} exportado en SIMATIC SD");
}
catch (Exception blockEx)
{
Console.WriteLine($"❌ Error con {block.Name}: {blockEx.Message}");
}
}
}
}
}
Console.WriteLine("🎉 Exportación SIMATIC SD completada");
}
catch (Exception ex)
{
Console.WriteLine($"❌ Error: {ex.Message}");
}
finally
{
project?.Close();
portal?.Close();
}
}
}
'''
# Save C# code to file
csharp_file = "SimaticSDExporter.cs"
with open(csharp_file, 'w', encoding='utf-8') as f:
f.write(csharp_code)
print(f"✅ Código C# guardado en: {csharp_file}")
print(f"\n📋 PARA COMPILAR Y USAR:")
print(f"1. Instalar Visual Studio o .NET SDK")
print(f"2. Agregar referencias a TIA Portal V20 DLLs")
print(f"3. Compilar: csc SimaticSDExporter.cs /r:Siemens.Engineering.dll")
print(f"4. Ejecutar: SimaticSDExporter.exe proyecto.ap20 directorio_export")
if __name__ == "__main__":
has_v20 = check_v20_dlls()
if not has_v20:
create_c_sharp_alternative()
print(f"\n" + "="*70)
print("📋 RESUMEN DE OPCIONES PARA SIMATIC SD:")
print("="*70)
print("❌ Python: API V19 no tiene SIMATIC SD")
print("✅ C#: Acceso directo a ExportAsDocuments")
print("🔧 Requiere: TIA Portal V20 + Visual Studio")
else:
print(f"\n🎉 ¡TIA Portal V20 disponible para Python!")
print("Puedo crear un exportador Python con pythonnet + V20 DLLs")
input("\nPresiona Enter para salir...")