"""
######################################################################
# Script Name:  OPC_UA_test_server.py
# Version:      1.0.0
# Author:       Eduard Dercho
# Company:      IBR Messtechnik GmbH & Co. KG  
# Date:         2025-08-22
# Description:  This python script file provides an example OPC_UA 
#               server to test the "OPC_UA_export_example.py" script.
#               This script starts an OPC_UA server and prints the 
#               value of his variable every second as long as the 
#               server runs. 
#
#               Purpose of this server is to get in touch with the 
#               OPC_UA communication and to see how the value of the
#               variable changes when the export script gets executed. 
#
#               Run this script by a terminal and see how the value 
#               changes when the export function gets called.
#
######################################################################
"""
#
#---# Import of additional Python librarys needed for this example :
#
from opcua import ua, Server
import time
#
#---# Main function and entry point of this script
#
def main():
    server = Server()
    server.set_endpoint("opc.tcp://0.0.0.0:4840/opcua/server/")

    # Add a namespace (optional)
    uri = "http://example.ibr.com"
    idx = server.register_namespace(uri)

    # Get the root object
    objects = server.get_objects_node()

    # Create new variable in the address field
    myvar = objects.add_variable(idx, "MyVariable", 0.0)
    myvar.set_writable()  # Allow writing of the variable

    server.start()
    print("OPC UA example server is running...")

    try:
        myvar.set_value(0)
        while True:
            # Print every second the current value of the variable
            time.sleep(1)
            print(f"MyVariable value : {myvar.get_value()}")
    finally:
        server.stop()
        print("Server stopped")

if __name__ == "__main__":
    main()
