asn1_value_editor.py 35.2 KB
Newer Older
1
2
3
4
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    TASTE ASN.1 Value Editor
Maxime Perrotin's avatar
Maxime Perrotin committed
5

6
7
8
9
10
11
12
13
14
15
    Main GUI widget

    Copyright (c) 2012-2015 European Space Agency

    Designed and implemented by Maxime Perrotin

    Contact: maxime.perrotin@esa.int

    License is LGPLv3 - Check the LICENSE file
"""
Maxime Perrotin's avatar
Maxime Perrotin committed
16
17

__author__ = "Maxime Perrotin"
18
__license__ = "LGPLv3"
19
__version__ = "1.0.7"
Maxime Perrotin's avatar
Maxime Perrotin committed
20
21
22
23
24
25
26
27
28
__url__ = "http://taste.tuxfamily.org"

import sys

try:
    from PySide import *
    from PySide.QtCore import *
    from PySide.QtGui import *
    from PySide.QtUiTools import *
29
30
except ImportError as err:
    print 'Pyside not found (package python-pyside missing)...' + str(err)
Maxime Perrotin's avatar
Maxime Perrotin committed
31
32
33
34
35
36
37
38
39
40
41

import vn

MIN_RANGE = Qt.UserRole + 1
MAX_RANGE = Qt.UserRole + 2
CHOICE_LIST = Qt.UserRole + 1
PLOTTERS = Qt.UserRole + 4
ASN1TYPE = Qt.UserRole


class myTextEdit(QTextEdit):
42
43
    ''' Customized text editor that contains a context menu for loading
    data from a file '''
Maxime Perrotin's avatar
Maxime Perrotin committed
44
    def __init__(self, parent=None):
45
        super(myTextEdit, self).__init__(parent)
Maxime Perrotin's avatar
Maxime Perrotin committed
46
47

    def contextMenuEvent(self, event):
48
49
        ''' When the context menu is open, add the Load from file action
        and open the menu '''
Maxime Perrotin's avatar
Maxime Perrotin committed
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
        myMenu = self.createStandardContextMenu()
        myAction = 'Load data from file'
        myMenu.addAction(myAction)
        action = myMenu.exec_(event.globalPos())
        if action is not None and action.text() == myAction:
            filename = QFileDialog.getOpenFileName(self, "Load string from file", ".", "All (*)")[0]
            if len(filename) == 0:
                return
            stringFile = QFile(filename)
            stringFile.open(QIODevice.ReadOnly)
            stringData = str(stringFile.readData(stringFile.size()))
            self.setText(stringData)
            stringFile.close()


class TreeDelegate(QStyledItemDelegate):
    '''Tree Delegate allows to define specific editors for each cell of the
tree view. This way, e.g. ASN.1 ENUMERATED values can be selected using a
combo box, while INTEGERS values can be set using a spin box.
Three functions have been redefined:
(1) createEditor, which  sets an editor to a cell, using the cell attributes
to learn about the ASN.1 basic type (stored in Qt.UserRole)
(2) SetEditorData, which is used at runtime to put the value in the given
editor when the user clicks on the cell
(3) SetModelData, which is called when the user is done with the editing: it
reads the value from the editor and place it back in the model '''
    seqof = Signal(QModelIndex, int, int)
    choice = Signal(QModelIndex, int, int)

    def __init__(self, oParent=None):
80
        super(TreeDelegate, self).__init__(oParent)
Maxime Perrotin's avatar
Maxime Perrotin committed
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103

    def createEditor(self, parent, option, index):
        ''' Define the delegate (editor) to use for a given cell.
index.data() returns the actual value, and index.data(role) points to
some user data when role >= 32. 32 is Qt.UserRole. '''
        # Check the (user-defined) type associated with the cell
        asnType = index.data(ASN1TYPE)
        if asnType == 'INTEGER':
            editor = QSpinBox(parent)
            # Qt's int is 32-bits signed, so we may get overflows
            try:
                editor.setMinimum(index.data(MIN_RANGE))
            except OverflowError:
                editor.setMinimum(sys.maxint)
            try:
                editor.setMaximum(index.data(MAX_RANGE))
            except OverflowError:
                editor.setMaximum(sys.maxint)
        elif asnType == 'SEQOF':
            editor = QSpinBox(parent)
            minVal = index.data(MIN_RANGE)
            maxVal = index.data(MAX_RANGE)
            editor.setRange(minVal, maxVal)
104
        elif asnType in ('ENUMERATED', 'CHOICE'):
Maxime Perrotin's avatar
Maxime Perrotin committed
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
            editor = QComboBox(parent)
            enumVal = index.data(CHOICE_LIST)
            for val in enumVal:
                editor.addItem(val)
        elif asnType == 'REAL':
            editor = QDoubleSpinBox(parent)
            minVal = index.data(MIN_RANGE)
            maxVal = index.data(MAX_RANGE)
            editor.setRange(float(minVal), float(maxVal))
        elif asnType == 'STRING':
            editor = myTextEdit(parent)
            # maxLen = index.data(MAX_RANGE)
            # editor.setMaxLength(maxLen) (not supported by QTextEdit, only QLineEdit)
        elif asnType == 'BOOLEAN':
            editor = QComboBox(parent)
            boolVal = index.data(CHOICE_LIST)
            for val in boolVal:
                editor.addItem(val)
            # I do not use QCheckBox because the position of the box changes when
            # the cell is edited, which is not good-looking
            #editor = QCheckBox(parent)
            #defState =  index.data(Qt.CheckStateRole)
            #editor.setCheckState(Qt.CheckState(defState))
        else:
            return  # Non-editable cells
        return editor

    def setEditorData(self, editor, index):
        ''' Set the curent value of the editor (when cell is clicked)
            in principle, take it from the model (index.data() = value) '''
        asnType = index.data(ASN1TYPE)
        if asnType in ('INTEGER', 'SEQOF'):
            editor. setValue(int(index.data()))
        elif asnType in ('ENUMERATED', 'CHOICE'):
            idx = editor.findText(index.data())
            editor.setCurrentIndex(idx)
            #editor. setEditText(index.data())
        elif asnType == 'REAL':
            editor.setValue(float(index.data()))
        elif asnType == 'STRING':
            editor.setText(index.data())
        elif asnType == 'BOOLEAN':
            idx = editor.findText(index.data())
            editor.setCurrentIndex(idx)
            #isChecked = index.model().data(index,  Qt.CheckStateRole)
            #editor.setCheckState(Qt.CheckState(isChecked))
        else:
            pass

    def setModelData(self, editor, model, index):
        '''  Once a choice has been made (by the user) take the value from
             the corresponding editor, and set it back in the model '''
        asnType = index.data(ASN1TYPE)
        if asnType == 'INTEGER':
            val = editor.value()
            model.setData(index, val)
        elif asnType == 'SEQOF':
            val = editor.value()
            model.setData(index, val)
            # Sequence of: display only the corresponding number of elements
            self.seqof.emit(index.sibling(index.row(), 0), val, index.data(MAX_RANGE))
        elif asnType == 'ENUMERATED':
            val = editor.currentText()
            model.setData(index, val)
        elif asnType == 'CHOICE':
            val = editor.currentText()
            model.setData(index, val)
            # display only the corresponding choice definition
            self.choice.emit(index.sibling(index.row(), 0), len(index.data(CHOICE_LIST)), editor.currentIndex())
        elif asnType == 'REAL':
            val = editor.value()
            model.setData(index, val)
        elif asnType == 'STRING':
            val = editor.toPlainText()
            model.setData(index, val)
        elif asnType == 'BOOLEAN':
            val = editor.currentText()
            model.setData(index, val)
            #if editor.isChecked(): model.setData (index, 'True')
            #else: model.setData (index,  'False')
            #model.setData (index, editor.checkState(),Qt.CheckStateRole)
        else:
            pass

    def updateEditorGeometry(self, editor, option, index):
        ''' Set editor geometry (bigger box for string types) '''
        asnType = index.data(ASN1TYPE)
        if asnType == 'STRING':
193
194
            r = QRect(option.rect.x(), option.rect.y(),
                      option.rect.width(), max(option.rect.height(), 100))
Maxime Perrotin's avatar
Maxime Perrotin committed
195
196
197
198
199
200
201
202
203
204
205
206
207
        else:
            r = option.rect
        editor.setGeometry(r)


class asn1Editor(QTreeView):
    ''' ASN.1 Fields editor to define, load, save and/or send TC '''
    expandTree = Signal()
    expandBranch = Signal(QModelIndex)
    statusBarMessage = Signal(str)
    msc = Signal(unicode, unicode)

    def __init__(self, parent=None):
208
        super(asn1Editor, self).__init__(parent)
Maxime Perrotin's avatar
Maxime Perrotin committed
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
        self.model = QStandardItemModel(1, 4)
        self.model.setHorizontalHeaderLabels(['Field', 'Type', 'Constraints', 'Value'])
        self.delegate = TreeDelegate()
        self.setItemDelegate(self.delegate)
        # Set selection mode and behavior to allow multiple rows to be selected with Ctrl/Shift keys
        self.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.setSelectionMode(QAbstractItemView.ExtendedSelection)

        self.setModel(self.model)
        self.setAlternatingRowColors(True)
        # Set Editing triggers so that a single click in a cell opens the editor
        self.setEditTriggers(QAbstractItemView.AllEditTriggers)
        # If we later want to drag & drop values (to plot, meter..):
        self.setDragEnabled(False)
        # When the number of elements for a sequence of is changed, signal "seqof"
        # is triggered by the delegate. Same for choice.
        self.delegate.seqof.connect(self.seqofDisplay)
        self.delegate.choice.connect(self.choiceDisplay)
        self.expandTree.connect(self.expandAll)
        self.expandBranch.connect(self.expand)
        self.plotterBackend = None
        self.backend = None
        self.plottedIdxs = []
        self.log = None
        self.pendingTM = None

    def hideExtraColumns(self):
        ''' Hide the columns containing the type and constraint '''
        self.setColumnHidden(1, True)
        self.setColumnHidden(2, True)

    def showExtraColumns(self):
        ''' Show the columns containing the type and constraint '''
        self.setColumnHidden(1, False)
        self.setColumnHidden(2, False)

245
    def setAsn1Model(self, dataview, row=0):
Maxime Perrotin's avatar
Maxime Perrotin committed
246
        self.item = dataview
247
248
        rootItem = self.addItem(self.item)
        self.treeItem = rootItem["item"]
Maxime Perrotin's avatar
Maxime Perrotin committed
249

250
251
252
        self.model.setItem(row, 1, QStandardItem(rootItem["type"]))
        self.model.setItem(row, 2, QStandardItem(rootItem["constraint"]))
        self.model.setItem(row, 3, QStandardItem(rootItem["value"]))
Maxime Perrotin's avatar
Maxime Perrotin committed
253
254

        # Add the item to the actual tree. 0,0 = 1st row, 1st column
255
        self.model.setItem(row, 0, self.treeItem)
Maxime Perrotin's avatar
Maxime Perrotin committed
256
        self.setWindowTitle('ASN.1 Variable editor')
257
        self.hideUnusedFields(self.treeItem, start=True, row=row)
Maxime Perrotin's avatar
Maxime Perrotin committed
258
259
260
        self.setColumnWidth(0, 200)
        self.setColumnWidth(1, 150)
        self.expandAll()
261
        return rootItem["item"]
Maxime Perrotin's avatar
Maxime Perrotin committed
262

263
    def hideUnusedFields(self, root, start=False, row=0):
Maxime Perrotin's avatar
Maxime Perrotin committed
264
        ''' Hide CHOICE unselected fields and SEQUENCE OF out-of-range fields '''
265
        rootType = self.model.item(row, 1).text()
Maxime Perrotin's avatar
Maxime Perrotin committed
266
        if rootType == 'CHOICE' and start:
267
268
            choices = self.model.item(row, 3).data(CHOICE_LIST)
            currValue = self.model.item(row, 3).text()
Maxime Perrotin's avatar
Maxime Perrotin committed
269
270
271
            for j in range(len(choices)):
                if currValue == choices[j]:
                    break
272
            rowIndex = self.model.item(row).index()
Maxime Perrotin's avatar
Maxime Perrotin committed
273
274
            self.choiceDisplay(rowIndex, len(choices), j)
        elif rootType == 'SEQOF' and start:
275
276
277
            maxValue = self.model.item(row, 3).data(MAX_RANGE)
            currValue = self.model.item(row, 3).text()
            rowIndex = self.model.item(row).index()
Maxime Perrotin's avatar
Maxime Perrotin committed
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
            self.seqofDisplay(rowIndex, currValue, maxValue)

        if root.hasChildren():
            for i in range(root.rowCount()):  # for each row
                self.hideUnusedFields(root.child(i))  # check recursively
                asnType = root.child(i, 1).text()
                if asnType == 'SEQOF':
                    maxValue = root.child(i, 3).data(MAX_RANGE)
                    currValue = root.child(i, 3).text()
                    rowIndex = root.child(i).index()
                    self.seqofDisplay(rowIndex, currValue, maxValue)
                elif asnType == 'CHOICE':
                    choices = root.child(i, 3).data(CHOICE_LIST)
                    currValue = root.child(i, 3).text()
                    for j in range(len(choices)):
                        if currValue == choices[j]:
                            break
                    rowIndex = root.child(i).index()
                    self.choiceDisplay(rowIndex, len(choices), j)

    def parseModel(self, root, nbRows=-1):
        ''' Parse the model to get all field values recursively (root type is QStandardItem) '''
        if root.hasChildren():
            resValue = {}
            seqofValue = []
            seqOf = False
            if nbRows == -1:
                nbRows = root.rowCount()
            else:
                seqOf = True
            for i in range(nbRows):  # for each child row
                name = root.child(i, 0).text()
                asnType = root.child(i, 1).text()
                value = root.child(i, 3).text()
                if asnType in ('SEQUENCE', 'SET'):
                    seqValue = self.parseModel(root.child(i))  # parse recursively
                    resValue[name] = seqValue
                    if seqOf:
                        seqofValue.append(seqValue)
                elif asnType == 'SEQOF':
                    seqOfValue = self.parseModel(root.child(i), nbRows=int(value))
                    resValue[name] = seqOfValue
                    if seqOf:
                        seqofValue.append(seqOfValue)
                elif asnType == 'CHOICE':
                    choiceValue = self.parseModel(root.child(i))  # parse recursively
                    resValue[name] = {"Choice": value, value: choiceValue[value]}
                    if seqOf:
                        seqofValue.append(resValue[name])
                elif asnType == 'INTEGER':
                    resValue[name] = int(value)
                    if seqOf:
                        seqofValue.append(int(value))
                elif asnType == 'REAL':
                    resValue[name] = float(value)
                    if seqOf:
                        seqofValue.append(float(value))
                elif asnType == 'BOOLEAN':
                    if value == 'True':
                        boolValue = True
                    else:
                        boolValue = False
                    resValue[name] = boolValue
                    if seqOf:
                        seqofValue.append(boolValue)
                elif asnType == 'ENUMERATED':
                    resValue[name] = {'Enum': value}
                    if seqOf:
                        seqofValue.append(resValue[name])
                else:  # Strings
                    resValue[name] = value
                    if seqOf:
                        seqofValue.append(value)
            if seqOf:
                return seqofValue
            else:
                return resValue
        else:  # single elements (all but SeqOF, Choice, Sequence)
            row = root.row()
            value = self.model.item(row, 3).text()
            asnType = self.model.item(row, 1).text()
            if asnType == 'INTEGER':
                value = int(value)
            elif asnType == 'REAL':
                value = float(value)
            elif asnType == 'BOOLEAN':
                value = True if value == 'True' else False
            elif asnType == 'ENUMERATED':
                value = {'Enum': value}
            else:
                pass
            return value

371
    def getVariable(self, root=None):
Maxime Perrotin's avatar
Maxime Perrotin committed
372
        ''' Read the ASN.1 variable from the tree editor '''
373
374
        root = root or self.treeItem
        row = root.row()
Maxime Perrotin's avatar
Maxime Perrotin committed
375
        name = root.text()
376
        asnType = self.model.item(row, 1).text()
Maxime Perrotin's avatar
Maxime Perrotin committed
377
        if asnType == 'SEQOF':
378
            nbRows = int(self.model.item(row, 3).text())
Maxime Perrotin's avatar
Maxime Perrotin committed
379
380
381
            value = self.parseModel(root, nbRows)
            return {name: value}
        elif asnType == 'CHOICE':
382
            value = self.model.item(row, 3).text()
Maxime Perrotin's avatar
Maxime Perrotin committed
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
            choiceValue = self.parseModel(root)
            return {name: {"Choice": value, value: choiceValue[value]}}
        else:
            value = self.parseModel(root)
            return {name: value}

    def updateModel(self, root, var, nbRows=-1):
        ''' Parse the model and update values '''
        if root.hasChildren():
            seqOf = False
            if nbRows == -1:
                nbRows = root.rowCount()
            else:
                seqOf = True
            for i in range(nbRows):
                name = root.child(i, 0).text()
399
                name_u = name.replace('-', '_')
Maxime Perrotin's avatar
Maxime Perrotin committed
400
401
402
403
404
                asnType = root.child(i, 1).text()
                child = root.child(i, 3)
                if seqOf:
                    value = var[i]
                else:
405
406
                    if name in var or name_u in var:
                        value = var.get(name, var[name_u])
Maxime Perrotin's avatar
Maxime Perrotin committed
407
408
409
410
411
412
413
414
415
416
417
418
419
420
                    else:
                        continue
                if asnType in ('INTEGER', 'REAL', 'SEQOF'):
                    plotters = root.child(i, 3).data(PLOTTERS)
                    if plotters is not None:
                        self.log.debug("updateModel - updatePlot call")
                        for plotter in plotters:
                            self.plotterBackend.updatePlot(plotter, value)
                        self.log.debug("updateModel - updatePlot end")
                if asnType in ('INTEGER', 'REAL', 'BOOLEAN', 'STRING'):
                    child.setText(str(value))
                elif asnType == 'ENUMERATED':
                    child.setText(value['Enum'])
                elif asnType in ('SEQUENCE', 'SET'):
421
                    self.updateModel(root.child(i), value) # update recursively
Maxime Perrotin's avatar
Maxime Perrotin committed
422
423
                elif asnType == 'CHOICE':
                    child.setText(str(value['Choice']))
424
                    self.updateModel(root.child(i), value) # update recursively
Maxime Perrotin's avatar
Maxime Perrotin committed
425
426
427
428
                elif asnType == 'SEQOF':
                    child.setText(str(len(value)))
                    self.updateModel(root.child(i), value, len(value))

Maxime Perrotin's avatar
Maxime Perrotin committed
429
    def updateVariable(self, var, root=None):
Maxime Perrotin's avatar
Maxime Perrotin committed
430
        ''' Update the variable value - used when loading a TC or receiving a TM '''
431
        root = root or self.treeItem
Maxime Perrotin's avatar
Maxime Perrotin committed
432
        row = root.row()
Maxime Perrotin's avatar
Maxime Perrotin committed
433
434
        name = root.text()
        value = var[name]
435
        asnType = self.model.item(row, 1).text()
Maxime Perrotin's avatar
Maxime Perrotin committed
436
        if asnType == 'SEQOF':
437
            self.model.item(row, 3).setText(str(len(value)))
Maxime Perrotin's avatar
Maxime Perrotin committed
438
439
            self.updateModel(root, var[name], len(value))
        elif asnType == 'CHOICE':
440
            self.model.item(row, 3).setText(str(value['Choice']))
Maxime Perrotin's avatar
Maxime Perrotin committed
441
442
            self.updateModel(root, value)
        elif asnType in ('INTEGER', 'REAL', 'STRING', 'BOOLEAN'):
443
            self.model.item(row, 3).setText(str(value))
Maxime Perrotin's avatar
Maxime Perrotin committed
444
        elif asnType == 'ENUMERATED':
445
            self.model.item(row, 3).setText(value['Enum'])
Maxime Perrotin's avatar
Maxime Perrotin committed
446
447
448
        else:  # SEQUENCE or SET
            self.updateModel(root, value)
        if asnType in ('INTEGER', 'REAL', 'SEQOF'):
449
            plotters = self.model.item(row, 3).data(PLOTTERS)
Maxime Perrotin's avatar
Maxime Perrotin committed
450
451
452
            if plotters != None:
                for plotter in plotters:
                    self.plotterBackend.updatePlot(plotter, value)
453
        self.hideUnusedFields(root, True, row=row)
Maxime Perrotin's avatar
Maxime Perrotin committed
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
        if self.plotterBackend is not None:
            self.plotterBackend.refresh()
        # Inform the thread to update the tree (expand all branches)
        self.expandTree.emit()

    def tmToEditor(self, pythonVar):
        ''' Check validity of a TM and update the viewer with the value '''
        self.log.debug("Entering tmToEditor")
        if pythonVar == {}:
            self.log.error('Error decoding ' + self.treeItem.text() + ' TM')
            self.statusBarMessage.emit('Error decoding ' + self.treeItem.text() + ' TM')
        else:
            self.updateVariable(pythonVar)
            for name in pythonVar:
                # Send value to the MSC recorder
                asnVN = vn.toASN1ValueNotation(pythonVar[name])
                msg = name + '(' + asnVN + ')'
                self.log.debug('Emitting input to MSC')  # + msg)
                self.msc.emit('in', msg)
        self.log.debug("Leaving tmToEditor")

    def ProcessTM(self, rawMsg):
        ''' Decode a TM received from the msgQ (not UDP) and update the model '''
        self.log.debug("Entering ProcessTM")
        native_tm = self.backend.decode_TM(rawMsg)
        pythonVar = self.backend.fromASN1ToPyside(native_tm)
        self.tmToEditor(pythonVar)
        self.log.debug("Leaving ProcessTM")

    @Slot()
    def receivedTM(self):
        ''' TM received from another thread (polling queue) '''
        if self.pendingTM:
            self.ProcessTM(self.pendingTM)
            self.pendingTM = None

    def ProcessUDPTM(self, uperMsg):
        ''' Decode an uPER-encoded TM (e.g. received from UDP sockets) and update the model '''
        native_tm = self.backend.decode_uPER(uperMsg)
        pythonVar = self.backend.fromASN1ToPyside(native_tm)
        self.tmToEditor(pythonVar)

    def saveTC(self):
        ''' Encode the data using GSER (ASN.1 Value Notation) and save it to a file'''
        data = self.getVariable()
        for name in data:
            asnVN = vn.toASN1ValueNotation(data[name]).replace('_', '-')
            self.log.debug('Saving ' + asnVN)
            #uPER_buffer = self.backend.encode_uPER(native_tc)
        filename = QFileDialog.getSaveFileName(self, "Save TC", ".", "ASN.1 Variable (*.tc)")[0]
        try:
            if filename.split('.')[-1] != 'tc':
                filename += ".tc"
            tcFile = QFile(filename)
            tcFile.open(QIODevice.WriteOnly | QIODevice.Text)
            #tcFile.write(uPER_buffer)
            tcFile.write(str(asnVN))
            tcFile.close()
        except:
            pass

515
516
517
518
519
520
521
    @property
    def gser(self, use_dash=False):
        ''' Helper API function: return the GSER representation of the data '''
        data, = self.getVariable().values()
        raw = vn.toASN1ValueNotation(data).strip()
        return raw if not use_dash else raw.replace('_', '-')

522
    def to_asn1scc_swig(self, root, dest, ASN1Swig, sort, ASN1_AST):
523
524
525
526
        ''' Helper API function: read variable and set ASN.1 SWIG variable
        Inputs: root: select which variable to parse
                dest: Swig variable (will be modified)
                ASN1Swig: python module containing SWIG DV access
527
528
                sort: root ASN.1 typename (with dash, no underscores)
                ASN1_AST: full AST generated by ASN1SCC
529
530
        '''
        var = self.getVariable(root).popitem()[1]
Maxime Perrotin's avatar
Maxime Perrotin committed
531
532
533
534
535
536
        vn.valueNotationToSwig(gser=None,
                               var=var,
                               dest=dest,
                               ASN1Swig=ASN1Swig,
                               sort=sort,
                               ASN1_AST=ASN1_AST)
537
538


Maxime Perrotin's avatar
Maxime Perrotin committed
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
    def sendTC(self):
        ''' Encode and send the TC to the main TASTE binary using message queue or UDP '''
        data = self.getVariable()
        for name in data:
            asnVN = vn.toASN1ValueNotation(data[name]).replace('_', '-').strip()
            msg = name + '(' + asnVN + ')'
            self.log.debug('out ' + msg)
            self.msc.emit('out', msg)
        asnVal = self.backend.fromPysideToASN1(data)
        self.backend.sendTC(asnVal)

    def loadTC(self):
        ''' Load/Decode a TC and populate the values in the model '''
        filename = QFileDialog.getOpenFileName(self, "Open TC", ".", "ASN.1 Variable (*.tc)")[0]
        if len(filename) == 0:
            return
        try:
            tcFile = QFile(filename)
            tcFile.open(QIODevice.ReadOnly | QIODevice.Text)
            asnVN = str(tcFile.readData(tcFile.size()))
            tcFile.close()
            pythonVar = vn.fromValueNotationToPySide(self.treeItem.text(), asnVN)
            self.updateVariable(pythonVar)
        except:
            pass

    def dataPath(self, idx):
        ''' Create a textual representation of a field path (e.g. myTM.myChoice.position.x) '''
        if not idx.isValid():
            return ''
        subpath = self.dataPath(idx.parent())
        if len(subpath)>0:
571
            subpath += '.'
Maxime Perrotin's avatar
Maxime Perrotin committed
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
        subpath += idx.data()
        return subpath

    def pathToIdx(self, path, root=None):
        ''' Find an index in the model based from a dot-splitted path representation '''
        if root is None:
            root = self.treeItem.index()
        if len(path) == 1:
            return QPersistentModelIndex(root) if root.data() == path[0] else None
        else:
            # Recursive call for each child
            for i in range(self.model.itemFromIndex(root).rowCount()):
                result = self.pathToIdx(path[1:], root.child(i, 0))
                if result is not None:
                    return result

    def newPlot(self, fifoId=-1, meter=False):
        ''' Add a set of data (based on selected lines) to a new plotter or speedometer '''
        selectedIdxs = self.selectedIndexes()
        # Count the number of eligible lines for plotting (discard non-numerical types)
        eligible=[]
        for idx in selectedIdxs:
            if idx.column() > 0:
                continue
            asntype = idx.sibling(idx.row(), 1).data()
            if asntype in ('INTEGER', 'REAL', 'SEQOF'):
                self.log.info('Candidate for plot: '+ self.dataPath(idx))
                discard = False
                if fifoId > 0:
                    currData=idx.sibling(idx.row(), 3).data(PLOTTERS)
                    if currData is not None:
                        for elem in currData:
                            if elem['fifoId'] == fifoId:
                                discard = True
                if not discard:
                    eligible.append(idx.sibling(idx.row(), 3))
                else:
                    self.log.info('(but discarding because already in current plot)')
            else:
                self.log.warning('Cannot plot {data} (type {asntype} is not numerical)'.format(data=idx.data(), asntype=asntype))
        if len(eligible) == 0:
            self.log.warning('No valid lines selected for the plot')
            self.statusBarMessage.emit('No valid lines selected for the plot')
            return
        if fifoId == -1 and not meter:
            fifoId = self.plotterBackend.newPlot()
        for idx in eligible:
            dataPath = self.dataPath(idx.sibling(idx.row(), 0))
            currData = idx.data(PLOTTERS)
            minRange = idx.data(MIN_RANGE)
            maxRange = idx.data(MAX_RANGE)
            if meter:
                fifoId = self.plotterBackend.newMeter(dataPath, minRange, maxRange)
            if currData is None:
                currData = []
            currData.append({'fifoId': int(fifoId), 'curveName': dataPath})
            idx.model().setData(idx, currData, PLOTTERS)
            # Keep track of all plotted values - used when saving the model state
            persistentIdx = QPersistentModelIndex(idx)
            if persistentIdx not in self.plottedIdxs:
                self.plottedIdxs.append(persistentIdx)

    def addToPlot(self):
        ''' Add a new curve to an existing plot window '''
        fifoId = self.sender().text().split()[-1]
        self.newPlot(int(fifoId))

    def setPlotterBackend(self, backend):
        ''' Set a "pointer" to the GnuPlot/Meter backend module '''
        self.plotterBackend = backend

    def meter(self):
        ''' Create speedometers for the selected values '''
        self.newPlot(meter=True)

    def displaytip(self, index):
        ''' Display a tip when the mouse moves above a cell '''
        asnType = index.sibling(index.row(), 1).data()
        constraint = index.sibling(index.row(), 2).data()
        self.statusBarMessage.emit(asnType + ' ' + (constraint if constraint is not None else ''))

    @Slot(QModelIndex, int, int)
    def seqofDisplay(self, parent, val, max):
        ''' Slot updating the number of SEQOF elements displayed '''
        for row in range(max):
            if int(row) < int(val):
                display = False
            else:
                display = True
            self.setRowHidden(row, parent, display)
        self.expandBranch.emit(parent)

    @Slot(QModelIndex, int, int)
    def choiceDisplay(self, parent, nbOfElem, choice):
        ''' Slot updating the current selected CHOICE element '''
        for row in range(nbOfElem):
            if int(choice) == int(row):
                display = False
            else:
                display = True
            self.setRowHidden(row, parent, display)
        self.expandBranch.emit(parent)

    def addInteger(self, elem):
        # Set default value (min range):
        val = QStandardItem('%d' % elem["minR"])
        # Define type attributes, later used to define the proper cell editor
        val.setData(elem["type"], ASN1TYPE)
        try:
            val.setData(elem["minR"], MIN_RANGE)
        except OverflowError:
            val.setData(-1000000, MIN_RANGE)
        try:
            val.setData(elem["maxR"], MAX_RANGE)
        except OverflowError:
            val.setData(1000000, MAX_RANGE)
        # Set the text for the constraint and add it to the 3rd column:
        constraint = QStandardItem('(%d..%d)' % (elem["minR"], elem["maxR"]))
        constraint.setData(QBrush(QColor("gray")), Qt.ForegroundRole)
        return {"value": val, "constraint": constraint}

    def addReal(self, elem):
        # Set default value (min range):
        val = QStandardItem('%.2f' % elem["minR"])
        # Define type attributes, later used to define the proper cell editor
        val.setData(elem["type"], ASN1TYPE)
        try:
            val.setData(elem["minR"], MIN_RANGE)
        except OverflowError:
            # Python cannot handle 64bit double - reducing the range in case of overflow
            val.setData(-10000000.0, MIN_RANGE)
        try:
            val.setData(elem["maxR"], MAX_RANGE)
        except OverflowError:
            val.setData(10000000.0, MAX_RANGE)
        # Set the text for the constraint and add it to the 3rd column:
        constraint = QStandardItem('(%.2f..%.2f)' % (elem["minR"], elem["maxR"]))
        constraint.setData(QBrush(QColor("gray")), Qt.ForegroundRole)
        return {"value": val, "constraint": constraint}

    def addEnum(self, elem):
        # Set default value (first enum value)
        val = QStandardItem(elem["values"][0])
        # Define type attributes, later used to define the proper cell editor
        val.setData(elem["type"], ASN1TYPE)  # type (ENUMERATED)
        val.setData(elem["values"], CHOICE_LIST)  # enum values
        constraint = QStandardItem()
        return {"value": val, "constraint": constraint}

    def addString(self, elem):
        # Set default value (empty string)
        if "default" in elem:
            defaultString = elem["default"]
        else:
            defaultString = ""
        val = QStandardItem(defaultString)
        # Define type attributes, later used to define the proper cell editor
        val.setData(elem["type"], ASN1TYPE)  # type (IA5String)
        val.setData(elem["minSize"], MIN_RANGE)  # size min
        val.setData(elem["maxSize"], MAX_RANGE)  # size max
        # Set the text for the constraint and add it to the 3rd column:
        if elem["minSize"] == elem["maxSize"]:
            constraintStr = 'SIZE(%d)' % elem["minSize"]
        else:
            constraintStr = 'SIZE(%d..%d)' % (elem["minSize"], elem["maxSize"])
        constraint = QStandardItem(constraintStr)
        constraint.setData(QBrush(QColor("gray")), Qt.ForegroundRole)
        return {"value": val, "constraint": constraint}

    def addBool(self, elem):
        # Set default value (True or False)
        val = QStandardItem(elem["default"])
        # Define type attributes, later used to define the proper cell editor
        val.setData(elem["type"], ASN1TYPE)  # type (BOOLEAN)
        val.setData(['True', 'False'], CHOICE_LIST)  # enum values
        constraint = QStandardItem()
        return {"value": val, "constraint": constraint}

    def addSequence(self, elem, parent):
        types = []
        values = []
        constraints = []

        for child in elem["children"]:
            field = self.addItem(child)
            parent.appendRow(field["item"])
            types.append(field["type"])
            values.append(field["value"])
            constraints.append(field["constraint"])

        parent.appendColumn(types)
        parent.appendColumn(constraints)
        parent.appendColumn(values)
        constraint = QStandardItem()
        val = QStandardItem()
        return {"value": val, "constraint": constraint}

    def addSeqOf(self, elem, parent):
        types = []
        values = []
        constraints = []
        for i in range(elem["maxSize"]):
            elem["seqoftype"]["id"] = "elem_%d" % i
            field = self.addItem(elem["seqoftype"])
            parent.appendRow(field["item"])
            types.append(field["type"])
            values.append(field["value"])
            constraints.append(field["constraint"])
        parent.appendColumn(types)
        parent.appendColumn(constraints)
        parent.appendColumn(values)
        if elem["minSize"] == elem["maxSize"]:
            constraintStr = 'SIZE(%d)' % elem["minSize"]
        else:
            constraintStr = 'SIZE(%d..%d)' % (elem["minSize"], elem["maxSize"])
        constraint = QStandardItem(constraintStr)
        constraint.setData(QBrush(QColor("gray")), Qt.ForegroundRole)
        val = QStandardItem('%d' % elem["minSize"])
        val.setData(elem["type"], ASN1TYPE)   # type (SEQOF)
        val.setData(elem["minSize"], MIN_RANGE)  # min number of elements
        val.setData(elem["maxSize"], MAX_RANGE)  # max number of elements
        return {"value": val, "constraint": constraint}

    def addChoice(self, elem, parent):
        types = []
        values = []
        constraints = []
        ids = []
        for choice in elem["choices"]:
            field = self.addItem(choice)
            ids.append(choice["id"])
            parent.appendRow(field["item"])
            types.append(field["type"])
            values.append(field["value"])
            constraints.append(field["constraint"])

        parent.appendColumn(types)
        parent.appendColumn(constraints)
        parent.appendColumn(values)

        val = QStandardItem(ids[0])  # default value: first choice
        # Define type attributes, later used to define the proper cell editor
        val.setData(elem["type"], ASN1TYPE)  # type (CHOICE)
        val.setData(ids, CHOICE_LIST)  # choice values
        constraint = QStandardItem()
        return {"value": val, "constraint": constraint}

    def addItem(self, elem):
        # Add field name on the first column:
        field = QStandardItem(elem["id"])
        # Add type on the second column in gray:
        asnType = QStandardItem(elem["type"])
        asnType.setData(QBrush(QColor("gray")), Qt.ForegroundRole)

        # get the Value and Contraints fields for the different types:
        if elem["type"] == 'INTEGER':
            data = self.addInteger(elem)
        elif elem["type"] == 'REAL':
            data = self.addReal(elem)
        elif elem["type"] == 'BOOLEAN':
            data = self.addBool(elem)
        elif elem["type"] == 'ENUMERATED':
            data = self.addEnum(elem)
        elif elem["type"] == 'STRING':
            data = self.addString(elem)
        elif elem["type"] in ('SEQUENCE', 'SET'):
            data = self.addSequence(elem, field)
        elif elem["type"] == 'SEQOF':
            data = self.addSeqOf(elem, field)
        elif elem["type"] == 'CHOICE':
            data = self.addChoice(elem, field)
        else:
            print 'You are using a non-supported type: ' + elem["type"]
            sys.exit(-1)
        return {"item": field, "type": asnType, "value": data["value"], "constraint": data["constraint"]}


class asn1Viewer(asn1Editor):
    ''' TM Viewing class. Fields are not editable '''
    def __init__(self, parent=None):
852
        super(asn1Viewer, self).__init__(parent)
Maxime Perrotin's avatar
Maxime Perrotin committed
853
        self.setEditTriggers(QAbstractItemView.NoEditTriggers)