forked from FreeOpcUa/python-opcua
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
85 lines (64 loc) · 2.15 KB
/
Copy pathserver.py
File metadata and controls
85 lines (64 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import os.path
try:
from IPython import embed
except ImportError:
import code
def embed():
vars = globals()
vars.update(locals())
shell = code.InteractiveConsole(vars)
shell.interact()
from opcua import ua, uamethod, Server
@uamethod
def say_hello_xml(parent, happy):
print("Calling say_hello_xml")
if happy:
result = "I'm happy"
else:
result = "I'm not happy"
print(result)
return result
@uamethod
def say_hello(parent, happy):
if happy:
result = "I'm happy"
else:
result = "I'm not happy"
print(result)
return result
@uamethod
def say_hello_array(parent, happy):
if happy:
result = "I'm happy"
else:
result = "I'm not happy"
print(result)
return [result, "Actually I am"]
class HelloServer:
def __init__(self, endpoint, name, model_filepath):
self.server = Server()
# This need to be imported at the start or else it will overwrite the data
self.server.import_xml(model_filepath)
self.server.set_endpoint(endpoint)
self.server.set_server_name(name)
objects = self.server.get_objects_node()
freeopcua_namespace = self.server.get_namespace_index("urn:freeopcua:python:server")
hellower = objects.get_child("0:Hellower")
hellower_say_hello = hellower.get_child("0:SayHello")
self.server.link_method(hellower_say_hello, say_hello_xml)
hellower.add_method(
freeopcua_namespace, "SayHello2", say_hello, [ua.VariantType.Boolean], [ua.VariantType.String])
hellower.add_method(
freeopcua_namespace, "SayHelloArray", say_hello_array, [ua.VariantType.Boolean], [ua.VariantType.String])
def __enter__(self):
self.server.start()
return self.server
def __exit__(self, exc_type, exc_val, exc_tb):
self.server.stop()
if __name__ == '__main__':
script_dir = os.path.dirname(__file__)
with HelloServer(
"opc.tcp://0.0.0.0:40840/freeopcua/server/",
"FreeOpcUa Example Server",
os.path.join(script_dir, "test_saying.xml")) as server:
embed()