Completed
Pull Request — master (#217)
by Olivier
04:21
created

string_to_val()   F

Complexity

Conditions 14

Size

Total Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 14
dl 0
loc 40
rs 2.7581
c 1
b 0
f 1

How to fix   Complexity   

Complexity

Complex classes like string_to_val() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

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, IntEnum
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 hasattr(val, "to_string"):
27
        val = val.to_string()
28
    elif isinstance(val, ua.StatusCode):
29
        val = val.name
30
    elif isinstance(val, (Enum, IntEnum)):
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
        val = str(val)
38
    elif isinstance(val, datetime):
39
        val = val.isoformat()
40
    elif isinstance(val, (int, float)):
41
        val = str(val)
42
    else:
43
        # FIXME: Some types are probably missing!
44
        val = str(val)
45
    return val
46
47
48
def variant_to_string(var):
49
    """
50
    convert a variant to a string which should be easy to understand for human
51
    easy to modify, and not too hard to parse back ....not easy
52
    meant for UI or command lines
53
    """
54
    return val_to_string(var.Value)
55
56
57
def string_to_val(string, vtype):
58
    """
59
    Convert back a string to a python or python-opcua object 
60
    """
61
    string = string.strip()
62
    if string.startswith("["):
63
        string = string[1:-1]
64
        var = []
65
        for s in string.split(","):
66
            s = s.strip()
67
            val = string_to_val(s, vtype)
68
            var.append(val)
69
        return var
70
71
    if vtype == ua.VariantType.Null:
72
        val = None
73
    elif vtype == ua.VariantType.Boolean:
74
        val = bool(string)
75
    elif 4 <= vtype.value < 9:
76
        val = int(string)
77
    elif vtype in (ua.VariantType.Float, ua.VariantType.Double):
78
        val = float(string)
79
    elif vtype in (ua.VariantType.String, ua.VariantType.XmlElement):
80
        val = string
81
    elif vtype in (ua.VariantType.SByte, ua.VariantType.Guid, ua.VariantType.ByteString):
82
        val = bytes(string)
83
    elif vtype in (ua.VariantType.NodeId, ua.VariantType.ExpandedNodeId):
84
        val = ua.NodeId.from_string(string)
85
    elif vtype == ua.VariantType.QualifiedName:
86
        val = ua.QualifiedName.from_string(string)
87
    elif vtype == ua.VariantType.DateTime:
88
        val = parser.parse(string)
89
    elif vtype == ua.VariantType.LocalizedText:
90
        val = ua.LocalizedText(string)
91
    elif vtype == ua.VariantType.StatusCode:
92
        val = ua.StatusCode(string)
93
    else:
94
        # FIXME: Some types are probably missing!
95
        raise NotImplementedError
96
    return val
97
98
99
def string_to_variant(string, vtype):
100
    """
101
    convert back a string to an ua.Variant
102
    """
103
    return ua.Variant(string_to_val(string, vtype), vtype)
104
105
106