import sys
sys.path.insert(0, "..")


from opcua import Client
from opcua import ua

class SubHandler(object):

    """
    Subscription Handler. To receive events from server for a subscription
    data_change and event methods are called directly from receiving thread.
    Do not do expensive, slow or network operation there. Create another 
    thread if you need to do such a thing
    """

    def datachange_notification(self, node, val, data):
        print("New data change", node, str(val))

    def event_notification(self, event):
        print("New event", event)


if __name__ == "__main__":

    client = Client("opc.tcp://localhost:4840")
    
    try:
        client.connect()

        # Client has a few methods to get proxy to UA nodes that should always be in address space such as Root or Objects
        root = client.get_root_node()
        print("Objects node is: ", root)

        # Node objects have methods to read and write node attributes as well as browse or populate address space
        print("Children of root are: ", root.get_children())


        # Now getting a variable node using its browse path
        iCounter = root.get_child(["0:Objects", "2:DeviceSet", "4:CODESYS Control for Raspberry Pi SL", "3:Resources", "4:Application", "3:Programs", "4:PLC_PRG", "4:iCounter"])
        iValue = root.get_child(["0:Objects", "2:DeviceSet", "4:CODESYS Control for Raspberry Pi SL", "3:Resources", "4:Application", "3:Programs", "4:PLC_PRG", "4:iValue"])
        
        #Create subscription
        handler = SubHandler()
        sub = client.create_subscription(500, handler)
        handle = sub.subscribe_data_change(iCounter)
        handle = sub.subscribe_data_change(iValue)

        #Write Values:
        tmp = ua.Variant(222, iValue.get_data_type_as_variant_type())
        iValue.set_value(tmp)

        input("Press Key")
        
        

    finally:
        client.disconnect()

        