pythontwincattwincat-ads

How to wait for a variable change when using Pyads library?


I am working on a project with TwinCat and AMR. I'm using Python as a communication medium between the two systems. I have an issue with waiting for the variable to change value. I have a variable of type BOOL and want to perform a certain action when the variable changes. Can someone help me with this?

P.S. I have notified for change in variable as well.

import pyads

PLC = pyads.Connection('127.0.0.1.1.1', pyads.PORT_SPS1)
PLC.open()

StnF = PLC.read_by_name('GVL.AGVgotoStnF', pyads.PLCTYPE_BOOL)
print(StnF)

if StnF == 'TRUE' :
    ArrStnF = PLC.write_by_name('GVL.iPosAGV',3,pyads.PLCTYPE_INT)
    print(ArrStnF)

Solution

  • Your looking for notifications. The documentation of pyads gives and example how to do this:

    import pyads
    from ctypes import sizeof
    
    # define the callback which extracts the value of the variable
    def callback(notification, data):
        contents = notification.contents
        var = next(map(int, bytearray(contents.data)[0:contents.cbSampleSize]))
    
    plc = pyads.Connection('127.0.0.1.1.1', pyads.PORT_SPS1)
    plc.open()
    attr = pyads.NotificationAttrib(sizeof(pyads.PLCTYPE_INT))
    
    # add_device_notification returns a tuple of notification_handle and
    # user_handle which we just store in handles
    handles = plc.add_device_notification('GVL.integer_value', attr, callback)
    
    # To remove the device notification just use the del_device_notication
    # function.
    plc.del_device_notification(*handles)