summaryrefslogtreecommitdiffstats
path: root/xdd2esilib.py
blob: 2b456f9753485256aacecc28e53c8a7b2f1a8609 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
#!/usr/bin/python
# vim: set fileencoding=utf-8 tabstop=8 expandtab shiftwidth=4 softtabstop=4 :

""" xdd2esilib.py
Converts xdd to esi using xddlib and esilib
Florian Bruhin
"""

import binascii
import logging
import warnings

import xddlib
import esilib
import canlib

esi = None

class XDD2ESIWarning(UserWarning):
    """ Base class for all warnings in this module """
    pass

class MissingFieldWarning(XDD2ESIWarning):
    """ Gets raised when an element does not have a mandatory field """
    pass

class NotImplementedWarning(XDD2ESIWarning):
    """ Gets raised when a feature is called which is not implemented yet """
    pass

class NoConvertFuncWarning(XDD2ESIWarning):
    """ Gets raised when there is no function to convert a given objtype """
    pass

class WrongObjectTypeWarning(XDD2ESIWarning):
    """ Gets raised when there is a subobject which is not a 'var' """
    pass

class NoDatatypeHandlerWarning(XDD2ESIWarning):
    """ Gets raised when there isn't any handler for a datatype """
    pass

def _xdd2esi(obj):
    """ Calls the functions to convert XDD to ESI """
    logging.debug("Converting {}".format(obj.getidentity()))
    newobj = obj.newsibling()
    handlers = {
        'index':        _get_direct_hex,
        'subindex':     _get_direct,
        'name':         _get_name,
        'datatype':     _get_datatype,
        'accesstype':   _get_accesstype,
        'category':     _get_category,
        'pdomapping':   _get_pdomapping,
        'infocomment':  _get_infocomment,
        'default':      _get_default,
        'maximum':      _get_direct_hex,
        'minimum':      _get_direct_hex,
        'dataorvalue':  _get_dataorvalue,
        'objflags':     _get_direct,
        'objecttype':   _get_direct,
        'subobjects':   _get_direct,
        'convertstate': _get_convertstate,
    }
    for attribute in handlers:
        convfunc = handlers[attribute]
        value = convfunc(obj, attribute)
        setattr(newobj, attribute, value)
    return newobj

def _get_name(obj, attr):
    """ Gets the name of the object """
    esi_name = obj.name
    if esi_name is None:
        warnings.warn("Element {} does not have a name!".format(obj),
                      MissingFieldWarning)
    return esi_name

def _get_pdomapping(obj, attr):
    """ Gets the PDO mapping of the object """
    if obj.pdomapping:
        esi_pdomapping = 'TR'
    else:
        esi_pdomapping = None
    return esi_pdomapping

def _get_infocomment(obj, attr):
    """ Gets the original string for strings before they were hexlified """
    if _is_string(obj):
        retval = obj.default
    else:
        retval = None
    return retval

def _get_default(obj, attr):
    """ Gets the default value of the object """
    if _is_string(obj) and obj.default is not None:
        esi_default = _hexlify(obj)
    elif _is_string(obj):
        esi_default = None
    elif isinstance(obj.default, str):
        esi_default = obj.default.replace("0x", "#x")
    else:
        esi_default = _inttohex(obj.default)
    return esi_default

def _get_accesstype(obj, attr):
    """ Gets the accesstype of the object """
    accesstype = obj.accesstype
    accesstype_mapping = {
        "ro":    "ro",
        "rw":    "rw",
        "wo":    "wo",
        "const": "ro",
        None:    None,
    }
    try:
        esi_accesstype = accesstype_mapping[accesstype]
    except KeyError:
        esi_accesstype = "UNKNOWN ({})".format(accesstype)
    if esi_accesstype is None:
        for subobj in obj.subobjects:
            if (getattr(subobj, "subindex", None) == 0 and
                  getattr(subobj, "accesstype", None) == "ro"):
                esi_accesstype = "ro"
    if esi_accesstype is None: # Still None
        esi_accesstype = "rw"

    return esi_accesstype

def _get_category(obj, attr):
    """ Gets the category of the object """
    return 'o'

def _get_convertstate(obj, attr):
    """ Gets the convertstate of an object (xdd/esi) """
    return 'esi'

def _get_direct(obj, attr):
    """ Gets an 1:1 value of an object """
    return getattr(obj, attr)

def _get_direct_hex(obj, attr):
    """ Gets an 1:1 value of an object, converted to hex """
    val = getattr(obj, attr)
    if val is None:
        retval = None
    else:
        retval = _inttohex(val)
    return retval

def _get_dataorvalue(obj, attr):
    """ Checks if the object needs [Default|Max|Min]Data or ...Value """
    if _is_string(obj):
        retval = 'data'
    else:
        retval = 'value'
    return retval

def _get_datatype(obj, attr):
    """ Returns the datatype of an object """
    if obj.objecttype == 'rec':
        datatype = "DT{0:X}".format(obj.index)
    elif obj.objecttype == 'var':
        datatype = esilib.type_to_esitype(obj.datatype)[0]
    elif obj.objecttype == 'arr':
        datatype = "DT{0:X}ARR".format(obj.index)
    else:
        warnings.warn("Don't know how to handle the datatype for the object "
                      "{} of type {}".format(obj, obj.objecttype),
                      NoDatatypeHandlerWarning)
    return datatype

def _get_basetype(obj, attr):
    """ Returns the basetype of an object """
    basetype = esilib.type_to_esitype(obj.subobjects[0].datatype)[0]
    return basetype

def _add_object(obj, parent=None, add_datatype=True):
    """ Adds a simple object to the ESI """
    if getattr(obj.datatype, 'type_', None) == 'octet' and add_datatype:
        esiname = esilib.type_to_esitype(obj.datatype)[0]
        basetype = canlib.Datatype(False, 'integer', 8, "OCTET")
        esi.add_array_datatype(esiname, basetype, obj.datatype.length,
                               octet=True)
    elif add_datatype:
        esi.add_var_datatype(obj.datatype)
    newobj = _xdd2esi(obj)
    if parent is None:
        xmlobj = esi.add_object(newobj)
    else:
        xmlobj = esi.add_subobject(newobj, parent)
    return (newobj, xmlobj)

def _get_element_count(obj):
    """ Returns the count of subobjects of an element """
    elements = len(obj.subobjects)
    return elements

def _is_var_object(obj):
    """ Checks if an object is a var-object """
    if obj.objecttype != 'var':
        warnings.warn("Got a subobject which does not have the object type "
                      "'var' like expected!\nNot adding object: {}".format(
                      obj), WrongObjectTypeWarning)
        retval = False
    else:
        retval = True
    return retval

def _add_arr_or_rec_object(obj, arr_or_rec):
    """ Adds a record or array to the ESI """
    datatype = _get_datatype(obj, None)
    if arr_or_rec == 'rec':
        maindt = esi.add_record_datatype(datatype)
    elif arr_or_rec == 'arr':
        elements = _get_element_count(obj)
        basetype = obj.subobjects[0].datatype
        maindt = esi.add_array_datatype(datatype, basetype, elements)
    for subobj in enumerate(obj.subobjects):
        _is_var_object(subobj[1])
        (newobj, xmlobj) = _add_object(subobj[1], parent=maindt)
        obj.subobjects[subobj[0]] = newobj
    (newobj, xmlobj) = _add_object(obj, add_datatype=False)
    esi.clear_bitoffset(datatype)
    esi.write_infotree(newobj, xmlobj)

def _add_rec_object(obj):
    """ Adds a record to the ESI """
    _add_arr_or_rec_object(obj, arr_or_rec='rec')

# FIXME this isn't used anymore because arrays in ESI are different than arrays in XDD.
def _add_arr_object(obj):
    """ Adds an array object to the ESI """
    _add_arr_or_rec_object(obj, arr_or_rec='arr')

def _add_basic_datatypes():
    """ Adds the basic datatypes to the ESI """
    basic_datatypes = [
        canlib.Datatype(True,  'integer', 8,  "BASIC_SINT"),
        canlib.Datatype(True,  'integer', 16, "BASIC_INT"),
        canlib.Datatype(True,  'integer', 32, "BASIC_DINT"),
        canlib.Datatype(False, 'integer', 8,  "BASIC_USINT"),
        canlib.Datatype(False, 'integer', 16, "BASIC_UINT"),
        canlib.Datatype(False, 'integer', 32, "BASIC_UDINT"),
    ]
    for datatype in basic_datatypes:
        esi.add_var_datatype(datatype)

def _is_string(obj):
    """ Checks if the object is of a string-dataType """
    py_datatype = obj.datatype
    if py_datatype is not None and (py_datatype.type_ == 'string' or
                                    py_datatype.type_ == 'unicode'):
        retval = True
    else:
        retval = False
    return retval

def _hexlify(obj):
    """ Converts a string to an hex-value """
    encodings = { 'string': 'ASCII', 'unicode': 'utf-8' }
    encoding = encodings[obj.datatype.type_]
    defaultstring = obj.default + '\0'
    esi_default_bytes = defaultstring.encode(encoding)
    hexlification_bytes = binascii.hexlify(esi_default_bytes)
    hexlification = hexlification_bytes.decode('ASCII')
    return hexlification

def _inttohex(value):
    """ Returns a decimal integer in the ESI hex format """
    if value is None:
        retval = None
    else:
        retval = "#x{0:X}".format(value)
    return retval

def _convert(xdd, addbasic=True):
    """ Converts xdd to esi with the correct dataType """
    if addbasic:
        _add_basic_datatypes()
    convfuncs = {
        'var': _add_object,
        'rec': _add_rec_object,
        'arr': _add_rec_object,
    }
    for obj in xdd.objlist:
        objtype = obj.objecttype
        try:
            convfunc = convfuncs[objtype]
        except KeyError:
            warnings.warn("I don't know how to convert the object {}!".format(
                          obj.getidentity()), NoConvertFuncWarning)
        else:
            convfunc(obj)

def output(outfile, pretty=True):
    """ Writes the ESI-tree to the outfile or dumps it """
    if outfile == '-':
        esi.dump(pretty)
    elif outfile is None:
        # dry run
        pass
    else:
        esi.totree()
        esi.tofile(outfile, pretty)

def run(infile, outfile, dump=False, pretty=True, shifts=None, addbasic=True,
        template=None, schema=None, versioninfo=None):
    """ Do the conversion using the libs """
    global esi
    esi = esilib.ESIFile(versioninfo)
    logging.info("Parsing XDD")
    xdd = xddlib.XDDFile()
    xdd.parse(infile)
    logging.info("Shifting indexes")
    if shifts is not None:
        for shift in shifts:
            xdd.shift(shift[0], shift[1], shift[2])
        xdd.sortobjs()
    if dump:
        xdd.dump()
        return True
    logging.info("Converting")
    _convert(xdd, addbasic)
    esi.flush_datatypes()
    logging.info("Merging to template")
    if template is not None:
        esi.merge_from_template(template)
    logging.info("Writing output")
    output(outfile, pretty)
    logging.info("Validating")
    if (schema is not None) and (template is not None):
        esi.validate(schema)
    elif (schema is not None):
        logging.error("Can't validate without using a template, ignoring "
                      "schema option.")
    logging.info("Done.")