Go to the documentation of this file.00001 '''
00002 This example demonstrates the use of custom enums by:
00003 - Create a custom enum type
00004 - Create an object that contains a variable of this type
00005 '''
00006 import sys
00007 sys.path.insert(0, "..")
00008
00009 try:
00010 from IPython import embed
00011 except ImportError:
00012 import code
00013
00014 def embed():
00015 vars = globals()
00016 vars.update(locals())
00017 shell = code.InteractiveConsole(vars)
00018 shell.interact()
00019
00020 interactive = True
00021
00022
00023 from opcua import ua, Server
00024 from opcua.common import node
00025 from enum import IntEnum
00026
00027
00028
00029 class MyEnum(IntEnum):
00030 ok = 0
00031 idle = 1
00032
00033
00034 def enum_to_stringlist(a_enum):
00035 items = []
00036 for value in a_enum:
00037 items.append(ua.LocalizedText(value.name))
00038 return items
00039
00040 if __name__ == "__main__":
00041
00042 server = Server()
00043 server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/")
00044
00045
00046 uri = "http://examples.freeopcua.github.io"
00047 nsidx = server.register_namespace(uri)
00048
00049
00050
00051
00052 enums = server.get_root_node().get_child(["0:Types", "0:DataTypes", "0:BaseDataType", "0:Enumeration"])
00053
00054
00055
00056 myenum_type = enums.add_data_type(nsidx, 'MyEnum')
00057
00058
00059
00060
00061
00062
00063
00064
00065
00066
00067 es = myenum_type.add_variable(0, "EnumStrings" , enum_to_stringlist(MyEnum))
00068
00069 es.set_value_rank(1)
00070 es.set_array_dimensions([0])
00071
00072
00073
00074
00075
00076 objects = server.get_objects_node()
00077
00078
00079 myobj = objects.add_object(nsidx, 'MyObjectWithEnumVar')
00080
00081
00082 myenum_var = myobj.add_variable(nsidx, 'MyEnum2Var', MyEnum.ok, datatype = myenum_type.nodeid)
00083 myenum_var.set_writable()
00084 myenum_var.set_value(MyEnum.idle)
00085
00086 server.start()
00087 try:
00088 if interactive:
00089 embed()
00090 else:
00091 while True:
00092 time.sleep(0.5)
00093
00094 except IOError:
00095 pass
00096 finally:
00097 server.stop()
00098 print("done")