Completed
Pull Request — master (#184)
by Olivier
03:02
created

server-enum.main()   A

Complexity

Conditions 3

Size

Total Lines 52
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 19
nop 0
dl 0
loc 52
rs 9.45
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
'''
2
  This example demonstrates the use of custom enums by:
3
  - Create a custom enum type
4
  - Create an object that contains a variable of this type
5
'''
6
import sys
7
sys.path.insert(0, "..")
8
import time
9
import asyncio
10
11
from IPython import embed
12
13
from asyncua import ua, Server
14
15
16
async def main():
17
    # setup our server
18
    server = Server()
19
    await server.init()
20
    server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/")
21
22
    # setup our own namespace, not really necessary but should as spec
23
    uri = "http://examples.freeopcua.github.io"
24
    nsidx = await server.register_namespace(uri)
25
26
    # --------------------------------------------------------
27
    # create custom enum data type
28
    # --------------------------------------------------------
29
30
    # 1.
31
    # Create Enum Type
32
    myenum_type = await server.nodes.enum_data_type.add_data_type(nsidx, 'MyEnum')
33
34
    # 2.
35
    # Add enumerations as EnumStrings (Not yet tested with EnumValues)
36
    # Essential to use namespace 0 for EnumStrings !
37
38
    es = await myenum_type.add_variable(0, "EnumStrings", [
39
        ua.LocalizedText("ok"),
40
        ua.LocalizedText("idle"),
41
    ])
42
43
    # 3. load enums froms erver
44
    await server.load_enums()
45
46
    # now we have a python enum available to play with
47
    val = ua.MyEnum.ok
48
49
    # not sure these are necessary
50
    #es.write_value_rank(1)
51
    #es.write_array_dimensions([0])
52
53
    # --------------------------------------------------------
54
    # create object with enum variable
55
    # --------------------------------------------------------
56
57
    # create object
58
    myobj = await server.nodes.objects.add_object(nsidx, 'MyObjectWithEnumVar')
59
60
    # add var with as type the custom enumeration
61
    myenum_var = await myobj.add_variable(nsidx, 'MyEnum2Var', val, datatype=myenum_type.nodeid)
62
    await myenum_var.set_writable()
63
    await myenum_var.write_value(ua.MyEnum.idle)  # change value of enumeration
64
65
    async with server:
66
        while True:
67
            time.sleep(0.5)
68
69
70
if __name__ == "__main__":
71
    asyncio.run(main())
72