g3projects 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.

Potentially problematic release.


This version of g3projects might be problematic. Click here for more details.

@@ -0,0 +1,19 @@
1
+ Copyright (c) 2018 The Python Packaging Authority
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.
@@ -0,0 +1,34 @@
1
+ Metadata-Version: 2.1
2
+ Name: g3projects
3
+ Version: 0.1.0
4
+ Summary: System G3 Project PLC files generator
5
+ Author-email: Konstantin Mykhailov <kmykhailov@elektroline.cz>
6
+ Project-URL: Homepage, https://gitlab.elektroline.cz/plc/systemg3-py/SystemG3ProjectBuilder
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Operating System :: OS Independent
10
+ Requires-Python: >=3.10
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENCE
13
+ Requires-Dist: jinja2
14
+ Requires-Dist: g3core
15
+ Requires-Dist: g3elements
16
+ Requires-Dist: g3hardware
17
+
18
+ # System G3 Project PLC files generator
19
+
20
+ ## Installation
21
+
22
+ ```sh
23
+ pip install g3projects
24
+ ```
25
+
26
+ ## Usage
27
+
28
+ ```python
29
+ # TODO
30
+ ```
31
+
32
+ ## License
33
+
34
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
@@ -0,0 +1,17 @@
1
+ # System G3 Project PLC files generator
2
+
3
+ ## Installation
4
+
5
+ ```sh
6
+ pip install g3projects
7
+ ```
8
+
9
+ ## Usage
10
+
11
+ ```python
12
+ # TODO
13
+ ```
14
+
15
+ ## License
16
+
17
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
@@ -0,0 +1,34 @@
1
+ [project]
2
+ name = "g3projects"
3
+ version = "0.1.0"
4
+ description = "System G3 Project PLC files generator"
5
+ readme = "README.md"
6
+ license = {file = "LICENSE"}
7
+ authors = [
8
+ { name = "Konstantin Mykhailov", email = "kmykhailov@elektroline.cz" },
9
+ ]
10
+ classifiers = [
11
+ "Programming Language :: Python :: 3",
12
+ "License :: OSI Approved :: MIT License",
13
+ "Operating System :: OS Independent",
14
+ ]
15
+ requires-python = ">=3.10"
16
+ dependencies = [
17
+ "jinja2",
18
+ "g3core",
19
+ "g3elements",
20
+ "g3hardware"
21
+ ]
22
+
23
+ [options]
24
+ package_dir = {"" = "src"}
25
+
26
+ [project.urls]
27
+ "Homepage" = "https://gitlab.elektroline.cz/plc/systemg3-py/SystemG3ProjectBuilder"
28
+
29
+ [project.scripts]
30
+ gen-project = "g3projects.main._main:main"
31
+
32
+ [build-system]
33
+ requires = ["setuptools>=69.0"]
34
+ build-backend = "setuptools.build_meta"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,4 @@
1
+ from . import logical
2
+
3
+
4
+ __all__ = ['logical']
@@ -0,0 +1,4 @@
1
+ from ._logical import generate_logical_files
2
+
3
+
4
+ __all__ = ['generate_logical_files']
@@ -0,0 +1,455 @@
1
+ import json
2
+ import os
3
+ import shutil
4
+ import logging
5
+
6
+ from datetime import datetime
7
+ from jinja2 import Environment, FileSystemLoader
8
+ from textwrap import indent
9
+
10
+ from g3core import G3Core
11
+ from g3elements.config import SWSystemDictWrapper
12
+ from g3elements.config.type_hinting import (
13
+ SystemDict, SWDeviceDict
14
+ )
15
+
16
+ from ..utils import (
17
+ format_template, combine_str, remove_multiple_newlines, write_to_file
18
+ )
19
+
20
+
21
+ env = Environment(
22
+ loader=FileSystemLoader(
23
+ os.path.join(os.path.dirname(__file__), 'templates/')
24
+ ),
25
+ keep_trailing_newline=False,
26
+ trim_blocks=True,
27
+ )
28
+ env.globals['timestamp'] = datetime.now().strftime("%Y/%m/%d %H:%M:%S")
29
+
30
+
31
+ def get_system_dict(path: str) -> SystemDict:
32
+ with open(path, 'r', encoding='utf-8') as file:
33
+ return json.load(file)
34
+
35
+
36
+ # ZONE #
37
+
38
+
39
+ # ST Declarations - ! these ideally need to go to G3Core ! #
40
+
41
+ def delete_config_keys_with_default_values(
42
+ system_data: SWSystemDictWrapper, g3core: G3Core
43
+ ) -> None:
44
+ for *_, path, device_data in system_data.iter_devices_system():
45
+ # find devType struct
46
+ if not (dev_type := device_data.get('control', {}).get('devType')):
47
+ print(device_data['general']['name'])
48
+ continue
49
+ struct_path, typ_struct = g3core.find_struct(dev_type)
50
+ try:
51
+ memb_config = [
52
+ memb for memb in typ_struct.members if memb.name == 'config'
53
+ ][0]
54
+ except IndexError:
55
+ raise
56
+ struct_path, config_struct = g3core.find_struct(
57
+ memb_config.dtype, search_here_first=struct_path
58
+ )
59
+ # find device config dict
60
+ config_data = device_data['control'].get('config', {})
61
+ config_data_updated = {}
62
+ for config_key, config_value in config_data.items():
63
+ matched = False
64
+ for member in config_struct.members:
65
+ if member.name == config_key:
66
+ if (
67
+ member.value != config_value and
68
+ config_value is not None
69
+ ):
70
+ config_data_updated[config_key] = {
71
+ 'value': config_value,
72
+ 'dtype': member.dtype
73
+ }
74
+ else:
75
+ info_msg = (
76
+ f'Key "{config_key}" at "{path}/control/config" '
77
+ f'contains default value of the "{member.name}" '
78
+ f'member of the "{config_struct.name}" config '
79
+ f'struct and will be ignored'
80
+ )
81
+ logging.info(info_msg)
82
+ matched = True
83
+ break
84
+ if not matched:
85
+ err_msg = (
86
+ f'Key "{config_key}" at "{path}/control/config" '
87
+ f'was not matched with any member of '
88
+ f'the "{config_struct.name}" config struct '
89
+ f'and will be ignored'
90
+ )
91
+ logging.warning(err_msg)
92
+ config_data.clear()
93
+ config_data.update(config_data_updated)
94
+
95
+
96
+ def get_fb_declaration(device_data: SWDeviceDict) -> str:
97
+ varname = device_data['general']['varname']
98
+ fb_name = SWSystemDictWrapper.get_device_control_fb(device_data)
99
+ if not fb_name:
100
+ name = device_data['general']['name']
101
+ logging.warning(
102
+ f'Could not generate function block declaration for {name}'
103
+ )
104
+ return ''
105
+ return f'fb{varname} : {fb_name.strip()};'
106
+
107
+
108
+ def get_dev_struct_declaration(device_data: SWDeviceDict) -> str:
109
+
110
+ def format_dict_recursive(d: dict):
111
+ elements = []
112
+ for key, value in d.items():
113
+ if isinstance(value, dict):
114
+ value_str = format_dict_recursive(value)
115
+ elements.append(
116
+ f"{key} := {value_str}"
117
+ )
118
+ else:
119
+ elements.append(
120
+ f"{key} := '{value}'"
121
+ if isinstance(value, str)
122
+ else f"{key} := {value}"
123
+ )
124
+ return f"({', '.join(elements)})"
125
+
126
+ def format_value(value_data) -> str:
127
+ try:
128
+ dtype = value_data['dtype'].lower()
129
+ value = value_data['value']
130
+ except KeyError:
131
+ name = device_data['general']['name']
132
+ logging.warning(f'Unable to format dev struct value at {name}')
133
+ return ''
134
+
135
+ if value is None:
136
+ return ''
137
+
138
+ if isinstance(value, dict):
139
+ return format_dict_recursive(value)
140
+ elif (
141
+ ("char" in dtype or "string" in dtype) and
142
+ not str(value).startswith("'")
143
+ ):
144
+ return f"'{value}'"
145
+ elif "time" in dtype and not str(value).startswith('T#'):
146
+ return f'T#{value}'
147
+ elif "bool" in dtype:
148
+ if value is True:
149
+ return "TRUE"
150
+ else:
151
+ return "FALSE"
152
+ elif "int" in dtype or "word" in dtype:
153
+ return str(int(value))
154
+ elif "real" in dtype:
155
+ return str(float(value))
156
+ else:
157
+ return str(value)
158
+
159
+ varname = device_data['general']['varname']
160
+ if not (dev_struct_type := device_data['control'].get('devType')):
161
+ name = device_data['general']['name']
162
+ logging.warning(
163
+ f'Could not generate struct declaration for {name}'
164
+ )
165
+ return ''
166
+ config_values_formatted = []
167
+ for memb_name, memb_value_data in device_data['control']['config'].items():
168
+ if (memb_value := format_value(memb_value_data)):
169
+ config_values_formatted.append((memb_name, memb_value))
170
+ config_vals = ", ".join(
171
+ f'{memb_name} := {memb_value}'
172
+ for memb_name, memb_value in config_values_formatted
173
+ )
174
+ if not config_vals:
175
+ return f'{varname} : {dev_struct_type};'
176
+ return f'{varname} : {dev_struct_type} := (config := ({config_vals}));'
177
+
178
+
179
+ def get_fb_assignment(device_data: SWDeviceDict) -> str:
180
+ varname = device_data['general']['varname']
181
+ connected_fbs = device_data['control'].get('connector')
182
+ if not connected_fbs:
183
+ return ""
184
+ fb_assignment_lines = []
185
+ for conn_name, conn_fb in connected_fbs.items():
186
+ if conn_fb:
187
+ conn_fb_ptr = f"&{conn_fb}"
188
+ else:
189
+ logging.warning(f'Connector "{conn_name}" not set.')
190
+ conn_fb_ptr = "NULL"
191
+ conn_assignment = f'fb{varname}.{conn_name} = {conn_fb_ptr};'
192
+ fb_assignment_lines.append(conn_assignment)
193
+ return '\n'.join(fb_assignment_lines)
194
+
195
+
196
+ def get_fb_call(device_data: SWDeviceDict) -> str:
197
+ varname = device_data['general']['varname']
198
+ fb_name = SWSystemDictWrapper.get_device_control_fb(device_data)
199
+ if not fb_name:
200
+ name = device_data['general']['name']
201
+ logging.warning(
202
+ f'Could not generate function block call for {name}'
203
+ )
204
+ return ''
205
+ return f'{fb_name}(&fb{varname});'
206
+
207
+
208
+ def get_route_layout_declaration(device_data: SWDeviceDict) -> str:
209
+ route_name = device_data['general']['varname']
210
+ route_layout_data = device_data['general']['layout']
211
+ declaration_lines = []
212
+ for route_element_data in route_layout_data:
213
+ name = route_element_data['name']
214
+ func = route_element_data['function']
215
+ if route_element_data['type'] == 'pointmachine':
216
+ pos = route_element_data['position']
217
+ line = f'{func}({pos}, &{name}.toRoute, &{route_name});'
218
+ else:
219
+ line = f'{func}(&{name}.toRoute, &{route_name});'
220
+ declaration_lines.append(line)
221
+ return "\n".join(declaration_lines)
222
+
223
+ # ST Declarations - END #
224
+
225
+
226
+ def generate_zone_files_contents(
227
+ system_config: SWSystemDictWrapper, zone_name: str
228
+ ) -> tuple[str, str]:
229
+ varibales_var = ''
230
+ main_c = ''
231
+ for _, path, device_data in system_config.iter_devices_zone(zone_name):
232
+ if not system_config.get_device_control_fb(device_data):
233
+ logging.warning('function block type is missing for "%s"', path)
234
+ continue
235
+ varibales_var = combine_str(
236
+ varibales_var,
237
+ get_fb_declaration(device_data),
238
+ get_dev_struct_declaration(device_data),
239
+ )
240
+ main_c = combine_str(
241
+ main_c,
242
+ get_fb_assignment(device_data),
243
+ get_fb_call(device_data),
244
+ )
245
+ if (
246
+ 'Route' in path and
247
+ 'NonSafety' in device_data['control'].get('function', '')
248
+ ):
249
+ main_c = combine_str(
250
+ main_c,
251
+ get_route_layout_declaration(device_data),
252
+ )
253
+ return (
254
+ indent(remove_multiple_newlines(varibales_var), ' '),
255
+ indent(remove_multiple_newlines(main_c), ' ')
256
+ )
257
+
258
+
259
+ # ZONE END #
260
+
261
+
262
+ # COMM #
263
+
264
+
265
+ def generate_comm_files_contents(
266
+ system_config: SWSystemDictWrapper
267
+ ) -> tuple[str, str]:
268
+ varibales_var = ''
269
+ main_c = ''
270
+ for *_, device_data in system_config.iter_devices_zone('Common'):
271
+ if device_data['general']['metatype'] != 'Comm':
272
+ continue
273
+ varibales_var = combine_str(
274
+ varibales_var,
275
+ get_fb_declaration(device_data),
276
+ )
277
+ main_c = combine_str(
278
+ main_c,
279
+ get_fb_assignment(device_data),
280
+ get_fb_call(device_data),
281
+ )
282
+ return (
283
+ indent(remove_multiple_newlines(varibales_var), ' '),
284
+ indent(remove_multiple_newlines(main_c), ' ')
285
+ )
286
+
287
+
288
+ # COMM END #
289
+
290
+
291
+ # SYSTEM #
292
+
293
+ def generate_system_files_contents(
294
+ system_config: SWSystemDictWrapper
295
+ ) -> tuple[str, str]:
296
+ context = {
297
+ 'has_system_safety': system_config.has_system_safety(),
298
+ 'has_shv': system_config.has_shv(),
299
+ 'has_elesys': system_config.has_elesys()
300
+ }
301
+ main_c = format_template(env, 'main_c_system.tpl', **context)
302
+ varibales_var = format_template(env, 'variables_var_system.tpl', **context)
303
+ return (
304
+ indent(remove_multiple_newlines(varibales_var), ' '),
305
+ indent(remove_multiple_newlines(main_c), ' ')
306
+ )
307
+
308
+ # SYSTEM END #
309
+
310
+
311
+ # ZONE.VAR #
312
+
313
+ def generate_zone_var_contents(
314
+ system_config: SWSystemDictWrapper
315
+ ) -> str:
316
+ zone_var = ''
317
+ for *_, device_data in system_config.iter_devices_zone('Common'):
318
+ if device_data['general']['metatype'] == 'Project':
319
+ continue
320
+ zone_var = combine_str(
321
+ zone_var,
322
+ get_dev_struct_declaration(device_data),
323
+ )
324
+ return indent(remove_multiple_newlines(zone_var), ' ')
325
+
326
+
327
+ # ZONE.VAR END #
328
+
329
+
330
+ def makedirs_logical(
331
+ project_name: str, system_name: str, zone_name: str
332
+ ) -> str:
333
+ path = os.path.join(
334
+ os.getcwd(),
335
+ 'Logical',
336
+ project_name,
337
+ system_name,
338
+ zone_name
339
+ )
340
+ os.makedirs(path, exist_ok=True)
341
+ return path
342
+
343
+
344
+ # general TODO: add update file logic
345
+
346
+
347
+ def generate_main_variables_ansic_files(
348
+ project_name: str,
349
+ system_name: str,
350
+ folder_name: str,
351
+ program_cyclic: str,
352
+ variables: str
353
+ ) -> str:
354
+ folder_path = makedirs_logical(
355
+ project_name, system_name, folder_name
356
+ )
357
+ write_to_file(
358
+ folder_path,
359
+ 'main.c',
360
+ format_template(env, 'main_c.tpl', program_cyclic=program_cyclic)
361
+ )
362
+ write_to_file(
363
+ folder_path,
364
+ 'Variables.var',
365
+ format_template(env, 'variables_var.tpl', variables=variables)
366
+ )
367
+ write_to_file(
368
+ folder_path,
369
+ 'ANSIC.prg',
370
+ format_template(env, 'ansic_prg.tpl')
371
+ )
372
+ return folder_path
373
+
374
+
375
+ def generate_logical_files(system_config_path: str) -> None:
376
+ g3core = G3Core.from_local('./Logical/Libraries')
377
+ system = get_system_dict(system_config_path)
378
+ sw_system_wrapper = SWSystemDictWrapper(system['Software'])
379
+ project_name = sw_system_wrapper.get_project_name()
380
+ system_name = sw_system_wrapper.get_system_name()
381
+ delete_config_keys_with_default_values(sw_system_wrapper, g3core)
382
+ # create Zones folder files
383
+ zone_tasknames: list[str] = []
384
+ for zone_name in system['Software']:
385
+ if zone_name == 'Common':
386
+ continue
387
+ varibales_var, main_c = generate_zone_files_contents(
388
+ sw_system_wrapper, zone_name
389
+ )
390
+ zone_taskname = sw_system_wrapper.get_zone_taskname(zone_name)
391
+ zone_tasknames.append(zone_taskname)
392
+ generate_main_variables_ansic_files(
393
+ project_name, system_name, zone_taskname, main_c, varibales_var
394
+ )
395
+ # create Comm folder files
396
+ varibales_var, main_c = generate_comm_files_contents(sw_system_wrapper)
397
+ generate_main_variables_ansic_files(
398
+ project_name, system_name, 'Comm', main_c, varibales_var
399
+ )
400
+ # create System folder files
401
+ varibales_var, main_c = generate_system_files_contents(sw_system_wrapper)
402
+ path = generate_main_variables_ansic_files(
403
+ project_name, system_name, 'System', main_c, varibales_var
404
+ )
405
+ system_folder_path = os.path.dirname(path)
406
+ project_folder_path = os.path.dirname(system_folder_path)
407
+ logical_folder_path = os.path.dirname(project_folder_path)
408
+ # create Zone.var file
409
+ zone_var = generate_zone_var_contents(sw_system_wrapper)
410
+ write_to_file(
411
+ system_folder_path,
412
+ 'Zone.var',
413
+ format_template(env, 'variables_var.tpl', variables=zone_var)
414
+ )
415
+ # create config.txt file
416
+ redmine_data = sw_system_wrapper.redmine_data
417
+ context = {
418
+ 'redmine_project_name': redmine_data['projectName'],
419
+ 'redmine_project_folder_id': redmine_data['projectFolderID']
420
+ }
421
+ write_to_file(
422
+ project_folder_path,
423
+ 'config.txt',
424
+ format_template(
425
+ env, 'config_txt.tpl', **context
426
+ )
427
+ )
428
+ # create Package.pkg files
429
+ write_to_file(
430
+ system_folder_path,
431
+ 'Package.pkg',
432
+ format_template(
433
+ env, 'package_pkg_system.tpl', zone_names=zone_tasknames
434
+ )
435
+ )
436
+ system_names = [sw_system_wrapper.get_system_name()]
437
+ write_to_file(
438
+ project_folder_path,
439
+ 'Package.pkg',
440
+ format_template(
441
+ env, 'package_pkg_project.tpl', system_names=system_names
442
+ )
443
+ )
444
+ project_names = [sw_system_wrapper.get_project_name()]
445
+ write_to_file(
446
+ logical_folder_path,
447
+ 'Package.pkg',
448
+ format_template(
449
+ env, 'package_pkg_logical.tpl', project_names=project_names
450
+ )
451
+ )
452
+ # remove the "Logical/Project" directory
453
+ logical_default_project_path = os.path.join(logical_folder_path, 'Project')
454
+ if os.path.isdir(logical_default_project_path):
455
+ shutil.rmtree(logical_default_project_path)
@@ -0,0 +1,4 @@
1
+ from ._main import generate_project_files
2
+
3
+
4
+ __all__ = ['generate_project_files']
@@ -0,0 +1,34 @@
1
+ import argparse
2
+
3
+ from ..logical import generate_logical_files
4
+ from ..physical import generate_physical_files
5
+
6
+
7
+ def parse_arguments() -> argparse.Namespace:
8
+ parser = argparse.ArgumentParser(
9
+ description=(
10
+ 'Create a G3 Project PLC files from a SystemConfig.json file.'
11
+ )
12
+ )
13
+ parser.add_argument(
14
+ '-s',
15
+ '--system-config',
16
+ type=argparse.FileType('r'),
17
+ required=True,
18
+ help='Path to the SystemConfig.json file'
19
+ )
20
+ return parser.parse_args()
21
+
22
+
23
+ def generate_project_files(system_config_path: str) -> None:
24
+ generate_logical_files(system_config_path)
25
+ generate_physical_files(system_config_path)
26
+
27
+
28
+ def main() -> None:
29
+ args = parse_arguments()
30
+ generate_project_files(args.system_config)
31
+
32
+
33
+ if __name__ == "__main__":
34
+ main()
@@ -0,0 +1,4 @@
1
+ from ._physical import generate_physical_files
2
+
3
+
4
+ __all__ = ['generate_physical_files']
@@ -0,0 +1,256 @@
1
+ import json
2
+ import os
3
+ import shutil
4
+ # import logging
5
+
6
+ from datetime import datetime
7
+ from jinja2 import Environment, FileSystemLoader
8
+ from textwrap import indent
9
+
10
+ from g3elements.config import SWSystemDictWrapper
11
+ from g3elements.config.type_hinting import SystemDict
12
+
13
+ from ..utils import (
14
+ format_template, write_to_file
15
+ )
16
+
17
+ from g3hardware import HWModule, HWIsle
18
+
19
+
20
+ env = Environment(
21
+ loader=FileSystemLoader(
22
+ os.path.join(os.path.dirname(__file__), 'templates/')
23
+ ),
24
+ keep_trailing_newline=False,
25
+ trim_blocks=True,
26
+ )
27
+ env.globals['timestamp'] = datetime.now().strftime("%Y/%m/%d %H:%M:%S")
28
+
29
+
30
+ def get_system_dict(path: str) -> SystemDict:
31
+ with open(path, 'r', encoding='utf-8') as file:
32
+ return json.load(file)
33
+
34
+
35
+ def makedirs_physical(system_name: str) -> str:
36
+ path = os.path.join(
37
+ os.getcwd(),
38
+ 'Physical',
39
+ system_name
40
+ )
41
+ os.makedirs(os.path.join(path, 'CPU'), exist_ok=True)
42
+ return path
43
+
44
+
45
+ # TODO: Would be nice to moce to some kind of wrapper
46
+
47
+ def is_safety_configuration(config_hw: list[dict]) -> bool:
48
+ for isle in config_hw:
49
+ if 'SL8101' in isle['head']['type']:
50
+ return True
51
+ return False
52
+
53
+
54
+ def get_hardware_module_name(module_type: str, config_hw: list[dict]) -> str:
55
+ module_type_lower = module_type.lower()
56
+ for isle in config_hw:
57
+ if module_type_lower in isle['head']['type'].lower():
58
+ head = isle['head']
59
+ return f"{head['type']}_{head['cabinet']}_{head['name_suffix']}"
60
+ raise ValueError(f'Module "{module_type}" data was not found')
61
+
62
+ # END TODO ##
63
+
64
+
65
+ # Hardware.hw #
66
+
67
+ def create_hw_isles(config_hw: dict) -> HWIsle | None:
68
+ isles: list[HWIsle] = []
69
+ for isle_data in config_hw:
70
+ module_type = isle_data['head']['type']
71
+ cabinet = isle_data['head']['cabinet']
72
+ name_suffix = isle_data['head']['name_suffix']
73
+ head = HWModule.new(
74
+ module_type=module_type,
75
+ module_name_suffix=f"{cabinet}_{name_suffix}"
76
+ )
77
+ tail = []
78
+ for module_data in isle_data['tail']:
79
+ module_type = module_data['type']
80
+ cabinet = module_data['cabinet']
81
+ name_suffix = module_data['name_suffix']
82
+ module = HWModule.new(
83
+ module_type=module_type,
84
+ module_name_suffix=f"{cabinet}_{name_suffix}"
85
+ )
86
+ tail.append(module)
87
+ isles.append(HWIsle(head, *tail))
88
+ # move the CPU isle to the start of the isle list
89
+ cp1584_isle_i = -1
90
+ for i, isle in enumerate(isles):
91
+ if isle.head.type == 'X20cCP1584':
92
+ cp1584_isle_i = i
93
+ break
94
+ if cp1584_isle_i == -1:
95
+ raise ValueError(
96
+ "X20cCP1584 CPU module was not found in the hardware configuration"
97
+ )
98
+ if cp1584_isle_i != 0:
99
+ isles.insert(0, isles.pop(cp1584_isle_i))
100
+ # connect the isles
101
+ for i, isle in enumerate(isles[:-1]):
102
+ isle.next_isle = isles[i + 1]
103
+ if not isles:
104
+ return None
105
+ return isles[0]
106
+
107
+
108
+ def generate_hardware_hw_contents(
109
+ config_hw: dict, system_name: str, cp1584_name: str
110
+ ) -> str:
111
+ if not (hw_isle := create_hw_isles(config_hw)):
112
+ return ''
113
+ contents = hw_isle.to_xml_str()
114
+ return contents.format(
115
+ HOST_NAME=f'{system_name}_plc',
116
+ PROJECT_ZONE=system_name,
117
+ CP1584_NAME=cp1584_name
118
+ )
119
+
120
+ # END Hardware.hw #
121
+
122
+
123
+ # Iomap.iom #
124
+
125
+ def generate_iomap_iom_contents(system: SWSystemDictWrapper) -> list[str]:
126
+ iomap_lines = []
127
+ for zone, _, device_path, device_data in system.iter_devices_system():
128
+ if zone == 'Common':
129
+ continue
130
+ zone_taskname = system.get_zone_taskname(zone)
131
+ for key, value in device_data['control'].get('iomap', {}).items():
132
+ device_varname = system.get_device_varname(device_data)
133
+ if (
134
+ (
135
+ 'RequestorDigital' in device_path and
136
+ 'inputs' in key and
137
+ 'Safety' not in key
138
+ ) or
139
+ (
140
+ 'GPIO' in device_path
141
+ )
142
+ ):
143
+ device = device_varname
144
+ else:
145
+ device = f'fb{device_varname}'
146
+ iomap_line = f'::{zone_taskname}:{device}.{key} AT {value};'
147
+ iomap_lines.append(indent(iomap_line, ' '))
148
+ return iomap_lines
149
+
150
+ # END Iomap.iom #
151
+
152
+
153
+ def generate_physical_files(system_config_path: str) -> None:
154
+ system = get_system_dict(system_config_path)
155
+ sw_system_wrapper = SWSystemDictWrapper(system['Software'])
156
+ project_name = sw_system_wrapper.get_project_name()
157
+ system_name = sw_system_wrapper.get_system_name()
158
+ zone_tasknames = sw_system_wrapper.zone_tasknames
159
+ physical_path = makedirs_physical(system_name)
160
+ # create Physical.pkg file
161
+ write_to_file(
162
+ os.path.dirname(physical_path),
163
+ 'Physical.pkg',
164
+ format_template(env, 'physical_pkg.tpl', system_names=[system_name])
165
+ )
166
+ # create Config.pkg file
167
+ write_to_file(
168
+ physical_path,
169
+ 'Config.pkg',
170
+ format_template(env, 'config_pkg.tpl', cpu_type='CPU')
171
+ )
172
+ # create Hardware.hw and Hardware.hwl files
173
+ cpu_name = get_hardware_module_name(
174
+ 'cp1584', system['Hardware'] # type: ignore
175
+ )
176
+ hardware_hw = generate_hardware_hw_contents(
177
+ system['Hardware'], system_name, cpu_name # type: ignore
178
+ )
179
+ write_to_file(
180
+ physical_path,
181
+ 'Hardware.hw',
182
+ format_template(env, 'hardware_hw.tpl', hardware=hardware_hw)
183
+ )
184
+ write_to_file(
185
+ physical_path,
186
+ 'Hardware.hwl',
187
+ '' # create an empty hwl file is enough
188
+ )
189
+ # create Cpu.pkg file
190
+ is_safety = is_safety_configuration(system['Hardware']) # type: ignore
191
+ physical_cp1584_path = os.path.join(physical_path, 'CPU')
192
+ write_to_file(
193
+ physical_cp1584_path,
194
+ 'Cpu.pkg',
195
+ format_template(env, 'cpu_pkg.tpl', add_mapp_safety=is_safety)
196
+ )
197
+ # optionally copy mappSafety:
198
+ if is_safety:
199
+ mapp_safety_path_src = os.path.join(
200
+ os.path.dirname(physical_path), 'Core', 'CPU', 'mappSafety'
201
+ )
202
+ mapp_safety_path_dst = os.path.join(
203
+ physical_path, 'CPU', 'mappSafety'
204
+ )
205
+ shutil.copytree(
206
+ mapp_safety_path_src, mapp_safety_path_dst, dirs_exist_ok=True
207
+ )
208
+ for path in (
209
+ os.path.join(mapp_safety_path_dst, '.git'),
210
+ os.path.join(mapp_safety_path_dst, '.gitignore')
211
+ ):
212
+ if os.path.isfile(path):
213
+ os.remove(path)
214
+ sl_name = get_hardware_module_name(
215
+ 'sl8101', system['Hardware'] # type: ignore
216
+ )
217
+ write_to_file(
218
+ mapp_safety_path_dst,
219
+ 'Config.sfdomain',
220
+ format_template(env, 'config_sfdomain.tpl', sl8101_name=sl_name)
221
+ )
222
+ # create IoMap.iom file
223
+ iomap = generate_iomap_iom_contents(sw_system_wrapper)
224
+ write_to_file(
225
+ physical_cp1584_path,
226
+ 'IoMap.iom',
227
+ format_template(env, 'iomap_iom.tpl', iomap=iomap)
228
+ )
229
+ # create Zone.sw file
230
+ tasks: dict[str, list[tuple[str, str]]] = {
231
+ 'tasks_cyclic1': [],
232
+ 'tasks_cyclic2': [
233
+ ('Comm', f'{project_name}.{system_name}.Comm.prg')
234
+ ],
235
+ 'tasks_cyclic3': [
236
+ ('System', f'{project_name}.{system_name}.System.prg')
237
+ ],
238
+ 'tasks_cyclic4': []
239
+ }
240
+ tasks_cyclic4 = tasks['tasks_cyclic4']
241
+ for taskname in zone_tasknames:
242
+ tasks_cyclic4.append(
243
+ (taskname, f'{project_name}.{system_name}.{taskname}.prg')
244
+ )
245
+ libraries_list = sw_system_wrapper.get_project_libraries()
246
+ libraries: list[tuple[str, str]] = []
247
+ for lib in libraries_list:
248
+ lib_cou, lib_name = lib.split('.')
249
+ libraries.append(
250
+ (lib_name, f'Libraries.Specific.{lib_cou}.{lib_name}.lby')
251
+ )
252
+ write_to_file(
253
+ physical_cp1584_path,
254
+ 'Zone.sw',
255
+ format_template(env, 'zone_sw.tpl', **tasks, libraries=libraries)
256
+ )
File without changes
@@ -0,0 +1,14 @@
1
+ from ._utils import (
2
+ format_template,
3
+ combine_str,
4
+ remove_multiple_newlines,
5
+ write_to_file
6
+ )
7
+
8
+
9
+ __all__ = [
10
+ 'format_template',
11
+ 'combine_str',
12
+ 'remove_multiple_newlines',
13
+ 'write_to_file'
14
+ ]
@@ -0,0 +1,37 @@
1
+ import os
2
+ import re
3
+ # import inspect
4
+
5
+ from jinja2 import Environment
6
+
7
+
8
+ # def get_template(template_name: str) -> str:
9
+ # if (current_frame := inspect.currentframe()) is None:
10
+ # raise RuntimeError("Cannot determine caller frame")
11
+ # if (caller_frame := current_frame.f_back) is None:
12
+ # err = f'Unexpected error while fetching template "{template_name}"'
13
+ # raise RuntimeError(err)
14
+ # caller_filename = caller_frame.f_globals["__file__"]
15
+ # file_dir = os.path.dirname(os.path.abspath(caller_filename))
16
+ # file_path = os.path.join(file_dir, 'templates', template_name)
17
+ # with open(file_path, 'r') as file:
18
+ # return file.read()
19
+
20
+
21
+ def combine_str(*strings: str) -> str:
22
+ return "\n".join(s for s in strings if s) + '\n'
23
+
24
+
25
+ def remove_multiple_newlines(string: str) -> str:
26
+ return re.sub('\n{3,}', '\n', string).strip()
27
+
28
+
29
+ def format_template(env: Environment, tpl_name: str, **kwargs) -> str:
30
+ template = env.get_template(tpl_name)
31
+ rendered = template.render(kwargs)
32
+ return remove_multiple_newlines(rendered)
33
+
34
+
35
+ def write_to_file(path: str, name: str, contents: str) -> None:
36
+ with open(os.path.join(path, name), 'w', encoding='utf-8') as file:
37
+ file.write(contents)
@@ -0,0 +1,34 @@
1
+ Metadata-Version: 2.1
2
+ Name: g3projects
3
+ Version: 0.1.0
4
+ Summary: System G3 Project PLC files generator
5
+ Author-email: Konstantin Mykhailov <kmykhailov@elektroline.cz>
6
+ Project-URL: Homepage, https://gitlab.elektroline.cz/plc/systemg3-py/SystemG3ProjectBuilder
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Operating System :: OS Independent
10
+ Requires-Python: >=3.10
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENCE
13
+ Requires-Dist: jinja2
14
+ Requires-Dist: g3core
15
+ Requires-Dist: g3elements
16
+ Requires-Dist: g3hardware
17
+
18
+ # System G3 Project PLC files generator
19
+
20
+ ## Installation
21
+
22
+ ```sh
23
+ pip install g3projects
24
+ ```
25
+
26
+ ## Usage
27
+
28
+ ```python
29
+ # TODO
30
+ ```
31
+
32
+ ## License
33
+
34
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
@@ -0,0 +1,19 @@
1
+ LICENCE
2
+ README.md
3
+ pyproject.toml
4
+ src/g3projects/__init__.py
5
+ src/g3projects/py.typed
6
+ src/g3projects.egg-info/PKG-INFO
7
+ src/g3projects.egg-info/SOURCES.txt
8
+ src/g3projects.egg-info/dependency_links.txt
9
+ src/g3projects.egg-info/entry_points.txt
10
+ src/g3projects.egg-info/requires.txt
11
+ src/g3projects.egg-info/top_level.txt
12
+ src/g3projects/logical/__init__.py
13
+ src/g3projects/logical/_logical.py
14
+ src/g3projects/main/__init__.py
15
+ src/g3projects/main/_main.py
16
+ src/g3projects/physical/__init__.py
17
+ src/g3projects/physical/_physical.py
18
+ src/g3projects/utils/__init__.py
19
+ src/g3projects/utils/_utils.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ gen-project = g3projects.main._main:main
@@ -0,0 +1,4 @@
1
+ jinja2
2
+ g3core
3
+ g3elements
4
+ g3hardware
@@ -0,0 +1 @@
1
+ g3projects