@codesys/mcp-toolkit 1.1.8 → 1.1.10
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/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,22 @@ All notable changes to this project will be documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## [1.1.10] - 2025-05-06
|
|
9
|
+
|
|
10
|
+
### Fixed
|
|
11
|
+
- Improved handling of Windows paths in `get_project_structure` and `ensure_project_open` functions
|
|
12
|
+
- Enhanced error handling and debugging for project structure tool
|
|
13
|
+
- Added more detailed logging to help diagnose connection issues with CODESYS
|
|
14
|
+
|
|
15
|
+
## [1.1.9] - 2025-05-06
|
|
16
|
+
|
|
17
|
+
### Added
|
|
18
|
+
- Added three new MCP tools that were previously only available as resources:
|
|
19
|
+
- `check_status`: Tool to check CODESYS environment and open project status
|
|
20
|
+
- `get_project_structure`: Tool to retrieve the structure of a CODESYS project
|
|
21
|
+
- `get_pou_code`: Tool to retrieve code from a specific POU
|
|
22
|
+
- These tools allow Claude and other AI assistants to directly access project inspection functionality
|
|
23
|
+
|
|
8
24
|
## [1.1.8] - 2025-05-06
|
|
9
25
|
|
|
10
26
|
### Fixed
|
|
@@ -8,10 +8,31 @@ import traceback
|
|
|
8
8
|
MAX_RETRIES = 3
|
|
9
9
|
RETRY_DELAY = 2.0 # seconds (use float for time.sleep)
|
|
10
10
|
|
|
11
|
+
# Special handling for Windows paths
|
|
12
|
+
def sanitize_windows_path(path_str):
|
|
13
|
+
"""Properly sanitize Windows paths for CODESYS scripting"""
|
|
14
|
+
# If it's already a Python raw string literal, return it as is
|
|
15
|
+
if path_str.startswith('r"') or path_str.startswith("r'"):
|
|
16
|
+
return path_str
|
|
17
|
+
|
|
18
|
+
# Make Windows paths with backslashes work correctly when passed to CODESYS
|
|
19
|
+
# We use actual backslashes (which will be doubled by Python raw string)
|
|
20
|
+
sanitized = path_str.replace('\\', '\\\\')
|
|
21
|
+
|
|
22
|
+
# Clean up any extraneous quotes
|
|
23
|
+
sanitized = sanitized.strip('"\'')
|
|
24
|
+
|
|
25
|
+
print(f"DEBUG: Sanitized path from '{path_str}' to '{sanitized}'")
|
|
26
|
+
return sanitized
|
|
27
|
+
|
|
11
28
|
def ensure_project_open(target_project_path):
|
|
12
29
|
print("DEBUG: Ensuring project is open: %s" % target_project_path)
|
|
30
|
+
|
|
31
|
+
# First sanitize the path for proper Windows path handling
|
|
32
|
+
sanitized_path = sanitize_windows_path(target_project_path)
|
|
33
|
+
|
|
13
34
|
# Normalize target path once
|
|
14
|
-
normalized_target_path = os.path.normcase(os.path.abspath(
|
|
35
|
+
normalized_target_path = os.path.normcase(os.path.abspath(sanitized_path))
|
|
15
36
|
|
|
16
37
|
for attempt in range(MAX_RETRIES):
|
|
17
38
|
print("DEBUG: Ensure project attempt %d/%d for %s" % (attempt + 1, MAX_RETRIES, normalized_target_path))
|
|
@@ -100,8 +121,12 @@ def ensure_project_open(target_project_path):
|
|
|
100
121
|
time.sleep(RETRY_DELAY) # Give CODESYS time
|
|
101
122
|
# Re-verify: Is the project now primary and accessible?
|
|
102
123
|
recheck_primary = None
|
|
103
|
-
try:
|
|
104
|
-
|
|
124
|
+
try:
|
|
125
|
+
recheck_primary = script_engine.projects.primary
|
|
126
|
+
print(f"DEBUG: Recheck primary project type: {type(recheck_primary).__name__}")
|
|
127
|
+
except Exception as recheck_primary_err:
|
|
128
|
+
print("WARN: Error getting primary project after reopen: %s" % recheck_primary_err)
|
|
129
|
+
traceback.print_exc() # Print full trace for primary project access issue
|
|
105
130
|
|
|
106
131
|
if recheck_primary:
|
|
107
132
|
recheck_path = ""
|
|
@@ -8,9 +8,14 @@ def ensure_project_open(target_project_path):
|
|
|
8
8
|
|
|
9
9
|
def get_object_structure(obj, indent=0, max_depth=10): # Add max_depth
|
|
10
10
|
lines = []; indent_str = " " * indent
|
|
11
|
+
if obj is None:
|
|
12
|
+
lines.append("%s- ERROR: Null object received" % indent_str)
|
|
13
|
+
return lines
|
|
14
|
+
|
|
11
15
|
if indent > max_depth:
|
|
12
16
|
lines.append("%s- Max recursion depth reached." % indent_str)
|
|
13
17
|
return lines
|
|
18
|
+
|
|
14
19
|
try:
|
|
15
20
|
name = "Unnamed"; obj_type = type(obj).__name__
|
|
16
21
|
guid_str = ""
|
|
@@ -37,10 +42,10 @@ def get_object_structure(obj, indent=0, max_depth=10): # Add max_depth
|
|
|
37
42
|
if can_have_children:
|
|
38
43
|
try:
|
|
39
44
|
children = obj.get_children(False)
|
|
40
|
-
|
|
45
|
+
print("DEBUG: '%s' has %d children" % (name, len(children)))
|
|
41
46
|
except Exception as get_child_err:
|
|
42
47
|
lines.append("%s ERROR getting children: %s" % (indent_str, get_child_err))
|
|
43
|
-
|
|
48
|
+
traceback.print_exc() # Now print detailed error
|
|
44
49
|
|
|
45
50
|
for child in children:
|
|
46
51
|
lines.extend(get_object_structure(child, indent + 1, max_depth)) # Recurse
|
|
@@ -49,15 +54,63 @@ def get_object_structure(obj, indent=0, max_depth=10): # Add max_depth
|
|
|
49
54
|
lines.append("%s- Error processing node: %s" % (indent_str, e))
|
|
50
55
|
traceback.print_exc() # Print detailed error for this node
|
|
51
56
|
return lines
|
|
57
|
+
|
|
58
|
+
# Normalize Windows paths for CODESYS scripting
|
|
59
|
+
def normalize_path(path_str):
|
|
60
|
+
# Replace backslashes with double backslashes for Python string in CODESYS
|
|
61
|
+
normalized = path_str.replace('\\', '\\\\')
|
|
62
|
+
# Remove any quotes that might be present
|
|
63
|
+
normalized = normalized.strip('"\'')
|
|
64
|
+
print(f"DEBUG: Normalized path from '{path_str}' to '{normalized}'")
|
|
65
|
+
return normalized
|
|
52
66
|
|
|
53
67
|
try:
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
68
|
+
# Normalize the project path for CODESYS
|
|
69
|
+
normalized_path = normalize_path(PROJECT_FILE_PATH)
|
|
70
|
+
print("DEBUG: Getting structure for project path: '%s'" % normalized_path)
|
|
71
|
+
|
|
72
|
+
# First confirm that CODESYS is running properly
|
|
73
|
+
print("DEBUG: CODESYS version info:")
|
|
74
|
+
try:
|
|
75
|
+
version_info = script_engine.get_version_info()
|
|
76
|
+
print(f"DEBUG: CODESYS Version: {version_info}")
|
|
77
|
+
except Exception as v_err:
|
|
78
|
+
print(f"DEBUG: Error getting CODESYS version: {v_err}")
|
|
79
|
+
|
|
80
|
+
print("DEBUG: Opening project...")
|
|
81
|
+
primary_project = ensure_project_open(normalized_path)
|
|
82
|
+
|
|
83
|
+
if primary_project is None:
|
|
84
|
+
print("DEBUG: ERROR - Project object is None after ensure_project_open")
|
|
85
|
+
raise ValueError(f"Failed to open project: {normalized_path} - project object is None")
|
|
86
|
+
|
|
87
|
+
print("DEBUG: Project object type: %s" % type(primary_project).__name__)
|
|
88
|
+
project_name = os.path.basename(normalized_path)
|
|
89
|
+
|
|
90
|
+
if hasattr(primary_project, 'get_name'):
|
|
91
|
+
print("DEBUG: Project name from object: %s" % primary_project.get_name())
|
|
92
|
+
else:
|
|
93
|
+
print("DEBUG: Project object does not have get_name() method")
|
|
94
|
+
|
|
95
|
+
# Check if project has useful methods
|
|
96
|
+
if hasattr(primary_project, 'get_children'):
|
|
97
|
+
print("DEBUG: Project has get_children method")
|
|
98
|
+
else:
|
|
99
|
+
print("DEBUG: WARNING - Project does not have get_children method")
|
|
100
|
+
|
|
101
|
+
if hasattr(primary_project, 'active_application'):
|
|
102
|
+
print("DEBUG: Project has active_application property")
|
|
103
|
+
app = primary_project.active_application
|
|
104
|
+
if app:
|
|
105
|
+
print("DEBUG: Active application name: %s" % getattr(app, 'get_name', lambda: "Unknown")())
|
|
106
|
+
else:
|
|
107
|
+
print("DEBUG: WARNING - Project does not have active_application property")
|
|
108
|
+
|
|
58
109
|
# Use the project object obtained from ensure_project_open
|
|
59
|
-
|
|
110
|
+
print("DEBUG: Starting recursion for project structure with max_depth=15")
|
|
111
|
+
structure_list = get_object_structure(primary_project, max_depth=15)
|
|
60
112
|
structure_output = "\\n".join(structure_list)
|
|
113
|
+
|
|
61
114
|
# Ensure markers are printed distinctly
|
|
62
115
|
print("\\n--- PROJECT STRUCTURE START ---")
|
|
63
116
|
print(structure_output)
|
package/dist/server.js
CHANGED
|
@@ -619,6 +619,153 @@ function startMcpServer(config) {
|
|
|
619
619
|
};
|
|
620
620
|
}
|
|
621
621
|
}));
|
|
622
|
+
server.tool("check_status", "Checks the status of the CODESYS environment and any open project", {}, () => __awaiter(this, void 0, void 0, function* () {
|
|
623
|
+
var _a, _b, _c, _d;
|
|
624
|
+
console.error(`Tool call: check_status`);
|
|
625
|
+
try {
|
|
626
|
+
const scriptContent = yield (0, scriptLoader_1.loadScriptTemplate)('check_status');
|
|
627
|
+
const result = yield (0, codesys_interop_1.executeCodesysScript)(scriptContent, codesysExePath, codesysProfileName);
|
|
628
|
+
if (!result.success) {
|
|
629
|
+
return {
|
|
630
|
+
content: [{ type: "text", text: `Failed to check CODESYS status: ${result.output}` }],
|
|
631
|
+
isError: true
|
|
632
|
+
};
|
|
633
|
+
}
|
|
634
|
+
const outputLines = result.output.split(/[\r\n]+/).filter(line => line.trim());
|
|
635
|
+
const statusData = {};
|
|
636
|
+
outputLines.forEach(line => {
|
|
637
|
+
const match = line.match(/^([^:]+):\s*(.*)$/);
|
|
638
|
+
if (match) {
|
|
639
|
+
statusData[match[1].trim()] = match[2].trim();
|
|
640
|
+
}
|
|
641
|
+
});
|
|
642
|
+
const statusText = `CODESYS Status:\n - Scripting OK: ${(_a = statusData['Scripting OK']) !== null && _a !== void 0 ? _a : 'Unknown'}\n - Project Open: ${(_b = statusData['Project Open']) !== null && _b !== void 0 ? _b : 'Unknown'}\n - Project Name: ${(_c = statusData['Project Name']) !== null && _c !== void 0 ? _c : 'Unknown'}\n - Project Path: ${(_d = statusData['Project Path']) !== null && _d !== void 0 ? _d : 'N/A'}`;
|
|
643
|
+
return {
|
|
644
|
+
content: [{ type: "text", text: statusText }],
|
|
645
|
+
isError: false
|
|
646
|
+
};
|
|
647
|
+
}
|
|
648
|
+
catch (error) {
|
|
649
|
+
console.error(`Error checking status:`, error);
|
|
650
|
+
return {
|
|
651
|
+
content: [{ type: "text", text: `Failed to check CODESYS status: ${error.message}` }],
|
|
652
|
+
isError: true
|
|
653
|
+
};
|
|
654
|
+
}
|
|
655
|
+
}));
|
|
656
|
+
server.tool("get_pou_code", "Retrieves the code (declaration and implementation) of a POU from a CODESYS project", {
|
|
657
|
+
projectFilePath: zod_1.z.string().describe("Path to the CODESYS project file."),
|
|
658
|
+
pouPath: zod_1.z.string().describe("Path to the POU within the project (e.g., 'Application/MyFB').")
|
|
659
|
+
}, (args) => __awaiter(this, void 0, void 0, function* () {
|
|
660
|
+
const { projectFilePath, pouPath } = args;
|
|
661
|
+
let absPath = path.normalize(path.isAbsolute(projectFilePath) ? projectFilePath : path.join(WORKSPACE_DIR, projectFilePath));
|
|
662
|
+
const sanitizedPouPath = String(pouPath).replace(/\\/g, '/').replace(/^\/+|\/+$/g, '');
|
|
663
|
+
console.error(`Tool call: get_pou_code: Project='${absPath}', POU='${sanitizedPouPath}'`);
|
|
664
|
+
try {
|
|
665
|
+
// Load script template and prepare parameters
|
|
666
|
+
const scriptTemplate = yield (0, scriptLoader_1.loadScriptTemplate)('get_pou_code');
|
|
667
|
+
const ensureProjectOpenTemplate = yield (0, scriptLoader_1.loadScriptTemplate)('ensure_project_open');
|
|
668
|
+
const findObjectByPathTemplate = yield (0, scriptLoader_1.loadScriptTemplate)('find_object_by_path');
|
|
669
|
+
const combinedScript = ensureProjectOpenTemplate + '\n\n' + findObjectByPathTemplate + '\n\n' + scriptTemplate;
|
|
670
|
+
const scriptContent = (0, scriptLoader_1.interpolateScript)(combinedScript, {
|
|
671
|
+
'PROJECT_FILE_PATH': absPath.replace(/\\/g, '\\\\'),
|
|
672
|
+
'POU_FULL_PATH': sanitizedPouPath
|
|
673
|
+
});
|
|
674
|
+
const result = yield (0, codesys_interop_1.executeCodesysScript)(scriptContent, codesysExePath, codesysProfileName);
|
|
675
|
+
if (!result.success) {
|
|
676
|
+
return {
|
|
677
|
+
content: [{ type: "text", text: `Failed to get POU code: ${result.output}` }],
|
|
678
|
+
isError: true
|
|
679
|
+
};
|
|
680
|
+
}
|
|
681
|
+
const declStartMarker = "### POU DECLARATION START ###";
|
|
682
|
+
const declEndMarker = "### POU DECLARATION END ###";
|
|
683
|
+
const implStartMarker = "### POU IMPLEMENTATION START ###";
|
|
684
|
+
const implEndMarker = "### POU IMPLEMENTATION END ###";
|
|
685
|
+
const declStartIdx = result.output.indexOf(declStartMarker);
|
|
686
|
+
const declEndIdx = result.output.indexOf(declEndMarker);
|
|
687
|
+
const implStartIdx = result.output.indexOf(implStartMarker);
|
|
688
|
+
const implEndIdx = result.output.indexOf(implEndMarker);
|
|
689
|
+
let declaration = "/* Declaration not found in output */";
|
|
690
|
+
let implementation = "/* Implementation not found in output */";
|
|
691
|
+
let isError = false;
|
|
692
|
+
if (declStartIdx !== -1 && declEndIdx !== -1 && declStartIdx < declEndIdx) {
|
|
693
|
+
declaration = result.output.substring(declStartIdx + declStartMarker.length, declEndIdx).replace(/\\n/g, '\n').trim();
|
|
694
|
+
}
|
|
695
|
+
else {
|
|
696
|
+
console.error(`WARN: Declaration markers not found correctly for ${sanitizedPouPath}`);
|
|
697
|
+
isError = true;
|
|
698
|
+
}
|
|
699
|
+
if (implStartIdx !== -1 && implEndIdx !== -1 && implStartIdx < implEndIdx) {
|
|
700
|
+
implementation = result.output.substring(implStartIdx + implStartMarker.length, implEndIdx).replace(/\\n/g, '\n').trim();
|
|
701
|
+
}
|
|
702
|
+
else {
|
|
703
|
+
console.error(`WARN: Implementation markers not found correctly for ${sanitizedPouPath}`);
|
|
704
|
+
isError = true;
|
|
705
|
+
}
|
|
706
|
+
const codeText = `// ----- Declaration -----\n${declaration}\n\n// ----- Implementation -----\n${implementation}`;
|
|
707
|
+
return {
|
|
708
|
+
content: [{ type: "text", text: codeText }],
|
|
709
|
+
isError: isError
|
|
710
|
+
};
|
|
711
|
+
}
|
|
712
|
+
catch (error) {
|
|
713
|
+
console.error(`Error getting POU code:`, error);
|
|
714
|
+
return {
|
|
715
|
+
content: [{ type: "text", text: `Failed to get POU code for '${pouPath}' in '${projectFilePath}': ${error.message}` }],
|
|
716
|
+
isError: true
|
|
717
|
+
};
|
|
718
|
+
}
|
|
719
|
+
}));
|
|
720
|
+
server.tool("get_project_structure", "Retrieves the structure of a CODESYS project including its POUs, methods, properties, etc.", {
|
|
721
|
+
projectFilePath: zod_1.z.string().describe("Path to the CODESYS project file to examine.")
|
|
722
|
+
}, (args) => __awaiter(this, void 0, void 0, function* () {
|
|
723
|
+
const { projectFilePath } = args;
|
|
724
|
+
let absPath = path.normalize(path.isAbsolute(projectFilePath) ? projectFilePath : path.join(WORKSPACE_DIR, projectFilePath));
|
|
725
|
+
console.error(`Tool call: get_project_structure: ${absPath}`);
|
|
726
|
+
try {
|
|
727
|
+
// Load the script templates and prepare with parameters
|
|
728
|
+
const scriptTemplate = yield (0, scriptLoader_1.loadScriptTemplate)('get_project_structure');
|
|
729
|
+
const ensureProjectOpenTemplate = yield (0, scriptLoader_1.loadScriptTemplate)('ensure_project_open');
|
|
730
|
+
const combinedScript = ensureProjectOpenTemplate + '\n\n' + scriptTemplate;
|
|
731
|
+
const scriptContent = (0, scriptLoader_1.interpolateScript)(combinedScript, {
|
|
732
|
+
'PROJECT_FILE_PATH': absPath.replace(/\\/g, '\\\\')
|
|
733
|
+
});
|
|
734
|
+
const result = yield (0, codesys_interop_1.executeCodesysScript)(scriptContent, codesysExePath, codesysProfileName);
|
|
735
|
+
if (!result.success) {
|
|
736
|
+
return {
|
|
737
|
+
content: [{ type: "text", text: `Failed to get project structure: ${result.output}` }],
|
|
738
|
+
isError: true
|
|
739
|
+
};
|
|
740
|
+
}
|
|
741
|
+
// Extract the structure from the output
|
|
742
|
+
let structureText = '';
|
|
743
|
+
const startMarker = "--- PROJECT STRUCTURE START ---";
|
|
744
|
+
const endMarker = "--- PROJECT STRUCTURE END ---";
|
|
745
|
+
const startIndex = result.output.indexOf(startMarker);
|
|
746
|
+
const endIndex = result.output.indexOf(endMarker);
|
|
747
|
+
if (startIndex !== -1 && endIndex !== -1 && startIndex < endIndex) {
|
|
748
|
+
structureText = result.output.substring(startIndex + startMarker.length, endIndex).replace(/\\n/g, '\n').trim();
|
|
749
|
+
return {
|
|
750
|
+
content: [{ type: "text", text: structureText }],
|
|
751
|
+
isError: false
|
|
752
|
+
};
|
|
753
|
+
}
|
|
754
|
+
else {
|
|
755
|
+
return {
|
|
756
|
+
content: [{ type: "text", text: `Could not parse structure markers in output for ${absPath}.\n\nOutput:\n${result.output}` }],
|
|
757
|
+
isError: true
|
|
758
|
+
};
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
catch (error) {
|
|
762
|
+
console.error(`Error tool get_project_structure:`, error);
|
|
763
|
+
return {
|
|
764
|
+
content: [{ type: "text", text: `Failed to get project structure for '${projectFilePath}': ${error.message}` }],
|
|
765
|
+
isError: true
|
|
766
|
+
};
|
|
767
|
+
}
|
|
768
|
+
}));
|
|
622
769
|
server.tool("compile_project", "Compiles (Builds) the primary application within a CODESYS project.", {
|
|
623
770
|
projectFilePath: zod_1.z.string().describe("Path to the project file containing the application to compile (e.g., 'C:/Projects/MyPLC.project').")
|
|
624
771
|
}, (args) => __awaiter(this, void 0, void 0, function* () {
|
package/package.json
CHANGED
|
@@ -8,10 +8,31 @@ import traceback
|
|
|
8
8
|
MAX_RETRIES = 3
|
|
9
9
|
RETRY_DELAY = 2.0 # seconds (use float for time.sleep)
|
|
10
10
|
|
|
11
|
+
# Special handling for Windows paths
|
|
12
|
+
def sanitize_windows_path(path_str):
|
|
13
|
+
"""Properly sanitize Windows paths for CODESYS scripting"""
|
|
14
|
+
# If it's already a Python raw string literal, return it as is
|
|
15
|
+
if path_str.startswith('r"') or path_str.startswith("r'"):
|
|
16
|
+
return path_str
|
|
17
|
+
|
|
18
|
+
# Make Windows paths with backslashes work correctly when passed to CODESYS
|
|
19
|
+
# We use actual backslashes (which will be doubled by Python raw string)
|
|
20
|
+
sanitized = path_str.replace('\\', '\\\\')
|
|
21
|
+
|
|
22
|
+
# Clean up any extraneous quotes
|
|
23
|
+
sanitized = sanitized.strip('"\'')
|
|
24
|
+
|
|
25
|
+
print(f"DEBUG: Sanitized path from '{path_str}' to '{sanitized}'")
|
|
26
|
+
return sanitized
|
|
27
|
+
|
|
11
28
|
def ensure_project_open(target_project_path):
|
|
12
29
|
print("DEBUG: Ensuring project is open: %s" % target_project_path)
|
|
30
|
+
|
|
31
|
+
# First sanitize the path for proper Windows path handling
|
|
32
|
+
sanitized_path = sanitize_windows_path(target_project_path)
|
|
33
|
+
|
|
13
34
|
# Normalize target path once
|
|
14
|
-
normalized_target_path = os.path.normcase(os.path.abspath(
|
|
35
|
+
normalized_target_path = os.path.normcase(os.path.abspath(sanitized_path))
|
|
15
36
|
|
|
16
37
|
for attempt in range(MAX_RETRIES):
|
|
17
38
|
print("DEBUG: Ensure project attempt %d/%d for %s" % (attempt + 1, MAX_RETRIES, normalized_target_path))
|
|
@@ -100,8 +121,12 @@ def ensure_project_open(target_project_path):
|
|
|
100
121
|
time.sleep(RETRY_DELAY) # Give CODESYS time
|
|
101
122
|
# Re-verify: Is the project now primary and accessible?
|
|
102
123
|
recheck_primary = None
|
|
103
|
-
try:
|
|
104
|
-
|
|
124
|
+
try:
|
|
125
|
+
recheck_primary = script_engine.projects.primary
|
|
126
|
+
print(f"DEBUG: Recheck primary project type: {type(recheck_primary).__name__}")
|
|
127
|
+
except Exception as recheck_primary_err:
|
|
128
|
+
print("WARN: Error getting primary project after reopen: %s" % recheck_primary_err)
|
|
129
|
+
traceback.print_exc() # Print full trace for primary project access issue
|
|
105
130
|
|
|
106
131
|
if recheck_primary:
|
|
107
132
|
recheck_path = ""
|
|
@@ -8,9 +8,14 @@ def ensure_project_open(target_project_path):
|
|
|
8
8
|
|
|
9
9
|
def get_object_structure(obj, indent=0, max_depth=10): # Add max_depth
|
|
10
10
|
lines = []; indent_str = " " * indent
|
|
11
|
+
if obj is None:
|
|
12
|
+
lines.append("%s- ERROR: Null object received" % indent_str)
|
|
13
|
+
return lines
|
|
14
|
+
|
|
11
15
|
if indent > max_depth:
|
|
12
16
|
lines.append("%s- Max recursion depth reached." % indent_str)
|
|
13
17
|
return lines
|
|
18
|
+
|
|
14
19
|
try:
|
|
15
20
|
name = "Unnamed"; obj_type = type(obj).__name__
|
|
16
21
|
guid_str = ""
|
|
@@ -37,10 +42,10 @@ def get_object_structure(obj, indent=0, max_depth=10): # Add max_depth
|
|
|
37
42
|
if can_have_children:
|
|
38
43
|
try:
|
|
39
44
|
children = obj.get_children(False)
|
|
40
|
-
|
|
45
|
+
print("DEBUG: '%s' has %d children" % (name, len(children)))
|
|
41
46
|
except Exception as get_child_err:
|
|
42
47
|
lines.append("%s ERROR getting children: %s" % (indent_str, get_child_err))
|
|
43
|
-
|
|
48
|
+
traceback.print_exc() # Now print detailed error
|
|
44
49
|
|
|
45
50
|
for child in children:
|
|
46
51
|
lines.extend(get_object_structure(child, indent + 1, max_depth)) # Recurse
|
|
@@ -49,15 +54,63 @@ def get_object_structure(obj, indent=0, max_depth=10): # Add max_depth
|
|
|
49
54
|
lines.append("%s- Error processing node: %s" % (indent_str, e))
|
|
50
55
|
traceback.print_exc() # Print detailed error for this node
|
|
51
56
|
return lines
|
|
57
|
+
|
|
58
|
+
# Normalize Windows paths for CODESYS scripting
|
|
59
|
+
def normalize_path(path_str):
|
|
60
|
+
# Replace backslashes with double backslashes for Python string in CODESYS
|
|
61
|
+
normalized = path_str.replace('\\', '\\\\')
|
|
62
|
+
# Remove any quotes that might be present
|
|
63
|
+
normalized = normalized.strip('"\'')
|
|
64
|
+
print(f"DEBUG: Normalized path from '{path_str}' to '{normalized}'")
|
|
65
|
+
return normalized
|
|
52
66
|
|
|
53
67
|
try:
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
68
|
+
# Normalize the project path for CODESYS
|
|
69
|
+
normalized_path = normalize_path(PROJECT_FILE_PATH)
|
|
70
|
+
print("DEBUG: Getting structure for project path: '%s'" % normalized_path)
|
|
71
|
+
|
|
72
|
+
# First confirm that CODESYS is running properly
|
|
73
|
+
print("DEBUG: CODESYS version info:")
|
|
74
|
+
try:
|
|
75
|
+
version_info = script_engine.get_version_info()
|
|
76
|
+
print(f"DEBUG: CODESYS Version: {version_info}")
|
|
77
|
+
except Exception as v_err:
|
|
78
|
+
print(f"DEBUG: Error getting CODESYS version: {v_err}")
|
|
79
|
+
|
|
80
|
+
print("DEBUG: Opening project...")
|
|
81
|
+
primary_project = ensure_project_open(normalized_path)
|
|
82
|
+
|
|
83
|
+
if primary_project is None:
|
|
84
|
+
print("DEBUG: ERROR - Project object is None after ensure_project_open")
|
|
85
|
+
raise ValueError(f"Failed to open project: {normalized_path} - project object is None")
|
|
86
|
+
|
|
87
|
+
print("DEBUG: Project object type: %s" % type(primary_project).__name__)
|
|
88
|
+
project_name = os.path.basename(normalized_path)
|
|
89
|
+
|
|
90
|
+
if hasattr(primary_project, 'get_name'):
|
|
91
|
+
print("DEBUG: Project name from object: %s" % primary_project.get_name())
|
|
92
|
+
else:
|
|
93
|
+
print("DEBUG: Project object does not have get_name() method")
|
|
94
|
+
|
|
95
|
+
# Check if project has useful methods
|
|
96
|
+
if hasattr(primary_project, 'get_children'):
|
|
97
|
+
print("DEBUG: Project has get_children method")
|
|
98
|
+
else:
|
|
99
|
+
print("DEBUG: WARNING - Project does not have get_children method")
|
|
100
|
+
|
|
101
|
+
if hasattr(primary_project, 'active_application'):
|
|
102
|
+
print("DEBUG: Project has active_application property")
|
|
103
|
+
app = primary_project.active_application
|
|
104
|
+
if app:
|
|
105
|
+
print("DEBUG: Active application name: %s" % getattr(app, 'get_name', lambda: "Unknown")())
|
|
106
|
+
else:
|
|
107
|
+
print("DEBUG: WARNING - Project does not have active_application property")
|
|
108
|
+
|
|
58
109
|
# Use the project object obtained from ensure_project_open
|
|
59
|
-
|
|
110
|
+
print("DEBUG: Starting recursion for project structure with max_depth=15")
|
|
111
|
+
structure_list = get_object_structure(primary_project, max_depth=15)
|
|
60
112
|
structure_output = "\\n".join(structure_list)
|
|
113
|
+
|
|
61
114
|
# Ensure markers are printed distinctly
|
|
62
115
|
print("\\n--- PROJECT STRUCTURE START ---")
|
|
63
116
|
print(structure_output)
|