@codesys/mcp-toolkit 1.0.6 → 1.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -60,18 +60,33 @@ const promises_1 = require("fs/promises"); // For file existence check
60
60
  // --- Configuration ---
61
61
  const WORKSPACE_DIR = process.cwd(); // Use current working directory as default workspace
62
62
  console.error(`Using Workspace Directory: ${WORKSPACE_DIR}`);
63
- // --- CODESYS Configuration ---
64
- let codesysExePath = process.argv[2];
65
- let codesysProfileName = process.argv[3];
63
+ // --- CODESYS Configuration - with multiple fallbacks ---
66
64
  console.error('Command line arguments:', process.argv);
65
+ // Get paths with multiple fallback mechanisms
66
+ let codesysExePath = process.argv[2] || process.env.CODESYS_PATH;
67
+ let codesysProfileName = process.argv[3] || process.env.CODESYS_PROFILE;
68
+ // Last-resort defaults
67
69
  if (!codesysExePath) {
68
- codesysExePath = "C:\\Program Files\\CODESYS 3.5.21.0\\CODESYS\\Common\\CODESYS.exe"; // Default Example - ADJUST IF NEEDED
70
+ codesysExePath = "C:\\Program Files\\CODESYS 3.5.21.0\\CODESYS\\Common\\CODESYS.exe";
69
71
  console.error(`WARNING: Using default CODESYS path: ${codesysExePath}`);
70
72
  }
71
73
  if (!codesysProfileName) {
72
- codesysProfileName = "CODESYS V3.5 SP21"; // Default Example - ADJUST IF NEEDED
74
+ codesysProfileName = "CODESYS V3.5 SP21";
73
75
  console.error(`WARNING: Using default CODESYS profile: ${codesysProfileName}`);
74
76
  }
77
+ // Sanity check - confirm the path exists if possible
78
+ try {
79
+ const fs = require('fs');
80
+ if (!fs.existsSync(codesysExePath)) {
81
+ console.error(`WARNING: CODESYS executable not found at: ${codesysExePath}`);
82
+ }
83
+ else {
84
+ console.error(`Confirmed CODESYS executable exists at: ${codesysExePath}`);
85
+ }
86
+ }
87
+ catch (err) {
88
+ console.error(`Error checking CODESYS path: ${err.message}`);
89
+ }
75
90
  console.error('INFO: Using command-line arguments is recommended for production.');
76
91
  console.error(`Using CODESYS Path: ${codesysExePath}`);
77
92
  console.error(`Using CODESYS Profile: ${codesysProfileName}`);
@@ -100,911 +115,911 @@ const server = new mcp_js_1.McpServer({
100
115
  });
101
116
  // --- Python Script Templates ---
102
117
  // (ENSURE_PROJECT_OPEN_PYTHON_SNIPPET remains the same as before)
103
- const ENSURE_PROJECT_OPEN_PYTHON_SNIPPET = `
104
- import sys
105
- import scriptengine as script_engine
106
- import os
107
- import time
108
- import traceback
109
-
110
- # --- Function to ensure the correct project is open ---
111
- MAX_RETRIES = 3
112
- RETRY_DELAY = 2.0 # seconds (use float for time.sleep)
113
-
114
- def ensure_project_open(target_project_path):
115
- print("DEBUG: Ensuring project is open: %s" % target_project_path)
116
- # Normalize target path once
117
- normalized_target_path = os.path.normcase(os.path.abspath(target_project_path))
118
-
119
- for attempt in range(MAX_RETRIES):
120
- print("DEBUG: Ensure project attempt %d/%d for %s" % (attempt + 1, MAX_RETRIES, normalized_target_path))
121
- primary_project = None
122
- try:
123
- # Getting primary project might fail if CODESYS instance is unstable
124
- primary_project = script_engine.projects.primary
125
- except Exception as primary_err:
126
- print("WARN: Error getting primary project: %s. Assuming none." % primary_err)
127
- # traceback.print_exc() # Optional: Print stack trace for this error
128
- primary_project = None
129
-
130
- current_project_path = ""
131
- project_ok = False # Flag to check if target is confirmed primary and accessible
132
-
133
- if primary_project:
134
- try:
135
- # Getting path should be relatively safe if primary_project object exists
136
- current_project_path = os.path.normcase(os.path.abspath(primary_project.path))
137
- print("DEBUG: Current primary project path: %s" % current_project_path)
138
- if current_project_path == normalized_target_path:
139
- # Found the right project as primary, now check if it's usable
140
- print("DEBUG: Target project path matches primary. Checking access...")
141
- try:
142
- # Try a relatively safe operation to confirm object usability
143
- # Getting children count is a reasonable check
144
- _ = len(primary_project.get_children(False))
145
- print("DEBUG: Target project '%s' is primary and accessible." % target_project_path)
146
- project_ok = True
147
- return primary_project # SUCCESS CASE 1: Already open and accessible
148
- except Exception as access_err:
149
- # Project found, but accessing it failed. Might be unstable.
150
- print("WARN: Primary project access check failed for '%s': %s. Will attempt reopen." % (current_project_path, access_err))
151
- # traceback.print_exc() # Optional: Print stack trace
152
- primary_project = None # Force reopen by falling through
153
- else:
154
- # A *different* project is primary
155
- print("DEBUG: Primary project is '%s', not the target '%s'." % (current_project_path, normalized_target_path))
156
- # Consider closing the wrong project if causing issues, but for now, just open target
157
- # try:
158
- # print("DEBUG: Closing incorrect primary project '%s'..." % current_project_path)
159
- # primary_project.close() # Be careful with unsaved changes
160
- # except Exception as close_err:
161
- # print("WARN: Failed to close incorrect primary project: %s" % close_err)
162
- primary_project = None # Force open target project
163
-
164
- except Exception as path_err:
165
- # Failed even to get the path of the supposed primary project
166
- print("WARN: Could not get path of current primary project: %s. Assuming not the target." % path_err)
167
- # traceback.print_exc() # Optional: Print stack trace
168
- primary_project = None # Force open target project
169
-
170
- # If target project not confirmed as primary and accessible, attempt to open/reopen
171
- if not project_ok:
172
- # Log clearly whether we are opening initially or reopening
173
- if primary_project is None and current_project_path == "":
174
- print("DEBUG: No primary project detected. Attempting to open target: %s" % target_project_path)
175
- elif primary_project is None and current_project_path != "":
176
- print("DEBUG: Primary project was '%s' but failed access check or needed close. Attempting to open target: %s" % (current_project_path, target_project_path))
177
- else: # Includes cases where wrong project was open
178
- print("DEBUG: Target project not primary or initial check failed. Attempting to open/reopen: %s" % target_project_path)
179
-
180
- try:
181
- # Set flags for silent opening, handle potential attribute errors
182
- update_mode = script_engine.VersionUpdateFlags.NoUpdates | script_engine.VersionUpdateFlags.SilentMode
183
- # try:
184
- # update_mode = script_engine.VersionUpdateFlags.NoUpdates | script_engine.VersionUpdateFlags.SilentMode
185
- # except AttributeError:
186
- # print("WARN: VersionUpdateFlags not found, using integer flags for open (1 | 2 = 3).")
187
- # update_mode = 3 # 1=NoUpdates, 2=SilentMode
188
-
189
- opened_project = None
190
- try:
191
- # The actual open call
192
- print("DEBUG: Calling script_engine.projects.open('%s', update_flags=%s)..." % (target_project_path, update_mode))
193
- opened_project = script_engine.projects.open(target_project_path, update_flags=update_mode)
194
-
195
- if not opened_project:
196
- # This is a critical failure if open returns None without exception
197
- print("ERROR: projects.open returned None for %s on attempt %d" % (target_project_path, attempt + 1))
198
- # Allow retry loop to continue
199
- else:
200
- # Open call returned *something*, let's verify
201
- print("DEBUG: projects.open call returned an object for: %s" % target_project_path)
202
- print("DEBUG: Pausing for stabilization after open...")
203
- time.sleep(RETRY_DELAY) # Give CODESYS time
204
- # Re-verify: Is the project now primary and accessible?
205
- recheck_primary = None
206
- try: recheck_primary = script_engine.projects.primary
207
- except Exception as recheck_primary_err: print("WARN: Error getting primary project after reopen: %s" % recheck_primary_err)
208
-
209
- if recheck_primary:
210
- recheck_path = ""
211
- try: # Getting path might fail
212
- recheck_path = os.path.normcase(os.path.abspath(recheck_primary.path))
213
- except Exception as recheck_path_err:
214
- print("WARN: Failed to get path after reopen: %s" % recheck_path_err)
215
-
216
- if recheck_path == normalized_target_path:
217
- print("DEBUG: Target project confirmed as primary after reopening.")
218
- try: # Final sanity check
219
- _ = len(recheck_primary.get_children(False))
220
- print("DEBUG: Reopened project basic access confirmed.")
221
- return recheck_primary # SUCCESS CASE 2: Successfully opened/reopened
222
- except Exception as access_err_reopen:
223
- print("WARN: Reopened project (%s) basic access check failed: %s." % (normalized_target_path, access_err_reopen))
224
- # traceback.print_exc() # Optional
225
- # Allow retry loop to continue
226
- else:
227
- print("WARN: Different project is primary after reopening! Expected '%s', got '%s'." % (normalized_target_path, recheck_path))
228
- # Allow retry loop to continue, maybe it fixes itself
229
- else:
230
- print("WARN: No primary project found after reopening attempt %d!" % (attempt+1))
231
- # Allow retry loop to continue
232
-
233
- except Exception as open_err:
234
- # Catch errors during the open call itself
235
- print("ERROR: Exception during projects.open call on attempt %d: %s" % (attempt + 1, open_err))
236
- traceback.print_exc() # Crucial for diagnosing open failures
237
- # Allow retry loop to continue
238
-
239
- except Exception as outer_open_err:
240
- # Catch errors in the flag setup etc.
241
- print("ERROR: Unexpected error during open setup/logic attempt %d: %s" % (attempt + 1, outer_open_err))
242
- traceback.print_exc()
243
-
244
- # If we didn't return successfully in this attempt, wait before retrying
245
- if attempt < MAX_RETRIES - 1:
246
- print("DEBUG: Ensure project attempt %d did not succeed. Waiting %f seconds..." % (attempt + 1, RETRY_DELAY))
247
- time.sleep(RETRY_DELAY)
248
- else: # Last attempt failed
249
- print("ERROR: Failed all ensure_project_open attempts for %s." % normalized_target_path)
250
-
251
-
252
- # If all retries fail after the loop
253
- raise RuntimeError("Failed to ensure project '%s' is open and accessible after %d attempts." % (target_project_path, MAX_RETRIES))
254
- # --- End of function ---
255
-
256
- # Placeholder for the project file path (must be set in scripts using this snippet)
257
- PROJECT_FILE_PATH = r"{PROJECT_FILE_PATH}"
118
+ const ENSURE_PROJECT_OPEN_PYTHON_SNIPPET = `
119
+ import sys
120
+ import scriptengine as script_engine
121
+ import os
122
+ import time
123
+ import traceback
124
+
125
+ # --- Function to ensure the correct project is open ---
126
+ MAX_RETRIES = 3
127
+ RETRY_DELAY = 2.0 # seconds (use float for time.sleep)
128
+
129
+ def ensure_project_open(target_project_path):
130
+ print("DEBUG: Ensuring project is open: %s" % target_project_path)
131
+ # Normalize target path once
132
+ normalized_target_path = os.path.normcase(os.path.abspath(target_project_path))
133
+
134
+ for attempt in range(MAX_RETRIES):
135
+ print("DEBUG: Ensure project attempt %d/%d for %s" % (attempt + 1, MAX_RETRIES, normalized_target_path))
136
+ primary_project = None
137
+ try:
138
+ # Getting primary project might fail if CODESYS instance is unstable
139
+ primary_project = script_engine.projects.primary
140
+ except Exception as primary_err:
141
+ print("WARN: Error getting primary project: %s. Assuming none." % primary_err)
142
+ # traceback.print_exc() # Optional: Print stack trace for this error
143
+ primary_project = None
144
+
145
+ current_project_path = ""
146
+ project_ok = False # Flag to check if target is confirmed primary and accessible
147
+
148
+ if primary_project:
149
+ try:
150
+ # Getting path should be relatively safe if primary_project object exists
151
+ current_project_path = os.path.normcase(os.path.abspath(primary_project.path))
152
+ print("DEBUG: Current primary project path: %s" % current_project_path)
153
+ if current_project_path == normalized_target_path:
154
+ # Found the right project as primary, now check if it's usable
155
+ print("DEBUG: Target project path matches primary. Checking access...")
156
+ try:
157
+ # Try a relatively safe operation to confirm object usability
158
+ # Getting children count is a reasonable check
159
+ _ = len(primary_project.get_children(False))
160
+ print("DEBUG: Target project '%s' is primary and accessible." % target_project_path)
161
+ project_ok = True
162
+ return primary_project # SUCCESS CASE 1: Already open and accessible
163
+ except Exception as access_err:
164
+ # Project found, but accessing it failed. Might be unstable.
165
+ print("WARN: Primary project access check failed for '%s': %s. Will attempt reopen." % (current_project_path, access_err))
166
+ # traceback.print_exc() # Optional: Print stack trace
167
+ primary_project = None # Force reopen by falling through
168
+ else:
169
+ # A *different* project is primary
170
+ print("DEBUG: Primary project is '%s', not the target '%s'." % (current_project_path, normalized_target_path))
171
+ # Consider closing the wrong project if causing issues, but for now, just open target
172
+ # try:
173
+ # print("DEBUG: Closing incorrect primary project '%s'..." % current_project_path)
174
+ # primary_project.close() # Be careful with unsaved changes
175
+ # except Exception as close_err:
176
+ # print("WARN: Failed to close incorrect primary project: %s" % close_err)
177
+ primary_project = None # Force open target project
178
+
179
+ except Exception as path_err:
180
+ # Failed even to get the path of the supposed primary project
181
+ print("WARN: Could not get path of current primary project: %s. Assuming not the target." % path_err)
182
+ # traceback.print_exc() # Optional: Print stack trace
183
+ primary_project = None # Force open target project
184
+
185
+ # If target project not confirmed as primary and accessible, attempt to open/reopen
186
+ if not project_ok:
187
+ # Log clearly whether we are opening initially or reopening
188
+ if primary_project is None and current_project_path == "":
189
+ print("DEBUG: No primary project detected. Attempting to open target: %s" % target_project_path)
190
+ elif primary_project is None and current_project_path != "":
191
+ print("DEBUG: Primary project was '%s' but failed access check or needed close. Attempting to open target: %s" % (current_project_path, target_project_path))
192
+ else: # Includes cases where wrong project was open
193
+ print("DEBUG: Target project not primary or initial check failed. Attempting to open/reopen: %s" % target_project_path)
194
+
195
+ try:
196
+ # Set flags for silent opening, handle potential attribute errors
197
+ update_mode = script_engine.VersionUpdateFlags.NoUpdates | script_engine.VersionUpdateFlags.SilentMode
198
+ # try:
199
+ # update_mode = script_engine.VersionUpdateFlags.NoUpdates | script_engine.VersionUpdateFlags.SilentMode
200
+ # except AttributeError:
201
+ # print("WARN: VersionUpdateFlags not found, using integer flags for open (1 | 2 = 3).")
202
+ # update_mode = 3 # 1=NoUpdates, 2=SilentMode
203
+
204
+ opened_project = None
205
+ try:
206
+ # The actual open call
207
+ print("DEBUG: Calling script_engine.projects.open('%s', update_flags=%s)..." % (target_project_path, update_mode))
208
+ opened_project = script_engine.projects.open(target_project_path, update_flags=update_mode)
209
+
210
+ if not opened_project:
211
+ # This is a critical failure if open returns None without exception
212
+ print("ERROR: projects.open returned None for %s on attempt %d" % (target_project_path, attempt + 1))
213
+ # Allow retry loop to continue
214
+ else:
215
+ # Open call returned *something*, let's verify
216
+ print("DEBUG: projects.open call returned an object for: %s" % target_project_path)
217
+ print("DEBUG: Pausing for stabilization after open...")
218
+ time.sleep(RETRY_DELAY) # Give CODESYS time
219
+ # Re-verify: Is the project now primary and accessible?
220
+ recheck_primary = None
221
+ try: recheck_primary = script_engine.projects.primary
222
+ except Exception as recheck_primary_err: print("WARN: Error getting primary project after reopen: %s" % recheck_primary_err)
223
+
224
+ if recheck_primary:
225
+ recheck_path = ""
226
+ try: # Getting path might fail
227
+ recheck_path = os.path.normcase(os.path.abspath(recheck_primary.path))
228
+ except Exception as recheck_path_err:
229
+ print("WARN: Failed to get path after reopen: %s" % recheck_path_err)
230
+
231
+ if recheck_path == normalized_target_path:
232
+ print("DEBUG: Target project confirmed as primary after reopening.")
233
+ try: # Final sanity check
234
+ _ = len(recheck_primary.get_children(False))
235
+ print("DEBUG: Reopened project basic access confirmed.")
236
+ return recheck_primary # SUCCESS CASE 2: Successfully opened/reopened
237
+ except Exception as access_err_reopen:
238
+ print("WARN: Reopened project (%s) basic access check failed: %s." % (normalized_target_path, access_err_reopen))
239
+ # traceback.print_exc() # Optional
240
+ # Allow retry loop to continue
241
+ else:
242
+ print("WARN: Different project is primary after reopening! Expected '%s', got '%s'." % (normalized_target_path, recheck_path))
243
+ # Allow retry loop to continue, maybe it fixes itself
244
+ else:
245
+ print("WARN: No primary project found after reopening attempt %d!" % (attempt+1))
246
+ # Allow retry loop to continue
247
+
248
+ except Exception as open_err:
249
+ # Catch errors during the open call itself
250
+ print("ERROR: Exception during projects.open call on attempt %d: %s" % (attempt + 1, open_err))
251
+ traceback.print_exc() # Crucial for diagnosing open failures
252
+ # Allow retry loop to continue
253
+
254
+ except Exception as outer_open_err:
255
+ # Catch errors in the flag setup etc.
256
+ print("ERROR: Unexpected error during open setup/logic attempt %d: %s" % (attempt + 1, outer_open_err))
257
+ traceback.print_exc()
258
+
259
+ # If we didn't return successfully in this attempt, wait before retrying
260
+ if attempt < MAX_RETRIES - 1:
261
+ print("DEBUG: Ensure project attempt %d did not succeed. Waiting %f seconds..." % (attempt + 1, RETRY_DELAY))
262
+ time.sleep(RETRY_DELAY)
263
+ else: # Last attempt failed
264
+ print("ERROR: Failed all ensure_project_open attempts for %s." % normalized_target_path)
265
+
266
+
267
+ # If all retries fail after the loop
268
+ raise RuntimeError("Failed to ensure project '%s' is open and accessible after %d attempts." % (target_project_path, MAX_RETRIES))
269
+ # --- End of function ---
270
+
271
+ # Placeholder for the project file path (must be set in scripts using this snippet)
272
+ PROJECT_FILE_PATH = r"{PROJECT_FILE_PATH}"
258
273
  `;
259
274
  // (CHECK_STATUS_SCRIPT remains the same)
260
- const CHECK_STATUS_SCRIPT = `
261
- import sys, scriptengine as script_engine, os, traceback
262
- project_open = False; project_name = "No project open"; project_path = "N/A"; scripting_ok = False
263
- try:
264
- scripting_ok = True; primary_project = script_engine.projects.primary
265
- if primary_project:
266
- project_open = True
267
- try:
268
- project_path = os.path.normcase(os.path.abspath(primary_project.path))
269
- try:
270
- project_name = primary_project.get_name() # Might fail
271
- if not project_name: project_name = "Unnamed (path: %s)" % os.path.basename(project_path)
272
- except: project_name = "Unnamed (path: %s)" % os.path.basename(project_path)
273
- except Exception as e_path: project_path = "N/A (Error: %s)" % e_path; project_name = "Unnamed (Path Error)"
274
- print("Project Open: %s" % project_open); print("Project Name: %s" % project_name)
275
- print("Project Path: %s" % project_path); print("Scripting OK: %s" % scripting_ok)
276
- print("SCRIPT_SUCCESS: Status check complete."); sys.exit(0)
277
- except Exception as e:
278
- error_message = "Error during status check: %s" % e
279
- print(error_message); print("Scripting OK: False")
280
- # traceback.print_exc() # Optional traceback
281
- print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
275
+ const CHECK_STATUS_SCRIPT = `
276
+ import sys, scriptengine as script_engine, os, traceback
277
+ project_open = False; project_name = "No project open"; project_path = "N/A"; scripting_ok = False
278
+ try:
279
+ scripting_ok = True; primary_project = script_engine.projects.primary
280
+ if primary_project:
281
+ project_open = True
282
+ try:
283
+ project_path = os.path.normcase(os.path.abspath(primary_project.path))
284
+ try:
285
+ project_name = primary_project.get_name() # Might fail
286
+ if not project_name: project_name = "Unnamed (path: %s)" % os.path.basename(project_path)
287
+ except: project_name = "Unnamed (path: %s)" % os.path.basename(project_path)
288
+ except Exception as e_path: project_path = "N/A (Error: %s)" % e_path; project_name = "Unnamed (Path Error)"
289
+ print("Project Open: %s" % project_open); print("Project Name: %s" % project_name)
290
+ print("Project Path: %s" % project_path); print("Scripting OK: %s" % scripting_ok)
291
+ print("SCRIPT_SUCCESS: Status check complete."); sys.exit(0)
292
+ except Exception as e:
293
+ error_message = "Error during status check: %s" % e
294
+ print(error_message); print("Scripting OK: False")
295
+ # traceback.print_exc() # Optional traceback
296
+ print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
282
297
  `;
283
298
  // (OPEN_PROJECT_SCRIPT_TEMPLATE remains the same)
284
- const OPEN_PROJECT_SCRIPT_TEMPLATE = `
285
- import sys, scriptengine as script_engine, os, traceback
286
- ${ENSURE_PROJECT_OPEN_PYTHON_SNIPPET}
287
- try:
288
- project = ensure_project_open(PROJECT_FILE_PATH)
289
- # Get name from object if possible, otherwise use path basename
290
- proj_name = "Unknown"
291
- try:
292
- if project: proj_name = project.get_name() or os.path.basename(PROJECT_FILE_PATH)
293
- else: proj_name = os.path.basename(PROJECT_FILE_PATH) + " (ensure_project_open returned None?)"
294
- except Exception:
295
- proj_name = os.path.basename(PROJECT_FILE_PATH) + " (name retrieval failed)"
296
- print("Project Opened: %s" % proj_name)
297
- print("SCRIPT_SUCCESS: Project opened successfully.")
298
- sys.exit(0)
299
- except Exception as e:
300
- error_message = "Error opening project %s: %s" % (PROJECT_FILE_PATH, e)
301
- print(error_message)
302
- traceback.print_exc()
303
- print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
299
+ const OPEN_PROJECT_SCRIPT_TEMPLATE = `
300
+ import sys, scriptengine as script_engine, os, traceback
301
+ ${ENSURE_PROJECT_OPEN_PYTHON_SNIPPET}
302
+ try:
303
+ project = ensure_project_open(PROJECT_FILE_PATH)
304
+ # Get name from object if possible, otherwise use path basename
305
+ proj_name = "Unknown"
306
+ try:
307
+ if project: proj_name = project.get_name() or os.path.basename(PROJECT_FILE_PATH)
308
+ else: proj_name = os.path.basename(PROJECT_FILE_PATH) + " (ensure_project_open returned None?)"
309
+ except Exception:
310
+ proj_name = os.path.basename(PROJECT_FILE_PATH) + " (name retrieval failed)"
311
+ print("Project Opened: %s" % proj_name)
312
+ print("SCRIPT_SUCCESS: Project opened successfully.")
313
+ sys.exit(0)
314
+ except Exception as e:
315
+ error_message = "Error opening project %s: %s" % (PROJECT_FILE_PATH, e)
316
+ print(error_message)
317
+ traceback.print_exc()
318
+ print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
304
319
  `;
305
320
  // (CREATE_PROJECT_SCRIPT_TEMPLATE remains the same)
306
- const CREATE_PROJECT_SCRIPT_TEMPLATE = `
307
- import sys, scriptengine as script_engine, os, shutil, time, traceback
308
- # Placeholders
309
- TEMPLATE_PROJECT_PATH = r'{TEMPLATE_PROJECT_PATH}' # Path to Standard.project
310
- PROJECT_FILE_PATH = r'{PROJECT_FILE_PATH}' # Path for the new project (Target Path)
311
- try:
312
- print("DEBUG: Python script create_project (copy from template):")
313
- print("DEBUG: Template Source = %s" % TEMPLATE_PROJECT_PATH)
314
- print("DEBUG: Target Path = %s" % PROJECT_FILE_PATH)
315
- if not PROJECT_FILE_PATH: raise ValueError("Target project file path empty.")
316
- if not TEMPLATE_PROJECT_PATH: raise ValueError("Template project file path empty.")
317
- if not os.path.exists(TEMPLATE_PROJECT_PATH): raise IOError("Template project file not found: %s" % TEMPLATE_PROJECT_PATH)
318
-
319
- # 1. Copy the template project file to the new location
320
- target_dir = os.path.dirname(PROJECT_FILE_PATH)
321
- if not os.path.exists(target_dir): print("DEBUG: Creating target directory: %s" % target_dir); os.makedirs(target_dir)
322
- # Check if target file already exists
323
- if os.path.exists(PROJECT_FILE_PATH): print("WARN: Target project file already exists, overwriting: %s" % PROJECT_FILE_PATH)
324
-
325
- print("DEBUG: Copying '%s' to '%s'..." % (TEMPLATE_PROJECT_PATH, PROJECT_FILE_PATH))
326
- shutil.copy2(TEMPLATE_PROJECT_PATH, PROJECT_FILE_PATH) # copy2 preserves metadata
327
- print("DEBUG: File copy complete.")
328
-
329
- # 2. Open the newly copied project file
330
- print("DEBUG: Opening the copied project: %s" % PROJECT_FILE_PATH)
331
- # Set flags for silent opening
332
- update_mode = script_engine.VersionUpdateFlags.NoUpdates | script_engine.VersionUpdateFlags.SilentMode
333
- # try:
334
- # update_mode = script_engine.VersionUpdateFlags.NoUpdates | script_engine.VersionUpdateFlags.SilentMode
335
- # except AttributeError:
336
- # print("WARN: VersionUpdateFlags not found, using integer flags for open (1 | 2 = 3).")
337
- # update_mode = 3
338
-
339
- project = script_engine.projects.open(PROJECT_FILE_PATH, update_flags=update_mode)
340
- print("DEBUG: script_engine.projects.open returned: %s" % project)
341
- if project:
342
- print("DEBUG: Pausing briefly after open...")
343
- time.sleep(1.0) # Allow CODESYS to potentially initialize things
344
- try:
345
- print("DEBUG: Explicitly saving project after opening copy...")
346
- project.save();
347
- print("DEBUG: Project save after opening copy succeeded.")
348
- except Exception as save_err:
349
- print("WARN: Explicit save after opening copy failed: %s" % save_err)
350
- # Decide if this is critical - maybe not, but good to know.
351
- print("Project Created from Template Copy at: %s" % PROJECT_FILE_PATH)
352
- print("SCRIPT_SUCCESS: Project copied from template and opened successfully.")
353
- sys.exit(0)
354
- else:
355
- error_message = "Failed to open project copy %s after copying template %s. projects.open returned None." % (PROJECT_FILE_PATH, TEMPLATE_PROJECT_PATH)
356
- print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
357
- except Exception as e:
358
- detailed_error = traceback.format_exc()
359
- error_message = "Error creating project '%s' from template '%s': %s\\n%s" % (PROJECT_FILE_PATH, TEMPLATE_PROJECT_PATH, e, detailed_error)
360
- print(error_message); print("SCRIPT_ERROR: Error copying/opening template: %s" % e); sys.exit(1)
321
+ const CREATE_PROJECT_SCRIPT_TEMPLATE = `
322
+ import sys, scriptengine as script_engine, os, shutil, time, traceback
323
+ # Placeholders
324
+ TEMPLATE_PROJECT_PATH = r'{TEMPLATE_PROJECT_PATH}' # Path to Standard.project
325
+ PROJECT_FILE_PATH = r'{PROJECT_FILE_PATH}' # Path for the new project (Target Path)
326
+ try:
327
+ print("DEBUG: Python script create_project (copy from template):")
328
+ print("DEBUG: Template Source = %s" % TEMPLATE_PROJECT_PATH)
329
+ print("DEBUG: Target Path = %s" % PROJECT_FILE_PATH)
330
+ if not PROJECT_FILE_PATH: raise ValueError("Target project file path empty.")
331
+ if not TEMPLATE_PROJECT_PATH: raise ValueError("Template project file path empty.")
332
+ if not os.path.exists(TEMPLATE_PROJECT_PATH): raise IOError("Template project file not found: %s" % TEMPLATE_PROJECT_PATH)
333
+
334
+ # 1. Copy the template project file to the new location
335
+ target_dir = os.path.dirname(PROJECT_FILE_PATH)
336
+ if not os.path.exists(target_dir): print("DEBUG: Creating target directory: %s" % target_dir); os.makedirs(target_dir)
337
+ # Check if target file already exists
338
+ if os.path.exists(PROJECT_FILE_PATH): print("WARN: Target project file already exists, overwriting: %s" % PROJECT_FILE_PATH)
339
+
340
+ print("DEBUG: Copying '%s' to '%s'..." % (TEMPLATE_PROJECT_PATH, PROJECT_FILE_PATH))
341
+ shutil.copy2(TEMPLATE_PROJECT_PATH, PROJECT_FILE_PATH) # copy2 preserves metadata
342
+ print("DEBUG: File copy complete.")
343
+
344
+ # 2. Open the newly copied project file
345
+ print("DEBUG: Opening the copied project: %s" % PROJECT_FILE_PATH)
346
+ # Set flags for silent opening
347
+ update_mode = script_engine.VersionUpdateFlags.NoUpdates | script_engine.VersionUpdateFlags.SilentMode
348
+ # try:
349
+ # update_mode = script_engine.VersionUpdateFlags.NoUpdates | script_engine.VersionUpdateFlags.SilentMode
350
+ # except AttributeError:
351
+ # print("WARN: VersionUpdateFlags not found, using integer flags for open (1 | 2 = 3).")
352
+ # update_mode = 3
353
+
354
+ project = script_engine.projects.open(PROJECT_FILE_PATH, update_flags=update_mode)
355
+ print("DEBUG: script_engine.projects.open returned: %s" % project)
356
+ if project:
357
+ print("DEBUG: Pausing briefly after open...")
358
+ time.sleep(1.0) # Allow CODESYS to potentially initialize things
359
+ try:
360
+ print("DEBUG: Explicitly saving project after opening copy...")
361
+ project.save();
362
+ print("DEBUG: Project save after opening copy succeeded.")
363
+ except Exception as save_err:
364
+ print("WARN: Explicit save after opening copy failed: %s" % save_err)
365
+ # Decide if this is critical - maybe not, but good to know.
366
+ print("Project Created from Template Copy at: %s" % PROJECT_FILE_PATH)
367
+ print("SCRIPT_SUCCESS: Project copied from template and opened successfully.")
368
+ sys.exit(0)
369
+ else:
370
+ error_message = "Failed to open project copy %s after copying template %s. projects.open returned None." % (PROJECT_FILE_PATH, TEMPLATE_PROJECT_PATH)
371
+ print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
372
+ except Exception as e:
373
+ detailed_error = traceback.format_exc()
374
+ error_message = "Error creating project '%s' from template '%s': %s\\n%s" % (PROJECT_FILE_PATH, TEMPLATE_PROJECT_PATH, e, detailed_error)
375
+ print(error_message); print("SCRIPT_ERROR: Error copying/opening template: %s" % e); sys.exit(1)
361
376
  `;
362
377
  // (SAVE_PROJECT_SCRIPT_TEMPLATE remains the same)
363
- const SAVE_PROJECT_SCRIPT_TEMPLATE = `
364
- import sys, scriptengine as script_engine, os, traceback
365
- ${ENSURE_PROJECT_OPEN_PYTHON_SNIPPET}
366
- try:
367
- primary_project = ensure_project_open(PROJECT_FILE_PATH)
368
- # Get name from object if possible, otherwise use path basename
369
- project_name = "Unknown"
370
- try:
371
- if primary_project: project_name = primary_project.get_name() or os.path.basename(PROJECT_FILE_PATH)
372
- else: project_name = os.path.basename(PROJECT_FILE_PATH) + " (ensure_project_open returned None?)"
373
- except Exception:
374
- project_name = os.path.basename(PROJECT_FILE_PATH) + " (name retrieval failed)"
375
-
376
- print("DEBUG: Saving project: %s (%s)" % (project_name, PROJECT_FILE_PATH))
377
- primary_project.save()
378
- print("DEBUG: project.save() executed.")
379
- print("Project Saved: %s" % project_name)
380
- print("SCRIPT_SUCCESS: Project saved successfully.")
381
- sys.exit(0)
382
- except Exception as e:
383
- error_message = "Error saving project %s: %s" % (PROJECT_FILE_PATH, e)
384
- print(error_message)
385
- traceback.print_exc()
386
- print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
378
+ const SAVE_PROJECT_SCRIPT_TEMPLATE = `
379
+ import sys, scriptengine as script_engine, os, traceback
380
+ ${ENSURE_PROJECT_OPEN_PYTHON_SNIPPET}
381
+ try:
382
+ primary_project = ensure_project_open(PROJECT_FILE_PATH)
383
+ # Get name from object if possible, otherwise use path basename
384
+ project_name = "Unknown"
385
+ try:
386
+ if primary_project: project_name = primary_project.get_name() or os.path.basename(PROJECT_FILE_PATH)
387
+ else: project_name = os.path.basename(PROJECT_FILE_PATH) + " (ensure_project_open returned None?)"
388
+ except Exception:
389
+ project_name = os.path.basename(PROJECT_FILE_PATH) + " (name retrieval failed)"
390
+
391
+ print("DEBUG: Saving project: %s (%s)" % (project_name, PROJECT_FILE_PATH))
392
+ primary_project.save()
393
+ print("DEBUG: project.save() executed.")
394
+ print("Project Saved: %s" % project_name)
395
+ print("SCRIPT_SUCCESS: Project saved successfully.")
396
+ sys.exit(0)
397
+ except Exception as e:
398
+ error_message = "Error saving project %s: %s" % (PROJECT_FILE_PATH, e)
399
+ print(error_message)
400
+ traceback.print_exc()
401
+ print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
387
402
  `;
388
403
  const PouTypeEnum = zod_1.z.enum(["Program", "FunctionBlock", "Function"]);
389
404
  const ImplementationLanguageEnum = zod_1.z.enum(["ST", "LD", "FBD", "SFC", "IL", "CFC", "StructuredText", "LadderDiagram", "FunctionBlockDiagram", "SequentialFunctionChart", "InstructionList", "ContinuousFunctionChart"]);
390
405
  // --- Path finding function (used by multiple templates) ---
391
- const FIND_OBJECT_BY_PATH_PYTHON_SNIPPET = `
392
- import traceback
393
- # --- Find object by path function ---
394
- def find_object_by_path_robust(start_node, full_path, target_type_name="object"):
395
- print("DEBUG: Finding %s by path: '%s'" % (target_type_name, full_path))
396
- normalized_path = full_path.replace('\\\\', '/').strip('/')
397
- path_parts = normalized_path.split('/')
398
- if not path_parts:
399
- print("ERROR: Path is empty.")
400
- return None
401
-
402
- # Determine the actual starting node (project or application)
403
- project = start_node # Assume start_node is project initially
404
- if not hasattr(start_node, 'active_application') and hasattr(start_node, 'project'):
405
- # If start_node is not project but has project ref (e.g., an application), get the project
406
- try: project = start_node.project
407
- except Exception as proj_ref_err:
408
- print("WARN: Could not get project reference from start_node: %s" % proj_ref_err)
409
- # Proceed assuming start_node might be the project anyway or search fails
410
-
411
- # Try to get the application object robustly if we think we have the project
412
- app = None
413
- if hasattr(project, 'active_application'):
414
- try: app = project.active_application
415
- except Exception: pass # Ignore errors getting active app
416
- if not app:
417
- try:
418
- apps = project.find("Application", True) # Search recursively
419
- if apps: app = apps[0]
420
- except Exception: pass
421
-
422
- # Check if the first path part matches the application name
423
- app_name_lower = ""
424
- if app:
425
- try: app_name_lower = (app.get_name() or "application").lower()
426
- except Exception: app_name_lower = "application" # Fallback
427
-
428
- # Decide where to start the traversal
429
- current_obj = start_node # Default to the node passed in
430
- if hasattr(project, 'active_application'): # Only adjust if start_node was likely the project
431
- if app and path_parts[0].lower() == app_name_lower:
432
- print("DEBUG: Path starts with Application name '%s'. Beginning search there." % path_parts[0])
433
- current_obj = app
434
- path_parts = path_parts[1:] # Consume the app name part
435
- # If path was *only* the application name
436
- if not path_parts:
437
- print("DEBUG: Target path is the Application object itself.")
438
- return current_obj
439
- else:
440
- print("DEBUG: Path does not start with Application name. Starting search from project root.")
441
- current_obj = project # Start search from the project root
442
- else:
443
- print("DEBUG: Starting search from originally provided node.")
444
-
445
-
446
- # Traverse the remaining path parts
447
- parent_path_str = getattr(current_obj, 'get_name', lambda: str(current_obj))() # Safer name getting
448
-
449
- for i, part_name in enumerate(path_parts):
450
- is_last_part = (i == len(path_parts) - 1)
451
- print("DEBUG: Searching for part [%d/%d]: '%s' under '%s'" % (i+1, len(path_parts), part_name, parent_path_str))
452
- found_in_parent = None
453
- try:
454
- # Prioritize non-recursive find for direct children
455
- children_of_current = current_obj.get_children(False)
456
- print("DEBUG: Found %d direct children under '%s'." % (len(children_of_current), parent_path_str))
457
- for child in children_of_current:
458
- child_name = getattr(child, 'get_name', lambda: None)() # Safer name getting
459
- # print("DEBUG: Checking child: '%s'" % child_name) # Verbose
460
- if child_name == part_name:
461
- found_in_parent = child
462
- print("DEBUG: Found direct child matching '%s'." % part_name)
463
- break # Found direct child, stop searching children
464
-
465
- # If not found directly, AND it's the last part, try recursive find from current parent
466
- if not found_in_parent and is_last_part:
467
- print("DEBUG: Direct find failed for last part '%s'. Trying recursive find under '%s'." % (part_name, parent_path_str))
468
- found_recursive_list = current_obj.find(part_name, True) # Recursive find
469
- if found_recursive_list:
470
- # Maybe add a check here if multiple are found?
471
- found_in_parent = found_recursive_list[0] # Take the first match
472
- print("DEBUG: Found last part '%s' recursively." % part_name)
473
- else:
474
- print("DEBUG: Recursive find also failed for last part '%s'." % part_name)
475
-
476
- # Update current object if found
477
- if found_in_parent:
478
- current_obj = found_in_parent
479
- parent_path_str = getattr(current_obj, 'get_name', lambda: part_name)() # Safer name getting
480
- print("DEBUG: Stepped into '%s'." % parent_path_str)
481
- else:
482
- # If not found at any point, the path is invalid from this parent
483
- print("ERROR: Path part '%s' not found under '%s'." % (part_name, parent_path_str))
484
- return None # Path broken
485
-
486
- except Exception as find_err:
487
- print("ERROR: Exception while searching for '%s' under '%s': %s" % (part_name, parent_path_str, find_err))
488
- traceback.print_exc()
489
- return None # Error during search
490
-
491
- # Final verification (optional but recommended): Check if the found object's name matches the last part
492
- final_expected_name = full_path.split('/')[-1]
493
- found_final_name = getattr(current_obj, 'get_name', lambda: None)() # Safer name getting
494
-
495
- if found_final_name == final_expected_name:
496
- print("DEBUG: Final %s found and name verified for path '%s': %s" % (target_type_name, full_path, found_final_name))
497
- return current_obj
498
- else:
499
- print("ERROR: Traversal ended on object '%s' but expected final name was '%s'." % (found_final_name, final_expected_name))
500
- return None # Name mismatch implies target not found as expected
501
-
502
- # --- End of find object function ---
406
+ const FIND_OBJECT_BY_PATH_PYTHON_SNIPPET = `
407
+ import traceback
408
+ # --- Find object by path function ---
409
+ def find_object_by_path_robust(start_node, full_path, target_type_name="object"):
410
+ print("DEBUG: Finding %s by path: '%s'" % (target_type_name, full_path))
411
+ normalized_path = full_path.replace('\\\\', '/').strip('/')
412
+ path_parts = normalized_path.split('/')
413
+ if not path_parts:
414
+ print("ERROR: Path is empty.")
415
+ return None
416
+
417
+ # Determine the actual starting node (project or application)
418
+ project = start_node # Assume start_node is project initially
419
+ if not hasattr(start_node, 'active_application') and hasattr(start_node, 'project'):
420
+ # If start_node is not project but has project ref (e.g., an application), get the project
421
+ try: project = start_node.project
422
+ except Exception as proj_ref_err:
423
+ print("WARN: Could not get project reference from start_node: %s" % proj_ref_err)
424
+ # Proceed assuming start_node might be the project anyway or search fails
425
+
426
+ # Try to get the application object robustly if we think we have the project
427
+ app = None
428
+ if hasattr(project, 'active_application'):
429
+ try: app = project.active_application
430
+ except Exception: pass # Ignore errors getting active app
431
+ if not app:
432
+ try:
433
+ apps = project.find("Application", True) # Search recursively
434
+ if apps: app = apps[0]
435
+ except Exception: pass
436
+
437
+ # Check if the first path part matches the application name
438
+ app_name_lower = ""
439
+ if app:
440
+ try: app_name_lower = (app.get_name() or "application").lower()
441
+ except Exception: app_name_lower = "application" # Fallback
442
+
443
+ # Decide where to start the traversal
444
+ current_obj = start_node # Default to the node passed in
445
+ if hasattr(project, 'active_application'): # Only adjust if start_node was likely the project
446
+ if app and path_parts[0].lower() == app_name_lower:
447
+ print("DEBUG: Path starts with Application name '%s'. Beginning search there." % path_parts[0])
448
+ current_obj = app
449
+ path_parts = path_parts[1:] # Consume the app name part
450
+ # If path was *only* the application name
451
+ if not path_parts:
452
+ print("DEBUG: Target path is the Application object itself.")
453
+ return current_obj
454
+ else:
455
+ print("DEBUG: Path does not start with Application name. Starting search from project root.")
456
+ current_obj = project # Start search from the project root
457
+ else:
458
+ print("DEBUG: Starting search from originally provided node.")
459
+
460
+
461
+ # Traverse the remaining path parts
462
+ parent_path_str = getattr(current_obj, 'get_name', lambda: str(current_obj))() # Safer name getting
463
+
464
+ for i, part_name in enumerate(path_parts):
465
+ is_last_part = (i == len(path_parts) - 1)
466
+ print("DEBUG: Searching for part [%d/%d]: '%s' under '%s'" % (i+1, len(path_parts), part_name, parent_path_str))
467
+ found_in_parent = None
468
+ try:
469
+ # Prioritize non-recursive find for direct children
470
+ children_of_current = current_obj.get_children(False)
471
+ print("DEBUG: Found %d direct children under '%s'." % (len(children_of_current), parent_path_str))
472
+ for child in children_of_current:
473
+ child_name = getattr(child, 'get_name', lambda: None)() # Safer name getting
474
+ # print("DEBUG: Checking child: '%s'" % child_name) # Verbose
475
+ if child_name == part_name:
476
+ found_in_parent = child
477
+ print("DEBUG: Found direct child matching '%s'." % part_name)
478
+ break # Found direct child, stop searching children
479
+
480
+ # If not found directly, AND it's the last part, try recursive find from current parent
481
+ if not found_in_parent and is_last_part:
482
+ print("DEBUG: Direct find failed for last part '%s'. Trying recursive find under '%s'." % (part_name, parent_path_str))
483
+ found_recursive_list = current_obj.find(part_name, True) # Recursive find
484
+ if found_recursive_list:
485
+ # Maybe add a check here if multiple are found?
486
+ found_in_parent = found_recursive_list[0] # Take the first match
487
+ print("DEBUG: Found last part '%s' recursively." % part_name)
488
+ else:
489
+ print("DEBUG: Recursive find also failed for last part '%s'." % part_name)
490
+
491
+ # Update current object if found
492
+ if found_in_parent:
493
+ current_obj = found_in_parent
494
+ parent_path_str = getattr(current_obj, 'get_name', lambda: part_name)() # Safer name getting
495
+ print("DEBUG: Stepped into '%s'." % parent_path_str)
496
+ else:
497
+ # If not found at any point, the path is invalid from this parent
498
+ print("ERROR: Path part '%s' not found under '%s'." % (part_name, parent_path_str))
499
+ return None # Path broken
500
+
501
+ except Exception as find_err:
502
+ print("ERROR: Exception while searching for '%s' under '%s': %s" % (part_name, parent_path_str, find_err))
503
+ traceback.print_exc()
504
+ return None # Error during search
505
+
506
+ # Final verification (optional but recommended): Check if the found object's name matches the last part
507
+ final_expected_name = full_path.split('/')[-1]
508
+ found_final_name = getattr(current_obj, 'get_name', lambda: None)() # Safer name getting
509
+
510
+ if found_final_name == final_expected_name:
511
+ print("DEBUG: Final %s found and name verified for path '%s': %s" % (target_type_name, full_path, found_final_name))
512
+ return current_obj
513
+ else:
514
+ print("ERROR: Traversal ended on object '%s' but expected final name was '%s'." % (found_final_name, final_expected_name))
515
+ return None # Name mismatch implies target not found as expected
516
+
517
+ # --- End of find object function ---
503
518
  `;
504
519
  // (CREATE_POU_SCRIPT_TEMPLATE uses FIND_OBJECT_BY_PATH_PYTHON_SNIPPET)
505
- const CREATE_POU_SCRIPT_TEMPLATE = `
506
- import sys, scriptengine as script_engine, os, traceback
507
- ${ENSURE_PROJECT_OPEN_PYTHON_SNIPPET}
508
- ${FIND_OBJECT_BY_PATH_PYTHON_SNIPPET}
509
- POU_NAME = "{POU_NAME}"; POU_TYPE_STR = "{POU_TYPE_STR}"; IMPL_LANGUAGE_STR = "{IMPL_LANGUAGE_STR}"; PARENT_PATH_REL = "{PARENT_PATH}"
510
- pou_type_map = { "Program": script_engine.PouType.Program, "FunctionBlock": script_engine.PouType.FunctionBlock, "Function": script_engine.PouType.Function }
511
- # Map common language names to ImplementationLanguages attributes if needed (optional, None usually works)
512
- # lang_map = { "ST": script_engine.ImplementationLanguage.st, ... }
513
-
514
- try:
515
- print("DEBUG: create_pou script: Name='%s', Type='%s', Lang='%s', ParentPath='%s', Project='%s'" % (POU_NAME, POU_TYPE_STR, IMPL_LANGUAGE_STR, PARENT_PATH_REL, PROJECT_FILE_PATH))
516
- primary_project = ensure_project_open(PROJECT_FILE_PATH)
517
- if not POU_NAME: raise ValueError("POU name empty.")
518
- if not PARENT_PATH_REL: raise ValueError("Parent path empty.")
519
-
520
- # Resolve POU Type Enum
521
- pou_type_enum = pou_type_map.get(POU_TYPE_STR)
522
- if not pou_type_enum: raise ValueError("Invalid POU type string: %s. Use Program, FunctionBlock, or Function." % POU_TYPE_STR)
523
-
524
- # Find parent object using the robust function
525
- parent_object = find_object_by_path_robust(primary_project, PARENT_PATH_REL, "parent container")
526
- if not parent_object: raise ValueError("Parent object not found for path: %s" % PARENT_PATH_REL)
527
-
528
- parent_name = getattr(parent_object, 'get_name', lambda: str(parent_object))()
529
- print("DEBUG: Using parent object: %s (Type: %s)" % (parent_name, type(parent_object).__name__))
530
-
531
- # Check if parent object supports creating POUs (should implement ScriptIecLanguageObjectContainer)
532
- if not hasattr(parent_object, 'create_pou'):
533
- raise TypeError("Parent object '%s' of type %s does not support create_pou." % (parent_name, type(parent_object).__name__))
534
-
535
- # Set language GUID to None (let CODESYS default based on parent/settings)
536
- lang_guid = None
537
- print("DEBUG: Setting language to None (will use default).")
538
- # Example if mapping language string: lang_guid = lang_map.get(IMPL_LANGUAGE_STR, None)
539
-
540
- print("DEBUG: Calling parent_object.create_pou: Name='%s', Type=%s, Lang=%s" % (POU_NAME, pou_type_enum, lang_guid))
541
-
542
- # Call create_pou using keyword arguments
543
- new_pou = parent_object.create_pou(
544
- name=POU_NAME,
545
- type=pou_type_enum,
546
- language=lang_guid # Pass None
547
- )
548
-
549
- print("DEBUG: parent_object.create_pou returned: %s" % new_pou)
550
- if new_pou:
551
- new_pou_name = getattr(new_pou, 'get_name', lambda: POU_NAME)()
552
- print("DEBUG: POU object created: %s" % new_pou_name)
553
-
554
- # --- SAVE THE PROJECT TO PERSIST THE NEW POU ---
555
- try:
556
- print("DEBUG: Saving Project...")
557
- primary_project.save() # Save the overall project file
558
- print("DEBUG: Project saved successfully after POU creation.")
559
- except Exception as save_err:
560
- print("ERROR: Failed to save Project after POU creation: %s" % save_err)
561
- detailed_error = traceback.format_exc()
562
- error_message = "Error saving Project after creating POU '%s': %s\\n%s" % (new_pou_name, save_err, detailed_error)
563
- print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
564
- # --- END SAVING ---
565
-
566
- print("POU Created: %s" % new_pou_name); print("Type: %s" % POU_TYPE_STR); print("Language: %s (Defaulted)" % IMPL_LANGUAGE_STR); print("Parent Path: %s" % PARENT_PATH_REL)
567
- print("SCRIPT_SUCCESS: POU created successfully."); sys.exit(0)
568
- else:
569
- error_message = "Failed to create POU '%s'. create_pou returned None." % POU_NAME; print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
570
- except Exception as e:
571
- detailed_error = traceback.format_exc()
572
- error_message = "Error creating POU '%s' in project '%s': %s\\n%s" % (POU_NAME, PROJECT_FILE_PATH, e, detailed_error)
573
- print(error_message); print("SCRIPT_ERROR: Error creating POU '%s': %s" % (POU_NAME, e)); sys.exit(1)
520
+ const CREATE_POU_SCRIPT_TEMPLATE = `
521
+ import sys, scriptengine as script_engine, os, traceback
522
+ ${ENSURE_PROJECT_OPEN_PYTHON_SNIPPET}
523
+ ${FIND_OBJECT_BY_PATH_PYTHON_SNIPPET}
524
+ POU_NAME = "{POU_NAME}"; POU_TYPE_STR = "{POU_TYPE_STR}"; IMPL_LANGUAGE_STR = "{IMPL_LANGUAGE_STR}"; PARENT_PATH_REL = "{PARENT_PATH}"
525
+ pou_type_map = { "Program": script_engine.PouType.Program, "FunctionBlock": script_engine.PouType.FunctionBlock, "Function": script_engine.PouType.Function }
526
+ # Map common language names to ImplementationLanguages attributes if needed (optional, None usually works)
527
+ # lang_map = { "ST": script_engine.ImplementationLanguage.st, ... }
528
+
529
+ try:
530
+ print("DEBUG: create_pou script: Name='%s', Type='%s', Lang='%s', ParentPath='%s', Project='%s'" % (POU_NAME, POU_TYPE_STR, IMPL_LANGUAGE_STR, PARENT_PATH_REL, PROJECT_FILE_PATH))
531
+ primary_project = ensure_project_open(PROJECT_FILE_PATH)
532
+ if not POU_NAME: raise ValueError("POU name empty.")
533
+ if not PARENT_PATH_REL: raise ValueError("Parent path empty.")
534
+
535
+ # Resolve POU Type Enum
536
+ pou_type_enum = pou_type_map.get(POU_TYPE_STR)
537
+ if not pou_type_enum: raise ValueError("Invalid POU type string: %s. Use Program, FunctionBlock, or Function." % POU_TYPE_STR)
538
+
539
+ # Find parent object using the robust function
540
+ parent_object = find_object_by_path_robust(primary_project, PARENT_PATH_REL, "parent container")
541
+ if not parent_object: raise ValueError("Parent object not found for path: %s" % PARENT_PATH_REL)
542
+
543
+ parent_name = getattr(parent_object, 'get_name', lambda: str(parent_object))()
544
+ print("DEBUG: Using parent object: %s (Type: %s)" % (parent_name, type(parent_object).__name__))
545
+
546
+ # Check if parent object supports creating POUs (should implement ScriptIecLanguageObjectContainer)
547
+ if not hasattr(parent_object, 'create_pou'):
548
+ raise TypeError("Parent object '%s' of type %s does not support create_pou." % (parent_name, type(parent_object).__name__))
549
+
550
+ # Set language GUID to None (let CODESYS default based on parent/settings)
551
+ lang_guid = None
552
+ print("DEBUG: Setting language to None (will use default).")
553
+ # Example if mapping language string: lang_guid = lang_map.get(IMPL_LANGUAGE_STR, None)
554
+
555
+ print("DEBUG: Calling parent_object.create_pou: Name='%s', Type=%s, Lang=%s" % (POU_NAME, pou_type_enum, lang_guid))
556
+
557
+ # Call create_pou using keyword arguments
558
+ new_pou = parent_object.create_pou(
559
+ name=POU_NAME,
560
+ type=pou_type_enum,
561
+ language=lang_guid # Pass None
562
+ )
563
+
564
+ print("DEBUG: parent_object.create_pou returned: %s" % new_pou)
565
+ if new_pou:
566
+ new_pou_name = getattr(new_pou, 'get_name', lambda: POU_NAME)()
567
+ print("DEBUG: POU object created: %s" % new_pou_name)
568
+
569
+ # --- SAVE THE PROJECT TO PERSIST THE NEW POU ---
570
+ try:
571
+ print("DEBUG: Saving Project...")
572
+ primary_project.save() # Save the overall project file
573
+ print("DEBUG: Project saved successfully after POU creation.")
574
+ except Exception as save_err:
575
+ print("ERROR: Failed to save Project after POU creation: %s" % save_err)
576
+ detailed_error = traceback.format_exc()
577
+ error_message = "Error saving Project after creating POU '%s': %s\\n%s" % (new_pou_name, save_err, detailed_error)
578
+ print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
579
+ # --- END SAVING ---
580
+
581
+ print("POU Created: %s" % new_pou_name); print("Type: %s" % POU_TYPE_STR); print("Language: %s (Defaulted)" % IMPL_LANGUAGE_STR); print("Parent Path: %s" % PARENT_PATH_REL)
582
+ print("SCRIPT_SUCCESS: POU created successfully."); sys.exit(0)
583
+ else:
584
+ error_message = "Failed to create POU '%s'. create_pou returned None." % POU_NAME; print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
585
+ except Exception as e:
586
+ detailed_error = traceback.format_exc()
587
+ error_message = "Error creating POU '%s' in project '%s': %s\\n%s" % (POU_NAME, PROJECT_FILE_PATH, e, detailed_error)
588
+ print(error_message); print("SCRIPT_ERROR: Error creating POU '%s': %s" % (POU_NAME, e)); sys.exit(1)
574
589
  `;
575
590
  // (SET_POU_CODE_SCRIPT_TEMPLATE uses FIND_OBJECT_BY_PATH_PYTHON_SNIPPET)
576
- const SET_POU_CODE_SCRIPT_TEMPLATE = `
577
- import sys, scriptengine as script_engine, os, traceback
578
- ${ENSURE_PROJECT_OPEN_PYTHON_SNIPPET}
579
- ${FIND_OBJECT_BY_PATH_PYTHON_SNIPPET}
580
- POU_FULL_PATH = "{POU_FULL_PATH}" # Expecting format like "Application/MyPOU" or "Folder/SubFolder/MyPOU"
581
- DECLARATION_CONTENT = """{DECLARATION_CONTENT}"""
582
- IMPLEMENTATION_CONTENT = """{IMPLEMENTATION_CONTENT}"""
583
-
584
- try:
585
- print("DEBUG: set_pou_code script: POU_FULL_PATH='%s', Project='%s'" % (POU_FULL_PATH, PROJECT_FILE_PATH))
586
- primary_project = ensure_project_open(PROJECT_FILE_PATH)
587
- if not POU_FULL_PATH: raise ValueError("POU full path empty.")
588
-
589
- # Find the target POU/Method/Property object
590
- target_object = find_object_by_path_robust(primary_project, POU_FULL_PATH, "target object")
591
- if not target_object: raise ValueError("Target object not found using path: %s" % POU_FULL_PATH)
592
-
593
- target_name = getattr(target_object, 'get_name', lambda: POU_FULL_PATH)()
594
- print("DEBUG: Found target object: %s" % target_name)
595
-
596
- # --- Set Declaration Part ---
597
- declaration_updated = False
598
- # Check if the content is actually provided (might be None/empty if only impl is set)
599
- has_declaration_content = 'DECLARATION_CONTENT' in locals() or 'DECLARATION_CONTENT' in globals()
600
- if has_declaration_content and DECLARATION_CONTENT is not None: # Check not None
601
- if hasattr(target_object, 'textual_declaration'):
602
- decl_obj = target_object.textual_declaration
603
- if decl_obj and hasattr(decl_obj, 'replace'):
604
- try:
605
- print("DEBUG: Accessing textual_declaration...")
606
- decl_obj.replace(DECLARATION_CONTENT)
607
- print("DEBUG: Set declaration text using replace().")
608
- declaration_updated = True
609
- except Exception as decl_err:
610
- print("ERROR: Failed to set declaration text: %s" % decl_err)
611
- traceback.print_exc() # Print stack trace for detailed error
612
- else:
613
- print("WARN: Target '%s' textual_declaration attribute is None or does not have replace(). Skipping declaration update." % target_name)
614
- else:
615
- print("WARN: Target '%s' does not have textual_declaration attribute. Skipping declaration update." % target_name)
616
- else:
617
- print("DEBUG: Declaration content not provided or is None. Skipping declaration update.")
618
-
619
-
620
- # --- Set Implementation Part ---
621
- implementation_updated = False
622
- has_implementation_content = 'IMPLEMENTATION_CONTENT' in locals() or 'IMPLEMENTATION_CONTENT' in globals()
623
- if has_implementation_content and IMPLEMENTATION_CONTENT is not None: # Check not None
624
- if hasattr(target_object, 'textual_implementation'):
625
- impl_obj = target_object.textual_implementation
626
- if impl_obj and hasattr(impl_obj, 'replace'):
627
- try:
628
- print("DEBUG: Accessing textual_implementation...")
629
- impl_obj.replace(IMPLEMENTATION_CONTENT)
630
- print("DEBUG: Set implementation text using replace().")
631
- implementation_updated = True
632
- except Exception as impl_err:
633
- print("ERROR: Failed to set implementation text: %s" % impl_err)
634
- traceback.print_exc() # Print stack trace for detailed error
635
- else:
636
- print("WARN: Target '%s' textual_implementation attribute is None or does not have replace(). Skipping implementation update." % target_name)
637
- else:
638
- print("WARN: Target '%s' does not have textual_implementation attribute. Skipping implementation update." % target_name)
639
- else:
640
- print("DEBUG: Implementation content not provided or is None. Skipping implementation update.")
641
-
642
-
643
- # --- SAVE THE PROJECT TO PERSIST THE CODE CHANGE ---
644
- # Only save if something was actually updated to avoid unnecessary saves
645
- if declaration_updated or implementation_updated:
646
- try:
647
- print("DEBUG: Saving Project (after code change)...")
648
- primary_project.save() # Save the overall project file
649
- print("DEBUG: Project saved successfully after code change.")
650
- except Exception as save_err:
651
- print("ERROR: Failed to save Project after setting code: %s" % save_err)
652
- detailed_error = traceback.format_exc()
653
- error_message = "Error saving Project after code change for '%s': %s\\n%s" % (target_name, save_err, detailed_error)
654
- print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
655
- else:
656
- print("DEBUG: No code parts were updated, skipping project save.")
657
- # --- END SAVING ---
658
-
659
- print("Code Set For: %s" % target_name)
660
- print("Path: %s" % POU_FULL_PATH)
661
- print("SCRIPT_SUCCESS: Declaration and/or implementation set successfully."); sys.exit(0)
662
-
663
- except Exception as e:
664
- detailed_error = traceback.format_exc()
665
- error_message = "Error setting code for object '%s' in project '%s': %s\\n%s" % (POU_FULL_PATH, PROJECT_FILE_PATH, e, detailed_error)
666
- print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
591
+ const SET_POU_CODE_SCRIPT_TEMPLATE = `
592
+ import sys, scriptengine as script_engine, os, traceback
593
+ ${ENSURE_PROJECT_OPEN_PYTHON_SNIPPET}
594
+ ${FIND_OBJECT_BY_PATH_PYTHON_SNIPPET}
595
+ POU_FULL_PATH = "{POU_FULL_PATH}" # Expecting format like "Application/MyPOU" or "Folder/SubFolder/MyPOU"
596
+ DECLARATION_CONTENT = """{DECLARATION_CONTENT}"""
597
+ IMPLEMENTATION_CONTENT = """{IMPLEMENTATION_CONTENT}"""
598
+
599
+ try:
600
+ print("DEBUG: set_pou_code script: POU_FULL_PATH='%s', Project='%s'" % (POU_FULL_PATH, PROJECT_FILE_PATH))
601
+ primary_project = ensure_project_open(PROJECT_FILE_PATH)
602
+ if not POU_FULL_PATH: raise ValueError("POU full path empty.")
603
+
604
+ # Find the target POU/Method/Property object
605
+ target_object = find_object_by_path_robust(primary_project, POU_FULL_PATH, "target object")
606
+ if not target_object: raise ValueError("Target object not found using path: %s" % POU_FULL_PATH)
607
+
608
+ target_name = getattr(target_object, 'get_name', lambda: POU_FULL_PATH)()
609
+ print("DEBUG: Found target object: %s" % target_name)
610
+
611
+ # --- Set Declaration Part ---
612
+ declaration_updated = False
613
+ # Check if the content is actually provided (might be None/empty if only impl is set)
614
+ has_declaration_content = 'DECLARATION_CONTENT' in locals() or 'DECLARATION_CONTENT' in globals()
615
+ if has_declaration_content and DECLARATION_CONTENT is not None: # Check not None
616
+ if hasattr(target_object, 'textual_declaration'):
617
+ decl_obj = target_object.textual_declaration
618
+ if decl_obj and hasattr(decl_obj, 'replace'):
619
+ try:
620
+ print("DEBUG: Accessing textual_declaration...")
621
+ decl_obj.replace(DECLARATION_CONTENT)
622
+ print("DEBUG: Set declaration text using replace().")
623
+ declaration_updated = True
624
+ except Exception as decl_err:
625
+ print("ERROR: Failed to set declaration text: %s" % decl_err)
626
+ traceback.print_exc() # Print stack trace for detailed error
627
+ else:
628
+ print("WARN: Target '%s' textual_declaration attribute is None or does not have replace(). Skipping declaration update." % target_name)
629
+ else:
630
+ print("WARN: Target '%s' does not have textual_declaration attribute. Skipping declaration update." % target_name)
631
+ else:
632
+ print("DEBUG: Declaration content not provided or is None. Skipping declaration update.")
633
+
634
+
635
+ # --- Set Implementation Part ---
636
+ implementation_updated = False
637
+ has_implementation_content = 'IMPLEMENTATION_CONTENT' in locals() or 'IMPLEMENTATION_CONTENT' in globals()
638
+ if has_implementation_content and IMPLEMENTATION_CONTENT is not None: # Check not None
639
+ if hasattr(target_object, 'textual_implementation'):
640
+ impl_obj = target_object.textual_implementation
641
+ if impl_obj and hasattr(impl_obj, 'replace'):
642
+ try:
643
+ print("DEBUG: Accessing textual_implementation...")
644
+ impl_obj.replace(IMPLEMENTATION_CONTENT)
645
+ print("DEBUG: Set implementation text using replace().")
646
+ implementation_updated = True
647
+ except Exception as impl_err:
648
+ print("ERROR: Failed to set implementation text: %s" % impl_err)
649
+ traceback.print_exc() # Print stack trace for detailed error
650
+ else:
651
+ print("WARN: Target '%s' textual_implementation attribute is None or does not have replace(). Skipping implementation update." % target_name)
652
+ else:
653
+ print("WARN: Target '%s' does not have textual_implementation attribute. Skipping implementation update." % target_name)
654
+ else:
655
+ print("DEBUG: Implementation content not provided or is None. Skipping implementation update.")
656
+
657
+
658
+ # --- SAVE THE PROJECT TO PERSIST THE CODE CHANGE ---
659
+ # Only save if something was actually updated to avoid unnecessary saves
660
+ if declaration_updated or implementation_updated:
661
+ try:
662
+ print("DEBUG: Saving Project (after code change)...")
663
+ primary_project.save() # Save the overall project file
664
+ print("DEBUG: Project saved successfully after code change.")
665
+ except Exception as save_err:
666
+ print("ERROR: Failed to save Project after setting code: %s" % save_err)
667
+ detailed_error = traceback.format_exc()
668
+ error_message = "Error saving Project after code change for '%s': %s\\n%s" % (target_name, save_err, detailed_error)
669
+ print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
670
+ else:
671
+ print("DEBUG: No code parts were updated, skipping project save.")
672
+ # --- END SAVING ---
673
+
674
+ print("Code Set For: %s" % target_name)
675
+ print("Path: %s" % POU_FULL_PATH)
676
+ print("SCRIPT_SUCCESS: Declaration and/or implementation set successfully."); sys.exit(0)
677
+
678
+ except Exception as e:
679
+ detailed_error = traceback.format_exc()
680
+ error_message = "Error setting code for object '%s' in project '%s': %s\\n%s" % (POU_FULL_PATH, PROJECT_FILE_PATH, e, detailed_error)
681
+ print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
667
682
  `;
668
683
  // --- CREATE_PROPERTY_SCRIPT_TEMPLATE uses FIND_OBJECT_BY_PATH_PYTHON_SNIPPET ---
669
- const CREATE_PROPERTY_SCRIPT_TEMPLATE = `
670
- import sys, scriptengine as script_engine, os, traceback
671
- ${ENSURE_PROJECT_OPEN_PYTHON_SNIPPET}
672
- ${FIND_OBJECT_BY_PATH_PYTHON_SNIPPET}
673
- PARENT_POU_FULL_PATH = "{PARENT_POU_FULL_PATH}" # e.g., "Application/MyFB"
674
- PROPERTY_NAME = "{PROPERTY_NAME}"
675
- PROPERTY_TYPE = "{PROPERTY_TYPE}"
676
- # Optional: Language for Getter/Setter (usually defaults to ST)
677
- # LANG_GUID_STR = "{LANG_GUID_STR}" # Example if needed
678
-
679
- try:
680
- print("DEBUG: create_property script: ParentPOU='%s', Name='%s', Type='%s', Project='%s'" % (PARENT_POU_FULL_PATH, PROPERTY_NAME, PROPERTY_TYPE, PROJECT_FILE_PATH))
681
- primary_project = ensure_project_open(PROJECT_FILE_PATH)
682
- if not PARENT_POU_FULL_PATH: raise ValueError("Parent POU full path empty.")
683
- if not PROPERTY_NAME: raise ValueError("Property name empty.")
684
- if not PROPERTY_TYPE: raise ValueError("Property type empty.")
685
-
686
- # Find the parent POU object
687
- parent_pou_object = find_object_by_path_robust(primary_project, PARENT_POU_FULL_PATH, "parent POU")
688
- if not parent_pou_object: raise ValueError("Parent POU object not found: %s" % PARENT_POU_FULL_PATH)
689
-
690
- parent_pou_name = getattr(parent_pou_object, 'get_name', lambda: PARENT_POU_FULL_PATH)()
691
- print("DEBUG: Found Parent POU object: %s" % parent_pou_name)
692
-
693
- # Check if parent object supports creating properties (should implement ScriptIecLanguageMemberContainer)
694
- if not hasattr(parent_pou_object, 'create_property'):
695
- raise TypeError("Parent object '%s' of type %s does not support create_property." % (parent_pou_name, type(parent_pou_object).__name__))
696
-
697
- # Default language to None (usually ST)
698
- lang_guid = None
699
- print("DEBUG: Calling create_property: Name='%s', Type='%s', Lang=%s" % (PROPERTY_NAME, PROPERTY_TYPE, lang_guid))
700
-
701
- # Call the create_property method ON THE PARENT POU
702
- new_property_object = parent_pou_object.create_property(
703
- name=PROPERTY_NAME,
704
- return_type=PROPERTY_TYPE,
705
- language=lang_guid # Pass None to use default
706
- )
707
-
708
- if new_property_object:
709
- new_prop_name = getattr(new_property_object, 'get_name', lambda: PROPERTY_NAME)()
710
- print("DEBUG: Property object created: %s" % new_prop_name)
711
-
712
- # --- SAVE THE PROJECT TO PERSIST THE NEW PROPERTY OBJECT ---
713
- try:
714
- print("DEBUG: Saving Project (after property creation)...")
715
- primary_project.save()
716
- print("DEBUG: Project saved successfully after property creation.")
717
- except Exception as save_err:
718
- print("ERROR: Failed to save Project after creating property: %s" % save_err)
719
- detailed_error = traceback.format_exc()
720
- error_message = "Error saving Project after creating property '%s': %s\\n%s" % (PROPERTY_NAME, save_err, detailed_error)
721
- print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
722
- # --- END SAVING ---
723
-
724
- print("Property Created: %s" % new_prop_name)
725
- print("Parent POU: %s" % PARENT_POU_FULL_PATH)
726
- print("Type: %s" % PROPERTY_TYPE)
727
- print("SCRIPT_SUCCESS: Property created successfully."); sys.exit(0)
728
- else:
729
- error_message = "Failed to create property '%s' under '%s'. create_property returned None." % (PROPERTY_NAME, parent_pou_name)
730
- print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
731
-
732
- except Exception as e:
733
- detailed_error = traceback.format_exc()
734
- error_message = "Error creating property '%s' under POU '%s' in project '%s': %s\\n%s" % (PROPERTY_NAME, PARENT_POU_FULL_PATH, PROJECT_FILE_PATH, e, detailed_error)
735
- print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
684
+ const CREATE_PROPERTY_SCRIPT_TEMPLATE = `
685
+ import sys, scriptengine as script_engine, os, traceback
686
+ ${ENSURE_PROJECT_OPEN_PYTHON_SNIPPET}
687
+ ${FIND_OBJECT_BY_PATH_PYTHON_SNIPPET}
688
+ PARENT_POU_FULL_PATH = "{PARENT_POU_FULL_PATH}" # e.g., "Application/MyFB"
689
+ PROPERTY_NAME = "{PROPERTY_NAME}"
690
+ PROPERTY_TYPE = "{PROPERTY_TYPE}"
691
+ # Optional: Language for Getter/Setter (usually defaults to ST)
692
+ # LANG_GUID_STR = "{LANG_GUID_STR}" # Example if needed
693
+
694
+ try:
695
+ print("DEBUG: create_property script: ParentPOU='%s', Name='%s', Type='%s', Project='%s'" % (PARENT_POU_FULL_PATH, PROPERTY_NAME, PROPERTY_TYPE, PROJECT_FILE_PATH))
696
+ primary_project = ensure_project_open(PROJECT_FILE_PATH)
697
+ if not PARENT_POU_FULL_PATH: raise ValueError("Parent POU full path empty.")
698
+ if not PROPERTY_NAME: raise ValueError("Property name empty.")
699
+ if not PROPERTY_TYPE: raise ValueError("Property type empty.")
700
+
701
+ # Find the parent POU object
702
+ parent_pou_object = find_object_by_path_robust(primary_project, PARENT_POU_FULL_PATH, "parent POU")
703
+ if not parent_pou_object: raise ValueError("Parent POU object not found: %s" % PARENT_POU_FULL_PATH)
704
+
705
+ parent_pou_name = getattr(parent_pou_object, 'get_name', lambda: PARENT_POU_FULL_PATH)()
706
+ print("DEBUG: Found Parent POU object: %s" % parent_pou_name)
707
+
708
+ # Check if parent object supports creating properties (should implement ScriptIecLanguageMemberContainer)
709
+ if not hasattr(parent_pou_object, 'create_property'):
710
+ raise TypeError("Parent object '%s' of type %s does not support create_property." % (parent_pou_name, type(parent_pou_object).__name__))
711
+
712
+ # Default language to None (usually ST)
713
+ lang_guid = None
714
+ print("DEBUG: Calling create_property: Name='%s', Type='%s', Lang=%s" % (PROPERTY_NAME, PROPERTY_TYPE, lang_guid))
715
+
716
+ # Call the create_property method ON THE PARENT POU
717
+ new_property_object = parent_pou_object.create_property(
718
+ name=PROPERTY_NAME,
719
+ return_type=PROPERTY_TYPE,
720
+ language=lang_guid # Pass None to use default
721
+ )
722
+
723
+ if new_property_object:
724
+ new_prop_name = getattr(new_property_object, 'get_name', lambda: PROPERTY_NAME)()
725
+ print("DEBUG: Property object created: %s" % new_prop_name)
726
+
727
+ # --- SAVE THE PROJECT TO PERSIST THE NEW PROPERTY OBJECT ---
728
+ try:
729
+ print("DEBUG: Saving Project (after property creation)...")
730
+ primary_project.save()
731
+ print("DEBUG: Project saved successfully after property creation.")
732
+ except Exception as save_err:
733
+ print("ERROR: Failed to save Project after creating property: %s" % save_err)
734
+ detailed_error = traceback.format_exc()
735
+ error_message = "Error saving Project after creating property '%s': %s\\n%s" % (PROPERTY_NAME, save_err, detailed_error)
736
+ print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
737
+ # --- END SAVING ---
738
+
739
+ print("Property Created: %s" % new_prop_name)
740
+ print("Parent POU: %s" % PARENT_POU_FULL_PATH)
741
+ print("Type: %s" % PROPERTY_TYPE)
742
+ print("SCRIPT_SUCCESS: Property created successfully."); sys.exit(0)
743
+ else:
744
+ error_message = "Failed to create property '%s' under '%s'. create_property returned None." % (PROPERTY_NAME, parent_pou_name)
745
+ print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
746
+
747
+ except Exception as e:
748
+ detailed_error = traceback.format_exc()
749
+ error_message = "Error creating property '%s' under POU '%s' in project '%s': %s\\n%s" % (PROPERTY_NAME, PARENT_POU_FULL_PATH, PROJECT_FILE_PATH, e, detailed_error)
750
+ print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
736
751
  `;
737
752
  // --- CREATE_METHOD_SCRIPT_TEMPLATE uses FIND_OBJECT_BY_PATH_PYTHON_SNIPPET ---
738
- const CREATE_METHOD_SCRIPT_TEMPLATE = `
739
- import sys, scriptengine as script_engine, os, traceback
740
- ${ENSURE_PROJECT_OPEN_PYTHON_SNIPPET}
741
- ${FIND_OBJECT_BY_PATH_PYTHON_SNIPPET}
742
- PARENT_POU_FULL_PATH = "{PARENT_POU_FULL_PATH}" # e.g., "Application/MyFB"
743
- METHOD_NAME = "{METHOD_NAME}"
744
- RETURN_TYPE = "{RETURN_TYPE}" # Can be empty string for no return type
745
- # Optional: Language
746
- # LANG_GUID_STR = "{LANG_GUID_STR}" # Example if needed
747
-
748
- try:
749
- print("DEBUG: create_method script: ParentPOU='%s', Name='%s', ReturnType='%s', Project='%s'" % (PARENT_POU_FULL_PATH, METHOD_NAME, RETURN_TYPE, PROJECT_FILE_PATH))
750
- primary_project = ensure_project_open(PROJECT_FILE_PATH)
751
- if not PARENT_POU_FULL_PATH: raise ValueError("Parent POU full path empty.")
752
- if not METHOD_NAME: raise ValueError("Method name empty.")
753
- # RETURN_TYPE can be empty
754
-
755
- # Find the parent POU object
756
- parent_pou_object = find_object_by_path_robust(primary_project, PARENT_POU_FULL_PATH, "parent POU")
757
- if not parent_pou_object: raise ValueError("Parent POU object not found: %s" % PARENT_POU_FULL_PATH)
758
-
759
- parent_pou_name = getattr(parent_pou_object, 'get_name', lambda: PARENT_POU_FULL_PATH)()
760
- print("DEBUG: Found Parent POU object: %s" % parent_pou_name)
761
-
762
- # Check if parent object supports creating methods (should implement ScriptIecLanguageMemberContainer)
763
- if not hasattr(parent_pou_object, 'create_method'):
764
- raise TypeError("Parent object '%s' of type %s does not support create_method." % (parent_pou_name, type(parent_pou_object).__name__))
765
-
766
- # Default language to None (usually ST)
767
- lang_guid = None
768
- # Use None if RETURN_TYPE is empty string, otherwise use the string
769
- actual_return_type = RETURN_TYPE if RETURN_TYPE else None
770
- print("DEBUG: Calling create_method: Name='%s', ReturnType=%s, Lang=%s" % (METHOD_NAME, actual_return_type, lang_guid))
771
-
772
- # Call the create_method method ON THE PARENT POU
773
- new_method_object = parent_pou_object.create_method(
774
- name=METHOD_NAME,
775
- return_type=actual_return_type,
776
- language=lang_guid # Pass None to use default
777
- )
778
-
779
- if new_method_object:
780
- new_meth_name = getattr(new_method_object, 'get_name', lambda: METHOD_NAME)()
781
- print("DEBUG: Method object created: %s" % new_meth_name)
782
-
783
- # --- SAVE THE PROJECT TO PERSIST THE NEW METHOD OBJECT ---
784
- try:
785
- print("DEBUG: Saving Project (after method creation)...")
786
- primary_project.save()
787
- print("DEBUG: Project saved successfully after method creation.")
788
- except Exception as save_err:
789
- print("ERROR: Failed to save Project after creating method: %s" % save_err)
790
- detailed_error = traceback.format_exc()
791
- error_message = "Error saving Project after creating method '%s': %s\\n%s" % (METHOD_NAME, save_err, detailed_error)
792
- print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
793
- # --- END SAVING ---
794
-
795
- print("Method Created: %s" % new_meth_name)
796
- print("Parent POU: %s" % PARENT_POU_FULL_PATH)
797
- print("Return Type: %s" % (RETURN_TYPE if RETURN_TYPE else "(None)"))
798
- print("SCRIPT_SUCCESS: Method created successfully."); sys.exit(0)
799
- else:
800
- error_message = "Failed to create method '%s' under '%s'. create_method returned None." % (METHOD_NAME, parent_pou_name)
801
- print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
802
-
803
- except Exception as e:
804
- detailed_error = traceback.format_exc()
805
- error_message = "Error creating method '%s' under POU '%s' in project '%s': %s\\n%s" % (METHOD_NAME, PARENT_POU_FULL_PATH, PROJECT_FILE_PATH, e, detailed_error)
806
- print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
753
+ const CREATE_METHOD_SCRIPT_TEMPLATE = `
754
+ import sys, scriptengine as script_engine, os, traceback
755
+ ${ENSURE_PROJECT_OPEN_PYTHON_SNIPPET}
756
+ ${FIND_OBJECT_BY_PATH_PYTHON_SNIPPET}
757
+ PARENT_POU_FULL_PATH = "{PARENT_POU_FULL_PATH}" # e.g., "Application/MyFB"
758
+ METHOD_NAME = "{METHOD_NAME}"
759
+ RETURN_TYPE = "{RETURN_TYPE}" # Can be empty string for no return type
760
+ # Optional: Language
761
+ # LANG_GUID_STR = "{LANG_GUID_STR}" # Example if needed
762
+
763
+ try:
764
+ print("DEBUG: create_method script: ParentPOU='%s', Name='%s', ReturnType='%s', Project='%s'" % (PARENT_POU_FULL_PATH, METHOD_NAME, RETURN_TYPE, PROJECT_FILE_PATH))
765
+ primary_project = ensure_project_open(PROJECT_FILE_PATH)
766
+ if not PARENT_POU_FULL_PATH: raise ValueError("Parent POU full path empty.")
767
+ if not METHOD_NAME: raise ValueError("Method name empty.")
768
+ # RETURN_TYPE can be empty
769
+
770
+ # Find the parent POU object
771
+ parent_pou_object = find_object_by_path_robust(primary_project, PARENT_POU_FULL_PATH, "parent POU")
772
+ if not parent_pou_object: raise ValueError("Parent POU object not found: %s" % PARENT_POU_FULL_PATH)
773
+
774
+ parent_pou_name = getattr(parent_pou_object, 'get_name', lambda: PARENT_POU_FULL_PATH)()
775
+ print("DEBUG: Found Parent POU object: %s" % parent_pou_name)
776
+
777
+ # Check if parent object supports creating methods (should implement ScriptIecLanguageMemberContainer)
778
+ if not hasattr(parent_pou_object, 'create_method'):
779
+ raise TypeError("Parent object '%s' of type %s does not support create_method." % (parent_pou_name, type(parent_pou_object).__name__))
780
+
781
+ # Default language to None (usually ST)
782
+ lang_guid = None
783
+ # Use None if RETURN_TYPE is empty string, otherwise use the string
784
+ actual_return_type = RETURN_TYPE if RETURN_TYPE else None
785
+ print("DEBUG: Calling create_method: Name='%s', ReturnType=%s, Lang=%s" % (METHOD_NAME, actual_return_type, lang_guid))
786
+
787
+ # Call the create_method method ON THE PARENT POU
788
+ new_method_object = parent_pou_object.create_method(
789
+ name=METHOD_NAME,
790
+ return_type=actual_return_type,
791
+ language=lang_guid # Pass None to use default
792
+ )
793
+
794
+ if new_method_object:
795
+ new_meth_name = getattr(new_method_object, 'get_name', lambda: METHOD_NAME)()
796
+ print("DEBUG: Method object created: %s" % new_meth_name)
797
+
798
+ # --- SAVE THE PROJECT TO PERSIST THE NEW METHOD OBJECT ---
799
+ try:
800
+ print("DEBUG: Saving Project (after method creation)...")
801
+ primary_project.save()
802
+ print("DEBUG: Project saved successfully after method creation.")
803
+ except Exception as save_err:
804
+ print("ERROR: Failed to save Project after creating method: %s" % save_err)
805
+ detailed_error = traceback.format_exc()
806
+ error_message = "Error saving Project after creating method '%s': %s\\n%s" % (METHOD_NAME, save_err, detailed_error)
807
+ print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
808
+ # --- END SAVING ---
809
+
810
+ print("Method Created: %s" % new_meth_name)
811
+ print("Parent POU: %s" % PARENT_POU_FULL_PATH)
812
+ print("Return Type: %s" % (RETURN_TYPE if RETURN_TYPE else "(None)"))
813
+ print("SCRIPT_SUCCESS: Method created successfully."); sys.exit(0)
814
+ else:
815
+ error_message = "Failed to create method '%s' under '%s'. create_method returned None." % (METHOD_NAME, parent_pou_name)
816
+ print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
817
+
818
+ except Exception as e:
819
+ detailed_error = traceback.format_exc()
820
+ error_message = "Error creating method '%s' under POU '%s' in project '%s': %s\\n%s" % (METHOD_NAME, PARENT_POU_FULL_PATH, PROJECT_FILE_PATH, e, detailed_error)
821
+ print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
807
822
  `;
808
823
  // (COMPILE_PROJECT_SCRIPT_TEMPLATE remains the same)
809
- const COMPILE_PROJECT_SCRIPT_TEMPLATE = `
810
- import sys, scriptengine as script_engine, os, traceback
811
- ${ENSURE_PROJECT_OPEN_PYTHON_SNIPPET}
812
- try:
813
- print("DEBUG: compile_project script: Project='%s'" % PROJECT_FILE_PATH)
814
- primary_project = ensure_project_open(PROJECT_FILE_PATH)
815
- project_name = os.path.basename(PROJECT_FILE_PATH)
816
- target_app = None
817
- app_name = "N/A"
818
-
819
- # Try getting active application first
820
- try:
821
- target_app = primary_project.active_application
822
- if target_app:
823
- app_name = getattr(target_app, 'get_name', lambda: "Unnamed App (Active)")()
824
- print("DEBUG: Found active application: %s" % app_name)
825
- except Exception as active_err:
826
- print("WARN: Could not get active application: %s. Searching..." % active_err)
827
-
828
- # If no active app, search for the first one
829
- if not target_app:
830
- print("DEBUG: Searching for first compilable application...")
831
- apps = []
832
- try:
833
- # Search recursively through all project objects
834
- all_children = primary_project.get_children(True)
835
- for child in all_children:
836
- # Check using the marker property and if build method exists
837
- if hasattr(child, 'is_application') and child.is_application and hasattr(child, 'build'):
838
- app_name_found = getattr(child, 'get_name', lambda: "Unnamed App")()
839
- print("DEBUG: Found potential application object: %s" % app_name_found)
840
- apps.append(child)
841
- break # Take the first one found
842
- except Exception as find_err: print("WARN: Error finding application object: %s" % find_err)
843
-
844
- if not apps: raise RuntimeError("No compilable application found in project '%s'" % project_name)
845
- target_app = apps[0]
846
- app_name = getattr(target_app, 'get_name', lambda: "Unnamed App (First Found)")()
847
- print("WARN: Compiling first found application: %s" % app_name)
848
-
849
- print("DEBUG: Calling build() on app '%s'..." % app_name)
850
- if not hasattr(target_app, 'build'):
851
- raise TypeError("Selected object '%s' is not an application or doesn't support build()." % app_name)
852
-
853
- # Execute the build
854
- target_app.build();
855
- print("DEBUG: Build command executed for application '%s'." % app_name)
856
-
857
- # Check messages is harder without direct access to message store from script.
858
- # Rely on CODESYS UI or log output for now.
859
- print("Compile Initiated For Application: %s" % app_name); print("In Project: %s" % project_name)
860
- print("SCRIPT_SUCCESS: Application compilation initiated."); sys.exit(0)
861
- except Exception as e:
862
- detailed_error = traceback.format_exc()
863
- error_message = "Error initiating compilation for project %s: %s\\n%s" % (PROJECT_FILE_PATH, e, detailed_error)
864
- print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
824
+ const COMPILE_PROJECT_SCRIPT_TEMPLATE = `
825
+ import sys, scriptengine as script_engine, os, traceback
826
+ ${ENSURE_PROJECT_OPEN_PYTHON_SNIPPET}
827
+ try:
828
+ print("DEBUG: compile_project script: Project='%s'" % PROJECT_FILE_PATH)
829
+ primary_project = ensure_project_open(PROJECT_FILE_PATH)
830
+ project_name = os.path.basename(PROJECT_FILE_PATH)
831
+ target_app = None
832
+ app_name = "N/A"
833
+
834
+ # Try getting active application first
835
+ try:
836
+ target_app = primary_project.active_application
837
+ if target_app:
838
+ app_name = getattr(target_app, 'get_name', lambda: "Unnamed App (Active)")()
839
+ print("DEBUG: Found active application: %s" % app_name)
840
+ except Exception as active_err:
841
+ print("WARN: Could not get active application: %s. Searching..." % active_err)
842
+
843
+ # If no active app, search for the first one
844
+ if not target_app:
845
+ print("DEBUG: Searching for first compilable application...")
846
+ apps = []
847
+ try:
848
+ # Search recursively through all project objects
849
+ all_children = primary_project.get_children(True)
850
+ for child in all_children:
851
+ # Check using the marker property and if build method exists
852
+ if hasattr(child, 'is_application') and child.is_application and hasattr(child, 'build'):
853
+ app_name_found = getattr(child, 'get_name', lambda: "Unnamed App")()
854
+ print("DEBUG: Found potential application object: %s" % app_name_found)
855
+ apps.append(child)
856
+ break # Take the first one found
857
+ except Exception as find_err: print("WARN: Error finding application object: %s" % find_err)
858
+
859
+ if not apps: raise RuntimeError("No compilable application found in project '%s'" % project_name)
860
+ target_app = apps[0]
861
+ app_name = getattr(target_app, 'get_name', lambda: "Unnamed App (First Found)")()
862
+ print("WARN: Compiling first found application: %s" % app_name)
863
+
864
+ print("DEBUG: Calling build() on app '%s'..." % app_name)
865
+ if not hasattr(target_app, 'build'):
866
+ raise TypeError("Selected object '%s' is not an application or doesn't support build()." % app_name)
867
+
868
+ # Execute the build
869
+ target_app.build();
870
+ print("DEBUG: Build command executed for application '%s'." % app_name)
871
+
872
+ # Check messages is harder without direct access to message store from script.
873
+ # Rely on CODESYS UI or log output for now.
874
+ print("Compile Initiated For Application: %s" % app_name); print("In Project: %s" % project_name)
875
+ print("SCRIPT_SUCCESS: Application compilation initiated."); sys.exit(0)
876
+ except Exception as e:
877
+ detailed_error = traceback.format_exc()
878
+ error_message = "Error initiating compilation for project %s: %s\\n%s" % (PROJECT_FILE_PATH, e, detailed_error)
879
+ print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
865
880
  `;
866
881
  // (GET_PROJECT_STRUCTURE_SCRIPT_TEMPLATE remains the same)
867
- const GET_PROJECT_STRUCTURE_SCRIPT_TEMPLATE = `
868
- import sys, scriptengine as script_engine, os, traceback
869
- ${ENSURE_PROJECT_OPEN_PYTHON_SNIPPET}
870
- # FIND_OBJECT_BY_PATH_PYTHON_SNIPPET is NOT needed here, we start from project root.
871
-
872
- def get_object_structure(obj, indent=0, max_depth=10): # Add max_depth
873
- lines = []; indent_str = " " * indent
874
- if indent > max_depth:
875
- lines.append("%s- Max recursion depth reached." % indent_str)
876
- return lines
877
- try:
878
- name = "Unnamed"; obj_type = type(obj).__name__
879
- guid_str = ""
880
- folder_str = ""
881
- try:
882
- name = getattr(obj, 'get_name', lambda: "Unnamed")() or "Unnamed" # Safer get_name
883
- if hasattr(obj, 'guid'): guid_str = " {%s}" % obj.guid
884
- if hasattr(obj, 'is_folder') and obj.is_folder: folder_str = " [Folder]"
885
- except Exception as name_err:
886
- print("WARN: Error getting name/guid/folder status for an object: %s" % name_err)
887
- name = "!!! Error Getting Name !!!"
888
-
889
- lines.append("%s- %s (%s)%s%s" % (indent_str, name, obj_type, folder_str, guid_str))
890
-
891
- # Get children only if the object potentially has them
892
- children = []
893
- can_have_children = hasattr(obj, 'get_children') and (
894
- not hasattr(obj, 'is_folder') or # If it's not clear if it's a folder (e.g., project root)
895
- (hasattr(obj, 'is_folder') and obj.is_folder) or # If it is a folder
896
- # Add known container types explicitly, check marker interfaces too
897
- hasattr(obj, 'is_project') or hasattr(obj, 'is_application') or hasattr(obj, 'is_device') or hasattr(obj,'is_pou')
898
- )
899
-
900
- if can_have_children:
901
- try:
902
- children = obj.get_children(False)
903
- # print("DEBUG: %s has %d children" % (name, len(children))) # Verbose
904
- except Exception as get_child_err:
905
- lines.append("%s ERROR getting children: %s" % (indent_str, get_child_err))
906
- # traceback.print_exc() # Optional
907
-
908
- for child in children:
909
- lines.extend(get_object_structure(child, indent + 1, max_depth)) # Recurse
910
-
911
- except Exception as e:
912
- lines.append("%s- Error processing node: %s" % (indent_str, e))
913
- traceback.print_exc() # Print detailed error for this node
914
- return lines
915
- try:
916
- print("DEBUG: Getting structure for: %s" % PROJECT_FILE_PATH)
917
- primary_project = ensure_project_open(PROJECT_FILE_PATH)
918
- project_name = os.path.basename(PROJECT_FILE_PATH)
919
- print("DEBUG: Getting structure for project: %s" % project_name)
920
- # Use the project object obtained from ensure_project_open
921
- structure_list = get_object_structure(primary_project, max_depth=15) # Set a reasonable depth
922
- structure_output = "\\n".join(structure_list)
923
- # Ensure markers are printed distinctly
924
- print("\\n--- PROJECT STRUCTURE START ---")
925
- print(structure_output)
926
- print("--- PROJECT STRUCTURE END ---\\n")
927
- print("SCRIPT_SUCCESS: Project structure retrieved."); sys.exit(0)
928
- except Exception as e:
929
- detailed_error = traceback.format_exc()
930
- error_message = "Error getting structure for %s: %s\\n%s" % (PROJECT_FILE_PATH, e, detailed_error)
931
- print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
882
+ const GET_PROJECT_STRUCTURE_SCRIPT_TEMPLATE = `
883
+ import sys, scriptengine as script_engine, os, traceback
884
+ ${ENSURE_PROJECT_OPEN_PYTHON_SNIPPET}
885
+ # FIND_OBJECT_BY_PATH_PYTHON_SNIPPET is NOT needed here, we start from project root.
886
+
887
+ def get_object_structure(obj, indent=0, max_depth=10): # Add max_depth
888
+ lines = []; indent_str = " " * indent
889
+ if indent > max_depth:
890
+ lines.append("%s- Max recursion depth reached." % indent_str)
891
+ return lines
892
+ try:
893
+ name = "Unnamed"; obj_type = type(obj).__name__
894
+ guid_str = ""
895
+ folder_str = ""
896
+ try:
897
+ name = getattr(obj, 'get_name', lambda: "Unnamed")() or "Unnamed" # Safer get_name
898
+ if hasattr(obj, 'guid'): guid_str = " {%s}" % obj.guid
899
+ if hasattr(obj, 'is_folder') and obj.is_folder: folder_str = " [Folder]"
900
+ except Exception as name_err:
901
+ print("WARN: Error getting name/guid/folder status for an object: %s" % name_err)
902
+ name = "!!! Error Getting Name !!!"
903
+
904
+ lines.append("%s- %s (%s)%s%s" % (indent_str, name, obj_type, folder_str, guid_str))
905
+
906
+ # Get children only if the object potentially has them
907
+ children = []
908
+ can_have_children = hasattr(obj, 'get_children') and (
909
+ not hasattr(obj, 'is_folder') or # If it's not clear if it's a folder (e.g., project root)
910
+ (hasattr(obj, 'is_folder') and obj.is_folder) or # If it is a folder
911
+ # Add known container types explicitly, check marker interfaces too
912
+ hasattr(obj, 'is_project') or hasattr(obj, 'is_application') or hasattr(obj, 'is_device') or hasattr(obj,'is_pou')
913
+ )
914
+
915
+ if can_have_children:
916
+ try:
917
+ children = obj.get_children(False)
918
+ # print("DEBUG: %s has %d children" % (name, len(children))) # Verbose
919
+ except Exception as get_child_err:
920
+ lines.append("%s ERROR getting children: %s" % (indent_str, get_child_err))
921
+ # traceback.print_exc() # Optional
922
+
923
+ for child in children:
924
+ lines.extend(get_object_structure(child, indent + 1, max_depth)) # Recurse
925
+
926
+ except Exception as e:
927
+ lines.append("%s- Error processing node: %s" % (indent_str, e))
928
+ traceback.print_exc() # Print detailed error for this node
929
+ return lines
930
+ try:
931
+ print("DEBUG: Getting structure for: %s" % PROJECT_FILE_PATH)
932
+ primary_project = ensure_project_open(PROJECT_FILE_PATH)
933
+ project_name = os.path.basename(PROJECT_FILE_PATH)
934
+ print("DEBUG: Getting structure for project: %s" % project_name)
935
+ # Use the project object obtained from ensure_project_open
936
+ structure_list = get_object_structure(primary_project, max_depth=15) # Set a reasonable depth
937
+ structure_output = "\\n".join(structure_list)
938
+ # Ensure markers are printed distinctly
939
+ print("\\n--- PROJECT STRUCTURE START ---")
940
+ print(structure_output)
941
+ print("--- PROJECT STRUCTURE END ---\\n")
942
+ print("SCRIPT_SUCCESS: Project structure retrieved."); sys.exit(0)
943
+ except Exception as e:
944
+ detailed_error = traceback.format_exc()
945
+ error_message = "Error getting structure for %s: %s\\n%s" % (PROJECT_FILE_PATH, e, detailed_error)
946
+ print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
932
947
  `;
933
948
  // (GET_POU_CODE_SCRIPT_TEMPLATE uses FIND_OBJECT_BY_PATH_PYTHON_SNIPPET)
934
- const GET_POU_CODE_SCRIPT_TEMPLATE = `
935
- import sys, scriptengine as script_engine, os, traceback
936
- ${ENSURE_PROJECT_OPEN_PYTHON_SNIPPET}
937
- ${FIND_OBJECT_BY_PATH_PYTHON_SNIPPET}
938
- POU_FULL_PATH = "{POU_FULL_PATH}"; CODE_START_MARKER = "### POU CODE START ###"; CODE_END_MARKER = "### POU CODE END ###"
939
- DECL_START_MARKER = "### POU DECLARATION START ###"; DECL_END_MARKER = "### POU DECLARATION END ###"
940
- IMPL_START_MARKER = "### POU IMPLEMENTATION START ###"; IMPL_END_MARKER = "### POU IMPLEMENTATION END ###"
941
-
942
- try:
943
- print("DEBUG: Getting code: POU_FULL_PATH='%s', Project='%s'" % (POU_FULL_PATH, PROJECT_FILE_PATH))
944
- primary_project = ensure_project_open(PROJECT_FILE_PATH)
945
- if not POU_FULL_PATH: raise ValueError("POU full path empty.")
946
-
947
- # Find the target POU/Method/Property object
948
- target_object = find_object_by_path_robust(primary_project, POU_FULL_PATH, "target object")
949
- if not target_object: raise ValueError("Target object not found using path: %s" % POU_FULL_PATH)
950
-
951
- target_name = getattr(target_object, 'get_name', lambda: POU_FULL_PATH)()
952
- print("DEBUG: Found target object: %s" % target_name)
953
-
954
- declaration_code = ""; implementation_code = ""
955
-
956
- # --- Get Declaration Part ---
957
- if hasattr(target_object, 'textual_declaration'):
958
- decl_obj = target_object.textual_declaration
959
- if decl_obj and hasattr(decl_obj, 'text'):
960
- try:
961
- declaration_code = decl_obj.text
962
- print("DEBUG: Got declaration text.")
963
- except Exception as decl_read_err:
964
- print("ERROR: Failed to read declaration text: %s" % decl_read_err)
965
- declaration_code = "/* ERROR reading declaration: %s */" % decl_read_err
966
- else:
967
- print("WARN: textual_declaration exists but is None or has no 'text' attribute.")
968
- else:
969
- print("WARN: No textual_declaration attribute.")
970
-
971
- # --- Get Implementation Part ---
972
- if hasattr(target_object, 'textual_implementation'):
973
- impl_obj = target_object.textual_implementation
974
- if impl_obj and hasattr(impl_obj, 'text'):
975
- try:
976
- implementation_code = impl_obj.text
977
- print("DEBUG: Got implementation text.")
978
- except Exception as impl_read_err:
979
- print("ERROR: Failed to read implementation text: %s" % impl_read_err)
980
- implementation_code = "/* ERROR reading implementation: %s */" % impl_read_err
981
- else:
982
- print("WARN: textual_implementation exists but is None or has no 'text' attribute.")
983
- else:
984
- print("WARN: No textual_implementation attribute.")
985
-
986
-
987
- print("Code retrieved for: %s" % target_name)
988
- # Print declaration between markers, ensuring markers are on separate lines
989
- print("\\n" + DECL_START_MARKER)
990
- print(declaration_code)
991
- print(DECL_END_MARKER + "\\n")
992
- # Print implementation between markers
993
- print(IMPL_START_MARKER)
994
- print(implementation_code)
995
- print(IMPL_END_MARKER + "\\n")
996
-
997
- # --- LEGACY MARKERS for backward compatibility if needed ---
998
- # Combine both for old marker format, adding a separator line
999
- # legacy_combined_code = declaration_code + "\\n\\n// Implementation\\n" + implementation_code
1000
- # print(CODE_START_MARKER); print(legacy_combined_code); print(CODE_END_MARKER)
1001
- # --- END LEGACY ---
1002
-
1003
- print("SCRIPT_SUCCESS: Code retrieved."); sys.exit(0)
1004
- except Exception as e:
1005
- detailed_error = traceback.format_exc()
1006
- error_message = "Error getting code for object '%s' in project '%s': %s\\n%s" % (POU_FULL_PATH, PROJECT_FILE_PATH, e, detailed_error)
1007
- print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
949
+ const GET_POU_CODE_SCRIPT_TEMPLATE = `
950
+ import sys, scriptengine as script_engine, os, traceback
951
+ ${ENSURE_PROJECT_OPEN_PYTHON_SNIPPET}
952
+ ${FIND_OBJECT_BY_PATH_PYTHON_SNIPPET}
953
+ POU_FULL_PATH = "{POU_FULL_PATH}"; CODE_START_MARKER = "### POU CODE START ###"; CODE_END_MARKER = "### POU CODE END ###"
954
+ DECL_START_MARKER = "### POU DECLARATION START ###"; DECL_END_MARKER = "### POU DECLARATION END ###"
955
+ IMPL_START_MARKER = "### POU IMPLEMENTATION START ###"; IMPL_END_MARKER = "### POU IMPLEMENTATION END ###"
956
+
957
+ try:
958
+ print("DEBUG: Getting code: POU_FULL_PATH='%s', Project='%s'" % (POU_FULL_PATH, PROJECT_FILE_PATH))
959
+ primary_project = ensure_project_open(PROJECT_FILE_PATH)
960
+ if not POU_FULL_PATH: raise ValueError("POU full path empty.")
961
+
962
+ # Find the target POU/Method/Property object
963
+ target_object = find_object_by_path_robust(primary_project, POU_FULL_PATH, "target object")
964
+ if not target_object: raise ValueError("Target object not found using path: %s" % POU_FULL_PATH)
965
+
966
+ target_name = getattr(target_object, 'get_name', lambda: POU_FULL_PATH)()
967
+ print("DEBUG: Found target object: %s" % target_name)
968
+
969
+ declaration_code = ""; implementation_code = ""
970
+
971
+ # --- Get Declaration Part ---
972
+ if hasattr(target_object, 'textual_declaration'):
973
+ decl_obj = target_object.textual_declaration
974
+ if decl_obj and hasattr(decl_obj, 'text'):
975
+ try:
976
+ declaration_code = decl_obj.text
977
+ print("DEBUG: Got declaration text.")
978
+ except Exception as decl_read_err:
979
+ print("ERROR: Failed to read declaration text: %s" % decl_read_err)
980
+ declaration_code = "/* ERROR reading declaration: %s */" % decl_read_err
981
+ else:
982
+ print("WARN: textual_declaration exists but is None or has no 'text' attribute.")
983
+ else:
984
+ print("WARN: No textual_declaration attribute.")
985
+
986
+ # --- Get Implementation Part ---
987
+ if hasattr(target_object, 'textual_implementation'):
988
+ impl_obj = target_object.textual_implementation
989
+ if impl_obj and hasattr(impl_obj, 'text'):
990
+ try:
991
+ implementation_code = impl_obj.text
992
+ print("DEBUG: Got implementation text.")
993
+ except Exception as impl_read_err:
994
+ print("ERROR: Failed to read implementation text: %s" % impl_read_err)
995
+ implementation_code = "/* ERROR reading implementation: %s */" % impl_read_err
996
+ else:
997
+ print("WARN: textual_implementation exists but is None or has no 'text' attribute.")
998
+ else:
999
+ print("WARN: No textual_implementation attribute.")
1000
+
1001
+
1002
+ print("Code retrieved for: %s" % target_name)
1003
+ # Print declaration between markers, ensuring markers are on separate lines
1004
+ print("\\n" + DECL_START_MARKER)
1005
+ print(declaration_code)
1006
+ print(DECL_END_MARKER + "\\n")
1007
+ # Print implementation between markers
1008
+ print(IMPL_START_MARKER)
1009
+ print(implementation_code)
1010
+ print(IMPL_END_MARKER + "\\n")
1011
+
1012
+ # --- LEGACY MARKERS for backward compatibility if needed ---
1013
+ # Combine both for old marker format, adding a separator line
1014
+ # legacy_combined_code = declaration_code + "\\n\\n// Implementation\\n" + implementation_code
1015
+ # print(CODE_START_MARKER); print(legacy_combined_code); print(CODE_END_MARKER)
1016
+ # --- END LEGACY ---
1017
+
1018
+ print("SCRIPT_SUCCESS: Code retrieved."); sys.exit(0)
1019
+ except Exception as e:
1020
+ detailed_error = traceback.format_exc()
1021
+ error_message = "Error getting code for object '%s' in project '%s': %s\\n%s" % (POU_FULL_PATH, PROJECT_FILE_PATH, e, detailed_error)
1022
+ print(error_message); print("SCRIPT_ERROR: %s" % error_message); sys.exit(1)
1008
1023
  `;
1009
1024
  // --- MCP Resources ---
1010
1025
  // (Resource definitions remain the same)