from opcua import Server
from random import randint
import time

server = Server()
try:
    # defining server
    url = "opc.tcp://127.0.0.3:4840"
    server.set_endpoint(url)
    nameOfServer = "OPCUA_Server"

    # creating new namespace
    addSpace = server.register_namespace(nameOfServer)

    # creating new object within namespace
    node = server.get_objects_node()
    var = node.add_object(addSpace, "Numbers")

    # adding variables to "Numbers" 
    randNum = var.add_variable(addSpace, "Random number", 0)
    randNum.set_writable()
    rand = randint(-50, 999)
    randNum.set_value(rand)

    num1 = var.add_variable(addSpace, "Number", 0)
    num1.set_writable()
    num1Value = 6.7
    num1.set_value(num1Value)

    # creating new object within namespace
    node2 = server.get_objects_node()
    var2 = node2.add_object(addSpace, "Strings")

    # adding variables to "String"
    string1 = var2.add_variable(addSpace, "Word", 0)
    string1.set_writable()
    string1.set_value("Court")

    server.start()
    print("Server started at: " + url)

    while True:
        print("Random number: ", randNum.get_value())
        print("Number 1: ", num1.get_value())
        print("Word 1: ", string1.get_value())
        print()
        time.sleep(2)
except:
    print("Server problem")
