Completed
Pull Request — master (#217)
by Olivier
02:16
created

string_to_val()   F

Complexity

Conditions 9

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 9
dl 0
loc 29
rs 3
c 1
b 0
f 1
1
"""
2
Usefull method and classes not belonging anywhere and depending on opcua library
3
"""
4
5
from dateutil import parser
6
from datetime import datetime
7
from enum import Enum
8
9
from opcua import ua
10
11
12
def val_to_string(val):
13
    """
14
    convert a python object or python-opcua object to a string
15
    which should be easy to understand for human
16
    easy to modify, and not too hard to parse back ....not easy
17
    meant for UI or command lines
18
19
    """
20
    if isinstance(val, (list, tuple)):
21
        res = []
22
        for v in val:
23
            res.append(val_to_string(v))
24
        return "[" + ", ".join(res) + "]"
25
26
    if isinstance(val, (ua.NodeId)):
27
        val = val.to_string()
28
    elif isinstance(val, (ua.QualifiedName, ua.LocalizedText)):
29
        val = val.to_string()
30
    elif isinstance(val, Enum):
31
        val = val.name
32
    elif isinstance(val, ua.DataValue):
33
        val = variant_to_string(val.Value)
34
    elif isinstance(val, str):
35
        pass
36
    elif isinstance(val, bytes):
37
        pass
38
    elif isinstance(val, datetime):
39
        val = val.isoformat()
40
    else:
41
        val = str(val)
42
    return val
43
44
45
def variant_to_string(var):
46
    """
47
    convert a variant to a string which should be easy to understand for human
48
    easy to modify, and not too hard to parse back ....not easy
49
    meant for UI or command lines
50
    """
51
    return val_to_string(var.Value)
52
53
54
def string_to_val(string, vtype):
55
    """
56
    Convert back a string to a python or python-opcua object 
57
    """
58
    string = string.strip()
59
    if string.startswith("["):
60
        string = string[1:-1]
61
        var = []
62
        for s in string.split(","):
63
            s = s.strip()
64
            val = string_to_val(s, vtype)
65
            var.append(val)
66
        return var
67
68
    if vtype == ua.VariantType.Boolean:
69
        val = bool(string)
70
    elif 4 <= vtype.value < 9:
71
        val = int(string)
72
    elif vtype in (ua.VariantType.Float, ua.VariantType.Double):
73
        val = float(string)
74
    elif vtype == ua.VariantType.String:
75
        val = string
76
    elif vtype == ua.VariantType.NodeId:
77
        val = ua.NodeId.from_string(string)
78
    elif vtype == ua.VariantType.DateTime:
79
        val = parser.parse(string)
80
    else:
81
        raise NotImplementedError
82
    return val
83
84
85
def string_to_variant(string, vtype):
86
    """
87
    convert back a string to an ua.Variant
88
    """
89
    return ua.Variant(string_to_val(string, vtype), vtype)
90
91
92