xrobot 0.1.0__tar.gz

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.
xrobot-0.1.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
xrobot-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,27 @@
1
+ Metadata-Version: 2.4
2
+ Name: xrobot
3
+ Version: 0.1.0
4
+ Summary: A Python package for parsing IOC files and generating C++ code.
5
+ Author-email: Xiao <2592509183@qq.com>
6
+ Maintainer-email: Xiao <2592509183@qq.com>
7
+ License: Apache-2.0
8
+ Project-URL: Homepage, https://github.com/xrobot-org
9
+ Project-URL: Documentation, https://xrobot-org.github.io
10
+ Project-URL: Repository, https://github.com/xrobot-org/XRobot
11
+ Project-URL: Bug Tracker, https://github.com/xrobot-org/XRobot/issues
12
+ Keywords: code generation,embedded systems,automation
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Operating System :: OS Independent
17
+ Requires-Python: >=3.8
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: argparse
21
+ Requires-Dist: pyyaml
22
+ Provides-Extra: gui
23
+ Requires-Dist: PyQt5; extra == "gui"
24
+ Provides-Extra: cli
25
+ Requires-Dist: rich; extra == "cli"
26
+ Requires-Dist: click; extra == "cli"
27
+ Dynamic: license-file
xrobot-0.1.0/README.md ADDED
File without changes
@@ -0,0 +1,50 @@
1
+ [build-system]
2
+ requires = ["setuptools", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "xrobot"
7
+ version = "0.1.0"
8
+ description = "A Python package for parsing IOC files and generating C++ code."
9
+ requires-python = ">=3.8"
10
+ authors = [
11
+ {name = "Xiao", email = "2592509183@qq.com"}
12
+ ]
13
+ maintainers = [
14
+ {name = "Xiao", email = "2592509183@qq.com"}
15
+ ]
16
+ readme = "README.md"
17
+ license = {text = "Apache-2.0"}
18
+ keywords = ["code generation", "embedded systems", "automation"]
19
+ dependencies = [
20
+ "argparse",
21
+ "pyyaml"
22
+ ]
23
+
24
+ classifiers = [
25
+ "Development Status :: 3 - Alpha",
26
+ "Programming Language :: Python :: 3",
27
+ "License :: OSI Approved :: Apache Software License",
28
+ "Operating System :: OS Independent",
29
+ ]
30
+
31
+ [project.optional-dependencies]
32
+ gui = ["PyQt5"]
33
+ cli = ["rich", "click"]
34
+
35
+ [project.urls]
36
+ Homepage = "https://github.com/xrobot-org"
37
+ Documentation = "https://xrobot-org.github.io"
38
+ Repository = "https://github.com/xrobot-org/XRobot"
39
+ "Bug Tracker" = "https://github.com/xrobot-org/XRobot/issues"
40
+
41
+ [project.scripts]
42
+ xrobot_gen_main = "xrobot.GenerateMain:main"
43
+ xrobot_mod_parser = "xrobot.ModuleParser:main"
44
+ xrobot_create_mod = "xrobot.ModuleCreator:main"
45
+ xrobot_init_mod = "xrobot.InitModule:main"
46
+ xrobot_setup = "xrobot.XRobotSetup:main"
47
+ xrobot_add_mod = "xrobot.AddModule:main"
48
+
49
+ [tool.setuptools.packages.find]
50
+ where = ["src"]
xrobot-0.1.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,120 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ xrobot_add_mod.py - 添加模块仓库或追加模块实例配置
4
+
5
+ Usage 示例:
6
+ # 添加模块仓库(默认写入 Modules/modules.yaml)
7
+ python xrobot_add_mod.py https://github.com/yourorg/BlinkLED.git --version main
8
+
9
+ # 追加模块实例(默认写入 User/xrobot.yaml)
10
+ python xrobot_add_mod.py BlinkLED
11
+ """
12
+
13
+ import argparse
14
+ import yaml
15
+ from pathlib import Path
16
+ from urllib.parse import urlparse
17
+ from collections import OrderedDict
18
+
19
+ DEFAULT_REPO_CONFIG = Path("Modules/modules.yaml")
20
+ DEFAULT_INSTANCE_CONFIG = Path("User/xrobot.yaml")
21
+ MODULES_DIR = Path("Modules")
22
+
23
+ def is_repo_url(s: str) -> bool:
24
+ return s.startswith("http://") or s.startswith("https://")
25
+
26
+ def extract_name_from_repo(repo: str) -> str:
27
+ return Path(urlparse(repo).path).stem
28
+
29
+ def load_yaml(path: Path) -> dict:
30
+ return yaml.safe_load(path.read_text(encoding="utf-8")) if path.exists() else {}
31
+
32
+ def save_yaml(path: Path, data: dict):
33
+ path.parent.mkdir(parents=True, exist_ok=True)
34
+ path.write_text(yaml.dump(data, sort_keys=False, allow_unicode=True), encoding="utf-8")
35
+
36
+ def parse_manifest_from_header(header_path: Path) -> dict:
37
+ content = header_path.read_text(encoding="utf-8")
38
+ lines = content.splitlines()
39
+ block = []
40
+ inside = False
41
+
42
+ for line in lines:
43
+ stripped = line.strip()
44
+ if stripped == "/* === MODULE MANIFEST ===":
45
+ inside = True
46
+ continue
47
+ if stripped == "=== END MANIFEST === */":
48
+ break
49
+ if inside:
50
+ block.append(line.replace("/*", " ").replace("*/", " ").rstrip())
51
+
52
+ try:
53
+ return yaml.safe_load("\n".join(block)) or {}
54
+ except yaml.YAMLError as e:
55
+ print(f"[ERROR] Failed to parse manifest: {e}")
56
+ return {}
57
+
58
+ def append_module_instance(module_name: str, config_path: Path):
59
+ header_path = MODULES_DIR / module_name / f"{module_name}.hpp"
60
+ if not header_path.exists():
61
+ print(f"[ERROR] Module header not found: {header_path}")
62
+ return
63
+
64
+ manifest = parse_manifest_from_header(header_path)
65
+ args = manifest.get("constructor_args", {})
66
+ args_ordered = OrderedDict()
67
+ if isinstance(args, dict):
68
+ args_ordered.update(args)
69
+ elif isinstance(args, list):
70
+ for item in args:
71
+ if isinstance(item, dict):
72
+ args_ordered.update(item)
73
+
74
+ data = load_yaml(config_path)
75
+ if "modules" not in data or not isinstance(data["modules"], list):
76
+ data["modules"] = []
77
+
78
+ data["modules"].append({
79
+ "name": module_name,
80
+ "constructor_args": dict(args_ordered)
81
+ })
82
+
83
+ save_yaml(config_path, data)
84
+ print(f"[SUCCESS] Appended module instance '{module_name}' to {config_path}")
85
+
86
+ def add_repo_entry(repo: str, version: str, config_path: Path):
87
+ name = extract_name_from_repo(repo)
88
+ data = load_yaml(config_path)
89
+ modules = data.get("modules", [])
90
+
91
+ if any(m.get("name") == name for m in modules):
92
+ print(f"[WARN] Module '{name}' already exists in {config_path}. Skipping.")
93
+ return
94
+
95
+ entry = {"name": name, "repo": repo}
96
+ if version:
97
+ entry["version"] = version
98
+ modules.append(entry)
99
+
100
+ save_yaml(config_path, {"modules": modules})
101
+ print(f"[SUCCESS] Added repo module '{name}' to {config_path}")
102
+
103
+ def main():
104
+ parser = argparse.ArgumentParser(description="Add module repo or instance config to YAML")
105
+ parser.add_argument("target", help="Repo URL or local module name")
106
+ parser.add_argument("--version", "-v", help="Branch or tag (repo only)")
107
+ parser.add_argument("--config", "-c", help="YAML file path to write (auto default)")
108
+
109
+ args = parser.parse_args()
110
+
111
+ # 判断类型并选择默认 config 路径
112
+ if is_repo_url(args.target):
113
+ config_path = Path(args.config) if args.config else DEFAULT_REPO_CONFIG
114
+ add_repo_entry(args.target, args.version, config_path)
115
+ else:
116
+ config_path = Path(args.config) if args.config else DEFAULT_INSTANCE_CONFIG
117
+ append_module_instance(args.target, config_path)
118
+
119
+ if __name__ == "__main__":
120
+ main()
@@ -0,0 +1,195 @@
1
+ import yaml
2
+ import argparse
3
+ from pathlib import Path
4
+ from collections import OrderedDict
5
+ from typing import Union, Dict, List
6
+
7
+
8
+ def parse_manifest_from_header(header_path: Path) -> Dict:
9
+ """Extract and parse manifest data from module header file."""
10
+ content = header_path.read_text(encoding="utf-8")
11
+ manifest_block = []
12
+ in_manifest = False
13
+
14
+ for line in content.splitlines():
15
+ stripped = line.strip()
16
+ if stripped == "/* === MODULE MANIFEST ===":
17
+ in_manifest = True
18
+ continue
19
+ if stripped == "=== END MANIFEST === */":
20
+ break
21
+ if in_manifest:
22
+ cleaned_line = line.replace("/*", " ").replace("*/", " ").rstrip()
23
+ manifest_block.append(cleaned_line)
24
+
25
+ try:
26
+ manifest_data = yaml.safe_load("\n".join(manifest_block)) or {}
27
+ except yaml.YAMLError as e:
28
+ print(f"[ERROR] YAML parsing failed: {str(e)}")
29
+ return {}
30
+
31
+ if 'constructor_args' in manifest_data:
32
+ raw_args = manifest_data['constructor_args']
33
+ ordered_args = OrderedDict()
34
+
35
+ if isinstance(raw_args, dict):
36
+ ordered_args.update(raw_args)
37
+ elif isinstance(raw_args, list):
38
+ for item in raw_args:
39
+ if isinstance(item, dict):
40
+ ordered_args.update(item)
41
+ else:
42
+ print(f"[WARN] Unsupported constructor_args type: {type(raw_args)}")
43
+
44
+ manifest_data['constructor_args'] = ordered_args
45
+
46
+ return manifest_data
47
+
48
+
49
+ def _format_cpp_value(value: Union[dict, list, str, int, float, bool]) -> str:
50
+ """Generate C++-compliant parameter values."""
51
+ if isinstance(value, dict):
52
+ inner = ", ".join(_format_cpp_value(v) for _, v in value.items())
53
+ return f"{{{inner}}}"
54
+ elif isinstance(value, list):
55
+ return "{" + ", ".join(_format_cpp_value(v) for v in value) + "}"
56
+ elif isinstance(value, bool):
57
+ return "true" if value else "false"
58
+ elif isinstance(value, str):
59
+ return f'"{value}"'
60
+ else:
61
+ return str(value)
62
+
63
+
64
+ def extract_constructor_args(modules: List[str], module_dir: Path, config_path: Path) -> Dict:
65
+ """Extract default constructor_args for each module and save to YAML in list format."""
66
+ output = {
67
+ "global_settings": {
68
+ "monitor_sleep_ms": 1000
69
+ },
70
+ "modules": []
71
+ }
72
+
73
+ for mod in modules:
74
+ hpp_path = module_dir / mod / f"{mod}.hpp"
75
+ if not hpp_path.exists():
76
+ print(f"[WARN] Header not found for module: {mod}")
77
+ continue
78
+
79
+ manifest = parse_manifest_from_header(hpp_path)
80
+ args_raw = manifest.get("constructor_args", {})
81
+ args_ordered = OrderedDict()
82
+
83
+ if isinstance(args_raw, dict):
84
+ args_ordered.update(args_raw)
85
+ elif isinstance(args_raw, list):
86
+ for item in args_raw:
87
+ if isinstance(item, dict):
88
+ args_ordered.update(item)
89
+
90
+ # Append as new module instance
91
+ output["modules"].append({
92
+ "name": mod,
93
+ "constructor_args": dict(args_ordered)
94
+ })
95
+
96
+ config_path.write_text(
97
+ yaml.dump(output, sort_keys=False, allow_unicode=True, indent=2),
98
+ encoding="utf-8"
99
+ )
100
+
101
+ return output
102
+
103
+
104
+ def generate_xrobot_main_code(hw_var: str, modules: List[str], config: Dict) -> str:
105
+ """Generate main application code with module instantiations."""
106
+ sleep_ms = config.get("global_settings", {}).get("monitor_sleep_ms", 1000)
107
+ headers = [
108
+ '#include "app_framework.hpp"',
109
+ '#include "libxr.hpp"',
110
+ "",
111
+ "// Module headers"
112
+ ] + [f'#include "{mod}.hpp"' for mod in modules]
113
+
114
+ body = [
115
+ f"template <typename HardwareContainer>",
116
+ f"static void XRobotMain(HardwareContainer &{hw_var}) {{",
117
+ f" using namespace LibXR;",
118
+ f" ApplicationManager appmgr;",
119
+ f"",
120
+ f" // Auto-generated module instantiations",
121
+ ]
122
+
123
+ module_entries = config.get("modules", [])
124
+ if not isinstance(module_entries, list):
125
+ raise TypeError("[ERROR] 'modules' must be a list of module instances")
126
+
127
+ instance_count = {}
128
+
129
+ for entry in module_entries:
130
+ mod = entry.get("name")
131
+ if mod not in modules:
132
+ continue
133
+
134
+ args_dict = entry.get("constructor_args", {})
135
+ args_list = [_format_cpp_value(v) for _, v in args_dict.items()]
136
+
137
+ # Support for multiple instances of the same module
138
+ count = instance_count.get(mod, 0)
139
+ instance_name = f"{mod.lower()}{count}" if count > 0 else mod.lower()
140
+ instance_count[mod] = count + 1
141
+
142
+ instance_line = f" {mod}<HardwareContainer> {instance_name}({hw_var}, appmgr"
143
+ if args_list:
144
+ instance_line += ", " + ", ".join(args_list)
145
+ instance_line += ");"
146
+ body.append(instance_line)
147
+
148
+ body += [
149
+ "",
150
+ f" while (true) {{",
151
+ f" appmgr.MonitorAll();",
152
+ f" Thread::Sleep({sleep_ms});",
153
+ f" }}",
154
+ f"}}"
155
+ ]
156
+
157
+ return "\n".join(headers + [""] + body)
158
+
159
+
160
+ def auto_discover_modules(modules_dir: Path = Path("Modules")) -> List[str]:
161
+ """Discover available modules in directory."""
162
+ return [sub.name for sub in modules_dir.iterdir() if sub.is_dir() and (sub / f"{sub.name}.hpp").exists()]
163
+
164
+
165
+ def main():
166
+ parser = argparse.ArgumentParser(description="XRobot code generation tool")
167
+ parser.add_argument("-o", "--output", required=True, help="Output CPP file path")
168
+ parser.add_argument("-m", "--modules", nargs="+", default=[], help="List of modules to include")
169
+ parser.add_argument("--hw", default="hw", help="Hardware container variable name")
170
+ parser.add_argument("-c", "--config", help="Configuration file path")
171
+
172
+ args = parser.parse_args()
173
+
174
+ # Module discovery
175
+ if not args.modules:
176
+ args.modules = auto_discover_modules()
177
+ print(f"Discovered modules: {', '.join(args.modules) or 'None'}")
178
+
179
+ # Configuration handling
180
+ config_data = {}
181
+ if args.config:
182
+ config_path = Path(args.config)
183
+ if config_path.exists():
184
+ config_data = yaml.safe_load(config_path.read_text(encoding="utf-8")) or {}
185
+ else:
186
+ config_data = extract_constructor_args(args.modules, Path("Modules"), config_path)
187
+
188
+ # Code generation
189
+ output_code = generate_xrobot_main_code(args.hw, args.modules, config_data)
190
+ Path(args.output).write_text(output_code, encoding="utf-8")
191
+ print(f"[SUCCESS] Generated entry file: {args.output}")
192
+
193
+
194
+ if __name__ == "__main__":
195
+ main()
@@ -0,0 +1,79 @@
1
+ import argparse
2
+ import subprocess
3
+ import yaml
4
+ from pathlib import Path
5
+
6
+ CONFIG_TEMPLATE = """# XRobot module configuration example
7
+ modules:
8
+ - name: BlinkLED
9
+ repo: https://github.com/xrobot-org/BlinkLED
10
+ version: master # optional: branch name or tag
11
+ """
12
+
13
+ def execute_git_command(cmd: list[str], workdir: Path = None):
14
+ """Execute git commands with error handling."""
15
+ try:
16
+ subprocess.run(cmd, cwd=workdir, check=True)
17
+ except subprocess.CalledProcessError as e:
18
+ print(f"[ERROR] Git command failed: {' '.join(cmd)}\n{str(e)}")
19
+
20
+ def sync_module(name: str, repo: str, version: str, base_dir: Path):
21
+ """Clone or update a module repository."""
22
+ module_path = base_dir / name
23
+
24
+ if module_path.exists() and (module_path / ".git").exists():
25
+ print(f"[INFO] Updating module: {name}")
26
+ execute_git_command(["git", "pull"], workdir=module_path)
27
+ if version:
28
+ execute_git_command(["git", "checkout", version], workdir=module_path)
29
+ else:
30
+ print(f"[INFO] Cloning new module: {name}")
31
+ clone_cmd = ["git", "clone", "--recurse-submodules"]
32
+ if version:
33
+ clone_cmd += ["--branch", version]
34
+ clone_cmd += [repo, str(module_path)]
35
+ execute_git_command(clone_cmd)
36
+
37
+ def load_configuration(config_path: Path) -> list[dict]:
38
+ """Load module configuration from YAML file."""
39
+ if not config_path.exists():
40
+ print(f"[WARN] Configuration file not found, creating template: {config_path}")
41
+ config_path.write_text(CONFIG_TEMPLATE, encoding="utf-8")
42
+ print("[INFO] Please edit the configuration file and rerun this script.")
43
+ return []
44
+
45
+ with config_path.open(encoding="utf-8") as f:
46
+ config_data = yaml.safe_load(f)
47
+ return config_data.get("modules", [])
48
+
49
+ def main():
50
+ """Main entry point for module synchronization."""
51
+ parser = argparse.ArgumentParser(
52
+ description="XRobot module synchronization tool",
53
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter
54
+ )
55
+ parser.add_argument("--config", "-c", default="modules.yaml",
56
+ help="Path to module configuration file")
57
+ parser.add_argument("--directory", "-d", default="Modules",
58
+ help="Output directory for module repositories")
59
+
60
+ args = parser.parse_args()
61
+ config_file = Path(args.config)
62
+ module_dir = Path(args.directory)
63
+ module_dir.mkdir(parents=True, exist_ok=True)
64
+
65
+ modules = load_configuration(config_file)
66
+ if not modules:
67
+ return
68
+
69
+ for module in modules:
70
+ if not all(key in module for key in ("name", "repo")):
71
+ print(f"[WARN] Skipping invalid module entry: {module}")
72
+ continue
73
+ version = module.get("version", None)
74
+ sync_module(module["name"], module["repo"], version, module_dir)
75
+
76
+ print("[SUCCESS] All modules processed")
77
+
78
+ if __name__ == "__main__":
79
+ main()
@@ -0,0 +1,107 @@
1
+ import argparse
2
+ from pathlib import Path
3
+
4
+ HEADER_TEMPLATE = """#pragma once
5
+
6
+ // clang-format off
7
+ /* === MODULE MANIFEST ===
8
+ module_name: {module_name}
9
+ module_description: {description}
10
+ {constructor_line}{hardware_line}{repo_line}=== END MANIFEST === */
11
+ // clang-format on
12
+
13
+ #include "app_framework.hpp"
14
+
15
+ template <typename HardwareContainer>
16
+ class {module_name} : public LibXR::Application {{
17
+ public:
18
+ {constructor_signature} {{
19
+ // Hardware initialization example:
20
+ // auto dev = hw.template Find<LibXR::GPIO>("led");
21
+ }}
22
+
23
+ private:
24
+ }};
25
+ """
26
+
27
+ README_TEMPLATE = """# {module_name}
28
+
29
+ {description}
30
+
31
+ ## Required Hardware
32
+ {hardware}
33
+
34
+ {repo_block}
35
+ """
36
+
37
+ def create_module(module_name: str,
38
+ description: str,
39
+ required_hardware: list[str],
40
+ repository: str,
41
+ output_dir: Path = Path("Modules")):
42
+ """Create a new XRobot module with standard structure"""
43
+ mod_dir = output_dir / module_name
44
+ mod_dir.mkdir(parents=True, exist_ok=True)
45
+
46
+ # Template configuration for constructor arguments
47
+ constructor_line = "constructor_args:\n - name: \"your_arg_name_here\"\n"
48
+ hardware_line = f"required_hardware: {' '.join(required_hardware)}\n" if required_hardware else ""
49
+ repo_line = f"repository: {repository}\n" if repository else ""
50
+
51
+ # Constructor signature template
52
+ constructor_signature = f"{module_name}(HardwareContainer &hw, LibXR::ApplicationManager &app)"
53
+
54
+ # Generate header file
55
+ hpp_code = HEADER_TEMPLATE.format(
56
+ module_name=module_name,
57
+ description=description,
58
+ constructor_line=constructor_line,
59
+ hardware_line=hardware_line,
60
+ repo_line=repo_line,
61
+ constructor_signature=constructor_signature
62
+ )
63
+
64
+ # Generate documentation
65
+ readme_code = README_TEMPLATE.format(
66
+ module_name=module_name,
67
+ description=description,
68
+ hardware=", ".join(required_hardware) or "None",
69
+ repo_block=f"## Repository\n{repository}" if repository else ""
70
+ )
71
+
72
+ (mod_dir / f"{module_name}.hpp").write_text(hpp_code, encoding="utf-8")
73
+ (mod_dir / "README.md").write_text(readme_code, encoding="utf-8")
74
+
75
+ # Generate build configuration
76
+ cmake_code = f"""# CMakeLists.txt for {module_name}
77
+
78
+ # Add module to include path
79
+ target_include_directories(xr PUBLIC ${{CMAKE_CURRENT_LIST_DIR}})
80
+
81
+ # Auto-include source files
82
+ file(GLOB MODULE_{module_name.upper()}_SRC
83
+ "${{CMAKE_CURRENT_LIST_DIR}}/*.cpp"
84
+ "${{CMAKE_CURRENT_LIST_DIR}}/*.c"
85
+ )
86
+
87
+ target_sources(xr PRIVATE ${{MODULE_{module_name.upper()}_SRC}})
88
+ """
89
+ (mod_dir / "CMakeLists.txt").write_text(cmake_code, encoding="utf-8")
90
+
91
+ print(f"[OK] Module {module_name} generated at {mod_dir}")
92
+
93
+
94
+ def main():
95
+ parser = argparse.ArgumentParser(description="Create a new XRobot module")
96
+ parser.add_argument("module_name", help="Module name (must match directory name)")
97
+ parser.add_argument("--desc", default="No description provided", help="Module description")
98
+ parser.add_argument("--hw", nargs="*", default=[], help="Required hardware interfaces (logical names)")
99
+ parser.add_argument("--repo", default="", help="GitHub repository URL (optional)")
100
+ parser.add_argument("--out", default="Modules", help="Output directory (default: Modules/)")
101
+
102
+ args = parser.parse_args()
103
+ create_module(args.module_name, args.desc, args.hw, args.repo, Path(args.out))
104
+
105
+
106
+ if __name__ == "__main__":
107
+ main()
@@ -0,0 +1,155 @@
1
+ import re
2
+ import yaml
3
+ import argparse
4
+ from pathlib import Path
5
+ from typing import Optional, Dict, Union, OrderedDict
6
+
7
+
8
+ def parse_constructor_args(text: str) -> OrderedDict:
9
+ """Parse constructor arguments with nested structure support.
10
+
11
+ Returns:
12
+ OrderedDict: Preserves argument order while maintaining nested structure awareness
13
+ """
14
+ args_dict = OrderedDict()
15
+ depth = 0
16
+ buffer = ""
17
+ key = None
18
+ i = 0
19
+
20
+ while i < len(text):
21
+ c = text[i]
22
+ if c in "{[(":
23
+ depth += 1
24
+ buffer += c
25
+ elif c in "}])":
26
+ depth -= 1
27
+ buffer += c
28
+ elif c == "," and depth == 0:
29
+ part = buffer.strip()
30
+ if "=" in part:
31
+ k, v = map(str.strip, part.split("=", 1))
32
+ args_dict[k] = v
33
+ elif key is not None:
34
+ args_dict[key] = part
35
+ buffer = ""
36
+ key = None
37
+ else:
38
+ buffer += c
39
+ i += 1
40
+
41
+ # Process final item
42
+ if buffer.strip():
43
+ part = buffer.strip()
44
+ if "=" in part:
45
+ k, v = map(str.strip, part.split("=", 1))
46
+ args_dict[k] = v
47
+ elif key is not None:
48
+ args_dict[key] = part
49
+
50
+ return args_dict
51
+
52
+
53
+ def parse_manifest_from_header(header_path: Path) -> Optional[dict]:
54
+ """Extract and parse manifest block from module header file."""
55
+ try:
56
+ content = header_path.read_text(encoding="utf-8-sig") # Handle BOM
57
+ except UnicodeDecodeError:
58
+ content = header_path.read_text(encoding="utf-8")
59
+
60
+ # Robust regex pattern allowing whitespace and line breaks
61
+ pattern = re.compile(
62
+ r"/\*\s*=== MODULE MANIFEST ===\s*[\r\n]+(.*?)[\r\n]+\s*=== END MANIFEST ===\s*\*/",
63
+ re.DOTALL
64
+ )
65
+ match = pattern.search(content)
66
+ if not match:
67
+ return None
68
+
69
+ manifest_block = match.group(1)
70
+ manifest_block = "\n".join(
71
+ [line.rstrip() for line in manifest_block.splitlines() if line.strip()]
72
+ )
73
+
74
+ try:
75
+ return yaml.safe_load(manifest_block)
76
+ except yaml.YAMLError:
77
+ return None
78
+
79
+
80
+ def parse_module_folder(folder: Path) -> Optional[Dict[str, Union[str, list[str], dict]]]:
81
+ """Locate and parse manifest from matching header file in module directory."""
82
+ if not folder.is_dir():
83
+ return None
84
+
85
+ hpp_name = folder.name + ".hpp"
86
+ hpp_path = folder / hpp_name
87
+ if not hpp_path.exists():
88
+ return None
89
+
90
+ return parse_manifest_from_header(hpp_path)
91
+
92
+
93
+ def parse_path(path: Path) -> Dict[str, Dict]:
94
+ """Main entry point: handles both module collections and individual modules."""
95
+ manifests = {}
96
+
97
+ if not path.exists():
98
+ return manifests
99
+
100
+ if path.is_dir():
101
+ # Check if path is a module directory
102
+ maybe_mod = path / (path.name + ".hpp")
103
+ if maybe_mod.exists():
104
+ if manifest := parse_module_folder(path):
105
+ manifests[manifest["module_name"]] = manifest
106
+ else:
107
+ # Process directory of modules
108
+ for sub in path.iterdir():
109
+ if sub.is_dir() and (manifest := parse_module_folder(sub)):
110
+ manifests[manifest["module_name"]] = manifest
111
+ return manifests
112
+
113
+
114
+ def print_manifest(name: str, manifest: dict):
115
+ """Display formatted module information."""
116
+ print(f"\n=== Module: {name} ===")
117
+
118
+ print(f"Description : {manifest.get('module_description', '(no description)')}")
119
+ if repo := manifest.get("repository"):
120
+ print(f"Repository : {repo}")
121
+
122
+ # Handle constructor arguments
123
+ args = manifest.get("constructor_args")
124
+ print("\nConstructor Args : ", end="")
125
+ if isinstance(args, list) and all(isinstance(a, dict) for a in args):
126
+ for item in args:
127
+ for k, v in item.items():
128
+ print(f"\n - {k:<18} = {v if v is not None else '(missing)'}")
129
+ else:
130
+ print("(invalid format)")
131
+
132
+ # Handle hardware requirements
133
+ hardware = manifest.get("required_hardware", [])
134
+ if isinstance(hardware, str):
135
+ hardware = [hardware]
136
+ print(f"\nRequired Hardware : {', '.join(hardware) if hardware else 'None'}")
137
+
138
+
139
+ def main():
140
+ parser = argparse.ArgumentParser(description="XRobot module manifest parser")
141
+ parser.add_argument("--path", "-p", required=True,
142
+ help="Path to module directory or module collection")
143
+ args = parser.parse_args()
144
+
145
+ manifests = parse_path(Path(args.path))
146
+ if not manifests:
147
+ print("[INFO] No module manifests found")
148
+ return
149
+
150
+ for name, manifest in manifests.items():
151
+ print_manifest(name, manifest)
152
+
153
+
154
+ if __name__ == "__main__":
155
+ main()
@@ -0,0 +1,142 @@
1
+ import subprocess
2
+ import sys
3
+ from pathlib import Path
4
+ import yaml
5
+ import argparse
6
+ import urllib.request
7
+
8
+ # Configuration paths
9
+ MODULE_CONFIG = Path("./Modules/modules.yaml")
10
+ MODULE_DIR = Path("./Modules/")
11
+ OUTPUT_CPP = Path("./User/xrobot_main.hpp")
12
+ CONSTRUCTOR_CONFIG: Path # Type hint, no initial value
13
+
14
+ # CLI tool names
15
+ INIT_MODULE_CLI = "xrobot_init_mod"
16
+ GENERATE_MAIN_CLI = "xrobot_gen_main"
17
+
18
+
19
+ def run_subprocess(cmd: list[str]):
20
+ """Execute external command with logging"""
21
+ print(f"[EXEC] {' '.join(cmd)}")
22
+ subprocess.run(cmd, check=True)
23
+
24
+
25
+ def ensure_module_config():
26
+ """Create default module configuration if missing"""
27
+ if not MODULE_CONFIG.exists():
28
+ MODULE_CONFIG.parent.mkdir(parents=True, exist_ok=True)
29
+ MODULE_CONFIG.write_text("""modules:
30
+ - name: BlinkLED
31
+ repo: https://github.com/xrobot-org/BlinkLED
32
+ """, encoding="utf-8")
33
+ print(f"[INFO] Default config created: {MODULE_CONFIG}")
34
+ print("Please edit the file and rerun.")
35
+ sys.exit(0)
36
+
37
+ def ensure_modules_cmakelists():
38
+ """Ensure a default CMakeLists.txt exists under Modules/, used to auto-include submodules"""
39
+ cmake_file = MODULE_DIR / "CMakeLists.txt"
40
+ if cmake_file.exists():
41
+ return # Do not overwrite existing file
42
+
43
+ cmake_code = r'''# Automatically include all module CMakeLists.txt files under Modules/
44
+
45
+ message(STATUS "[XRobot] Scanning module directory: Modules/")
46
+
47
+ file(GLOB MODULE_DIRS RELATIVE ${CMAKE_CURRENT_LIST_DIR} ${CMAKE_CURRENT_LIST_DIR}/*)
48
+
49
+ foreach(MOD ${MODULE_DIRS})
50
+ if(IS_DIRECTORY "${CMAKE_CURRENT_LIST_DIR}/${MOD}")
51
+ if(EXISTS "${CMAKE_CURRENT_LIST_DIR}/${MOD}/CMakeLists.txt")
52
+ message(STATUS "[XRobot] Including module: ${MOD}")
53
+ include("${CMAKE_CURRENT_LIST_DIR}/${MOD}/CMakeLists.txt")
54
+ endif()
55
+ endif()
56
+ endforeach()
57
+ '''
58
+ cmake_file.write_text(cmake_code, encoding="utf-8")
59
+ print(f"[INFO] Generated default Modules/CMakeLists.txt at: {cmake_file}")
60
+
61
+
62
+ def resolve_config_path(user_input: str | None) -> Path:
63
+ """Resolve config path from local path or URL"""
64
+ default_path = Path("./User/xrobot.yaml")
65
+
66
+ if not user_input:
67
+ return default_path
68
+
69
+ if user_input.startswith("http://") or user_input.startswith("https://"):
70
+ # Download remote YAML to local path
71
+ print(f"[INFO] Downloading config from URL: {user_input}")
72
+ default_path.parent.mkdir(parents=True, exist_ok=True)
73
+ urllib.request.urlretrieve(user_input, default_path)
74
+ print(f"[INFO] Config downloaded to: {default_path}")
75
+ return default_path
76
+
77
+ return Path(user_input)
78
+
79
+
80
+ def extract_modules() -> list[str]:
81
+ """Retrieve module list from configuration"""
82
+ if not MODULE_CONFIG.exists():
83
+ return []
84
+
85
+ with MODULE_CONFIG.open(encoding="utf-8") as f:
86
+ data = yaml.safe_load(f)
87
+
88
+ return [m["name"] for m in data.get("modules", []) if "name" in m]
89
+
90
+
91
+ def main():
92
+ """Main automation workflow"""
93
+ print("Starting XRobot auto-configuration")
94
+
95
+ parser = argparse.ArgumentParser(description="XRobot setup automation")
96
+ parser.add_argument("--config", help="Path or URL to constructor config YAML")
97
+ args = parser.parse_args()
98
+
99
+ # Step 0: Resolve config path
100
+ global CONSTRUCTOR_CONFIG
101
+ CONSTRUCTOR_CONFIG = resolve_config_path(args.config)
102
+
103
+ # Configuration validation
104
+ ensure_module_config()
105
+ modules = extract_modules()
106
+
107
+ if not modules:
108
+ print("[ERROR] No modules found in configuration")
109
+ sys.exit(1)
110
+
111
+ # Step 1: Repository management
112
+ run_subprocess([
113
+ INIT_MODULE_CLI,
114
+ "--config", str(MODULE_CONFIG),
115
+ "--dir", str(MODULE_DIR)
116
+ ])
117
+
118
+ ensure_modules_cmakelists()
119
+
120
+ # Step 2: Generate constructor config if missing
121
+ if not CONSTRUCTOR_CONFIG.exists():
122
+ run_subprocess([
123
+ GENERATE_MAIN_CLI,
124
+ "--output", str(OUTPUT_CPP),
125
+ "--config", str(CONSTRUCTOR_CONFIG)
126
+ ])
127
+ print(f"[INFO] Constructor config generated: {CONSTRUCTOR_CONFIG}")
128
+ print("Modify the configuration and rerun to apply changes")
129
+ sys.exit(0)
130
+
131
+ # Step 3: Code generation
132
+ run_subprocess([
133
+ GENERATE_MAIN_CLI,
134
+ "--output", str(OUTPUT_CPP),
135
+ "--config", str(CONSTRUCTOR_CONFIG)
136
+ ])
137
+
138
+ print(f"\nAll done! Main function generated at: {OUTPUT_CPP}")
139
+
140
+
141
+ if __name__ == "__main__":
142
+ main()
File without changes
@@ -0,0 +1,27 @@
1
+ Metadata-Version: 2.4
2
+ Name: xrobot
3
+ Version: 0.1.0
4
+ Summary: A Python package for parsing IOC files and generating C++ code.
5
+ Author-email: Xiao <2592509183@qq.com>
6
+ Maintainer-email: Xiao <2592509183@qq.com>
7
+ License: Apache-2.0
8
+ Project-URL: Homepage, https://github.com/xrobot-org
9
+ Project-URL: Documentation, https://xrobot-org.github.io
10
+ Project-URL: Repository, https://github.com/xrobot-org/XRobot
11
+ Project-URL: Bug Tracker, https://github.com/xrobot-org/XRobot/issues
12
+ Keywords: code generation,embedded systems,automation
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Operating System :: OS Independent
17
+ Requires-Python: >=3.8
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: argparse
21
+ Requires-Dist: pyyaml
22
+ Provides-Extra: gui
23
+ Requires-Dist: PyQt5; extra == "gui"
24
+ Provides-Extra: cli
25
+ Requires-Dist: rich; extra == "cli"
26
+ Requires-Dist: click; extra == "cli"
27
+ Dynamic: license-file
@@ -0,0 +1,16 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/xrobot/AddModule.py
5
+ src/xrobot/GenerateMain.py
6
+ src/xrobot/InitModule.py
7
+ src/xrobot/ModuleCreator.py
8
+ src/xrobot/ModuleParser.py
9
+ src/xrobot/XRobotSetup.py
10
+ src/xrobot/__init__.py
11
+ src/xrobot.egg-info/PKG-INFO
12
+ src/xrobot.egg-info/SOURCES.txt
13
+ src/xrobot.egg-info/dependency_links.txt
14
+ src/xrobot.egg-info/entry_points.txt
15
+ src/xrobot.egg-info/requires.txt
16
+ src/xrobot.egg-info/top_level.txt
@@ -0,0 +1,7 @@
1
+ [console_scripts]
2
+ xrobot_add_mod = xrobot.AddModule:main
3
+ xrobot_create_mod = xrobot.ModuleCreator:main
4
+ xrobot_gen_main = xrobot.GenerateMain:main
5
+ xrobot_init_mod = xrobot.InitModule:main
6
+ xrobot_mod_parser = xrobot.ModuleParser:main
7
+ xrobot_setup = xrobot.XRobotSetup:main
@@ -0,0 +1,9 @@
1
+ argparse
2
+ pyyaml
3
+
4
+ [cli]
5
+ rich
6
+ click
7
+
8
+ [gui]
9
+ PyQt5
@@ -0,0 +1 @@
1
+ xrobot