Exemple #1
0
class CanBusViewPluginGUI(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self, parent)

        self.create_widgets(parent)

        self._bus_ids = []
        self.prev = {}
        self.idx = {}
        self._plot_vals = {}
        self._extender = 1

        self._last_time = {}

    def create_widgets(self, parent):

        # Layout and Label
        vbox = QtGui.QVBoxLayout()
        self.label = QtGui.QLabel()
        self.label.setText("Bus View")

        # Plot and Curves
        view = pg.GraphicsLayoutWidget(parent)
        self.plot = view.addPlot(title="Bus View")
        self.plot.showGrid(x=True, y=True)
        self.plot_1 = self.plot.plot(pen=(255, 0, 0),
                                     name="Red curve",
                                     fillLevel=0,
                                     fillBrush=(255, 255, 255, 30))

        self.plot.setLabel('left', 'Datarate [KB/s]')
        self.plot.setLabel('bottom', 'Time [sec]')

        # Combobox
        self.bus_selection_cb = GBuilder().combobox(
            self, [], self._ecu_selection_changed)

        # Checkbuttons
        h_lay = QHBoxLayout()

        # Layout
        vbox.addWidget(self.label)
        vbox.addWidget(view)
        h_lay.addWidget(self.bus_selection_cb)
        vbox.addLayout(h_lay)
        self.setLayout(vbox)

    def save(self):
        return [self._plot_vals, self._bus_ids]

    def load(self, data):
        self._plot_vals = data[0]
        for el in data[1]:
            self.bus_selection_cb.addItem(el)
        self._plot_it()

    def update_gui(self, datarates_l):

        datarates = datarates_l[0]

        for bus_id in datarates:

            info = datarates[bus_id]
            t_0 = info[0]
            rate = info[2]

            # Check if BUs available and add it to combobox
            try:
                self._add_bus(bus_id)
            except:
                pass

            # Update View
            try:

                cur_idx = self.idx[bus_id]

                # extend array
                self._extend_array(cur_idx, bus_id)

                # Extend plot values
                self._extend_plot_vals(bus_id, cur_idx, t_0, rate)

            except:
                pass

        # Plot values
        self._plot_it()

    def _add_bus(self, bus_id):
        ''' 
        adds the ecu to the view if needed
        '''
        if not bus_id in self._bus_ids:
            if not self._text_in_cb(bus_id, self.bus_selection_cb):
                self.bus_selection_cb.addItem(bus_id)
                self._bus_ids.append(bus_id)

                self._last_time[bus_id] = 0
                self.idx[bus_id] = 0
                self.prev[bus_id] = -1
                self._plot_vals[bus_id] = np.zeros((50000, 2), dtype=float)

    def _extend_array(self, cur_idx, bus_id):
        if cur_idx >= (50000 * self._extender):
            self._plot_vals[bus_id] = np.concatenate(
                (self._plot_vals[bus_id], np.zeros((50000, 2), dtype=float)))
            self._plot_vals[bus_id] = np.concatenate(
                (self._plot_vals[bus_id], np.zeros((50000, 2), dtype=float)))
            self._extender += 1

    def _extend_plot_vals(self, cur_id, cur_idx, t, data):

        self.prev[cur_id] = t
        self._plot_vals[cur_id][cur_idx][0] = t
        self._plot_vals[cur_id][cur_idx][1] = data  # y val
        self.idx[cur_id] += 1

    def _plot_it(self):
        try:
            vals = self._plot_vals[self.bus_selection_cb.currentText()]
            vals = vals[~np.all(vals == 0, axis=1)]

            self.plot_1.setData(vals)
            self.plot_1.show()
        except:
            pass

    def _ecu_selection_changed(self):
        try:
            print(self.bus_selection_cb.currentText())
        except:
            pass
        self._plot_it()

    def _text_in_cb(self, txt, combobox):
        for i in range(combobox.count()):
            if txt == combobox.itemText(i):
                return True
        return False

    def _wrong_data_format(self, data, cur_id, cur_idx, t):
        if not isinstance(data, (int, float, complex)):
            return True
        if t < self.prev[cur_id]:
            return True
        if cur_idx > 1:
            test = cur_idx - 1
        else:
            test = 0
        if (self._plot_vals[cur_id][test][0] == t):
            return True
        return False
Exemple #2
0
class CheckpointViewPluginGUI(QWidget):
            
    def __init__(self, parent):
        QWidget.__init__(self, parent)

        self.create_widgets(parent)
            
        self._ecu_ids = []    
        self.prev = {}
        self.idx = {}
        self._plot_vals = {}
        self._extender = 1
        self._cp_collections = {}
        self._show_sets = {}        
        self._ex_comps = []
        
    def create_widgets(self, parent):
        
        hbox = QHBoxLayout()
        
        # Left side
        
        # Layout and Label
        vbox_left = QtGui.QVBoxLayout()      
        vbox_right = QtGui.QVBoxLayout()    
             
        # Header
        up_hbox = QHBoxLayout()
                
        self._label = QtGui.QLabel(self)
        self._label.setText("Choose the communication partner")      
        self._label.setFixedWidth(170)  
        self._ecu_1_label = QtGui.QLabel(self)
        self._ecu_1_label.setText("   ECU 1:")    
        self._ecu_1_label.setFixedWidth(50)
        self._ecu_2_label = QtGui.QLabel(self)
        self._ecu_2_label.setText("    ECU 2:")      
        self._ecu_2_label.setFixedWidth(50)     
        self._ecu_1_cb = GBuilder().combobox(self, [], self._on_ecu_selection_changed)
        self._ecu_1_cb.addItem("<< No Selection >>")
        self._ecu_1_cb.addItem("Unknown")
        self._ecu_2_cb = GBuilder().combobox(self, [], self._on_ecu_selection_changed)
        self._ecu_2_cb.addItem("<< No Selection >>")
        self._ecu_2_cb.addItem("Unknown")
        self._ass_cb = QCheckBox("Show only associated")
        self._ass_cb.setFixedWidth(130)
        self._ass_cb.stateChanged.connect(self._on_ecu_selection_changed)
        
        up_hbox.addWidget(self._label)
        up_hbox.addWidget(self._ecu_1_label)
        up_hbox.addWidget(self._ecu_1_cb)
        up_hbox.addWidget(self._ecu_2_label)
        up_hbox.addWidget(self._ecu_2_cb)
        up_hbox.addWidget(self._ass_cb)

        # Table
        self._time_table = GBuilder().table(self, 0, 3, ["Time", "ECU", 'Event'], False)
        self._time_table.setColumnWidth(0, 100)
        self._time_table.setColumnWidth(1, 170)
        self._time_table.setSortingEnabled(True)
        self._time_table.horizontalHeader().setResizeMode(0, QHeaderView.Fixed);
        self._time_table.horizontalHeader().setResizeMode(1, QHeaderView.Fixed);
        self._time_table.horizontalHeader().setResizeMode(2, QHeaderView.Stretch);
        
        # Layout
        vbox_left.addLayout(up_hbox)
        vbox_left.addWidget(self._time_table)
        
        # Right side
        v_lay = QVBoxLayout()
        self._times_gb = GBuilder().groupbox(self, "Times") 
        self._times_gb.setFixedWidth(450)
        self._times_gb.setLayout(v_lay)
        vbox_right.addWidget(self._times_gb)
        
        self._up_info = GBuilder().label(self, self._label_up("-", "-", "-", "-", "-"))
        self._down_info = GBuilder().label(self, self._label_down("-"))
        v_lay.addWidget(self._up_info)
        v_lay.addWidget(self._down_info)

        hbox.addLayout(vbox_left)
        hbox.addLayout(vbox_right)
        self.setLayout(hbox)
         
    def save(self):
        data = [self._cp_collections]
        return data
         
    def load(self, data):
        self.update_gui([data[0]])
         
    def update_gui(self, monitor_input_lst):

        # add new entries
        for monitor_input in monitor_input_lst:
            self._add_missing_keys(monitor_input[1])
             
            self._extend_table(monitor_input)
 
             
    def _extend_table(self, monitor_input):           
         
        # row already existing -> Continue
        txt = EventlineInterpreter().core.cp_string(eval(monitor_input[3]), monitor_input[2], monitor_input[7], monitor_input[5])

        txt_2 = str([monitor_input[0], monitor_input[1], txt])
        if txt_2 in self._ex_comps:
            return
          
        # insert a row at right point
        row_nr = self._get_suiting_row(self._time_table, monitor_input[0], 0)
          

          
        self._time_table.insertRow(row_nr)
          
        itab = TableCheckpointItem(); itab.set_checkpoint(monitor_input); itab.setText(str(monitor_input[0]));      
        itab_2 = TableCheckpointItem(); itab_2.set_checkpoint(monitor_input); itab_2.setText(monitor_input[1]);
        itab_3 = TableCheckpointItem(); itab_3.set_checkpoint(monitor_input); itab_3.setText(txt);
          
        self._time_table.setItem(row_nr, 0, itab);
        self._time_table.setItem(row_nr, 1, itab_2);
        self._time_table.setItem(row_nr, 2, itab_3);
        self._time_table.setSelectionBehavior(QAbstractItemView.SelectRows); 
        self._time_table.itemSelectionChanged.connect(self._selection_changed)
          
        self._set_row_color(self._time_table, EventlineInterpreter().core._category_by_tag(eval(monitor_input[3])), row_nr)
          
        # Add to show set
        self._show_sets[monitor_input[1]].add(row_nr, monitor_input[2])
        self._ex_comps.append(str([monitor_input[0], monitor_input[1], txt]))
                  
    def _add_missing_keys(self, comp_id):
             
        if comp_id not in self._ecu_ids:
            self._show_sets[comp_id] = TableShowSet(self._time_table)
             
            # Add entry to comboboxes
            self._ecu_1_cb.addItem(comp_id)
            self._ecu_2_cb.addItem(comp_id)            
            self._ecu_ids.append(comp_id)
        

    
    def _get_suiting_row(self, table, val, col_idx):
        ''' returns the row where val is bigger than the upper and smaller than the lower'''
        prev = 0
        for r in range(table.rowCount()):
            item = table.item(r, col_idx)            
            if val < float(item.text()):
                break            
            prev = r 
        return prev
         
    def _hide_all_rows(self, table):        
        for r in range(table.rowCount()):
            table.setRowHidden(r, True)
#         
    def _label_up(self, msg_id, msg_ctnt, msg_size, msg_cat, msg_stream):
        return "Checkpoint Details:\n\nMessage ID:\t\t\n%s\nMessage Content:\t\t\n%s\nMessage Size\t\t\n%s\nMessage Category\t\t\n%s\n Message Stream\t\t\n%s" % (msg_id, msg_ctnt, msg_size, msg_cat, msg_stream)
             
    def _label_down(self, time_passed):
        return"Selection Details:\nTime passed:%s" % (time_passed)
#             
    def _on_ecu_selection_changed(self):
        self._show_selection()
#     
    def _selection_changed(self):
         
        # show the first selected
        lst = self._time_table.selectedIndexes()
        for it in lst:
            r = it.row()
            c = it.column()            
            itm = self._time_table.item(r, c)
            cp = itm.checkpoint()
            self._up_info.setText(self._label_up(cp[4], cp[5], cp[6], EventlineInterpreter().core._category_by_tag(eval(cp[3])), cp[7]))
            break
         
        # Show the connected information
        if len(lst) > 4:
            itm_2 = self._time_table.item(lst[4].row(), lst[4].column())
            cp_2 = itm_2.checkpoint()
            self._down_info.setText(self._label_down(abs(cp.time - cp_2.time)))
         
         
        print(list)
     
    def _set_row_color(self, table, category, row_nr):
        red = QColor(255, 143, 143)
        green = QColor(204, 255, 204)
        blue = QColor(204, 230, 255)
         
        for c in range(table.columnCount()):
            item = table.item(row_nr, c)
         
            if category in [CPCategory.ECU_AUTHENTICATION_ENC, CPCategory.ECU_AUTHENTICATION_TRANS]:
                item.setData(QtCore.Qt.BackgroundRole, red);
                 
            if category in [CPCategory.STREAM_AUTHORIZATION_ENC, CPCategory.STREAM_AUTHORIZATION_TRANS]:
                item.setData(QtCore.Qt.BackgroundRole, green);
                 
            if category in [CPCategory.SIMPLE_MESSAGE_ENC, CPCategory.SIMPLE_MESSAGE_TRANS]:
                item.setData(QtCore.Qt.BackgroundRole, blue);
                 
    def _show_selection(self):
        try:
            # Hide all sets 
            self._hide_all_rows(self._time_table)
             
            # No selection made in either of the boxes -> show all
            if self._ecu_1_cb.currentText() == "<< No Selection >>" and self._ecu_2_cb.currentText() == "<< No Selection >>":
                for ky in self._show_sets:
                    self._show_sets[ky].show()
                return
                 
            # one of the boxes has no selection: show other
            if self._ecu_1_cb.currentText() == "<< No Selection >>":
                self._show_sets[self._ecu_2_cb.currentText()].show()
                return            
            if self._ecu_2_cb.currentText() == "<< No Selection >>":
                self._show_sets[self._ecu_1_cb.currentText()].show()
                return
             
            # Show all selected sets / option show only associated             
            # If show associated hit: Show only associated
            if self._ass_cb.isChecked():
                self._show_sets[self._ecu_1_cb.currentText()].show_asc(self._ecu_2_cb.currentText())
                self._show_sets[self._ecu_2_cb.currentText()].show_asc(self._ecu_1_cb.currentText())
                 
            # Show both
            else:
                self._show_sets[self._ecu_1_cb.currentText()].show()
                self._show_sets[self._ecu_2_cb.currentText()].show()
                 
        except:
            pass
class SecureECUAddWidget(AbstractAddPlugin):
    ''' This is the interface that connects the GUI and the actions to
        execute for a SecureECU when it is to be created in the new
        simulation window '''
    
    GUI_NAME = "ECU Secure"
    GUI_ICON = os.getcwd() + r'/icons/secure_ecu.png'

    def __init__(self, parent):
        AbstractAddPlugin.__init__(self, parent)        
        self._create_widgets(parent)
        self.parent = parent
                
        self.set_ecu_settings = {}
        self.set_time_lib = {}
        self.has_sec_mod_cert = False
        self.id = uuid.uuid4()
        
        self.ecu_group = None
        
    def set_gui(self, mapp):
        ''' set the gui from the map received '''
        try:
            if "id_list" in mapp: self.id_list.setText(str(mapp["id_list"]))
            if "send_buffer" in mapp: self.send_buf_textedit.setText(str(mapp["send_buffer"]))
            if "rec_buffer" in mapp: self.rec_buf_textedit.setText(str(mapp["rec_buffer"]))
            if "nr_ecus" in mapp: self.nr_ecus_textedit.setText(str(mapp["nr_ecus"]))
            
            if "ecu_settings" in mapp: self.set_ecu_settings = mapp["ecu_settings"]
            self._set_cb_changed()
            
            if "ecu_timing" in mapp: self.set_time_lib = mapp["ecu_timing"]
            index = self.ecu_set_time_sel_cb.findText(self.set_time_lib[self.ecu_set_time_cb.currentText()])
            self.ecu_set_time_sel_cb.setCurrentIndex(index)  
            self._cur_set_time_entry = self.ecu_set_time_cb.currentText()  
            
            if "has_sec_mod_cert" in mapp: self.has_sec_mod_cert = mapp["has_sec_mod_cert"]
            if not self.has_sec_mod_cert: self.has_sec_mod_cert_cb.setCurrentIndex(0)
            
        except:
            ECULogger().log_traceback()

    def get_map(self):
        
        
        mapping_values = {}
        # Read the values from the gui and save them  
        # General Information      
        mapping_values["id_list"] = self._wrap(eval, self.id_list.text(), [])
        mapping_values["send_buffer"] = self._wrap(int, self.send_buf_textedit.text(), 200)
        mapping_values["rec_buffer"] = self._wrap(int, self.rec_buf_textedit.text(), 200)
        mapping_values["nr_ecus"] = self._wrap(int, self.nr_ecus_textedit.text(), 0)
        
        if self.ecu_set_te.text():
            self.set_ecu_settings[self._cur_set_entry] = self.ecu_set_te.text()
        mapping_values["ecu_settings"] = self.set_ecu_settings
        
        # Certification and Timing
        self.set_time_lib[self._cur_set_time_entry] = self.ecu_set_time_sel_cb.currentText()  # Final entry
        mapping_values['ecu_timing'] = self.set_time_lib
        mapping_values['has_sec_mod_cert'] = self.has_sec_mod_cert        

#         mapping_values['connected_sec_mod'] = None
        
        return mapping_values

    def preprocess(self, env, mapp):
        
        self.ecu_spec = SimpleECUSpec(mapp["id_list"] , mapp["send_buffer"], mapp["rec_buffer"])        
        for k in mapp["ecu_settings"]:
            self.ecu_spec.set_ecu_setting(k, mapp["ecu_settings"][k])  
                
        self.ecu_group = api.ecu_sim_api.set_ecus(env, mapp["nr_ecus"], 'SecureECU', self.ecu_spec)
    
    def get_actions(self):
        ''' returns the connections that can be made '''        
        
        actions = {}
        
        actions['valid_cert'] = 'Generate Valid Certificate'
                
        return actions
        
    def execute_action(self, env_connect, *args):
        pass

    def main_process(self, env, mapp):
        print("Main")

    def postprocess(self, env, mapp):
        print("Post")

    def _create_widgets(self, parent):

        # Layout
        GBuilder().set_props(self, None, 100, 100)  
        main_lo = QVBoxLayout()
        self.setLayout(main_lo)
        
        # Title
        main_lo.addWidget(GBuilder().label(parent, "<b>Description:</b>"))
        hl = QHBoxLayout()        
        self.desc_label = GBuilder().label(parent, "Add a new SecureECU. This ECU resembles the ECU Part in a Lightweight Authentication Mechanism.")
        self.desc_label.setFixedWidth(400)
        self.icon = GBuilder().image(parent, SecureECUAddWidget.GUI_ICON, 2)        
        hl.addWidget(self.desc_label)
        hl.addWidget(self.icon)
        main_lo.addLayout(hl)
        
        line = GBuilder().hor_line(parent)
        main_lo.addWidget(line);
                
        # Constructor Inputs
        main_lo.addWidget(GBuilder().label(parent, "<b>General Information:</b>"))
        lo0, self.id_list = GBuilder().label_text(parent, "List of IDs (optional):", label_width=120)
        lo1, self.send_buf_textedit = GBuilder().label_text(parent, "Sending BufferSize:", label_width=120)
        lo2, self.rec_buf_textedit = GBuilder().label_text(parent, "Receiving Buffer Size:", label_width=120)
        lo3, self.nr_ecus_textedit = GBuilder().label_text(parent, "Number of ECUs:", label_width=120)
        main_lo.addLayout(lo0)
        main_lo.addLayout(lo1)
        main_lo.addLayout(lo2)
        main_lo.addLayout(lo3)

        # ECU Settings
        items = self._get_ecu_settings()
        hl, self.ecu_set_cb, self.ecu_set_te = GBuilder().combobox_text(parent, items, self._set_cb_changed)
        self._cur_set_entry = self.ecu_set_cb.currentText()
        main_lo.addLayout(hl)
        
        # Timing Mapping 
        line = GBuilder().hor_line(parent)
        main_lo.addWidget(line);
        lab = GBuilder().label(parent, "<b>Timing and Certification:</b>")
        lab.setFixedHeight(20)
        main_lo.addWidget(lab)
        
        itm = StdSecurECUTimingFunctions()
        avail_items = itm.available_tags
        items = itm.function_map.keys()        
        hl1 = QHBoxLayout()
        self.ecu_set_time_cb = GBuilder().combobox(parent, items, self._set_time_cb_changed)
        self._cur_set_time_entry = self.ecu_set_time_cb.currentText()   
        
        self.ecu_set_time_sel_cb = GBuilder().combobox(parent, avail_items, self._set_time_cb_changed)
        self._cur_set_time_sel_entry = self.ecu_set_time_sel_cb.currentText()
        hl1.addWidget(self.ecu_set_time_cb)
        hl1.addWidget(self.ecu_set_time_sel_cb)
        main_lo.addLayout(hl1)

        # Certification (has a valid certificate or not)
#         hl, self.has_sec_mod_cert_cb, lab = GBuilder().label_combobox(parent, "Has Security Module Certificate", ["Yes", "No"], self._has_sec_mod_cb_changed)
#         main_lo.addLayout(hl)

    def _get_ecu_settings(self):
        SecureECU().settings = sorted(SecureECU().settings, key=lambda key: SecureECU().settings[key])
        
        return SecureECU().settings
        
    def _has_sec_mod_cb_changed(self):
        try:
            if self.has_sec_mod_cert_cb.currentText() == "Yes":
                self.has_sec_mod_cert = True
            else:
                self.has_sec_mod_cert = False
        except:
            pass
        
    def _set_time_cb_changed(self):   

        try:
            # Save old value
            if self._cur_set_time_entry == self.ecu_set_time_cb.currentText():
                self.set_time_lib[self._cur_set_time_entry] = self.ecu_set_time_sel_cb.currentText()
                self._cur_set_time_entry = self.ecu_set_time_cb.currentText()
                return
            
            # Load the next one
            try:
                index = self.ecu_set_time_sel_cb.findText(self.set_time_lib[self.ecu_set_time_cb.currentText()])
                self.ecu_set_time_sel_cb.setCurrentIndex(index)                           
            except:
                self.ecu_set_time_sel_cb.setCurrentIndex(0)        
            self._cur_set_time_entry = self.ecu_set_time_cb.currentText()                           
        except:
            pass
        
    def _set_cb_changed(self):        
        try:
            # Save old value
            if self.ecu_set_te.text():
                self.set_ecu_settings[self._cur_set_entry] = self.ecu_set_te.text()
            
            # Load the next one
            try:
                self.ecu_set_te.setText(self.set_ecu_settings[self.ecu_set_cb.currentText()])                
            except:
                self.ecu_set_te.setText('')            
            self._cur_set_entry = self.ecu_set_cb.currentText()
        except:
            pass
        
    def _wrap(self, func, prime, second):
        try:
            el = func(prime)
            return el
        except:
            return second
Exemple #4
0
class BufferViewPluginGUI(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self, parent)

        self.create_widgets(parent)

        self._ecu_ids = []
        self.prev = {}
        self.idx = {}
        self._plot_vals = {}
        self._extender = 1

    def create_widgets(self, parent):

        # Layout and Label
        vbox = QtGui.QVBoxLayout()
        self.label = QtGui.QLabel()
        self.label.setText("Buffer View")

        # Plot and Curves
        view = pg.GraphicsLayoutWidget(parent)
        self.plot = view.addPlot(title="Buffer View")
        self.plot.setLabel('left', 'Buffer Memory [B]')
        self.plot.setLabel('bottom', 'Time [sec]')

        self.plot.showGrid(x=True, y=True)
        self.plot_1 = self.plot.plot(pen=(255, 0, 0),
                                     name="Red curve",
                                     fillLevel=0,
                                     fillBrush=(255, 255, 255, 30))
        self.plot_2 = self.plot.plot(pen=(0, 255, 0),
                                     name="Green curve",
                                     fillLevel=0,
                                     fillBrush=(255, 255, 255, 30))

        # Combobox
        self.ecu_selection_cb = GBuilder().combobox(
            self, [], self._ecu_selection_changed)

        # Checkbuttons
        h_lay = QHBoxLayout()
        self.transmit_cb = QCheckBox("Transmit Buffer (red)")
        self.transmit_cb.setFixedWidth(150)
        self.transmit_cb.setFixedHeight(20)
        self.transmit_cb.setChecked(True)
        self.transmit_cb.stateChanged.connect(self._ecu_selection_changed)
        self.receive_cb = QCheckBox("Receive Buffer (green)")
        self.receive_cb.setFixedWidth(150)
        self.receive_cb.setChecked(True)
        self.receive_cb.setFixedHeight(20)
        self.receive_cb.stateChanged.connect(self._ecu_selection_changed)

        # Layout
        vbox.addWidget(self.label)
        vbox.addWidget(view)
        h_lay.addWidget(self.ecu_selection_cb)
        h_lay.addWidget(self.transmit_cb)
        h_lay.addWidget(self.receive_cb)
        vbox.addLayout(h_lay)
        self.setLayout(vbox)

    def save(self):
        return [self._plot_vals, self._ecu_ids]

    def link_axis(self):
        return self.plot

    def load(self, data):
        self._plot_vals = data[0]

        for el in data[1]:
            self.ecu_selection_cb.addItem(el)

        self._plot_it()

    def update_gui(self, monitor_input_lst):

        for monitor_input in monitor_input_lst:

            data = float(monitor_input[9])

            # Check if ECU available and add it to combobox
            tag = eval(monitor_input[3])
            try:
                self._add_ecu(monitor_input[1])
            except:
                pass

            # Update View
            try:
                # Extract data
                cur_id = monitor_input[1]
                t = monitor_input[0]
                cur_idx = self.idx[tag][cur_id]

                # extend array
                self._extend_array(cur_idx, monitor_input)

                # Check format
                if self._wrong_data_format(data, tag, cur_id, cur_idx, t):
                    continue

                # Extend plot values
                self._extend_plot_vals(tag, cur_id, cur_idx, t, data)
            except:
                pass

            # Plot values
            self._plot_it()

    def _add_ecu(self, ecu_id):
        ''' 
        adds the ecu to the view if needed
        '''
        if not ecu_id in self._ecu_ids:
            if not self._text_in_cb(ecu_id, self.ecu_selection_cb):
                self.ecu_selection_cb.addItem(ecu_id)
                self._ecu_ids.append(ecu_id)

                for in_tag in [
                        MonitorTags.BT_ECU_TRANSMIT_BUFFER,
                        MonitorTags.BT_ECU_RECEIVE_BUFFER
                ]:
                    if in_tag not in self.idx: self.idx[in_tag] = {}
                    if in_tag not in self.prev: self.prev[in_tag] = {}
                    if in_tag not in self._plot_vals:
                        self._plot_vals[in_tag] = {}

                    self.idx[in_tag][ecu_id] = 0
                    self.prev[in_tag][ecu_id] = -1
                    self._plot_vals[in_tag][ecu_id] = np.zeros((50000, 2),
                                                               dtype=float)

    def _extend_array(self, cur_idx, monitor_input):
        if cur_idx >= (50000 * self._extender):
            self._plot_vals[MonitorTags.BT_ECU_TRANSMIT_BUFFER][
                monitor_input[1]] = np.concatenate(
                    (self._plot_vals[MonitorTags.BT_ECU_TRANSMIT_BUFFER][
                        monitor_input[1]], np.zeros((50000, 2), dtype=float)))
            self._plot_vals[MonitorTags.BT_ECU_RECEIVE_BUFFER][
                monitor_input[1]] = np.concatenate(
                    (self._plot_vals[MonitorTags.BT_ECU_RECEIVE_BUFFER][
                        monitor_input[1]], np.zeros((50000, 2), dtype=float)))
            self._extender += 1

    def _extend_plot_vals(self, tag, cur_id, cur_idx, t, data):
        self.prev[tag][cur_id] = t
        self._plot_vals[tag][cur_id][cur_idx][0] = t
        self._plot_vals[tag][cur_id][cur_idx][1] = data  # y val
        self.idx[tag][cur_id] += 1

    def _plot_it(self):
        try:
            if self.transmit_cb.isChecked():

                vals = self._plot_vals[MonitorTags.BT_ECU_TRANSMIT_BUFFER][
                    self.ecu_selection_cb.currentText()]
                vals = vals[~np.all(vals == 0, axis=1)]

                self.plot_1.setData(vals)
                self.plot_1.show()
            else:
                self.plot_1.hide()
        except:
            pass
        try:
            if self.receive_cb.isChecked():
                vals = self._plot_vals[MonitorTags.BT_ECU_RECEIVE_BUFFER][
                    self.ecu_selection_cb.currentText()]
                vals = vals[~np.all(vals == 0, axis=1)]
                self.plot_2.setData(vals)
                self.plot_2.show()
            else:
                self.plot_2.hide()
        except:
            pass

    def _ecu_selection_changed(self):
        try:
            print(self.ecu_selection_cb.currentText())
        except:
            pass
        self._plot_it()

    def _text_in_cb(self, txt, combobox):
        for i in range(combobox.count()):
            if txt == combobox.itemText(i):
                return True
        return False

    def _wrong_data_format(self, data, tag, cur_id, cur_idx, t):
        if not isinstance(data, (int, float, complex)):
            return True
        if t < self.prev[tag][cur_id]:
            return True
        if cur_idx > 1:
            test = cur_idx - 1
        else:
            test = 0
        if (self._plot_vals[tag][cur_id][test][0] == t):
            return True
        return False
class CanBusViewPluginGUI(QWidget):
            
    def __init__(self, parent):
        QWidget.__init__(self, parent)

        self.create_widgets(parent)
                        
        self._bus_ids = []    
        self.prev = {}
        self.idx = {}
        self._plot_vals = {}
        self._extender = 1
        
        self._last_time = {}
        
        
    def create_widgets(self, parent):
        
        # Layout and Label
        vbox = QtGui.QVBoxLayout()        
        self.label = QtGui.QLabel()
        self.label.setText("Bus View")
        
        # Plot and Curves
        view = pg.GraphicsLayoutWidget(parent) 
        self.plot = view.addPlot(title="Bus View")
        self.plot.showGrid(x=True, y=True)
        self.plot_1 = self.plot.plot(pen=(255, 0, 0), name="Red curve", fillLevel=0, fillBrush=(255, 255, 255, 30))        
    
        self.plot.setLabel('left', 'Datarate [KB/s]')
        self.plot.setLabel('bottom', 'Time [sec]')
    
        # Combobox
        self.bus_selection_cb = GBuilder().combobox(self, [], self._ecu_selection_changed)

        # Checkbuttons
        h_lay = QHBoxLayout()
        
        # Layout
        vbox.addWidget(self.label)
        vbox.addWidget(view)
        h_lay.addWidget(self.bus_selection_cb)
        vbox.addLayout(h_lay)
        self.setLayout(vbox)
      
    def save(self):
        return [self._plot_vals, self._bus_ids]
        
    def load(self, data):
        self._plot_vals = data[0]
        for el in data[1]:
            self.bus_selection_cb.addItem(el)
        self._plot_it()
        
    def update_gui(self, datarates_l):
                
        datarates = datarates_l[0]
                
        for bus_id in datarates:


            info = datarates[bus_id]
            t_0 = info[0]  
            rate = info[2]
                        
            # Check if BUs available and add it to combobox
            try:   
                self._add_bus(bus_id)
            except:
                pass

            # Update View
            try:

                cur_idx = self.idx[bus_id]

                # extend array
                self._extend_array(cur_idx, bus_id)

                # Extend plot values
                self._extend_plot_vals(bus_id, cur_idx, t_0, rate)
                
            except:
                pass
                     
        # Plot values
        self._plot_it()
       
    def _add_bus(self, bus_id):    
        ''' 
        adds the ecu to the view if needed
        '''
        if not bus_id in self._bus_ids:
            if not self._text_in_cb(bus_id, self.bus_selection_cb):
                self.bus_selection_cb.addItem(bus_id)
                self._bus_ids.append(bus_id)
                
                self._last_time[bus_id] = 0
                self.idx[bus_id] = 0
                self.prev[bus_id] = -1
                self._plot_vals[bus_id] = np.zeros((50000, 2), dtype=float)
       
    def _extend_array(self, cur_idx, bus_id):
        if cur_idx >= (50000 * self._extender):
            self._plot_vals[bus_id] = np.concatenate((self._plot_vals[bus_id], np.zeros((50000, 2), dtype=float)))
            self._plot_vals[bus_id] = np.concatenate((self._plot_vals[bus_id], np.zeros((50000, 2), dtype=float)))
            self._extender += 1
       
    def _extend_plot_vals(self, cur_id, cur_idx, t, data):
        
        self.prev[cur_id] = t
        self._plot_vals[cur_id][cur_idx][0] = t
        self._plot_vals[cur_id][cur_idx][1] = data  # y val                
        self.idx[cur_id] += 1
    
    def _plot_it(self):        
        try:
            vals = self._plot_vals[self.bus_selection_cb.currentText()]                
            vals = vals[~np.all(vals == 0, axis=1)]
            
            self.plot_1.setData(vals)
            self.plot_1.show()
        except:
            pass
       
    def _ecu_selection_changed(self):
        try:
            print(self.bus_selection_cb.currentText())
        except:
            pass        
        self._plot_it()
                    
    def _text_in_cb(self, txt, combobox):
        for i in range(combobox.count()):
            if txt == combobox.itemText(i):
                return True
        return False
        
    def _wrong_data_format(self, data, cur_id, cur_idx, t):
        if not isinstance(data, (int, float, complex)):
            return True            
        if t < self.prev[cur_id]:
            return True           
        if cur_idx > 1:
            test = cur_idx - 1
        else:
            test = 0    
        if (self._plot_vals[cur_id][test][0] == t):
            return True   
        return False
class BufferViewPluginGUI(QWidget):
            
    def __init__(self, parent):
        QWidget.__init__(self, parent)

        self.create_widgets(parent)
                        
        self._ecu_ids = []    
        self.prev = {}
        self.idx = {}
        self._plot_vals = {}
        self._extender = 1
        
        
    def create_widgets(self, parent):
        
        # Layout and Label
        vbox = QtGui.QVBoxLayout()        
        self.label = QtGui.QLabel()
        self.label.setText("Buffer View")
        
        # Plot and Curves
        view = pg.GraphicsLayoutWidget(parent) 
        self.plot = view.addPlot(title="Buffer View")
        self.plot.setLabel('left', 'Buffer Memory [B]')
        self.plot.setLabel('bottom', 'Time [sec]')
        
        self.plot.showGrid(x=True, y=True)
        self.plot_1 = self.plot.plot(pen=(255, 0, 0), name="Red curve", fillLevel=0, fillBrush=(255, 255, 255, 30))        
        self.plot_2 = self.plot.plot(pen=(0, 255, 0), name="Green curve", fillLevel=0, fillBrush=(255, 255, 255, 30))     
        
        
        # Combobox
        self.ecu_selection_cb = GBuilder().combobox(self, [], self._ecu_selection_changed)

        # Checkbuttons
        h_lay = QHBoxLayout()
        self.transmit_cb = QCheckBox("Transmit Buffer (red)")
        self.transmit_cb.setFixedWidth(150)
        self.transmit_cb.setFixedHeight(20)
        self.transmit_cb.setChecked(True)
        self.transmit_cb.stateChanged.connect(self._ecu_selection_changed)
        self.receive_cb = QCheckBox("Receive Buffer (green)")
        self.receive_cb.setFixedWidth(150)
        self.receive_cb.setChecked(True)
        self.receive_cb.setFixedHeight(20)
        self.receive_cb.stateChanged.connect(self._ecu_selection_changed)
        
        # Layout
        vbox.addWidget(self.label)
        vbox.addWidget(view)
        h_lay.addWidget(self.ecu_selection_cb)
        h_lay.addWidget(self.transmit_cb)
        h_lay.addWidget(self.receive_cb)
        vbox.addLayout(h_lay)
        self.setLayout(vbox)
      
    def save(self):
        return [self._plot_vals, self._ecu_ids]
        
    def link_axis(self):
        return self.plot
        
    def load(self, data):
        self._plot_vals = data[0]
        
        for el in data[1]:
            self.ecu_selection_cb.addItem(el)
        
        self._plot_it()
        
    def update_gui(self, monitor_input_lst):
                
        for monitor_input in monitor_input_lst:
            
            data = float(monitor_input[9])
            
            # Check if ECU available and add it to combobox
            tag = eval(monitor_input[3])      
            try:   
                self._add_ecu(monitor_input[1])
            except:
                pass
            
            # Update View
            try:
                # Extract data
                cur_id = monitor_input[1]
                t = monitor_input[0]
                cur_idx = self.idx[tag][cur_id]
        
                # extend array
                self._extend_array(cur_idx, monitor_input)
                          
                # Check format
                if self._wrong_data_format(data, tag, cur_id, cur_idx, t):
                    continue                                
                
                # Extend plot values
                self._extend_plot_vals(tag, cur_id, cur_idx, t, data)
            except:
                pass
                    
            # Plot values
            self._plot_it()
       
    def _add_ecu(self, ecu_id):    
        ''' 
        adds the ecu to the view if needed
        '''
        if not ecu_id in self._ecu_ids:
            if not self._text_in_cb(ecu_id, self.ecu_selection_cb):
                self.ecu_selection_cb.addItem(ecu_id)
                self._ecu_ids.append(ecu_id)
                
                for in_tag in [MonitorTags.BT_ECU_TRANSMIT_BUFFER, MonitorTags.BT_ECU_RECEIVE_BUFFER]:
                    if in_tag not in self.idx: self.idx[in_tag] = {}
                    if in_tag not in self.prev: self.prev[in_tag] = {}
                    if in_tag not in self._plot_vals: self._plot_vals[in_tag] = {}
                    
                    self.idx[in_tag][ecu_id] = 0
                    self.prev[in_tag][ecu_id] = -1
                    self._plot_vals[in_tag][ecu_id] = np.zeros((50000, 2), dtype=float)
       
    def _extend_array(self, cur_idx, monitor_input):
        if cur_idx >= (50000 * self._extender):
            self._plot_vals[MonitorTags.BT_ECU_TRANSMIT_BUFFER][monitor_input[1]] = np.concatenate((self._plot_vals[MonitorTags.BT_ECU_TRANSMIT_BUFFER][monitor_input[1]], np.zeros((50000, 2), dtype=float)))
            self._plot_vals[MonitorTags.BT_ECU_RECEIVE_BUFFER][monitor_input[1]] = np.concatenate((self._plot_vals[MonitorTags.BT_ECU_RECEIVE_BUFFER][monitor_input[1]], np.zeros((50000, 2), dtype=float)))
            self._extender += 1
       
    def _extend_plot_vals(self, tag, cur_id, cur_idx, t, data):
        self.prev[tag][cur_id] = t
        self._plot_vals[tag][cur_id][cur_idx][0] = t
        self._plot_vals[tag][cur_id][cur_idx][1] = data  # y val                
        self.idx[tag][cur_id] += 1
    
    def _plot_it(self):        
        try:            
            if self.transmit_cb.isChecked():
              
                vals = self._plot_vals[MonitorTags.BT_ECU_TRANSMIT_BUFFER][self.ecu_selection_cb.currentText()]                
                vals = vals[~np.all(vals == 0, axis=1)]
                
                self.plot_1.setData(vals)
                self.plot_1.show()
            else:
                self.plot_1.hide()
        except:
            pass
        try:
            if self.receive_cb.isChecked():
                vals = self._plot_vals[MonitorTags.BT_ECU_RECEIVE_BUFFER][self.ecu_selection_cb.currentText()]
                vals = vals[~np.all(vals == 0, axis=1)]
                self.plot_2.setData(vals)
                self.plot_2.show()
            else:
                self.plot_2.hide()
        except:
            pass
       
    def _ecu_selection_changed(self):
        try:
            print(self.ecu_selection_cb.currentText())
        except:
            pass        
        self._plot_it()
                    
    def _text_in_cb(self, txt, combobox):
        for i in range(combobox.count()):
            if txt == combobox.itemText(i):
                return True
        return False
        
    def _wrong_data_format(self, data, tag, cur_id, cur_idx, t):
        if not isinstance(data, (int, float, complex)):
            return True            
        if t < self.prev[tag][cur_id]:
            return True           
        if cur_idx > 1:
            test = cur_idx - 1
        else:
            test = 0    
        if (self._plot_vals[tag][cur_id][test][0] == t):
            return True   
        return False