Agregando Scrips de Exportacion de Tia Portal y conversion de la configuracion de hardware a md
This commit is contained in:
parent
8762fe64ef
commit
239126bb96
Binary file not shown.
Binary file not shown.
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
}
|
|
@ -0,0 +1,277 @@
|
|||
"""
|
||||
export_logic_from_tia :
|
||||
Script para exportar el software de un PLC desde TIA Portal en archivos XML y SCL.
|
||||
"""
|
||||
import tkinter as tk
|
||||
from tkinter import filedialog
|
||||
import os
|
||||
import sys
|
||||
import traceback
|
||||
|
||||
script_root = os.path.dirname(
|
||||
os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
|
||||
)
|
||||
sys.path.append(script_root)
|
||||
from backend.script_utils import load_configuration
|
||||
|
||||
# --- Configuration ---
|
||||
TIA_PORTAL_VERSION = "18.0" # Target TIA Portal version (e.g., "18.0")
|
||||
EXPORT_OPTIONS = None # Use default export options
|
||||
KEEP_FOLDER_STRUCTURE = True # Replicate TIA project folder structure in export directory
|
||||
|
||||
# --- TIA Scripting Import Handling ---
|
||||
# Check if the TIA_SCRIPTING environment variable is set
|
||||
if os.getenv('TIA_SCRIPTING'):
|
||||
sys.path.append(os.getenv('TIA_SCRIPTING'))
|
||||
else:
|
||||
# Optional: Define a fallback path if the environment variable isn't set
|
||||
# fallback_path = "C:\\path\\to\\your\\TIA_Scripting_binaries"
|
||||
# if os.path.exists(fallback_path):
|
||||
# sys.path.append(fallback_path)
|
||||
pass # Allow import to fail if not found
|
||||
|
||||
try:
|
||||
import siemens_tia_scripting as ts
|
||||
EXPORT_OPTIONS = ts.Enums.ExportOptions.WithDefaults # Set default options now that 'ts' is imported
|
||||
except ImportError:
|
||||
print("ERROR: Failed to import 'siemens_tia_scripting'.")
|
||||
print("Ensure:")
|
||||
print(f"1. TIA Portal Openness for V{TIA_PORTAL_VERSION} is installed.")
|
||||
print("2. The 'siemens_tia_scripting' Python module is installed (pip install ...) or")
|
||||
print(" the path to its binaries is set in the 'TIA_SCRIPTING' environment variable.")
|
||||
print("3. You are using a compatible Python version (e.g., 3.12.X as per documentation).")
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
print(f"An unexpected error occurred during import: {e}")
|
||||
traceback.print_exc()
|
||||
sys.exit(1)
|
||||
|
||||
# --- Functions ---
|
||||
|
||||
def select_project_file():
|
||||
"""Opens a dialog to select a TIA Portal project file."""
|
||||
root = tk.Tk()
|
||||
root.withdraw() # Hide the main tkinter window
|
||||
file_path = filedialog.askopenfilename(
|
||||
title="Select TIA Portal Project File",
|
||||
filetypes=[(f"TIA Portal V{TIA_PORTAL_VERSION} Projects", f"*.ap{TIA_PORTAL_VERSION.split('.')[0]}")] # e.g. *.ap18
|
||||
)
|
||||
root.destroy()
|
||||
if not file_path:
|
||||
print("No project file selected. Exiting.")
|
||||
sys.exit(0)
|
||||
return file_path
|
||||
|
||||
def select_export_directory():
|
||||
"""Opens a dialog to select the export directory."""
|
||||
root = tk.Tk()
|
||||
root.withdraw() # Hide the main tkinter window
|
||||
dir_path = filedialog.askdirectory(
|
||||
title="Select Export Directory"
|
||||
)
|
||||
root.destroy()
|
||||
if not dir_path:
|
||||
print("No export directory selected. Exiting.")
|
||||
sys.exit(0)
|
||||
return dir_path
|
||||
|
||||
def export_plc_data(plc, export_base_dir):
|
||||
"""Exports Blocks, UDTs, and Tag Tables from a given PLC."""
|
||||
plc_name = plc.get_name()
|
||||
print(f"\n--- Processing PLC: {plc_name} ---")
|
||||
|
||||
# Define base export path for this PLC
|
||||
plc_export_dir = os.path.join(export_base_dir, plc_name)
|
||||
os.makedirs(plc_export_dir, exist_ok=True)
|
||||
|
||||
# --- Export Program Blocks ---
|
||||
blocks_exported = 0
|
||||
blocks_skipped = 0
|
||||
print(f"\n[PLC: {plc_name}] Exporting Program Blocks...")
|
||||
xml_blocks_path = os.path.join(plc_export_dir, "ProgramBlocks_XML")
|
||||
scl_blocks_path = os.path.join(plc_export_dir, "ProgramBlocks_SCL")
|
||||
os.makedirs(xml_blocks_path, exist_ok=True)
|
||||
os.makedirs(scl_blocks_path, exist_ok=True)
|
||||
print(f" XML Target: {xml_blocks_path}")
|
||||
print(f" SCL Target: {scl_blocks_path}")
|
||||
|
||||
try:
|
||||
program_blocks = plc.get_program_blocks() #
|
||||
print(f" Found {len(program_blocks)} program blocks.")
|
||||
for block in program_blocks:
|
||||
block_name = block.get_name() # Assuming get_name() exists
|
||||
print(f" Processing block: {block_name}...")
|
||||
try:
|
||||
if not block.is_consistent(): #
|
||||
print(f" Compiling block {block_name}...")
|
||||
block.compile() #
|
||||
if not block.is_consistent():
|
||||
print(f" WARNING: Block {block_name} inconsistent after compile. Skipping.")
|
||||
blocks_skipped += 1
|
||||
continue
|
||||
|
||||
print(f" Exporting {block_name} as XML...")
|
||||
block.export(target_directory_path=xml_blocks_path, #
|
||||
export_options=EXPORT_OPTIONS, #
|
||||
export_format=ts.Enums.ExportFormats.SimaticML, #
|
||||
keep_folder_structure=KEEP_FOLDER_STRUCTURE) #
|
||||
|
||||
try:
|
||||
prog_language = block.get_property(name="ProgrammingLanguage")
|
||||
if prog_language == "SCL":
|
||||
print(f" Exporting {block_name} as SCL...")
|
||||
block.export(target_directory_path=scl_blocks_path,
|
||||
export_options=EXPORT_OPTIONS,
|
||||
export_format=ts.Enums.ExportFormats.ExternalSource, #
|
||||
keep_folder_structure=KEEP_FOLDER_STRUCTURE)
|
||||
except Exception as prop_ex:
|
||||
print(f" Could not get ProgrammingLanguage for {block_name}. Skipping SCL. Error: {prop_ex}")
|
||||
|
||||
blocks_exported += 1
|
||||
except Exception as block_ex:
|
||||
print(f" ERROR exporting block {block_name}: {block_ex}")
|
||||
blocks_skipped += 1
|
||||
print(f" Program Blocks Export Summary: Exported={blocks_exported}, Skipped/Errors={blocks_skipped}")
|
||||
except Exception as e:
|
||||
print(f" ERROR processing Program Blocks: {e}")
|
||||
traceback.print_exc()
|
||||
|
||||
# --- Export PLC Data Types (UDTs) ---
|
||||
udts_exported = 0
|
||||
udts_skipped = 0
|
||||
print(f"\n[PLC: {plc_name}] Exporting PLC Data Types (UDTs)...")
|
||||
udt_export_path = os.path.join(plc_export_dir, "PlcDataTypes")
|
||||
os.makedirs(udt_export_path, exist_ok=True)
|
||||
print(f" Target: {udt_export_path}")
|
||||
|
||||
try:
|
||||
udts = plc.get_user_data_types() #
|
||||
print(f" Found {len(udts)} UDTs.")
|
||||
for udt in udts:
|
||||
udt_name = udt.get_name() #
|
||||
print(f" Processing UDT: {udt_name}...")
|
||||
try:
|
||||
if not udt.is_consistent(): #
|
||||
print(f" Compiling UDT {udt_name}...")
|
||||
udt.compile() #
|
||||
if not udt.is_consistent():
|
||||
print(f" WARNING: UDT {udt_name} inconsistent after compile. Skipping.")
|
||||
udts_skipped += 1
|
||||
continue
|
||||
|
||||
print(f" Exporting {udt_name}...")
|
||||
udt.export(target_directory_path=udt_export_path, #
|
||||
export_options=EXPORT_OPTIONS, #
|
||||
# export_format defaults to SimaticML for UDTs
|
||||
keep_folder_structure=KEEP_FOLDER_STRUCTURE) #
|
||||
udts_exported += 1
|
||||
except Exception as udt_ex:
|
||||
print(f" ERROR exporting UDT {udt_name}: {udt_ex}")
|
||||
udts_skipped += 1
|
||||
print(f" UDT Export Summary: Exported={udts_exported}, Skipped/Errors={udts_skipped}")
|
||||
except Exception as e:
|
||||
print(f" ERROR processing UDTs: {e}")
|
||||
traceback.print_exc()
|
||||
|
||||
# --- Export PLC Tag Tables ---
|
||||
tags_exported = 0
|
||||
tags_skipped = 0
|
||||
print(f"\n[PLC: {plc_name}] Exporting PLC Tag Tables...")
|
||||
tags_export_path = os.path.join(plc_export_dir, "PlcTags")
|
||||
os.makedirs(tags_export_path, exist_ok=True)
|
||||
print(f" Target: {tags_export_path}")
|
||||
|
||||
try:
|
||||
tag_tables = plc.get_plc_tag_tables() #
|
||||
print(f" Found {len(tag_tables)} Tag Tables.")
|
||||
for table in tag_tables:
|
||||
table_name = table.get_name() #
|
||||
print(f" Processing Tag Table: {table_name}...")
|
||||
try:
|
||||
# Note: Consistency check might not be available/needed for tag tables like blocks/UDTs
|
||||
print(f" Exporting {table_name}...")
|
||||
table.export(target_directory_path=tags_export_path, #
|
||||
export_options=EXPORT_OPTIONS, #
|
||||
# export_format defaults to SimaticML for Tag Tables
|
||||
keep_folder_structure=KEEP_FOLDER_STRUCTURE) #
|
||||
tags_exported += 1
|
||||
except Exception as table_ex:
|
||||
print(f" ERROR exporting Tag Table {table_name}: {table_ex}")
|
||||
tags_skipped += 1
|
||||
print(f" Tag Table Export Summary: Exported={tags_exported}, Skipped/Errors={tags_skipped}")
|
||||
except Exception as e:
|
||||
print(f" ERROR processing Tag Tables: {e}")
|
||||
traceback.print_exc()
|
||||
|
||||
print(f"\n--- Finished processing PLC: {plc_name} ---")
|
||||
|
||||
|
||||
# --- Main Script ---
|
||||
|
||||
if __name__ == "__main__":
|
||||
configs = load_configuration()
|
||||
|
||||
print("--- TIA Portal Data Exporter (Blocks, UDTs, Tags) ---")
|
||||
|
||||
# 1. Select Files/Folders
|
||||
project_file = select_project_file()
|
||||
export_dir = select_export_directory()
|
||||
|
||||
print(f"\nSelected Project: {project_file}")
|
||||
print(f"Selected Export Directory: {export_dir}")
|
||||
|
||||
portal_instance = None
|
||||
project_object = None
|
||||
|
||||
try:
|
||||
# 2. Connect to TIA Portal
|
||||
print(f"\nConnecting to TIA Portal V{TIA_PORTAL_VERSION}...")
|
||||
portal_instance = ts.open_portal(
|
||||
version=TIA_PORTAL_VERSION,
|
||||
portal_mode=ts.Enums.PortalMode.WithGraphicalUserInterface
|
||||
)
|
||||
print("Connected to TIA Portal.")
|
||||
print(f"Portal Process ID: {portal_instance.get_process_id()}") #
|
||||
|
||||
# 3. Open Project
|
||||
print(f"Opening project: {os.path.basename(project_file)}...")
|
||||
project_object = portal_instance.open_project(project_file_path=project_file) #
|
||||
if project_object is None:
|
||||
print("Project might already be open, attempting to get handle...")
|
||||
project_object = portal_instance.get_project() #
|
||||
if project_object is None:
|
||||
raise Exception("Failed to open or get the specified project.")
|
||||
print("Project opened successfully.")
|
||||
|
||||
# 4. Get PLCs
|
||||
plcs = project_object.get_plcs() #
|
||||
if not plcs:
|
||||
print("No PLC devices found in the project.")
|
||||
else:
|
||||
print(f"Found {len(plcs)} PLC(s). Starting export process...")
|
||||
|
||||
# 5. Iterate and Export Data for each PLC
|
||||
for plc_device in plcs:
|
||||
export_plc_data(plc=plc_device, export_base_dir=export_dir)
|
||||
|
||||
print("\nExport process completed.")
|
||||
|
||||
except ts.TiaException as tia_ex:
|
||||
print(f"\nTIA Portal Openness Error: {tia_ex}")
|
||||
traceback.print_exc()
|
||||
except FileNotFoundError:
|
||||
print(f"\nERROR: Project file not found at {project_file}")
|
||||
except Exception as e:
|
||||
print(f"\nAn unexpected error occurred: {e}")
|
||||
traceback.print_exc()
|
||||
finally:
|
||||
# 6. Cleanup
|
||||
if portal_instance:
|
||||
try:
|
||||
print("\nClosing TIA Portal...")
|
||||
portal_instance.close_portal() #
|
||||
print("TIA Portal closed.")
|
||||
except Exception as close_ex:
|
||||
print(f"Error during TIA Portal cleanup: {close_ex}")
|
||||
|
||||
print("\nScript finished.")
|
|
@ -0,0 +1,269 @@
|
|||
"""
|
||||
export_CAx_from_tia :
|
||||
Script que exporta los datos CAx de un proyecto de TIA Portal y genera un resumen en Markdown.
|
||||
"""
|
||||
import tkinter as tk
|
||||
from tkinter import filedialog
|
||||
import os
|
||||
import sys
|
||||
import traceback
|
||||
import xml.etree.ElementTree as ET # Library to parse XML (AML)
|
||||
|
||||
script_root = os.path.dirname(
|
||||
os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
|
||||
)
|
||||
sys.path.append(script_root)
|
||||
from backend.script_utils import load_configuration
|
||||
|
||||
# --- Configuration ---
|
||||
TIA_PORTAL_VERSION = "18.0" # Target TIA Portal version
|
||||
|
||||
# --- TIA Scripting Import Handling ---
|
||||
# (Same import handling as the previous script)
|
||||
if os.getenv('TIA_SCRIPTING'):
|
||||
sys.path.append(os.getenv('TIA_SCRIPTING'))
|
||||
else:
|
||||
pass
|
||||
|
||||
try:
|
||||
import siemens_tia_scripting as ts
|
||||
except ImportError:
|
||||
print("ERROR: Failed to import 'siemens_tia_scripting'.")
|
||||
print("Ensure TIA Openness, the module, and Python 3.12.X are set up.")
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
print(f"An unexpected error occurred during import: {e}")
|
||||
traceback.print_exc()
|
||||
sys.exit(1)
|
||||
|
||||
# --- Functions ---
|
||||
|
||||
def select_project_file():
|
||||
"""Opens a dialog to select a TIA Portal project file."""
|
||||
root = tk.Tk()
|
||||
root.withdraw()
|
||||
file_path = filedialog.askopenfilename(
|
||||
title="Select TIA Portal Project File",
|
||||
filetypes=[(f"TIA Portal V{TIA_PORTAL_VERSION} Projects", f"*.ap{TIA_PORTAL_VERSION.split('.')[0]}")]
|
||||
)
|
||||
root.destroy()
|
||||
if not file_path:
|
||||
print("No project file selected. Exiting.")
|
||||
sys.exit(0)
|
||||
return file_path
|
||||
|
||||
def select_output_directory():
|
||||
"""Opens a dialog to select the output directory."""
|
||||
root = tk.Tk()
|
||||
root.withdraw()
|
||||
dir_path = filedialog.askdirectory(
|
||||
title="Select Output Directory for AML and MD files"
|
||||
)
|
||||
root.destroy()
|
||||
if not dir_path:
|
||||
print("No output directory selected. Exiting.")
|
||||
sys.exit(0)
|
||||
return dir_path
|
||||
|
||||
def find_elements(element, path):
|
||||
"""Helper to find elements using namespaces commonly found in AML."""
|
||||
# AutomationML namespaces often vary slightly or might be default
|
||||
# This basic approach tries common prefixes or no prefix
|
||||
namespaces = {
|
||||
'': element.tag.split('}')[0][1:] if '}' in element.tag else '', # Default namespace if present
|
||||
'caex': 'http://www.dke.de/CAEX', # Common CAEX namespace
|
||||
# Add other potential namespaces if needed based on file inspection
|
||||
}
|
||||
# Try finding with common prefixes or the default namespace
|
||||
for prefix, uri in namespaces.items():
|
||||
# Construct path with namespace URI if prefix is defined
|
||||
namespaced_path = path
|
||||
if prefix:
|
||||
parts = path.split('/')
|
||||
namespaced_parts = [f"{{{uri}}}{part}" if part != '.' else part for part in parts]
|
||||
namespaced_path = '/'.join(namespaced_parts)
|
||||
|
||||
# Try findall with the constructed path
|
||||
found = element.findall(namespaced_path)
|
||||
if found:
|
||||
return found # Return first successful find
|
||||
|
||||
# Fallback: try finding without explicit namespace (might work if default ns is used throughout)
|
||||
# This might require adjusting the path string itself depending on the XML structure
|
||||
try:
|
||||
# Simple attempt without namespace handling if the above fails
|
||||
return element.findall(path)
|
||||
except SyntaxError: # Handle potential errors if path isn't valid without namespaces
|
||||
return []
|
||||
|
||||
|
||||
def parse_aml_to_markdown(aml_file_path, md_file_path):
|
||||
"""Parses the AML file and generates a Markdown summary."""
|
||||
print(f"Parsing AML file: {aml_file_path}")
|
||||
try:
|
||||
tree = ET.parse(aml_file_path)
|
||||
root = tree.getroot()
|
||||
|
||||
markdown_lines = ["# Project CAx Data Summary (AutomationML)", ""]
|
||||
|
||||
# Find InstanceHierarchy - usually contains the project structure
|
||||
# Note: Namespace handling in ElementTree can be tricky. Adjust '{...}' part if needed.
|
||||
# We will use a helper function 'find_elements' to try common patterns
|
||||
instance_hierarchies = find_elements(root, './/InstanceHierarchy') # Common CAEX tag
|
||||
|
||||
if not instance_hierarchies:
|
||||
markdown_lines.append("Could not find InstanceHierarchy in the AML file.")
|
||||
print("Warning: Could not find InstanceHierarchy element.")
|
||||
else:
|
||||
# Assuming the first InstanceHierarchy is the main one
|
||||
ih = instance_hierarchies[0]
|
||||
markdown_lines.append(f"## Instance Hierarchy: {ih.get('Name', 'N/A')}")
|
||||
markdown_lines.append("")
|
||||
|
||||
# Look for InternalElements which represent devices/components
|
||||
internal_elements = find_elements(ih, './/InternalElement') # Common CAEX tag
|
||||
|
||||
if not internal_elements:
|
||||
markdown_lines.append("No devices (InternalElement) found in InstanceHierarchy.")
|
||||
print("Info: No InternalElement tags found under InstanceHierarchy.")
|
||||
else:
|
||||
markdown_lines.append(f"Found {len(internal_elements)} device(s)/component(s):")
|
||||
markdown_lines.append("")
|
||||
markdown_lines.append("| Name | SystemUnitClass | RefBaseSystemUnitPath | Attributes |")
|
||||
markdown_lines.append("|---|---|---|---|")
|
||||
|
||||
for elem in internal_elements:
|
||||
name = elem.get('Name', 'N/A')
|
||||
ref_path = elem.get('RefBaseSystemUnitPath', 'N/A') # Path to class definition
|
||||
|
||||
# Try to get the class name from the RefBaseSystemUnitPath or SystemUnitClassLib
|
||||
su_class_path = find_elements(elem, './/SystemUnitClass') # Check direct child first
|
||||
su_class = su_class_path[0].get('Path', 'N/A') if su_class_path else ref_path.split('/')[-1] # Fallback to last part of path
|
||||
|
||||
attributes_md = ""
|
||||
attributes = find_elements(elem, './/Attribute') # Find attributes
|
||||
attr_list = []
|
||||
for attr in attributes:
|
||||
attr_name = attr.get('Name', '')
|
||||
attr_value_elem = find_elements(attr, './/Value') # Get Value element
|
||||
attr_value = attr_value_elem[0].text if attr_value_elem and attr_value_elem[0].text else 'N/A'
|
||||
|
||||
# Look for potential IP addresses (common attribute names)
|
||||
if "Address" in attr_name or "IP" in attr_name:
|
||||
attr_list.append(f"**{attr_name}**: {attr_value}")
|
||||
else:
|
||||
attr_list.append(f"{attr_name}: {attr_value}")
|
||||
|
||||
attributes_md = "<br>".join(attr_list) if attr_list else "None"
|
||||
|
||||
|
||||
markdown_lines.append(f"| {name} | {su_class} | `{ref_path}` | {attributes_md} |")
|
||||
|
||||
# Write to Markdown file
|
||||
with open(md_file_path, 'w', encoding='utf-8') as f:
|
||||
f.write("\n".join(markdown_lines))
|
||||
print(f"Markdown summary written to: {md_file_path}")
|
||||
|
||||
except ET.ParseError as xml_err:
|
||||
print(f"ERROR parsing XML file {aml_file_path}: {xml_err}")
|
||||
with open(md_file_path, 'w', encoding='utf-8') as f:
|
||||
f.write(f"# Error\n\nFailed to parse AML file: {os.path.basename(aml_file_path)}\n\nError: {xml_err}")
|
||||
except Exception as e:
|
||||
print(f"ERROR processing AML file {aml_file_path}: {e}")
|
||||
traceback.print_exc()
|
||||
with open(md_file_path, 'w', encoding='utf-8') as f:
|
||||
f.write(f"# Error\n\nAn unexpected error occurred while processing AML file: {os.path.basename(aml_file_path)}\n\nError: {e}")
|
||||
|
||||
|
||||
# --- Main Script ---
|
||||
|
||||
if __name__ == "__main__":
|
||||
configs = load_configuration()
|
||||
print("--- TIA Portal Project CAx Exporter and Analyzer ---")
|
||||
|
||||
# 1. Select Files/Folders
|
||||
project_file = select_project_file()
|
||||
output_dir = select_output_directory()
|
||||
|
||||
print(f"\nSelected Project: {project_file}")
|
||||
print(f"Selected Output Directory: {output_dir}")
|
||||
|
||||
# Define output file names
|
||||
project_base_name = os.path.splitext(os.path.basename(project_file))[0]
|
||||
aml_file = os.path.join(output_dir, f"{project_base_name}_CAx_Export.aml")
|
||||
md_file = os.path.join(output_dir, f"{project_base_name}_CAx_Summary.md")
|
||||
log_file = os.path.join(output_dir, f"{project_base_name}_CAx_Export.log") # Log file for the export process
|
||||
|
||||
print(f"Will export CAx data to: {aml_file}")
|
||||
print(f"Will generate summary to: {md_file}")
|
||||
print(f"Export log file: {log_file}")
|
||||
|
||||
|
||||
portal_instance = None
|
||||
project_object = None
|
||||
cax_export_successful = False
|
||||
|
||||
try:
|
||||
# 2. Connect to TIA Portal
|
||||
print(f"\nConnecting to TIA Portal V{TIA_PORTAL_VERSION}...")
|
||||
portal_instance = ts.open_portal(
|
||||
version=TIA_PORTAL_VERSION,
|
||||
portal_mode=ts.Enums.PortalMode.WithGraphicalUserInterface
|
||||
)
|
||||
print("Connected.")
|
||||
|
||||
# 3. Open Project
|
||||
print(f"Opening project: {os.path.basename(project_file)}...")
|
||||
project_object = portal_instance.open_project(project_file_path=project_file)
|
||||
if project_object is None:
|
||||
project_object = portal_instance.get_project()
|
||||
if project_object is None:
|
||||
raise Exception("Failed to open or get the specified project.")
|
||||
print("Project opened.")
|
||||
|
||||
# 4. Export CAx Data (Project Level)
|
||||
print(f"Exporting CAx data for the project to {aml_file}...")
|
||||
# Ensure output directory exists for the log file as well
|
||||
os.makedirs(os.path.dirname(log_file), exist_ok=True)
|
||||
|
||||
export_result = project_object.export_cax_data(export_file_path=aml_file, log_file_path=log_file) # [cite: 361]
|
||||
|
||||
if export_result:
|
||||
print("CAx data exported successfully.")
|
||||
cax_export_successful = True
|
||||
else:
|
||||
print("CAx data export failed. Check the log file for details:")
|
||||
print(f" Log file: {log_file}")
|
||||
# Write basic error message to MD file if export fails
|
||||
with open(md_file, 'w', encoding='utf-8') as f:
|
||||
f.write(f"# Error\n\nCAx data export failed. Check log file: {log_file}")
|
||||
|
||||
|
||||
except ts.TiaException as tia_ex:
|
||||
print(f"\nTIA Portal Openness Error: {tia_ex}")
|
||||
traceback.print_exc()
|
||||
except FileNotFoundError:
|
||||
print(f"\nERROR: Project file not found at {project_file}")
|
||||
except Exception as e:
|
||||
print(f"\nAn unexpected error occurred during TIA interaction: {e}")
|
||||
traceback.print_exc()
|
||||
finally:
|
||||
# Close TIA Portal before processing the file (or detach)
|
||||
if portal_instance:
|
||||
try:
|
||||
print("\nClosing TIA Portal...")
|
||||
portal_instance.close_portal()
|
||||
print("TIA Portal closed.")
|
||||
except Exception as close_ex:
|
||||
print(f"Error during TIA Portal cleanup: {close_ex}")
|
||||
|
||||
# 5. Parse AML and Generate Markdown (only if export was successful)
|
||||
if cax_export_successful:
|
||||
if os.path.exists(aml_file):
|
||||
parse_aml_to_markdown(aml_file, md_file)
|
||||
else:
|
||||
print(f"ERROR: Export was reported successful, but AML file not found at {aml_file}")
|
||||
with open(md_file, 'w', encoding='utf-8') as f:
|
||||
f.write(f"# Error\n\nExport was reported successful, but AML file not found:\n{aml_file}")
|
||||
|
||||
print("\nScript finished.")
|
File diff suppressed because it is too large
Load Diff
|
@ -1,5 +1,6 @@
|
|||
import os
|
||||
import json
|
||||
import inspect
|
||||
from typing import Dict, Any
|
||||
|
||||
|
||||
|
@ -20,8 +21,11 @@ def load_configuration() -> Dict[str, Any]:
|
|||
working_dir = configs.get("working_directory", "")
|
||||
"""
|
||||
try:
|
||||
# Get directory of the calling script
|
||||
script_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
# Obtener el frame del llamador
|
||||
caller_frame = inspect.stack()[1]
|
||||
caller_file = caller_frame.filename
|
||||
# Obtener el directorio del script que llama a esta función
|
||||
script_dir = os.path.dirname(os.path.abspath(caller_file))
|
||||
|
||||
# Path to the config file
|
||||
config_file_path = os.path.join(script_dir, "script_config.json")
|
||||
|
|
|
@ -423,11 +423,12 @@ class ConfigurationManager:
|
|||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
bufsize=1,
|
||||
encoding='utf-8', # <--- Añadir explícitamente la codificación UTF-8
|
||||
errors='replace', # Opcional: reemplazar caracteres mal formados en lugar de fallar
|
||||
bufsize=1, # Line buffered
|
||||
env=dict(
|
||||
os.environ,
|
||||
# SCRIPT_CONFIGS=json.dumps(configs), # Commented out as we now use a file
|
||||
PYTHONIOENCODING="utf-8",
|
||||
PYTHONIOENCODING="utf-8", # Mantener esto también es bueno
|
||||
),
|
||||
)
|
||||
|
||||
|
|
17
data/log.txt
17
data/log.txt
|
@ -1,16 +1 @@
|
|||
[21:32:28] Configuraciones guardadas en d:\Proyectos\Scripts\ParamManagerScripts\backend\script_groups\example_group\script_config.json
|
||||
[21:32:28] Iniciando ejecución de x1.py
|
||||
[21:32:33] Configuration file not found: d:\Proyectos\Scripts\ParamManagerScripts\backend\script_config.json
|
||||
[21:32:33] === Ejecutando Script de Prueba 1 ===
|
||||
[21:32:33] Configuraciones cargadas:
|
||||
[21:32:33] Nivel 1: {}
|
||||
[21:32:33] Nivel 2: {}
|
||||
[21:32:33] Nivel 3: {}
|
||||
[21:32:33] Simulando procesamiento...
|
||||
[21:32:33] Progreso: 20%
|
||||
[21:32:33] Progreso: 40%
|
||||
[21:32:33] Progreso: 60%
|
||||
[21:32:33] Progreso: 80%
|
||||
[21:32:33] Progreso: 100%
|
||||
[21:32:33] ¡Proceso completado!
|
||||
[21:32:33] Ejecución completada
|
||||
[22:54:35] Error: Directorio de trabajo no configurado
|
||||
|
|
Loading…
Reference in New Issue