stlehmann / pyads

Python wrapper for TwinCAT ADS
MIT License
254 stars 94 forks source link

Simplify structure definitions for fields which are not arrays #288

Open stlehmann opened 2 years ago

stlehmann commented 2 years ago

Currently a structure definition is a list/tuple of tuples with 3 elements: name, plc-type and array size.

S_RESULTS_DEF = (
    ("sequence_id", pyads.PLCTYPE_INT, 1),
    ("sequence_counter", pyads.PLCTYPE_INT, 1),
)

In most cases array size will be 1 as it is just a single field. So it would be a great benefit if one could write the above structure definition in a shorter way, omitting the array size part:

S_RESULTS_DEF = (
    ("sequence_id", pyads.PLCTYPE_INT),
    ("sequence_counter", pyads.PLCTYPE_INT),
)
chrisbeardy commented 2 years ago

We could do this making as you suggest the norm but also allowing

S_RESULTS_DEF = (
    ("sequence_id", pyads.PLCTYPE_INT, 1),
    ("sequence_counter", pyads.PLCTYPE_INT, 1),
)

we could then adapt:

           try:
                var, plc_datatype, size = item  # type: ignore
                str_len = None
            except ValueError:
                var, plc_datatype, size, str_len = item  # type: ignore

to cater for both by removing to try statement and instead checking how many items are in the tuple.

Linking it with #289 we could then make it perform better if we create an intermediate function which changes the easy to understand human written tuple which defines the structure to something which the machine can use instead. Then the read_structure_by_name and dict_from_bytes function can accept this new computer optimised structure def as an option too.