function to match a native TIA portal export to a DB layout specification string
Hi, as anticipated I was working on a function that could ingest a native TIA portal export of a non-optimized db to generate a string compatible with the DB class layout_specification
It also manage names duplicates by adding a suffix "_X" at the end of the variables, where "X" is a progressive numeration.
@Novecento99 Nice work
Code Review
Thanks for contributing this TIA Portal export parser! This is a useful feature. However, there are several issues that need to be addressed before we can merge.
1. Bug: Duplicate name detection is broken for underscored variables
The current logic uses rsplit("_")[0] which fails for variable names containing underscores:
>>> "my_value_0".rsplit("_")
['my', 'value', '0']
>>> "my_value_0".rsplit("_")[0]
'my' # Expected: 'my_value'
This means duplicates of my_value will all get _0 suffix instead of _0, _1, _2:
# Current behavior:
'my_value' -> 'my_value_0'
'my_value' -> 'my_value_0' # BUG: should be 'my_value_1'
Fix: Use rsplit("_", 1) to split only on the last underscore:
if name.rsplit("_", 1)[0] == var_name:
to_add = "_" + str(int(name.rsplit("_", 1)[-1]) + 1)
2. Remove debug print statement
Line with print(name.rsplit("_")[-1]) should be removed or replaced with logger.debug().
3. Docstring parameter mismatch
The docstring says tia_export but the parameter is named txt_path.
4. Missing error handling
What happens if:
- A line doesn't have 3 tab-separated fields?
- The file doesn't exist?
- The offset field isn't valid?
Consider adding try/except or validation.
5. Incomplete type list
The valid_list is missing types that are supported elsewhere in the codebase:
WORD,UINT,UDINT,LREAL,SINT,USINT,TIME,DATE
Consider matching the types supported in Row.get_value() and Row.set_value().
6. Inefficient string concatenation
Using db_specification = db_specification + "\n" + new_line in a loop is O(n²). Use a list instead:
lines = []
for line in file:
...
if var_type in valid_list:
lines.append(f"{var_offset}\t{var_name}\t{var_type}")
return "\n".join(lines)
7. No tests
Please add unit tests. At minimum:
- Test with a sample TIA export file
- Test duplicate name handling (including names with underscores)
- Test with missing/invalid fields
8. Separate formatting changes
The PR includes many unrelated line-wrapping changes. Please split those into a separate PR or remove them to keep this PR focused.
Summary of required changes:
- Fix the
rsplitbug (usersplit("_", 1)) - Remove
print()statement - Fix docstring
- Add basic error handling
- Add missing types to
valid_list - Use list + join instead of string concatenation
- Add unit tests
- Remove unrelated formatting changes
Happy to help if you have questions!