stlehmann / pyads

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

Added fallback to type detection to allow automatic ENUM usage #397

Open RobertoRoos opened 1 month ago

RobertoRoos commented 1 month ago

+ Added exception raising for unknown types

Fixes #263 . The issue is almost three years old, but still relevant.

This allows using enums both with plc.read_by_name() and through AdsSymbol.read().

Tested the code with:

from pyads import Connection
import pyads

def main():
    plc = Connection(
        ams_net_id="127.0.0.1.1.1",
        ams_net_port=851,
    )

    variables = [
        "my_double",
        "my_enum",
        "my_double_array",
        "my_enum_array",
        "my_struct",
    ]

    with plc:

        for var in variables:
            try:
                value = plc.read_by_name(f"GVL_Main.{var}", cache_symbol_info=False)
            except pyads.ADSError as err:
                print("ERROR:", err)
            else:
                print("Value:", value)

        for var in variables:
            try:
                symbol = plc.get_symbol(f"GVL_Main.{var}")
                value = symbol.read()
            except pyads.ADSError as err:
                print("ERROR:", err)
            else:
                print("Value:", value)

    return

if __name__ == "__main__":
    main()

Output:

Value: 0.0 Value: 1 Value: [0.0, 0.0, 0.0, 0.0, 0.0] Value: [2, 2, 2, 2, 2] ERROR: ADSError: Failed to detect datatype for GVL_Main.my_struct Value: 0.0 Value: 1 Value: [0.0, 0.0, 0.0, 0.0, 0.0] Value: [2, 2, 2, 2, 2] ERROR: ADSError: Cannot read data with unknown datatype for symbol GVL_Main.my_struct (MyStructure)

coveralls commented 1 month ago

Pull Request Test Coverage Report for Build 10661739215

Details


Changes Missing Coverage Covered Lines Changed/Added Lines %
pyads/symbol.py 23 24 95.83%
pyads/connection.py 7 9 77.78%
<!-- Total: 30 33 90.91% -->
Totals Coverage Status
Change from base Build 10633721828: 0.06%
Covered Lines: 1753
Relevant Lines: 1845

💛 - Coveralls
chrisbeardy commented 2 weeks ago

thanks @RobertoRoos , just had a look at this, I'm generally happy with this implementation. Could you just solve the conflict, please. I've also left a comment too in the review. It may be worth a few more tests, either unit or manual, to make sure we haven't broken any other edge cases such as when the user does pass in the type, or the wrong type etc. Also, maybe when structures are passed in, I wonder how it will handle ENUMS in structures....(not sure if that is possible in the struct def actually).

Can't see any reason why it would have broken anything else but being paranoid.