Completed
Pull Request — master (#172)
by
unknown
06:26
created

UaJSONDecoder.__init__()   A

Complexity

Conditions 1

Size

Total Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
c 1
b 0
f 0
dl 0
loc 2
rs 10
1
"""
2
JSON encoder / decoder for OPC UA objects
3
Not yet used anywhere, but could be useful in the future for sending data to
4
external system such as a web based app
5
"""
6
7
from json import JSONEncoder, JSONDecoder
8
9
from opcua import ua
10
from datetime import datetime
11
12
# FIXME this JSON utility is not finished, should implement encoding / decoding of useful UA types
13
14
15
class UaJSONEncoder(JSONEncoder):
16
    """
17
    JSON encoder utility which is extended to handle opc ua objects
18
    """
19
    def default(self, o):
20
        if isinstance(o, datetime):
21
            return {
22
                '__type__': 'datetime',
23
                'year': o.year,
24
                'month': o.month,
25
                'day': o.day,
26
                'hour': o.hour,
27
                'minute': o.minute,
28
                'second': o.second,
29
                'microsecond': o.microsecond
30
            }
31
        elif isinstance(o, ua.NodeId):
32
            return {
33
                '__type__': 'NodeId',
34
                'Identifier': o.Identifier,
35
                'NamespaceIndex': o.NamespaceIndex,
36
            }
37
        else:
38
            return JSONEncoder.default(self, o)
39
40
41
class UaJSONDecoder(JSONDecoder):
42
    """
43
    JSON decoder utility which is extended to handle opc ua objects
44
    """
45
    def __init__(self):
46
        JSONDecoder.__init__(self, object_hook=self.dict_to_object)
47
48
    def dict_to_object(self, d):
49
        if '__type__' not in d:
50
            return d
51
52
        type = d.pop('__type__')
53
        if type == 'datetime':
54
            return datetime(**d)
55
        elif type == 'NodeId':
56
            return ua.NodeId(**d)
57
        else:
58
            #  decoder subclass can't handle this object type; put it back in the dict so super throws TypeError
59
            d['__type__'] = type
60
            return d
61