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 __init__(self, *args, **kwargs): QDialog.__init__(self, *args, **kwargs) self.builder = GBuilder() self.setWindowIcon(QtGui.QIcon( os.getcwd() +r'/icons/tumcreatelogo2.png')) self.setWindowTitle("Timing Set Manager") self.selected_tab_row = 0 self.create_widgets() self._load_variables()
def __init__(self, views, *args, **kwargs): QtGui.QMainWindow.__init__(self, *args, **kwargs) ''' 1. members ''' self.builder = GBuilder() ''' 2. initialize the gui factories ''' self.view_plugins = views ''' 3. actions ''' self.init_actions() self.create_widgets()
class SetManagerPluginGUI(QWidget): def __init__(self, *args, **kwargs): QWidget.__init__(self, *args, **kwargs) self.builder = GBuilder() self.create_widgets() def create_widgets(self): ''' Widgets''' self.desc_label = self.builder.label(self, "<b>Decription:</b> Configure the settings for the mapping Timing - Project Sets") self.desc_label.setFixedHeight(25) self.desc_label.setFixedWidth(400) self.selection_cb = self.builder.combobox(self, [], self.cb_selection_changed) self.selection_cb.setFixedHeight(25) self.sec_label = self.builder.label(self, "<b>Use Set: </b>") self.sec_label.setFixedHeight(25) self.sec_label.setFixedWidth(50) self.open_manager = self.builder.pushbutton(self, "Setting Manager", self._open_manager_act,\ icon_path = os.getcwd() +r'/icons/settings.png') self.open_manager.setFixedHeight(35) ''' Layout ''' vbox = QtGui.QVBoxLayout() hl = QtGui.QHBoxLayout() hl.addWidget(self.desc_label) hl.addWidget(self.open_manager) vbox.addLayout(hl) hl = QtGui.QHBoxLayout() hl.addWidget(self.sec_label) hl.addWidget(self.selection_cb) vbox.addLayout(hl) self.setLayout(vbox) # self.open_manager_act() def cb_selection_changed(self): pass def _open_manager_act(self): man = SettingManager() man.exec()
def _fill_environment_box(self): # Main Layout main_lo = QVBoxLayout() self.environment_gb.setLayout(main_lo) # Combobox lo, self.env_select_cb, lab = GBuilder().label_combobox(self, "Current Environment:", [], self._env_select_changed) hl = QHBoxLayout() hl.addLayout(lo) but = GBuilder().pushbutton(self, "New", self._new_env_hit) but.setFixedWidth(40) hl.addWidget(but) lab.setFixedWidth(140) self.env_select_cb.setFixedHeight(22) self.env_select_cb.setFixedWidth(350) main_lo.addLayout(hl) # Groupbox (to make it look nicer) self.content_gb = EnvironmentView(self.environment_gb) main_lo.addWidget(self.content_gb) self.content_gb.setFixedHeight(550) self.content_gb.setFixedWidth(1000) self.content_gb.setLayout(lo) # QStackedWidget with environments self.stacked_env = QStackedWidget() lo.addWidget(self.stacked_env)
def __init__(self, parent): dockarea.DockArea.__init__(self) self.builder = GBuilder() self.widget_index = {} self.widget_text = {} self.dock_index = {} self._external_core = CheckpointInterpreterCore() self._information_box_items = ['Time', 'Associated Id', 'Monitor Tag', 'Message Id', 'Message', 'Size', 'Stream Id', 'Monitor Data', 'Description'] self._information_checked = {'Time': True, 'Associated Id': True, 'Monitor Tag': True, 'Message Id': True, 'Message': True, 'Size': True, 'Stream Id': False, 'Monitor Data': False, 'Description': True} self._info_widget_index = {} self.known = [] self.create_widgets(parent)
def __init__(self, condition, request, spec, q_tab_item): QWidget.__init__(self) self.builder = GBuilder() self.edited_item = q_tab_item self.condition = condition self.request = request self.spec_node = spec self._create_widget() self._fill_widgets() self.exec()
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 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 __init__(self, *args, **kwargs): QtGui.QMainWindow.__init__(self, *args, **kwargs) ''' 1. members ''' self.builder = GBuilder() self.monitor = Monitor() self.setWindowTitle('TUMCreate - Automotive Simulator') self.setWindowIcon(QtGui.QIcon(os.path.join(os.path.dirname(__file__), r'../icons/tumcreatelogo2.png'))) ''' 2. initialize the gui factories ''' ViewerPluginFactory().load_classes() SettingsPluginFactory().load_classes() ''' 3. actions ''' self.init_actions() self.create_widgets()
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 Standard Bus. This CAN Bus is a simple implementation of a automotive link.") self.desc_label.setFixedWidth(400) self.icon = GBuilder().image(parent, StdBusAddWidget.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.nr_ecus_textedit = GBuilder().label_text(parent, "Number of Busses:", label_width=120) main_lo.addLayout(lo0) main_lo.addLayout(lo1)
def _draw_lines(self, prime_env_el, connected_env_els): try: DragSelection().connected[self.selected_env] except: DragSelection().connected[self.selected_env] = [] DragSelection().connected[self.selected_env].append(LineConnection(prime_env_el.move_icon, [o.move_icon for o in connected_env_els]))
def __init__(self, parent): dockarea.DockArea.__init__(self) self.builder = GBuilder() self._bin = {} self.widget_index = {} self.widget_text = {} self.send_plot_text = {} self.rec_plot_text = {} self.dock_index = {} self._ecu_ids = [] self._information_box_items = ["a"] self._info_widget_index = {} self._init_tag_list() self.known = [] self.create_widgets(parent)
def create_widgets(self, parent): vbox = QtGui.QVBoxLayout() self.label = QtGui.QLabel() self.label.setText("Constellation") self.label.setFixedHeight(20) self.fc = Flowchart(terminals={'Connection': {'io': 'in'}}) self.fc._nodes['Input'].close() self.fc._nodes['Output'].close() self.view = self.fc.widget() wig = self.view.chartWidget self.view.chartWidget.hoverDock.hide() self.view.chartWidget.selectedTree.hide() self.view.chartWidget.selDock.label.setText("Selected Comp.") # add selection label self.selection_label = self.view.chartWidget.selDescLabel self.selection_label.setText("") self.selection_label.setFixedHeight(15) # add information table self.info_table = GBuilder().table(self.view.chartWidget.selDock, 1, 2, ["Settings", "Value"]) for r in range(self.info_table.rowCount()): self.info_table.setRowHeight(r, 20) self.info_table.horizontalHeader().hide() self.info_table.verticalHeader().hide() self.info_table.setSelectionBehavior(QAbstractItemView.SelectRows) self.info_table.setSortingEnabled(True) # self.view.chartWidget.selInfoLayout.addWidget(self.selection_label) self.view.chartWidget.selInfoLayout.addWidget(self.info_table) # override on selection self.view.chartWidget._scene.selectionChanged.connect( self._selection_changed) vbox.addWidget(self.label) vbox.addWidget(wig) self.setLayout(vbox)
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, SecLwAuthSecurityModuleAddWidget.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 = StdSecurLwSecModTimingFunctions() 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)
def _show_env(self, selected_env, env_map): GBuilder().update_connected(self.content_gb, self.environment_gb.pos(), self.content_gb.pos(), self.content_gb.selected_env) # Mainwindow for chil in self.children(): if isinstance(chil, DragLabel): try: a = self._get_env_elem_by_icon(env_map[selected_env], chil) if a == None: chil.hide() else: chil.show() except: chil.hide()
def create_widgets(self, parent): # Main Layout vbox = QtGui.QVBoxLayout() self.setLayout(vbox) # Label vl_left = QVBoxLayout() self.top_label = GBuilder().label(parent, "Create a new Simulation or select a existing one from the list", None, None) vl_left.addWidget(self.top_label) hl_out = QHBoxLayout() vbox.addLayout(hl_out) # Buttons vl_right = QVBoxLayout() self.new_button = GBuilder().pushbutton(parent, "New", self._new_hit, os.getcwd() + r'/icons/new.png') vl_right.addWidget(self.new_button) self.import_button = GBuilder().pushbutton(parent, "Import", self._import_hit, os.getcwd() + r'/icons/import.png') vl_right.addWidget(self.import_button) self.save_button = GBuilder().pushbutton(parent, "Export", self._save_hit, os.getcwd() + r'/icons/save.png') vl_right.addWidget(self.save_button) self.build_button = GBuilder().pushbutton(parent, "Build Simulation", self._build_hit, os.getcwd() + r'/icons/build.png', 35, 35) self.build_button.setFixedHeight(40) vl_right.addWidget(self.build_button) # Table self.sims_table = GBuilder().table(parent, 5, 2, ["A"], False) self.sims_table.horizontalHeader().setResizeMode(1, QHeaderView.Fixed); self.sims_table.horizontalHeader().setResizeMode(0, QHeaderView.Stretch); self.sims_table.setColumnWidth(1, 32) # self.check_buts = GBuilder().add_checkbuttons(self.sims_table, 0, 1) self.sims_table.verticalHeader().setDefaultSectionSize(25) self.sims_table.verticalHeader().hide() self.sims_table.horizontalHeader().hide() self.sims_table.setFixedHeight(110) vl_left.addWidget(self.sims_table) hl_out.addLayout(vl_left) hl_out.addLayout(vl_right)
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 create_widgets(self, parent): vbox = QtGui.QVBoxLayout() self.label = QtGui.QLabel() self.label.setText("Constellation") self.label.setFixedHeight(20) self.fc = Flowchart(terminals={'Connection': {'io': 'in'}}) self.fc._nodes['Input'].close() self.fc._nodes['Output'].close() self.view = self.fc.widget() wig = self.view.chartWidget self.view.chartWidget.hoverDock.hide() self.view.chartWidget.selectedTree.hide() self.view.chartWidget.selDock.label.setText("Selected Comp.") # add selection label self.selection_label = self.view.chartWidget.selDescLabel self.selection_label.setText("") self.selection_label.setFixedHeight(15) # add information table self.info_table = GBuilder().table(self.view.chartWidget.selDock, 1, 2, ["Settings", "Value"]) for r in range(self.info_table.rowCount()): self.info_table.setRowHeight(r, 20) self.info_table.horizontalHeader().hide() self.info_table.verticalHeader().hide() self.info_table.setSelectionBehavior(QAbstractItemView.SelectRows); self.info_table.setSortingEnabled(True) # self.view.chartWidget.selInfoLayout.addWidget(self.selection_label) self.view.chartWidget.selInfoLayout.addWidget(self.info_table) # override on selection self.view.chartWidget._scene.selectionChanged.connect(self._selection_changed) vbox.addWidget(self.label) vbox.addWidget(wig) self.setLayout(vbox)
class MessageCountViewPluginGUI(dockarea.DockArea): def __init__(self, parent): dockarea.DockArea.__init__(self) self.builder = GBuilder() self._bin = {} self.widget_index = {} self.widget_text = {} self.send_plot_text = {} self.rec_plot_text = {} self.dock_index = {} self._ecu_ids = [] self._information_box_items = ["a"] self._info_widget_index = {} self._init_tag_list() self.known = [] self.create_widgets(parent) # def _already_there(self, mon_input): # ''' handles duplicates''' # if hash(mon_input) in self.known: # return True # self.known.append(hash(mon_input)) # if len(self.known) > 1000: # del self.known[:floor(float(len(self.known)) / 2.0)] # return False def create_widgets(self, parent): h_layout = QHBoxLayout() self.viewer_cbox = self.builder.checkable_combobox(parent, [], self._set_cb_changed) h_layout.addWidget(self.viewer_cbox) h_layout.addItem(QSpacerItem(10, 10)) # add ecu selection self.label_top = QtGui.QLabel() self.label_top.setText("Message View: green: received messages red: send message") self.viewDock = dockarea.Dock('view', size=(1000, 600)) self.layout.addWidget(self.label_top) self.label_top.setFixedHeight(20) self.layout.addLayout(h_layout) self.layout.addItem(QSpacerItem(10, 10)) def _add_items_ecu_ids(self, ecu_ids): items = [] for ecu_id in ecu_ids: try: items += [self.add_item(ecu_id)] except: pass if not items: return for i in items: i.setCheckState(QtCore.Qt.Unchecked) items[0].setCheckState(QtCore.Qt.Checked) self._set_cb_changed(None) def _set_cb_changed(self, e): # clear all try: for ky in self.dock_index: self.dock_index[ky].setParent(None) except: ECULogger().log_traceback() # get checked items checked_idx = [] for cnt in range(self.viewer_cbox.count()): item = self.viewer_cbox.model().item(cnt, 0) if item.checkState(): checked_idx.append(cnt) for ky in range(self.viewer_cbox.count()): # selected draw if ky in checked_idx: self.addDock(self.dock_index[ky], 'right') self.widget_index[ky].verticalScrollBar().setValue(self.widget_index[ky].verticalScrollBar().maximum()); def add_item(self, title_text): # add item to dock new_dock = dockarea.Dock(title_text, size=(1000, 20)) new_dock.setOrientation('horizontal') widget, send_plot = self._new_plot_widget(new_dock) new_dock.addWidget(widget) self.addDock(new_dock, 'right') # add item to combobox self.viewer_cbox.addItem(title_text) new_row = self.viewer_cbox.count() - 1 item = self.viewer_cbox.model().item(new_row, 0) item.setCheckState(QtCore.Qt.Checked) # link items self.widget_index[new_row] = widget self.widget_text[title_text] = widget self.send_plot_text[title_text] = send_plot self.dock_index[new_row] = new_dock return item def _new_plot_widget(self, parent): widget = pg.GraphicsLayoutWidget(parent) # self.axis = ECUShowAxis(orientation='left') send_plot = widget.addPlot() # axisItems={'left': self.axis}) send_plot.setLabel('left', 'Number of messages') send_plot.setLabel('bottom', 'Message ID') send_plot.showGrid(x=True, y=True) x = [] y = [] try: barGraphItem = pg.BarGraphItem(x=x, height=y, width=0.5) send_plot.addItem(barGraphItem) except: ECULogger().log_traceback() # send_plot.plot(x, y, stepMode=True, fillLevel=0, brush=(0, 0, 255, 150)) # rec_plot.plot(x, y, stepMode=True, fillLevel=0, brush=(255, 0, 0, 150)) return widget, barGraphItem def save(self): data = {} data["ecu ids"] = self._ecu_ids data["bin"] = self._bin return data def load(self, data): self._ecu_ids = data["ecu ids"] self._bin = data["bin"] self._add_items_ecu_ids(self._ecu_ids) self._plot_bin() def _init_tag_list(self): # NO TESLA TAGS HERE YET! self._sent_tags = [MonitorTags.CP_SEC_ECNRYPTED_CONFIRMATION_MESSAGE, MonitorTags.CP_SEC_INIT_AUTHENTICATION, MonitorTags.CP_SEC_ENCRYPTED_DENY_MESSAGE, MonitorTags.CP_SEC_ENCRYPTED_GRANT_MESSAGE, MonitorTags.CP_ECU_INTENT_SEND_SIMPLE_MESSAGE, MonitorTags.CP_ECU_SEND_REG_MESSAGE, MonitorTags.CP_ECU_ENCRYPTED_REQ_MESSAGE, MonitorTags.CP_SEND_CLIENT_HELLO, MonitorTags.CP_SEND_SERVER_HELLO, MonitorTags.CP_SEND_SERVER_CERTIFICATE, MonitorTags.CP_SEND_SERVER_KEYEXCHANGE, MonitorTags.CP_SEND_CERTIFICATE_REQUEST, MonitorTags.CP_SEND_SERVER_HELLO_DONE, MonitorTags.CP_SEND_CLIENT_CERTIFICATE, MonitorTags.CP_ENCRYPTED_CERTIFICATE_VERIFY, MonitorTags.CP_SEND_CIPHER_SPEC, MonitorTags.CP_GENERATED_HASH_FROM_PRF_CLIENT_FINISHED, MonitorTags.CP_SESSION_AVAILABLE_SEND_MESSAGE, MonitorTags.CP_SETUP_FINISHED_CREATE_KEYS, MonitorTags.CP_INIT_TRANSMIT_MESSAGE, MonitorTags.CP_SEND_SYNC_MESSAGE, MonitorTags.CP_SEND_SYNC_RESPONSE_MESSAGE, MonitorTags.CP_ENCRYPTED_EXCHANGE_FIRST_KEY_KN] self._received_tags = [MonitorTags.CP_SEC_RECEIVE_REG_MESSAGE, MonitorTags.CP_SEC_RECEIVE_REQ_MESSAGE, MonitorTags.CP_ECU_RECEIVE_SIMPLE_MESSAGE, MonitorTags.CP_ECU_RECEIVE_SEC_MOD_ADVERTISEMENT, MonitorTags.CP_ECU_RECEIVE_CONF_MESSAGE, MonitorTags.CP_ECU_RECEIVE_DENY_MESSAGE, MonitorTags.CP_ECU_RECEIVE_GRANT_MESSAGE, MonitorTags.CP_RECEIVE_CLIENT_HELLO, MonitorTags.CP_RECEIVE_SERVER_HELLO, MonitorTags.CP_RECEIVE_SERVER_CERTIFICATE, MonitorTags.CP_RECEIVE_SERVER_KEYEXCHANGE, MonitorTags.CP_RECEIVE_CERTIFICATE_REQUEST, MonitorTags.CP_RECEIVE_SERVER_HELLO_DONE, MonitorTags.CP_RECEIVE_CLIENT_CERTIFICATE, MonitorTags.CP_RECEIVE_CLIENT_KEYEXCHANGE, MonitorTags.CP_DECRYPTED_CERTIFICATE_VERIFY, MonitorTags.CP_RECEIVED_CHANGE_CIPHER_SPEC, MonitorTags.CP_RECEIVE_CLIENT_FINISHED, MonitorTags.CP_RECEIVE_SERVER_FINISHED, MonitorTags.CP_GENERATED_HASH_FROM_PRF_SERVER_FINISHED, MonitorTags.CP_RECEIVE_SIMPLE_MESSAGE, MonitorTags.CP_RECEIVED_SIMPLE_MESSAGE, MonitorTags.CP_RECEIVED_EXCHANGE_FIRST_KEY_KN, MonitorTags.CP_RECEIVE_SYNC_RESPONSE_MESSAGE, MonitorTags.CP_RECEIVE_SYNC_MESSAGE] @try_ex def update_gui(self, monitor_input_list): # receive the ecu ids: show only the once selected then try: if isinstance(monitor_input_list[0], str): return constellation = monitor_input_list[0].data ecu_groups = constellation[0] self._ecu_ids = [e.ecu_id for e in APICore()._ecu_list_from_groups(ecu_groups)] self._add_items_ecu_ids(self._ecu_ids) return except: pass try: monitor_input_list.sort(key=lambda x: x[0], reverse=False) except: pass # receive simple inputs for monitor_input in monitor_input_list: # if self._already_there(monitor_input): continue # read information ecu_id = monitor_input[1] tag = eval(monitor_input[3]) message_id = monitor_input[4] stream_id = message_id # monitor_input[7] if stream_id in [-1, 0]: continue if tag in self._sent_tags: add_tag = 'sender' elif tag in self._received_tags: add_tag = 'receiver' else: continue if not General().four_dict_exists(self._bin, ecu_id, stream_id, add_tag): General().add_to_four_dict(self._bin, ecu_id, stream_id, add_tag, 1) else: self._bin[ecu_id][stream_id][add_tag] += 1 # workaround tesla if tag == MonitorTags.CP_SEND_SYNC_RESPONSE_MESSAGE: if not General().four_dict_exists(self._bin, ecu_id, can_registration.CAN_TESLA_TIME_SYNC, "receiver"): General().add_to_four_dict(self._bin, ecu_id, can_registration.CAN_TESLA_TIME_SYNC, "receiver", 1) else: self._bin[ecu_id][can_registration.CAN_TESLA_TIME_SYNC]["receiver"] += 1 # show updated self._plot_bin() def _plot_bin(self): # collect information for ecu_id in self._bin.keys(): x_values_send = [] y_values_send = [] color = [] for stream_id in self._bin[ecu_id].keys(): if stream_id == -1: continue # sender or receiver color? add_tag = list(self._bin[ecu_id][stream_id].keys())[0] x_values_send += [stream_id] y_values_send += [self._bin[ecu_id][stream_id][add_tag]] if add_tag == 'sender': color += [QColor(255, 0, 0)] elif add_tag == 'receiver': color += [QColor(0, 255, 0)] else: continue try: # send self.send_plot_text[ecu_id].setOpts(x=x_values_send, height=y_values_send, width=0.5, brushes=color) except KeyError: pass except: ECULogger().log_traceback()
def create_widgets(self, parent): # Layout GBuilder().set_props(self, min_sz_x=900, min_sz_y=700) self.setWindowTitle("Simulation Configuration") self.setFixedHeight(700) self.setFixedWidth(1350) main_lo = QVBoxLayout() self.setLayout(main_lo) # Label self.desc_label = GBuilder().label(self, "Create a new simulation. Create one or more environments and"\ " fill them with components. Then connect the components.", None, None) self.desc_label.setFixedHeight(20) main_lo.addWidget(self.desc_label) # Horizontal Layout hl_1 = QHBoxLayout() main_lo.addLayout(hl_1) # Groupboxes self.components_gb = GBuilder().hand_groupbox(self, "Components", None, None) self.components_gb.setFixedWidth(300) self.environment_gb = GBuilder().groupbox(self, "Environments", None, None) hl_1.addWidget(self.components_gb) hl_1.addWidget(self.environment_gb) # Components Boxes self.comps_layout = QVBoxLayout() self.components_gb.setLayout(self.comps_layout) self._add_component_boxes() # Buttons main_lo.addWidget(GBuilder().hor_line(self)) hl = QHBoxLayout() hl.addWidget(GBuilder().label(self, "")) ok_but = GBuilder().pushbutton(self, "OK", self._ok_hit) ok_but.setFixedWidth(150) ok_but.setFixedHeight(25) cancel_but = GBuilder().pushbutton(self, "Cancel", self._ok_hit) cancel_but.setFixedWidth(150) cancel_but.setFixedHeight(25) hl.addWidget(ok_but) hl.addWidget(cancel_but) main_lo.addLayout(hl) # Fill Components Boxes self._fill_ecu_boxes() self._fill_bus_boxes() self._fill_others_boxes() # Fill environment self._fill_environment_box() # Style self._set_stle()
def _fill_bus_boxes(self): kys = BusFactory().createable_objects() row = 0 col = 0 for ky in list(kys): # Information gathering name = self._load_gui_name(ky, BusFactory()) ico = self._load_gui_icon(ky, BusFactory()) # New Element per Object gb = GBuilder().groupbox(self, name, None, None) gb.setFont(QtGui.QFont('SansSerif', 7)) gb.setFixedHeight(70) gb.setFixedWidth(70) db = GBuilder().dragbutton(gb, '', self._add_component_boxes, ico, icon_x=45, icon_y=45, size_x=60, size_y=50, pos_x=5, pos_y=15) db.set_drop_func(self.core.add_bus_box_to_env) db.set_move_icon_context_acts(self.core.load_context_menu_actions(ky)) db.ecu_key = ky db.setCheckable(True) db.setStyleSheet('QPushButton {background-color: #F2F2F2; color: red;border: 0px solid gray;border-radius: 12px;}') # Add to Layout self.bus_box.addWidget(gb, row, col, Qt.AlignTop) col += 1 if col == 3: row += 1 col = 0 # Add Widget self.bus_box.addWidget(QWidget())
class ConstellationViewPluginGUI(QWidget): def __init__(self, parent): QWidget.__init__(self, parent) self._radius = 350 self._gw_distance = 2 * self._radius self._bus_distance = 4 * self._radius self._last_bus_pos = [0, 0] self._last_bus_steps = [0, 0] self._bus_node = {} self._bus_position = {} self._ecu_terminals = {} self._ecu_position = {} self._ecu_node = {} self._show_dict = {} self.lastClicked = [] self._all_points = [] self.create_widgets(parent) self.map_points = {} self.COLOR_ECU_AUTH = (255, 0, 0) self.COLOR_STR_AUTH = (0, 255, 0) self.COLOR_SIMPLE = (0, 0, 255) self.COLOR_PROCESS = (123, 123, 0) self.COLOR_PROCESS_2 = (0, 123, 123) self._init_categories() self._mode = 'LW_AUTH' self._pts_ecu = {} def _clicked(self, plot, points): for p in self.lastClicked: p.resetPen() try: info = points[0].data() except: info = False if info: try: info[5] except: info += [0, 0, 0, 0, 0] if len(str(info[2])) > 100: showos = info[2][:99] else: showos = info[2] self.label.setText("ECU: %s\t\t Time:%s \t\nMessageID: %s \tMessage: %s \t\nSize: %s \t\t\tCorresponding ID: %s \tStream ID: %s" % (info[0], info[-1], self._id_to_str(info[1]), showos, info[3], info[6], info[5])) for p in points: p.setPen('b', width=2) self.lastClicked = points def _init_categories(self): # TESLA self.tesla_time_sync_send = [MonitorTags.CP_SEND_SYNC_MESSAGE, MonitorTags.CP_SEND_SYNC_RESPONSE_MESSAGE] self.tesla_time_sync_rec = [MonitorTags.CP_RECEIVE_SYNC_RESPONSE_MESSAGE] self.tesla_setup_send = [MonitorTags.CP_ENCRYPTED_EXCHANGE_FIRST_KEY_KN] self.tesla_setup_rec = [MonitorTags.CP_RECEIVED_EXCHANGE_FIRST_KEY_KN] self.tesla_simple_message_send = [MonitorTags.CP_MACED_TRANSMIT_MESSAGE] self.tesla_simple_message_rec = [MonitorTags.CP_BUFFERED_SIMPLE_MESSAGE] self.tesla_message_authenticated = [MonitorTags.CP_RETURNED_AUTHENTICATED_SIMPLE_MESSAGE] self.tesla = self.tesla_time_sync_send + self.tesla_time_sync_rec + self.tesla_setup_send + self.tesla_setup_rec + self.tesla_simple_message_send + self.tesla_simple_message_rec + self.tesla_message_authenticated # TLS self.hand_shake_tag_server_send = [MonitorTags.CP_SEND_SERVER_HELLO, MonitorTags.CP_SEND_SERVER_CERTIFICATE, MonitorTags.CP_SEND_SERVER_KEYEXCHANGE, MonitorTags.CP_SEND_CERTIFICATE_REQUEST, MonitorTags.CP_SEND_SERVER_HELLO_DONE, \ MonitorTags.CP_CLIENT_FINISHED_GENERATED_HASH_PRF] self.hand_shake_tag_server_rec = [MonitorTags.CP_RECEIVE_CLIENT_CERTIFICATE, MonitorTags.CP_RECEIVE_CLIENT_KEYEXCHANGE, MonitorTags.CP_RECEIVE_CERTIFICATE_VERIFY, MonitorTags.CP_RECEIVED_CHANGE_CIPHER_SPEC, \ MonitorTags.CP_RECEIVE_CLIENT_FINISHED] self.hand_shake_tag_server_process = [MonitorTags.CP_CLIENT_CERTIFICATE_VALIDATED, MonitorTags.CP_DECRYPTED_CLIENT_KEYEXCHANGE, MonitorTags.CP_DECRYPTED_CERTIFICATE_VERIFY , MonitorTags.CP_GENERATED_MASTER_SECRET_CERT_VERIFY, \ MonitorTags.CP_CLIENT_FINISHED_HASHED_COMPARISON_HASH , MonitorTags.CP_CLIENT_AUTHENTICATED] self.hand_shake_tag_client_send = [MonitorTags.CP_SEND_CLIENT_HELLO, MonitorTags.CP_SEND_CLIENT_CERTIFICATE , MonitorTags.CP_INIT_SEND_CLIENT_KEYEXCHANGE , \ MonitorTags.CP_SEND_CIPHER_SPEC , MonitorTags.CP_GENERATED_HASH_FROM_PRF_CLIENT_FINISHED, MonitorTags.CP_GENERATED_HASH_FROM_PRF_SERVER_FINISHED] self.hand_shake_tag_client_rec = [MonitorTags.CP_RECEIVE_CLIENT_HELLO, MonitorTags.CP_RECEIVE_SERVER_HELLO, MonitorTags.CP_RECEIVE_SERVER_CERTIFICATE , MonitorTags.CP_RECEIVE_SERVER_KEYEXCHANGE, \ MonitorTags.CP_RECEIVE_CERTIFICATE_REQUEST, MonitorTags.CP_RECEIVE_SERVER_HELLO_DONE, MonitorTags.CP_RECEIVE_SERVER_FINISHED ] self.hand_shake_tag_client_process = [MonitorTags.CP_SERVER_HELLO_DONE_VALIDATED_CERT, MonitorTags.CP_ENCRYPTED_CLIENT_KEYEXCHANGE , MonitorTags.CP_GENERATED_MASTERSEC_CLIENT_KEYEXCHANGE , MonitorTags.CP_INIT_SEND_CERTIFICATE_VERIFY, \ MonitorTags.CP_ENCRYPTED_CERTIFICATE_VERIFY, MonitorTags.CP_INIT_CLIENT_FINISHED , MonitorTags.CP_HASHED_CLIENT_FINISHED, MonitorTags.CP_SERVER_FINISHED_HASHED_COMPARISON_HASH , \ MonitorTags.CP_SERVER_FINISHED_GENERATED_HASH_PRF, MonitorTags.CP_INIT_SERVER_FINISHED , MonitorTags.CP_HASHED_SERVER_FINISHED, MonitorTags.CP_SERVER_AUTHENTICATED ] self.simple_tags_send = [MonitorTags.CP_SESSION_AVAILABLE_SEND_MESSAGE] self.simple_tags_rec = [ MonitorTags.CP_RECEIVE_SIMPLE_MESSAGE ] self.tls = self.hand_shake_tag_server_send + self.hand_shake_tag_server_rec + self.hand_shake_tag_server_process + self.hand_shake_tag_client_send + self.hand_shake_tag_client_rec + self.hand_shake_tag_client_process \ + self.simple_tags_send + self.simple_tags_rec # authentication self.sec_mod_tags = [MonitorTags.CP_SEC_INIT_AUTHENTICATION, MonitorTags.CP_SEC_ECNRYPTED_CONFIRMATION_MESSAGE, MonitorTags.CP_SEC_COMPARED_HASH_REG_MSG, \ MonitorTags.CP_SEC_ENCRYPTED_DENY_MESSAGE, MonitorTags.CP_SEC_ENCRYPTED_GRANT_MESSAGE, MonitorTags.CP_SEC_DECRYPTED_REQ_MESSAGE, MonitorTags.CP_SEC_RECEIVE_REG_MESSAGE] self.authent_tags_send = [MonitorTags.CP_SEC_INIT_AUTHENTICATION, MonitorTags.CP_SEC_ECNRYPTED_CONFIRMATION_MESSAGE, MonitorTags.CP_ECU_SEND_REG_MESSAGE] self.authent_tags_receive = [MonitorTags.CP_SEC_COMPARED_HASH_REG_MSG, MonitorTags.CP_ECU_VALIDATED_SEC_MOD_CERTIFICATE, MonitorTags.CP_ECU_DECRYPTED_CONF_MESSAGE] self.author_tags_send = [MonitorTags.CP_SEC_ENCRYPTED_DENY_MESSAGE, MonitorTags.CP_SEC_ENCRYPTED_GRANT_MESSAGE, MonitorTags.CP_ECU_ENCRYPTED_REQ_MESSAGE] self.author_tags_receive = [MonitorTags.CP_ECU_DECRYPTED_DENY_MESSAGE, MonitorTags.CP_ECU_DECRYPTED_GRANT_MESSAGE, MonitorTags.CP_SEC_DECRYPTED_REQ_MESSAGE] self.simp_tags_send = [MonitorTags.CP_ECU_ENCRYPTED_SEND_SIMPLE_MESSAGE] self.simp_tags_receive = [MonitorTags.CP_ECU_DECRYPTED_SIMPLE_MESSAGE] self.lw_auth = self.sec_mod_tags + self.authent_tags_send + self.authent_tags_receive + self.author_tags_send + self.author_tags_receive + self.simp_tags_send + self.simp_tags_receive def create_widgets(self, parent): vbox = QtGui.QVBoxLayout() self.label = QtGui.QLabel() self.label.setText("Constellation") self.label.setFixedHeight(20) self.fc = Flowchart(terminals={'Connection': {'io': 'in'}}) self.fc._nodes['Input'].close() self.fc._nodes['Output'].close() self.view = self.fc.widget() wig = self.view.chartWidget self.view.chartWidget.hoverDock.hide() self.view.chartWidget.selectedTree.hide() self.view.chartWidget.selDock.label.setText("Selected Comp.") # add selection label self.selection_label = self.view.chartWidget.selDescLabel self.selection_label.setText("") self.selection_label.setFixedHeight(15) # add information table self.info_table = GBuilder().table(self.view.chartWidget.selDock, 1, 2, ["Settings", "Value"]) for r in range(self.info_table.rowCount()): self.info_table.setRowHeight(r, 20) self.info_table.horizontalHeader().hide() self.info_table.verticalHeader().hide() self.info_table.setSelectionBehavior(QAbstractItemView.SelectRows); self.info_table.setSortingEnabled(True) # self.view.chartWidget.selInfoLayout.addWidget(self.selection_label) self.view.chartWidget.selInfoLayout.addWidget(self.info_table) # override on selection self.view.chartWidget._scene.selectionChanged.connect(self._selection_changed) vbox.addWidget(self.label) vbox.addWidget(wig) self.setLayout(vbox) def save(self): data = {} bus_ecu_connections = self.bus_ecu_connections # pur so uebernehmen bus_data = self._get_save_bus() ecu_data = self._get_save_ecu() data['bus_data'] = bus_data data['ecu_data'] = ecu_data data['ecu_positions'] = self._ecu_position data['bus_positions'] = self._bus_position data['bus_ecu_connections'] = bus_ecu_connections print("SSVR I") return data def load(self, data): self._ecu_position = data['ecu_positions'] self._bus_position = data['bus_positions'] bus_data = data['bus_data'] ecu_data = data['ecu_data'] bus_ecu_connections = data['bus_ecu_connections'] # add busses self._add_buses_load(bus_data) # add ecus self._add_ecus_load(ecu_data, bus_ecu_connections) def update_gui(self, monitor_input_list): ''' this method is called exactly once and should show all information ''' # extract information try: constellation = monitor_input_list[0].data except: return ecu_groups = constellation[0] bus_groups = constellation[1] bus_ecu_connections = constellation[2] self.bus_ecu_connections = bus_ecu_connections # set cans self._add_buses(bus_groups) # add ecus self._add_ecus(ecu_groups, bus_ecu_connections) def _selection_changed(self): items = self.view.chartWidget._scene.selectedItems() if len(items) == 0: data = None else: item = items[0] if hasattr(item, 'node') and isinstance(item.node, Node): print(item.node) print("SELECTED %s" % item.node.settings_dict) self._show_node_information(item.node) else: data = None # self.selectedTree.setData(data, hideRoot=True) def _show_node_information(self, node): # hide all rows for r in range(self.info_table.rowCount()): self.info_table.setRowHidden(r, True) # add new information save dict[ecu_id][settings_id] = row_nr comp_id = node.settings_dict['comp_id'] self.selection_label.setText("Selected ECU: %s" % comp_id) for set_key in node.settings_dict.keys(): # if already exists -> show its row and skip try: row_nr = self._show_dict[comp_id][set_key] self.info_table.setRowHidden(row_nr, False) continue except: pass # else add it to table and show row self.info_table.setRowCount(self.info_table.rowCount() + 1) row_nr = self.info_table.rowCount() item_1 = QTableWidgetItem() item_1.setData(QtCore.Qt.EditRole, set_key) item_2 = QTableWidgetItem() item_2.setText(str(node.settings_dict[set_key])); General().add_to_three_dict(self._show_dict, comp_id, set_key, row_nr) self.info_table.setItem(row_nr - 1, 0, item_1) self.info_table.setItem(row_nr - 1, 1, item_2) self.info_table.setRowHeight(row_nr - 1, 20) def _get_save_bus(self): buses = [] for bus_id in self._bus_node: node = self._bus_node[bus_id] settings = node.get_string_settings() buses.append([bus_id, settings]) return buses def _add_buses_load(self, bus_data): nr_buses = len(bus_data) for b_group in bus_data: bus_id = b_group[0] bus_settings = b_group[1] # place the busses [x, y] = self._bus_position[bus_id] node = InformationNode(bus_id) node.settings_dict = bus_settings self._bus_node[bus_id] = node self.fc.addNode(node, bus_id, [x, y]) self._bus_position[bus_id] = [x, y] def _add_buses(self, bus_groups): first = True nr_buses = len(bus_groups) for b_group in bus_groups: bus = b_group[0] # place the busses if not first: [x, y] = self._next_bus_pos(nr_buses) else: [x, y] = [0, 0] first = False node = InformationNode(bus.comp_id) node.set_settings(bus) self._bus_node[bus.comp_id] = node self.fc.addNode(node, bus.comp_id, [x, y]) self._bus_position[bus.comp_id] = [x, y] def _get_save_ecu(self): ecus = [] for ecu_id in self._ecu_node: node = self._ecu_node[ecu_id] settings = node.get_string_settings() ecus.append([ecu_id, settings]) return ecus def _add_ecus_load(self, ecu_data, bus_ecu_connections): ''' add all ecus to the respective buses ''' ecu_dict = self._can_ecu_list_dictionary(bus_ecu_connections) for bus_id in ecu_dict: idx = 0 ecu_list = ecu_dict[bus_id] for ecu_id in ecu_list: if isinstance(ecu_id, UUID): ecu_id = "GW\n%s" % str(ecu_id.hex) ecu_dat = self._ecu_dat_from_id(ecu_id, ecu_data) ecu_id = ecu_dat[0] ecu_settings = ecu_dat[1] [x, y] = self._ecu_position[ecu_id] ecu_id_show = ecu_id # shorten name if to long if len(ecu_id) >= 13: ecu_id_show = ecu_id[:13] # calculate positions idx += 1 try: # if this already exists gets a second connection ecu_terminal = False if ecu_id in self._ecu_node.keys(): ecu_terminal = self._ecu_node[ecu_id].addInput('C%s' % idx) # create new node if not ecu_terminal: node = InformationNode(ecu_id_show) # set information node.settings_dict = ecu_settings self.fc.addNode(node, ecu_id_show, [x, y]) self._ecu_position[ecu_id] = [x, y] self._ecu_node[ecu_id] = node ecu_terminal = node.addInput('C%s' % idx) bus_terminal = self._bus_node[bus_id].addInput('C%s' % idx) except: traceback.print_exc() # connector to bus try: self.fc.connectTerminals(bus_terminal, ecu_terminal) except: pass def _add_ecus(self, ecu_groups, bus_ecu_connections): ''' add all ecus to the respective buses ''' ecu_dict = self._can_ecu_list_dictionary(bus_ecu_connections) for bus_id in ecu_dict: ecu_list = ecu_dict[bus_id] nr_ecus = len(ecu_list) pos_bus = self._bus_position[bus_id] idx = 0 if bus_id == "CAN0": a = 0 for ecu_id in ecu_list: ecu_id_show = ecu_id ecu = self._ecu_from_group(ecu_groups, ecu_id) [x, y] = self._next_ecu_pos(pos_bus, nr_ecus, idx) if isinstance(ecu_id, UUID): ecu_id = "GW\n%s" % ecu_id.hex [x, y] = self._get_gw_position(ecu) # shorten name if to long if len(ecu_id) >= 13: ecu_id_show = ecu_id[:13] # calculate positions idx += 1 try: # if this already exists gets a second connection ecu_terminal = False if ecu_id in self._ecu_node.keys(): ecu_terminal = self._ecu_node[ecu_id].addInput('C%s' % idx) # create new node if not ecu_terminal: node = InformationNode(ecu_id_show) # set information node.set_settings(ecu) self.fc.addNode(node, ecu_id_show, [x, y]) self._ecu_position[ecu_id] = [x, y] self._ecu_node[ecu_id] = node ecu_terminal = node.addInput('C%s' % idx) bus_terminal = self._bus_node[bus_id].addInput('C%s' % idx) except: traceback.print_exc() # connector to bus try: self.fc.connectTerminals(bus_terminal, ecu_terminal) except: pass def _ecu_dat_from_id(self, ecu_id, ecu_data): for ecu_dat in ecu_data: if ecu_dat[0] == ecu_id: return ecu_dat return None def _ecu_from_group(self, ecu_groups, ecu_id): for ecu_lists in ecu_groups: ecu_list = ecu_lists[0] ecu_spec = ecu_lists[1] for ecu in ecu_list: if ecu.ecu_id == ecu_id: return ecu return None def _get_gw_position(self, gateway): x_points = [] y_points = [] for bus in gateway.connected_bus: x_points.append(self._bus_position[bus.comp_id][0]) y_points.append(self._bus_position[bus.comp_id][1]) x = float(sum(x_points)) / float(len(x_points)) y = float(sum(y_points)) / float(len(y_points)) for bus in gateway.connected_bus: if self._bus_position[bus.comp_id][0] == x and self._bus_position[bus.comp_id][1] == y: y += self._gw_distance return [x, y] def _can_ecu_list_dictionary(self, bus_ecu_connections): ''' creates a dictinary of form key: bus id and value list of ecu ids connected to the bus Input: bus_ecu_connections list Output: ecu_dict dictionary ''' out_dict = {} for connection in bus_ecu_connections: General().force_add_dict_list(out_dict, connection[0], connection[1]) return out_dict def _next_ecu_pos(self, pos_bus, nr_ecus, idx): ''' determines the next position of the ecu''' alpha = (360 / nr_ecus) * 1.00000001 angle = idx * alpha # radius varies with the number of ECUs connected (less means closer) radius = (math.sqrt(2) * 190) / (2 * math.sin(2 * math.pi * (alpha / 360))) angle /= 360 angle *= 2 * math.pi x = radius * math.cos(angle) + pos_bus[0] y = radius * math.sin(angle) + pos_bus[1] return [x, y] def _next_bus_pos(self, nr_buses): ''' determines the next position of the bus''' if nr_buses < 5: [x, y] = self._last_bus_pos [lr, ud] = self._last_bus_steps x += self._bus_distance self._last_bus_pos[0] = x return [x, y] [x, y] = self._last_bus_pos [lr, ud] = self._last_bus_steps step = round(sqrt(nr_buses / 3)) y += self._bus_distance if ud == step: y = 0 ud = 0 x += self._bus_distance self._last_bus_steps = [lr + 1, 0] lr += 1 ud += 1 self._last_bus_steps = [lr, ud] self._last_bus_pos = [x, y] return [x, y] def _is_sec_mod(self, ecu): try: ecu._SECMODULE return True except: pass return False
class NewSimulationWindow(QDialog): def __init__(self, parent): QDialog.__init__(self, parent) self.core = NewSimulationCore(self) self.create_widgets(parent) self.environments = [] self.env_wid = {} # Environment Name to Environment Widget self.env_obj = {} # Environment Name to Environment Objects self.exec() def create_widgets(self, parent): # Layout GBuilder().set_props(self, min_sz_x=900, min_sz_y=700) self.setWindowTitle("Simulation Configuration") self.setFixedHeight(700) self.setFixedWidth(1350) main_lo = QVBoxLayout() self.setLayout(main_lo) # Label self.desc_label = GBuilder().label(self, "Create a new simulation. Create one or more environments and"\ " fill them with components. Then connect the components.", None, None) self.desc_label.setFixedHeight(20) main_lo.addWidget(self.desc_label) # Horizontal Layout hl_1 = QHBoxLayout() main_lo.addLayout(hl_1) # Groupboxes self.components_gb = GBuilder().hand_groupbox(self, "Components", None, None) self.components_gb.setFixedWidth(300) self.environment_gb = GBuilder().groupbox(self, "Environments", None, None) hl_1.addWidget(self.components_gb) hl_1.addWidget(self.environment_gb) # Components Boxes self.comps_layout = QVBoxLayout() self.components_gb.setLayout(self.comps_layout) self._add_component_boxes() # Buttons main_lo.addWidget(GBuilder().hor_line(self)) hl = QHBoxLayout() hl.addWidget(GBuilder().label(self, "")) ok_but = GBuilder().pushbutton(self, "OK", self._ok_hit) ok_but.setFixedWidth(150) ok_but.setFixedHeight(25) cancel_but = GBuilder().pushbutton(self, "Cancel", self._ok_hit) cancel_but.setFixedWidth(150) cancel_but.setFixedHeight(25) hl.addWidget(ok_but) hl.addWidget(cancel_but) main_lo.addLayout(hl) # Fill Components Boxes self._fill_ecu_boxes() self._fill_bus_boxes() self._fill_others_boxes() # Fill environment self._fill_environment_box() # Style self._set_stle() def _add_component_boxes(self): # ECU Box self.ecu_box_wid = QScrollArea() wid = QWidget() self.ecu_box_wid.setWidget(wid) self.ecu_box_wid.setWidgetResizable(True) self.ecu_box = QGridLayout() wid.setLayout(self.ecu_box) self.ecu_box_wid_wid = wid self.comps_layout.addWidget(self.ecu_box_wid) # Bus Box self.bus_box_wid = QScrollArea() wid = QWidget() self.bus_box_wid.setWidget(wid) self.bus_box_wid.setWidgetResizable(True) self.bus_box = QGridLayout() wid.setLayout(self.bus_box) self.bus_box_wid_wid = wid self.comps_layout.addWidget(self.bus_box_wid) # Others Box self.others_box_wid = QScrollArea() wid = QWidget() self.others_box_wid.setWidget(wid) self.others_box_wid.setWidgetResizable(True) self.others_box = QGridLayout() wid.setLayout(self.others_box) self.others_box_wid_wid = wid self.comps_layout.addWidget(self.others_box_wid) def _fill_ecu_boxes(self): # Creatable Objects kys = ECUFactory().createable_objects() row = 0 col = 0 for ky in list(kys): # Information gathering name = self._load_gui_name(ky, ECUFactory()) ico = self._load_gui_icon(ky, ECUFactory()) # New Element per Object gb = GBuilder().groupbox(self, name, None, None) gb.setFont(QtGui.QFont('SansSerif', 7)) gb.setFixedHeight(70) gb.setFixedWidth(70) db = GBuilder().dragbutton(gb, '', self._add_component_boxes, ico, icon_x=45, icon_y=45, size_x=60, size_y=50, pos_x=5, pos_y=15) db.set_drop_func(self.core.add_ecu_box_to_env) db.set_move_icon_context_acts(self.core.load_context_menu_actions(ky)) db.ecu_key = ky db.setCheckable(True) db.setStyleSheet('QPushButton {background-color: #F2F2F2; color: red;border: 0px solid gray;border-radius: 12px;}') # Add to Layout self.ecu_box.addWidget(gb, row, col, Qt.AlignTop) col += 1 if col == 3: row += 1 col = 0 # Add Widget self.ecu_box.addWidget(QWidget()) def _fill_bus_boxes(self): kys = BusFactory().createable_objects() row = 0 col = 0 for ky in list(kys): # Information gathering name = self._load_gui_name(ky, BusFactory()) ico = self._load_gui_icon(ky, BusFactory()) # New Element per Object gb = GBuilder().groupbox(self, name, None, None) gb.setFont(QtGui.QFont('SansSerif', 7)) gb.setFixedHeight(70) gb.setFixedWidth(70) db = GBuilder().dragbutton(gb, '', self._add_component_boxes, ico, icon_x=45, icon_y=45, size_x=60, size_y=50, pos_x=5, pos_y=15) db.set_drop_func(self.core.add_bus_box_to_env) db.set_move_icon_context_acts(self.core.load_context_menu_actions(ky)) db.ecu_key = ky db.setCheckable(True) db.setStyleSheet('QPushButton {background-color: #F2F2F2; color: red;border: 0px solid gray;border-radius: 12px;}') # Add to Layout self.bus_box.addWidget(gb, row, col, Qt.AlignTop) col += 1 if col == 3: row += 1 col = 0 # Add Widget self.bus_box.addWidget(QWidget()) def _fill_others_boxes(self): kys = ECUFactory().createable_objects() row = 0 col = 0 def _fill_environment_box(self): # Main Layout main_lo = QVBoxLayout() self.environment_gb.setLayout(main_lo) # Combobox lo, self.env_select_cb, lab = GBuilder().label_combobox(self, "Current Environment:", [], self._env_select_changed) hl = QHBoxLayout() hl.addLayout(lo) but = GBuilder().pushbutton(self, "New", self._new_env_hit) but.setFixedWidth(40) hl.addWidget(but) lab.setFixedWidth(140) self.env_select_cb.setFixedHeight(22) self.env_select_cb.setFixedWidth(350) main_lo.addLayout(hl) # Groupbox (to make it look nicer) self.content_gb = EnvironmentView(self.environment_gb) main_lo.addWidget(self.content_gb) self.content_gb.setFixedHeight(550) self.content_gb.setFixedWidth(1000) self.content_gb.setLayout(lo) # QStackedWidget with environments self.stacked_env = QStackedWidget() lo.addWidget(self.stacked_env) def _set_stle(self): self.content_gb.setStyleSheet('QGroupBox {background-color: #F2F2F2; color: red; border: 2px solid gray;border-radius: 12px;} EnvironmentView {background-color: #F2F2F2; color: red; border: 2px solid gray;border-radius: 12px;}') self.ecu_box_wid_wid.setStyleSheet('QWidget { border: 0.5px solid gray;border-radius: 3px;}') self.ecu_box_wid.setStyleSheet('QWidget { border: 0.5px solid gray;border-radius: 3px;}') self.bus_box_wid_wid.setStyleSheet('QWidget { border: 0.5px solid gray;border-radius: 3px;}') self.bus_box_wid.setStyleSheet('QWidget { border: 0.5px solid gray;border-radius: 3px;}') self.others_box_wid_wid.setStyleSheet('QWidget { border: 0.5px solid gray;border-radius: 3px;}') self.others_box_wid.setStyleSheet('QWidget { border: 0.5px solid gray;border-radius: 3px;}') def _ok_hit(self): # 1. Create environments using defined processing methods environments_list = NewSimulationCore().run_processes() # 2. Save environments via API / Load them via API as well self.close() def _cancel_hit(self): print("Cancel") self.close() def _new_env_hit(self): # Add to list nr = len(self.environments) self.environments.append("Environment %s" % nr) self.env_select_cb.addItem(self.environments[-1]) self.env_select_cb.setCurrentIndex(nr) # Create new Stacked widget entry wid = QWidget() self.stacked_env.addWidget(wid) self.env_wid["Environment %s" % nr] = wid lo = QVBoxLayout() wid.setLayout(lo) self.stacked_env.setCurrentIndex(nr) def _env_select_changed(self): idx = self.env_select_cb.currentIndex() self.stacked_env.setCurrentIndex(idx) NewSimulationCore().selected_env = self.env_select_cb.currentText() self.content_gb.selected_env = self.env_select_cb.currentText() self._show_env(NewSimulationCore().selected_env, NewSimulationCore().env_map) def _get_env_elem_by_icon(self, env_elems, move_icon): for elem in env_elems: if str(elem.move_icon) == str(move_icon): return elem return None def _load_gui_name(self, ky, factory): try: cls = factory.get_class(ky) name = cls.GUI_NAME except: name = ky return name def _load_gui_icon(self, ky, factory): try: cls = factory.get_class(ky) name = cls.GUI_ICON except: name = os.getcwd() + r'/icons/standard_ecu.png' return name def _show_env(self, selected_env, env_map): GBuilder().update_connected(self.content_gb, self.environment_gb.pos(), self.content_gb.pos(), self.content_gb.selected_env) # Mainwindow for chil in self.children(): if isinstance(chil, DragLabel): try: a = self._get_env_elem_by_icon(env_map[selected_env], chil) if a == None: chil.hide() else: chil.show() except: chil.hide()
class ConstellationViewPluginGUI(QWidget): def __init__(self, parent): QWidget.__init__(self, parent) self._radius = 350 self._gw_distance = 2 * self._radius self._bus_distance = 4 * self._radius self._last_bus_pos = [0, 0] self._last_bus_steps = [0, 0] self._bus_node = {} self._bus_position = {} self._ecu_terminals = {} self._ecu_position = {} self._ecu_node = {} self._show_dict = {} self.lastClicked = [] self._all_points = [] self.create_widgets(parent) self.map_points = {} self.COLOR_ECU_AUTH = (255, 0, 0) self.COLOR_STR_AUTH = (0, 255, 0) self.COLOR_SIMPLE = (0, 0, 255) self.COLOR_PROCESS = (123, 123, 0) self.COLOR_PROCESS_2 = (0, 123, 123) self._init_categories() self._mode = 'LW_AUTH' self._pts_ecu = {} def _clicked(self, plot, points): for p in self.lastClicked: p.resetPen() try: info = points[0].data() except: info = False if info: try: info[5] except: info += [0, 0, 0, 0, 0] if len(str(info[2])) > 100: showos = info[2][:99] else: showos = info[2] self.label.setText( "ECU: %s\t\t Time:%s \t\nMessageID: %s \tMessage: %s \t\nSize: %s \t\t\tCorresponding ID: %s \tStream ID: %s" % (info[0], info[-1], self._id_to_str( info[1]), showos, info[3], info[6], info[5])) for p in points: p.setPen('b', width=2) self.lastClicked = points def _init_categories(self): # TESLA self.tesla_time_sync_send = [ MonitorTags.CP_SEND_SYNC_MESSAGE, MonitorTags.CP_SEND_SYNC_RESPONSE_MESSAGE ] self.tesla_time_sync_rec = [ MonitorTags.CP_RECEIVE_SYNC_RESPONSE_MESSAGE ] self.tesla_setup_send = [ MonitorTags.CP_ENCRYPTED_EXCHANGE_FIRST_KEY_KN ] self.tesla_setup_rec = [MonitorTags.CP_RECEIVED_EXCHANGE_FIRST_KEY_KN] self.tesla_simple_message_send = [ MonitorTags.CP_MACED_TRANSMIT_MESSAGE ] self.tesla_simple_message_rec = [ MonitorTags.CP_BUFFERED_SIMPLE_MESSAGE ] self.tesla_message_authenticated = [ MonitorTags.CP_RETURNED_AUTHENTICATED_SIMPLE_MESSAGE ] self.tesla = self.tesla_time_sync_send + self.tesla_time_sync_rec + self.tesla_setup_send + self.tesla_setup_rec + self.tesla_simple_message_send + self.tesla_simple_message_rec + self.tesla_message_authenticated # TLS self.hand_shake_tag_server_send = [MonitorTags.CP_SEND_SERVER_HELLO, MonitorTags.CP_SEND_SERVER_CERTIFICATE, MonitorTags.CP_SEND_SERVER_KEYEXCHANGE, MonitorTags.CP_SEND_CERTIFICATE_REQUEST, MonitorTags.CP_SEND_SERVER_HELLO_DONE, \ MonitorTags.CP_CLIENT_FINISHED_GENERATED_HASH_PRF] self.hand_shake_tag_server_rec = [MonitorTags.CP_RECEIVE_CLIENT_CERTIFICATE, MonitorTags.CP_RECEIVE_CLIENT_KEYEXCHANGE, MonitorTags.CP_RECEIVE_CERTIFICATE_VERIFY, MonitorTags.CP_RECEIVED_CHANGE_CIPHER_SPEC, \ MonitorTags.CP_RECEIVE_CLIENT_FINISHED] self.hand_shake_tag_server_process = [MonitorTags.CP_CLIENT_CERTIFICATE_VALIDATED, MonitorTags.CP_DECRYPTED_CLIENT_KEYEXCHANGE, MonitorTags.CP_DECRYPTED_CERTIFICATE_VERIFY , MonitorTags.CP_GENERATED_MASTER_SECRET_CERT_VERIFY, \ MonitorTags.CP_CLIENT_FINISHED_HASHED_COMPARISON_HASH , MonitorTags.CP_CLIENT_AUTHENTICATED] self.hand_shake_tag_client_send = [MonitorTags.CP_SEND_CLIENT_HELLO, MonitorTags.CP_SEND_CLIENT_CERTIFICATE , MonitorTags.CP_INIT_SEND_CLIENT_KEYEXCHANGE , \ MonitorTags.CP_SEND_CIPHER_SPEC , MonitorTags.CP_GENERATED_HASH_FROM_PRF_CLIENT_FINISHED, MonitorTags.CP_GENERATED_HASH_FROM_PRF_SERVER_FINISHED] self.hand_shake_tag_client_rec = [MonitorTags.CP_RECEIVE_CLIENT_HELLO, MonitorTags.CP_RECEIVE_SERVER_HELLO, MonitorTags.CP_RECEIVE_SERVER_CERTIFICATE , MonitorTags.CP_RECEIVE_SERVER_KEYEXCHANGE, \ MonitorTags.CP_RECEIVE_CERTIFICATE_REQUEST, MonitorTags.CP_RECEIVE_SERVER_HELLO_DONE, MonitorTags.CP_RECEIVE_SERVER_FINISHED ] self.hand_shake_tag_client_process = [MonitorTags.CP_SERVER_HELLO_DONE_VALIDATED_CERT, MonitorTags.CP_ENCRYPTED_CLIENT_KEYEXCHANGE , MonitorTags.CP_GENERATED_MASTERSEC_CLIENT_KEYEXCHANGE , MonitorTags.CP_INIT_SEND_CERTIFICATE_VERIFY, \ MonitorTags.CP_ENCRYPTED_CERTIFICATE_VERIFY, MonitorTags.CP_INIT_CLIENT_FINISHED , MonitorTags.CP_HASHED_CLIENT_FINISHED, MonitorTags.CP_SERVER_FINISHED_HASHED_COMPARISON_HASH , \ MonitorTags.CP_SERVER_FINISHED_GENERATED_HASH_PRF, MonitorTags.CP_INIT_SERVER_FINISHED , MonitorTags.CP_HASHED_SERVER_FINISHED, MonitorTags.CP_SERVER_AUTHENTICATED ] self.simple_tags_send = [MonitorTags.CP_SESSION_AVAILABLE_SEND_MESSAGE] self.simple_tags_rec = [MonitorTags.CP_RECEIVE_SIMPLE_MESSAGE] self.tls = self.hand_shake_tag_server_send + self.hand_shake_tag_server_rec + self.hand_shake_tag_server_process + self.hand_shake_tag_client_send + self.hand_shake_tag_client_rec + self.hand_shake_tag_client_process \ + self.simple_tags_send + self.simple_tags_rec # authentication self.sec_mod_tags = [MonitorTags.CP_SEC_INIT_AUTHENTICATION, MonitorTags.CP_SEC_ECNRYPTED_CONFIRMATION_MESSAGE, MonitorTags.CP_SEC_COMPARED_HASH_REG_MSG, \ MonitorTags.CP_SEC_ENCRYPTED_DENY_MESSAGE, MonitorTags.CP_SEC_ENCRYPTED_GRANT_MESSAGE, MonitorTags.CP_SEC_DECRYPTED_REQ_MESSAGE, MonitorTags.CP_SEC_RECEIVE_REG_MESSAGE] self.authent_tags_send = [ MonitorTags.CP_SEC_INIT_AUTHENTICATION, MonitorTags.CP_SEC_ECNRYPTED_CONFIRMATION_MESSAGE, MonitorTags.CP_ECU_SEND_REG_MESSAGE ] self.authent_tags_receive = [ MonitorTags.CP_SEC_COMPARED_HASH_REG_MSG, MonitorTags.CP_ECU_VALIDATED_SEC_MOD_CERTIFICATE, MonitorTags.CP_ECU_DECRYPTED_CONF_MESSAGE ] self.author_tags_send = [ MonitorTags.CP_SEC_ENCRYPTED_DENY_MESSAGE, MonitorTags.CP_SEC_ENCRYPTED_GRANT_MESSAGE, MonitorTags.CP_ECU_ENCRYPTED_REQ_MESSAGE ] self.author_tags_receive = [ MonitorTags.CP_ECU_DECRYPTED_DENY_MESSAGE, MonitorTags.CP_ECU_DECRYPTED_GRANT_MESSAGE, MonitorTags.CP_SEC_DECRYPTED_REQ_MESSAGE ] self.simp_tags_send = [ MonitorTags.CP_ECU_ENCRYPTED_SEND_SIMPLE_MESSAGE ] self.simp_tags_receive = [MonitorTags.CP_ECU_DECRYPTED_SIMPLE_MESSAGE] self.lw_auth = self.sec_mod_tags + self.authent_tags_send + self.authent_tags_receive + self.author_tags_send + self.author_tags_receive + self.simp_tags_send + self.simp_tags_receive def create_widgets(self, parent): vbox = QtGui.QVBoxLayout() self.label = QtGui.QLabel() self.label.setText("Constellation") self.label.setFixedHeight(20) self.fc = Flowchart(terminals={'Connection': {'io': 'in'}}) self.fc._nodes['Input'].close() self.fc._nodes['Output'].close() self.view = self.fc.widget() wig = self.view.chartWidget self.view.chartWidget.hoverDock.hide() self.view.chartWidget.selectedTree.hide() self.view.chartWidget.selDock.label.setText("Selected Comp.") # add selection label self.selection_label = self.view.chartWidget.selDescLabel self.selection_label.setText("") self.selection_label.setFixedHeight(15) # add information table self.info_table = GBuilder().table(self.view.chartWidget.selDock, 1, 2, ["Settings", "Value"]) for r in range(self.info_table.rowCount()): self.info_table.setRowHeight(r, 20) self.info_table.horizontalHeader().hide() self.info_table.verticalHeader().hide() self.info_table.setSelectionBehavior(QAbstractItemView.SelectRows) self.info_table.setSortingEnabled(True) # self.view.chartWidget.selInfoLayout.addWidget(self.selection_label) self.view.chartWidget.selInfoLayout.addWidget(self.info_table) # override on selection self.view.chartWidget._scene.selectionChanged.connect( self._selection_changed) vbox.addWidget(self.label) vbox.addWidget(wig) self.setLayout(vbox) def save(self): data = {} bus_ecu_connections = self.bus_ecu_connections # pur so uebernehmen bus_data = self._get_save_bus() ecu_data = self._get_save_ecu() data['bus_data'] = bus_data data['ecu_data'] = ecu_data data['ecu_positions'] = self._ecu_position data['bus_positions'] = self._bus_position data['bus_ecu_connections'] = bus_ecu_connections print("SSVR I") return data def load(self, data): self._ecu_position = data['ecu_positions'] self._bus_position = data['bus_positions'] bus_data = data['bus_data'] ecu_data = data['ecu_data'] bus_ecu_connections = data['bus_ecu_connections'] # add busses self._add_buses_load(bus_data) # add ecus self._add_ecus_load(ecu_data, bus_ecu_connections) def update_gui(self, monitor_input_list): ''' this method is called exactly once and should show all information ''' # extract information try: constellation = monitor_input_list[0].data except: return ecu_groups = constellation[0] bus_groups = constellation[1] bus_ecu_connections = constellation[2] self.bus_ecu_connections = bus_ecu_connections # set cans self._add_buses(bus_groups) # add ecus self._add_ecus(ecu_groups, bus_ecu_connections) def _selection_changed(self): items = self.view.chartWidget._scene.selectedItems() if len(items) == 0: data = None else: item = items[0] if hasattr(item, 'node') and isinstance(item.node, Node): print(item.node) print("SELECTED %s" % item.node.settings_dict) self._show_node_information(item.node) else: data = None # self.selectedTree.setData(data, hideRoot=True) def _show_node_information(self, node): # hide all rows for r in range(self.info_table.rowCount()): self.info_table.setRowHidden(r, True) # add new information save dict[ecu_id][settings_id] = row_nr comp_id = node.settings_dict['comp_id'] self.selection_label.setText("Selected ECU: %s" % comp_id) for set_key in node.settings_dict.keys(): # if already exists -> show its row and skip try: row_nr = self._show_dict[comp_id][set_key] self.info_table.setRowHidden(row_nr, False) continue except: pass # else add it to table and show row self.info_table.setRowCount(self.info_table.rowCount() + 1) row_nr = self.info_table.rowCount() item_1 = QTableWidgetItem() item_1.setData(QtCore.Qt.EditRole, set_key) item_2 = QTableWidgetItem() item_2.setText(str(node.settings_dict[set_key])) General().add_to_three_dict(self._show_dict, comp_id, set_key, row_nr) self.info_table.setItem(row_nr - 1, 0, item_1) self.info_table.setItem(row_nr - 1, 1, item_2) self.info_table.setRowHeight(row_nr - 1, 20) def _get_save_bus(self): buses = [] for bus_id in self._bus_node: node = self._bus_node[bus_id] settings = node.get_string_settings() buses.append([bus_id, settings]) return buses def _add_buses_load(self, bus_data): nr_buses = len(bus_data) for b_group in bus_data: bus_id = b_group[0] bus_settings = b_group[1] # place the busses [x, y] = self._bus_position[bus_id] node = InformationNode(bus_id) node.settings_dict = bus_settings self._bus_node[bus_id] = node self.fc.addNode(node, bus_id, [x, y]) self._bus_position[bus_id] = [x, y] def _add_buses(self, bus_groups): first = True nr_buses = len(bus_groups) for b_group in bus_groups: bus = b_group[0] # place the busses if not first: [x, y] = self._next_bus_pos(nr_buses) else: [x, y] = [0, 0] first = False node = InformationNode(bus.comp_id) node.set_settings(bus) self._bus_node[bus.comp_id] = node self.fc.addNode(node, bus.comp_id, [x, y]) self._bus_position[bus.comp_id] = [x, y] def _get_save_ecu(self): ecus = [] for ecu_id in self._ecu_node: node = self._ecu_node[ecu_id] settings = node.get_string_settings() ecus.append([ecu_id, settings]) return ecus def _add_ecus_load(self, ecu_data, bus_ecu_connections): ''' add all ecus to the respective buses ''' ecu_dict = self._can_ecu_list_dictionary(bus_ecu_connections) for bus_id in ecu_dict: idx = 0 ecu_list = ecu_dict[bus_id] for ecu_id in ecu_list: if isinstance(ecu_id, UUID): ecu_id = "GW\n%s" % str(ecu_id.hex) ecu_dat = self._ecu_dat_from_id(ecu_id, ecu_data) ecu_id = ecu_dat[0] ecu_settings = ecu_dat[1] [x, y] = self._ecu_position[ecu_id] ecu_id_show = ecu_id # shorten name if to long if len(ecu_id) >= 13: ecu_id_show = ecu_id[:13] # calculate positions idx += 1 try: # if this already exists gets a second connection ecu_terminal = False if ecu_id in self._ecu_node.keys(): ecu_terminal = self._ecu_node[ecu_id].addInput('C%s' % idx) # create new node if not ecu_terminal: node = InformationNode(ecu_id_show) # set information node.settings_dict = ecu_settings self.fc.addNode(node, ecu_id_show, [x, y]) self._ecu_position[ecu_id] = [x, y] self._ecu_node[ecu_id] = node ecu_terminal = node.addInput('C%s' % idx) bus_terminal = self._bus_node[bus_id].addInput('C%s' % idx) except: traceback.print_exc() # connector to bus try: self.fc.connectTerminals(bus_terminal, ecu_terminal) except: pass def _add_ecus(self, ecu_groups, bus_ecu_connections): ''' add all ecus to the respective buses ''' ecu_dict = self._can_ecu_list_dictionary(bus_ecu_connections) for bus_id in ecu_dict: ecu_list = ecu_dict[bus_id] nr_ecus = len(ecu_list) pos_bus = self._bus_position[bus_id] idx = 0 if bus_id == "CAN0": a = 0 for ecu_id in ecu_list: ecu_id_show = ecu_id ecu = self._ecu_from_group(ecu_groups, ecu_id) [x, y] = self._next_ecu_pos(pos_bus, nr_ecus, idx) if isinstance(ecu_id, UUID): ecu_id = "GW\n%s" % ecu_id.hex [x, y] = self._get_gw_position(ecu) # shorten name if to long if len(ecu_id) >= 13: ecu_id_show = ecu_id[:13] # calculate positions idx += 1 try: # if this already exists gets a second connection ecu_terminal = False if ecu_id in self._ecu_node.keys(): ecu_terminal = self._ecu_node[ecu_id].addInput('C%s' % idx) # create new node if not ecu_terminal: node = InformationNode(ecu_id_show) # set information node.set_settings(ecu) self.fc.addNode(node, ecu_id_show, [x, y]) self._ecu_position[ecu_id] = [x, y] self._ecu_node[ecu_id] = node ecu_terminal = node.addInput('C%s' % idx) bus_terminal = self._bus_node[bus_id].addInput('C%s' % idx) except: traceback.print_exc() # connector to bus try: self.fc.connectTerminals(bus_terminal, ecu_terminal) except: pass def _ecu_dat_from_id(self, ecu_id, ecu_data): for ecu_dat in ecu_data: if ecu_dat[0] == ecu_id: return ecu_dat return None def _ecu_from_group(self, ecu_groups, ecu_id): for ecu_lists in ecu_groups: ecu_list = ecu_lists[0] ecu_spec = ecu_lists[1] for ecu in ecu_list: if ecu.ecu_id == ecu_id: return ecu return None def _get_gw_position(self, gateway): x_points = [] y_points = [] for bus in gateway.connected_bus: x_points.append(self._bus_position[bus.comp_id][0]) y_points.append(self._bus_position[bus.comp_id][1]) x = float(sum(x_points)) / float(len(x_points)) y = float(sum(y_points)) / float(len(y_points)) for bus in gateway.connected_bus: if self._bus_position[bus.comp_id][0] == x and self._bus_position[ bus.comp_id][1] == y: y += self._gw_distance return [x, y] def _can_ecu_list_dictionary(self, bus_ecu_connections): ''' creates a dictinary of form key: bus id and value list of ecu ids connected to the bus Input: bus_ecu_connections list Output: ecu_dict dictionary ''' out_dict = {} for connection in bus_ecu_connections: General().force_add_dict_list(out_dict, connection[0], connection[1]) return out_dict def _next_ecu_pos(self, pos_bus, nr_ecus, idx): ''' determines the next position of the ecu''' alpha = (360 / nr_ecus) * 1.00000001 angle = idx * alpha # radius varies with the number of ECUs connected (less means closer) radius = (math.sqrt(2) * 190) / (2 * math.sin(2 * math.pi * (alpha / 360))) angle /= 360 angle *= 2 * math.pi x = radius * math.cos(angle) + pos_bus[0] y = radius * math.sin(angle) + pos_bus[1] return [x, y] def _next_bus_pos(self, nr_buses): ''' determines the next position of the bus''' if nr_buses < 5: [x, y] = self._last_bus_pos [lr, ud] = self._last_bus_steps x += self._bus_distance self._last_bus_pos[0] = x return [x, y] [x, y] = self._last_bus_pos [lr, ud] = self._last_bus_steps step = round(sqrt(nr_buses / 3)) y += self._bus_distance if ud == step: y = 0 ud = 0 x += self._bus_distance self._last_bus_steps = [lr + 1, 0] lr += 1 ud += 1 self._last_bus_steps = [lr, ud] self._last_bus_pos = [x, y] return [x, y] def _is_sec_mod(self, ecu): try: ecu._SECMODULE return True except: pass return False
def __init__(self, *args, **kwargs): QWidget.__init__(self, *args, **kwargs) self.builder = GBuilder() self.create_widgets()
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)
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 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 DBElemEditor(QDialog): def __init__(self, condition, request, spec, q_tab_item): QWidget.__init__(self) self.builder = GBuilder() self.edited_item = q_tab_item self.condition = condition self.request = request self.spec_node = spec self._create_widget() self._fill_widgets() self.exec() def _create_widget(self): self.builder.set_props(self, False, 820, 300) self.setWindowIcon(QtGui.QIcon( os.getcwd() +r'/icons/tumcreatelogo2.png')) self.tit_label = self.builder.label(self, "Description: \nEdit the Database request and the conditions") self.left_label = self.builder.label(self, "Database request:") self.db_textbox = QtGui.QTextEdit() self.cond_label = self.builder.label(self, "Conditions for Database with ID:") self.condition_tab = self.builder.table(self, len(self.condition), 6, ["ID", 'Lookup DB', "Var Name", "Var Config", "Type", "Value"], False) self.condition_tab.verticalHeader().hide() self.condition_tab.setColumnWidth(2, 250) self.add_pb = self.builder.pushbutton(self, "Add Item", self.add_hit, icon_path = os.getcwd() +r'/icons/add.png') self.add_pb.setFixedHeight(30) self.add_pb.setFixedWidth(200) self.del_pb = self.builder.pushbutton(self, "Delete Item", self.delete_hit, icon_path = os.getcwd() +r'/icons/delete.png') self.del_pb.setFixedHeight(30) self.del_pb.setFixedWidth(200) self.space = self.builder.label(self, "") self.ok_pb = self.builder.pushbutton(self, "Ok", self.ok_hit) self.ok_pb.setFixedHeight(30) self.ok_pb.setFixedWidth(140) self.cancel_pb = self.builder.pushbutton(self, "Cancel", self.cancel_hit) self.cancel_pb.setFixedHeight(30) self.cancel_pb.setFixedWidth(140) ''' Layout ''' v_lay = QVBoxLayout() v_lay.addWidget(self.tit_label) v_lay.addWidget(self.left_label) v_lay.addWidget(self.db_textbox) v_lay.addWidget(self.cond_label) v_lay.addWidget(self.condition_tab) hl = QHBoxLayout() hl.addWidget(self.add_pb) hl.addWidget(self.del_pb) hl.addWidget(self.space) hl.addWidget(self.ok_pb) hl.addWidget(self.cancel_pb) v_lay.addLayout(hl) self.setLayout(v_lay) def _fill_widgets(self): self.db_textbox.setText(self.request) db_path = self.spec_node.attrib['dbpath'] spec_id = self.spec_node.attrib['id'] found_vars = self.spec_node.findall('{http://www.tum-create.edu.sg/timingSchema}variable') if found_vars == None: return i = 0 for var in found_vars: var_name = var.attrib['name'] var_config = var.attrib['config'] var_type = var.attrib['type'] val = var.find('{http://www.tum-create.edu.sg/timingSchema}value') if val == None: return var_value = val.text self.condition_tab.setItem(i, 0, QTableWidgetItem(spec_id)) self.condition_tab.setItem(i, 1, QTableWidgetItem(db_path)) self.condition_tab.setItem(i, 2, QTableWidgetItem(var_name)) self.condition_tab.setItem(i, 3, QTableWidgetItem(var_config)) self.condition_tab.setItem(i, 4, QTableWidgetItem(var_type)) self.condition_tab.setItem(i, 5, QTableWidgetItem(var_value)) i += 1 def add_hit(self): self.condition_tab.setRowCount(self.condition_tab.rowCount() + 1) def delete_hit(self): cur_row = self.condition_tab.currentRow() self.condition_tab.removeRow(cur_row) def ok_hit(self): # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ''' CONTINUE HERE: TODO: Read out changes from the table and write it back to the timing Mapping file and save it (but only after Editor closed) ''' for i in range(self.condition_tab.rowCount()): for j in range(self.condition_tab.columnCount()): itm = self.condition_tab.item(i, j) if j == 0: k = 1 print("ok") def cancel_hit(self): self.close()
class DirectViewWindow(QtGui.QMainWindow): ''' View Window that can be connected to a simulation ''' def __init__(self, views, *args, **kwargs): QtGui.QMainWindow.__init__(self, *args, **kwargs) ''' 1. members ''' self.builder = GBuilder() ''' 2. initialize the gui factories ''' self.view_plugins = views ''' 3. actions ''' self.init_actions() self.create_widgets() @try_ex def create_widgets(self): ''' 1. Main window ''' self.setWindowTitle('TUMCreate - Automotive Simulator - Direct View') self.setWindowIcon(QtGui.QIcon(os.path.join(os.path.dirname(__file__), r'../icons/tumcreatelogo2.png'))) self.builder.set_props(self, ctr_lout=True, min_sz_x=1200, min_sz_y=700) ''' 2. Two Group Boxes ''' self.groupb_info = self.builder.groupbox(self, 'Information', max_height=200, max_width=2000) self.set_info_group() self.groupb_viewer = self.builder.groupbox(self, 'View') self.set_viewer_group() ''' 3. Init Menubar ''' self.init_menubar(); ''' 4. Toolbar''' self.toolbar_gen_sets = self.builder.toolbar(self, GEnums.T_TOP, actions=self.gen_set_actions) ''' 5. Create Layout''' self.init_layout() @try_ex def init_actions(self): ''' 1. Create General Settings''' self.exit_action = QtGui.QAction(QtGui.QIcon(os.path.join(os.path.dirname(__file__), r'../icons/exit.png')), '&Exit', self) self.exit_action.setShortcut('Ctrl+Q') self.exit_action.setStatusTip('Exit application') self.exit_action.triggered.connect(QtGui.qApp.quit) self.help_action = QtGui.QAction(QtGui.QIcon(os.path.join(os.path.dirname(__file__), r'../icons/help.png')), '&Help', self) self.help_action.setShortcut('F3') self.help_action.setStatusTip('Open Help') self.help_action.triggered.connect(QtGui.qApp.quit) self.clear_action = QtGui.QAction(QtGui.QIcon(os.path.join(os.path.dirname(__file__), r'../icons/clear.png')), '&Clear all parameters', self) self.clear_action.setShortcut('Ctrl+Shift+N') self.clear_action.setStatusTip('Open Help') self.clear_action.triggered.connect(QtGui.qApp.quit) self.load_action = QtGui.QAction(QtGui.QIcon(os.path.join(os.path.dirname(__file__), r'../icons/load.png')), '&Clear all parameters', self) self.load_action.setShortcut('Ctrl+Shift+L') self.load_action.setStatusTip('Load file') self.load_action.triggered.connect(self._load_views_hit) ''' 2. define all actions that will appear in the general Toolbar ''' self.gen_set_actions = [self.clear_action, self.help_action, self.load_action] @try_ex def init_layout(self): ''' Sets the layout for the three main groupboxes ''' main_layout = self.centralWidget().layout() h_layout = QtGui.QHBoxLayout() h_layout.addWidget(self.groupb_info) main_layout.addLayout(h_layout) main_layout.addWidget(self.groupb_viewer) @try_ex def init_menubar(self): ''' 1. Create Menubar''' menubar = self.menuBar() ''' 2. add Menus and actions''' # File file_menu = menubar.addMenu('&File') file_menu.addAction(self.exit_action) # Help help_menu = menubar.addMenu('&Help') help_menu.addAction(self.help_action) def link_axis(self): link_plot = False for view in self.view_plugins: # check if there are link axis p = view.link_axis() if p != None: if link_plot: p.setXLink(link_plot) else: link_plot = p @try_ex def set_cb_changed_event_set(self): self.settings_stack.setCurrentIndex(self.settings_cbox.currentIndex()) @try_ex def set_info_group(self): ''' 1. Logo''' self.space = QtGui.QLabel() self.info_label = QtGui.QLabel("\nTitle: \t%s \nAuthor: \t%s\nCompany:\t%s\nDepartement:\t%s\nVersion: \t%s" % (__title__, __author__, __enterprise__, __departement__ , __version__)) self.space.setFixedWidth(10) self.info_logo = self.builder.image(self.groupb_info, os.path.dirname(__file__)[:-4] + r'/icons/tumcreatelogo.png', 2.4) self.info_logo.setMaximumWidth(270) ''' 2. Description Text ''' self.desc_txt = self.builder.label(self.groupb_info, "<b>Description: </b>" + '\n\nThis application simulates an automotive environment. It offers the possibility to perform timing analyses of communication flows between a certain number of ECUs.') ''' 3. Groupbox Layout''' v_layout = QtGui.QVBoxLayout(self.groupb_info) h_layout_one = QtGui.QHBoxLayout() h_layout_one.addWidget(self.space) h_layout_one.addWidget(self.info_label) h_layout_one.addWidget(self.info_logo) v_layout.addLayout(h_layout_one) v_layout.addWidget(self.desc_txt) @try_ex def set_cb_changed_event_view(self, e): # check which items are selected and show all of them try: # clear all try: for ky in self.wid_to_idx: self.wid_to_idx[ky].setParent(None) except: ECULogger().log_traceback() # get checked items checked_idx = [] for cnt in range(self.viewer_cbox.count()): item = self.viewer_cbox.model().item(cnt, 0) if item.checkState(): checked_idx.append(cnt) row_nr = int(self.arrange_rows.text()) col_nr = int(self.arrange_cols.text()) if row_nr * col_nr < len(checked_idx): row_nr = ceil(float(len(checked_idx)) / col_nr) self.arrange_rows.setText(str(row_nr)) # arrange cnt = 0 for r in range(row_nr): hlay = QHBoxLayout() for c in range(col_nr): try: wid = self.wid_to_idx[checked_idx[cnt]]; cnt += 1 hlay.addWidget(wid) except: pass try: self.main_v_layout.addLayout(hlay) except: pass except: pass @try_ex def set_viewer_group(self): ''' 1. Load Items from viewer factory ''' self.wid_to_idx = {} self.viewer_cbox = self.builder.checkable_combobox(self.groupb_viewer, [], self.set_cb_changed_event_view) self.save_but = self.builder.pushbutton(self.groupb_viewer, "Save", self._save_hit) self.save_but.setFixedWidth(100) # field to enter arrangement [lay_r, self.arrange_rows] = self.builder.label_text(self.groupb_viewer, "rows:", 25, 40, self.set_cb_changed_event_view) self.arrange_rows.setText('2') [lay_c, self.arrange_cols] = self.builder.label_text(self.groupb_viewer, "columns:", 40, 40, self.set_cb_changed_event_view) self.arrange_cols.setText('2') cnt = 0 for view in self.view_plugins: if view != None: self.viewer_cbox.addItem(view.get_combobox_name()) item = self.viewer_cbox.model().item(cnt, 0) item.setCheckState(QtCore.Qt.Checked) self.wid_to_idx[cnt] = view.get_widget(self) cnt += 1 ''' Layout ''' self.main_v_layout = QVBoxLayout() self.viewer_cbox.setFixedHeight(25) hl = QHBoxLayout() hl.addWidget(self.viewer_cbox) hl.addLayout(lay_r) hl.addLayout(lay_c) hl.addWidget(self.save_but) self.main_v_layout.addLayout(hl) self.groupb_viewer.setLayout(self.main_v_layout) self.set_cb_changed_event_view(None) def _load_views_hit(self, filename=False): if not filename: filename = QtGui.QFileDialog.getOpenFileName(self, 'Load', '', 'Simulation (*.tum)') with open(filename, 'rb') as f: save_vals = pickle.load(f) for view in self.view_plugins: if view != None: try: save_val = save_vals[view.get_combobox_name()] except: logging.warn("Warning: On GUI load no saved values found for %s" % view.__class__.__name__) # ECULogger().log_traceback() continue view.load(save_val) def _save_hit(self): save_vals = {} for view in self.view_plugins: if view != None: try: print("Call save on %s" % view) save_val = view.save() print("OK!") except: ECULogger().log_traceback() continue save_vals[view.get_combobox_name()] = save_val filename = QtGui.QFileDialog.getSaveFileName(self, "Save file", "", ".tum") with open(filename, 'wb') as f: pickle.dump(save_vals, f, pickle.HIGHEST_PROTOCOL)
class StdBusAddWidget(AbstractAddPlugin): ''' This is the interface that connects the GUI and the actions to execute ''' GUI_NAME = "CAN BUS" GUI_ICON = os.getcwd() + r'/icons/can.png' def __init__(self, parent): AbstractAddPlugin.__init__(self, parent) self._create_widgets(parent) self.parent = parent self.id = uuid.uuid4() self.bus_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 "nr_busses" in mapp: self.nr_ecus_textedit.setText(str(mapp["nr_busses"])) 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["nr_busses"] = self._wrap(int, self.nr_ecus_textedit.text(), 0) return mapping_values def preprocess(self, env, mapp): pass def get_actions(self): ''' returns the connections that can be made ''' actions = {} actions['connect_group'] = 'Connect ECU Group' 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 Standard Bus. This CAN Bus is a simple implementation of a automotive link.") self.desc_label.setFixedWidth(400) self.icon = GBuilder().image(parent, StdBusAddWidget.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.nr_ecus_textedit = GBuilder().label_text(parent, "Number of Busses:", label_width=120) main_lo.addLayout(lo0) main_lo.addLayout(lo1) def _wrap(self, func, prime, second): try: el = func(prime) return el except: return second
class ECUMessagesViewPluginGUI(dockarea.DockArea): def __init__(self, parent): dockarea.DockArea.__init__(self) self.builder = GBuilder() self.widget_index = {} self.widget_text = {} self.dock_index = {} self._external_core = CheckpointInterpreterCore() self._information_box_items = ['Time', 'Associated Id', 'Monitor Tag', 'Message Id', 'Message', 'Size', 'Stream Id', 'Monitor Data', 'Description'] self._information_checked = {'Time': True, 'Associated Id': True, 'Monitor Tag': True, 'Message Id': True, 'Message': True, 'Size': True, 'Stream Id': False, 'Monitor Data': False, 'Description': True} self._info_widget_index = {} self.known = [] self.create_widgets(parent) def _already_there(self, mon_input): ''' handles duplicates''' if hash(mon_input) in self.known: return True self.known.append(hash(mon_input)) if len(self.known) > 1000: del self.known[:floor(float(len(self.known)) / 2.0)] return False def create_widgets(self, parent): h_layout = QHBoxLayout() self.viewer_cbox = self.builder.checkable_combobox(parent, [], self._set_cb_changed) self.information_cbox = self.builder.checkable_combobox(parent, [], self._set_information_changed) self.information_cbox.setFixedWidth(150) cnt = 0 for info in self._information_box_items: self.information_cbox.addItem(info) new_row = self.information_cbox.count() - 1 item = self.information_cbox.model().item(new_row, 0) if self._information_checked[info]: item.setCheckState(QtCore.Qt.Checked) else: item.setCheckState(QtCore.Qt.Unchecked) self._info_widget_index[cnt] = info cnt += 1 h_layout.addWidget(self.viewer_cbox) h_layout.addItem(QSpacerItem(10, 10)) h_layout.addWidget(self.information_cbox) # add ecu selection self.label_top = QtGui.QLabel() self.label_top.setText("Message View") self.viewDock = dockarea.Dock('view', size=(1000, 600)) self.layout.addWidget(self.label_top) self.label_top.setFixedHeight(20) self.layout.addLayout(h_layout) self.layout.addItem(QSpacerItem(10, 10)) def _set_information_changed(self, e): # get checked items checked_idx = [] for cnt in range(self.information_cbox.count()): item = self.information_cbox.model().item(cnt, 0) if item.checkState(): checked_idx.append(cnt) # checked items set them for idx in self._info_widget_index.keys(): info = self._info_widget_index[idx] if idx in checked_idx: self._information_checked[info] = True else: self._information_checked[info] = False def _add_items_ecu_ids(self, ecu_ids): items = [] for ecu_id in ecu_ids: try: items += [self.add_item(ecu_id)] except: pass if not items: return for i in items: i.setCheckState(QtCore.Qt.Unchecked) items[0].setCheckState(QtCore.Qt.Checked) self._set_cb_changed(None) def add_item(self, title_text): # add item to dock new_widget = QTextEdit() new_widget.setText("") new_widget.setReadOnly(True) new_dock = dockarea.Dock(title_text, size=(1000, 20)) new_dock.setOrientation('horizontal') new_dock.addWidget(new_widget) self.addDock(new_dock, 'right') # add item to combobox self.viewer_cbox.addItem(title_text) new_row = self.viewer_cbox.count() - 1 item = self.viewer_cbox.model().item(new_row, 0) item.setCheckState(QtCore.Qt.Checked) # link items self.widget_index[new_row] = new_widget self.widget_text[title_text] = new_widget self.dock_index[new_row] = new_dock return item def _set_cb_changed(self, e): # clear all try: for ky in self.dock_index: self.dock_index[ky].setParent(None) except: ECULogger().log_traceback() # get checked items checked_idx = [] for cnt in range(self.viewer_cbox.count()): item = self.viewer_cbox.model().item(cnt, 0) if item.checkState(): checked_idx.append(cnt) for ky in range(self.viewer_cbox.count()): # selected draw if ky in checked_idx: self.addDock(self.dock_index[ky], 'right') self.widget_index[ky].verticalScrollBar().setValue(self.widget_index[ky].verticalScrollBar().maximum()); def save(self): return [] def load(self, val_pairs): pass def update_gui(self, monitor_input_list): # receive the ecu ids try: if isinstance(monitor_input_list[0], str): return constellation = monitor_input_list[0].data ecu_groups = constellation[0] ecu_ids = [e.ecu_id for e in APICore()._ecu_list_from_groups(ecu_groups)] self._add_items_ecu_ids(ecu_ids) return except: pass monitor_input_list.sort(key=lambda x: x[0], reverse=False) # receive simple inputs for monitor_input in monitor_input_list: # read information time = monitor_input[0] ecu_id = monitor_input[1] associated_id = monitor_input[2] tag = eval(monitor_input[3]) message_id = monitor_input[4] message = monitor_input[5] message_size = monitor_input[6] stream_id = monitor_input[7] unique_id = monitor_input[8] input_data = monitor_input[9] description = self._external_core.cp_string(tag, associated_id, stream_id, message) # get textedit text_edit = self.widget_text[ecu_id] # current_text = text_edit.toPlainText() # create new text part_append = "" if self._information_checked['Time']: part_append += "\n\nTime: \t%s" % time if self._information_checked['Associated Id']: part_append += "\nAssociated Id: \t%s" % associated_id if self._information_checked['Monitor Tag']: part_append += "\nMonitor Tag: \t%s" % tag if self._information_checked['Message Id']: part_append += "\nMessage Id: \t%s" % message_id if self._information_checked['Message']: part_append += "\nMessage: \t%s" % message if self._information_checked['Size']: part_append += "\nSize: \t%s" % message_size if self._information_checked['Stream Id']: part_append += "\nStream Id: \t%s" % stream_id if self._information_checked['Monitor Data']: part_append += "\nMonitor Data: \t%s" % input_data if self._information_checked['Description']: part_append += "\nDescription: \t%s" % description # add new part text_edit.append(part_append) # current_text += part_append # text_edit.setText(current_text) text_edit.verticalScrollBar().setValue(text_edit.verticalScrollBar().maximum());
def _connect(self): ''' connect two items''' # open Connect window, self._cur_selected_connection = None self.dia = QDialog(self.gui); main_lo = QVBoxLayout() GBuilder().set_props(self.dia, None, 250, 130, max_sz_x=400, max_sz_y=250) try: self.selected_env_elems = EnvironmentElement.icons_to_env_els(DragSelection().selected, self.env_map[self.selected_env]) self.clicked_elem = EnvironmentElement.icons_to_env_els([DragSelection().clicked], self.env_map[self.selected_env])[0] self.selected_env_elems.remove(self.clicked_elem) except: return # show possible connections if not self.selected_env_elems: return acts = self.clicked_elem.processor.get_actions() main_lo.addWidget(GBuilder().label(self.dia, "Select a connection to be executed between type %s and type %s" % (self.clicked_elem.comp_type, self.selected_env_elems[0].comp_type))) hl, self._con_cb, te = GBuilder().label_combobox(self.dia, "Select Connection ", list(acts.values()), self.dia.show) main_lo.addLayout(hl) # ok cancel main_lo.addWidget(GBuilder().hor_line(self.dia)) ok = GBuilder().pushbutton(self.dia, "Apply", self._ok_dia_hit); ok.setFixedWidth(100) canc = GBuilder().pushbutton(self.dia, "Cancel", self._cancel_dia_hit); canc.setFixedWidth(100) hl = QHBoxLayout() hl.addWidget(GBuilder().label(self.dia, "")) hl.addWidget(ok) hl.addWidget(canc) main_lo.addLayout(hl) self.dia.setLayout(main_lo)
class SettingManager(QDialog): def __init__(self, *args, **kwargs): QDialog.__init__(self, *args, **kwargs) self.builder = GBuilder() self.setWindowIcon(QtGui.QIcon( os.getcwd() +r'/icons/tumcreatelogo2.png')) self.setWindowTitle("Timing Set Manager") self.selected_tab_row = 0 self.create_widgets() self._load_variables() def create_widgets(self): ''' Create Widgets''' self.builder.set_props(self, False, 1200, 740) self.desc_label = self.builder.label(self, "Description: \nEdit an existing Timing Mapping Parameter Set or create a new one") self.desc_label.setFixedHeight(50) self.set_cb = self.builder.combobox(self, [], self.set_cb_selection_changed) self.set_cb.setFixedHeight(22) self.set_plus_pb = self.builder.pushbutton(self, "Add", self.add_hit, os.getcwd() +r'/icons/add.png') self.set_plus_pb.setFixedWidth(100) self.set_plus_pb.setFixedHeight(30) self.elem_tab = self.builder.table(self, 0, 5, ["Affiliation", "Timing Variable", "Type", "Value", "Condition"]) self.elem_tab.cellDoubleClicked.connect(self._cell_double_clicked) ''' Save and Exit Buttons ''' self.space = self.builder.label(self, "") # self.space.setFixedWidth(300) self.ok_pb = self.builder.pushbutton(self, "Ok", self.ok_hit) self.ok_pb.setFixedHeight(30) self.ok_pb.setFixedWidth(140) self.apply_pb = self.builder.pushbutton(self, "Apply", self.apply_hit) self.apply_pb.setFixedHeight(30) self.apply_pb.setFixedWidth(140) self.cancel_pb = self.builder.pushbutton(self, "Cancel", self.cancel_hit) self.cancel_pb.setFixedHeight(30) self.cancel_pb.setFixedWidth(140) ''' Layout ''' v_lay = QVBoxLayout() v_lay.addWidget(self.desc_label) hl = QHBoxLayout() hl.addWidget(self.set_plus_pb) hl.addWidget(self.set_cb) v_lay.addLayout(hl) v_lay.addWidget(self.elem_tab) hl = QHBoxLayout() hl.addWidget(self.space) hl.addWidget(self.ok_pb) hl.addWidget(self.cancel_pb) hl.addWidget(self.apply_pb) v_lay.addLayout(hl) self.setLayout(v_lay) def _load_variables(self): ''' Load all timing Variables that are specified in the timing.ini ''' timing_vars = [] self.db_lookup_dict = {} ''' 1. Load the variables ''' for reg_tim in Registrator().reg_simple_timings.keys(): for l in Registrator().reg_simple_timings[reg_tim]: dic = Registrator().reg_simple_timings[reg_tim][l] lst = list(dic.keys()) try: lst += Registrator().db_lookup_timings[reg_tim][l] self.db_lookup_dict[l] = list(Registrator().db_lookup_timings[reg_tim][l].keys()) except: pass timing_vars.append([l, lst, reg_tim, dic]) ''' 2. Set table from variables''' self._set_timing_tab(timing_vars) def _set_timing_tab(self, timing_vars): self.elem_tab.setRowCount(len(timing_vars)) self.db_lookup_idx_to_info = {} self.type_cb_to_idx = {} self.type_idx_to_cb = {} self.type_item_state = {} self.type_to_dict = {} for i in range(len(timing_vars)): cur_var = timing_vars[i][0] cur_vals = timing_vars[i][1] cur_ass = timing_vars[i][2] cur_vals_dict = timing_vars[i][3] ''' 1. Set Variable Name ''' self.elem_tab.setItem(i, 0, QTableWidgetItem(cur_ass)) self.elem_tab.setItem(i, 1, QTableWidgetItem(cur_var)) self.elem_tab.setItem(i, 2, QTableWidgetItem()) self.type_to_dict[cur_var] = cur_vals_dict ''' 2. Set Setting ''' wid = QWidget() vl = QVBoxLayout() cb = self.builder.combobox(self, cur_vals + ["new Setting ..."], self.on_type_cb_itemchanged) self.type_cb_to_idx[str(cb)] = i self.type_idx_to_cb[i] = cb cb.setFixedHeight(20) vl.addWidget(cb) wid.setLayout(vl) self.elem_tab.setCellWidget(i, 2, wid) self.type_item_state[i] = cb.currentText() ''' 3. Set value''' self.elem_tab.setItem(i, 3, QTableWidgetItem(str(cur_vals_dict[cb.currentText()]))) def on_type_cb_itemchanged(self): ''' changed index if new Setting hit create new Setting''' for i in range(self.elem_tab.rowCount()): try: cb = self.type_idx_to_cb[i] if(cb.currentText() == "new Setting ..."): idx = cb.findText(self.type_item_state[i]) cb.setCurrentIndex(idx) self.new_setting(i) continue if cb.currentText() != self.type_item_state[i] and cb.currentText() != 'CUSTOMIZED': ''' load values '''# itm = self.elem_tab.item(i, 1) txt = itm.text() cor_dic = self.type_to_dict[txt] try: val = cor_dic[cb.currentText()] self.elem_tab.setItem(i, 3, QTableWidgetItem(str(val))) except: pass self.db_lookup_dict[txt] itm1 = self.elem_tab.item(i, 0) itm2 = self.elem_tab.item(i, 1) ''' if DB Lookup show request -> double click opens window: edit request and edit the condition ''' [request, spec] = TimingDBMap().lookup_from_spec(itm1.text(), itm2.text(), cb.currentText()) [condition, spec] = TimingDBMap().conditions_from_spec(itm1.text(), itm2.text(), cb.currentText()) itm = QTableWidgetItem(request) self.elem_tab.setItem(i, 4, itm) itm.setToolTip("Conditions: \n%s" % self._pretty_str_cond(condition)) self.db_lookup_idx_to_info[i] = [condition, request, spec] self.type_item_state[i] = cb.currentText() except: pass def _pretty_str_cond(self, conditions): out_str = "" for el in conditions: out_str += "\nName:\t\t" out_str += el['name'] out_str += "\nConfig:\t\t" out_str += str(el['config']) out_str += "\nValue:\t\t" out_str += str(el['value']) out_str += "\n" return out_str def _cell_double_clicked(self, row, col): print("DOUBLE CLICKED row %s" % row) try: [condition, request, spec] = self.db_lookup_idx_to_info[row] DBElemEditor(condition, request, spec, self.elem_tab.item(row, 4)) except: pass def new_setting(self, row): print("Create new setting in row %s" % row) def add_hit(self): print("asd") def ok_hit(self): print("ok") def apply_hit(self): print("Apply") def cancel_hit(self): self.close() def set_cb_selection_changed(self): pass
def create_widgets(self, parent, mapp=False): # Layout GBuilder().set_props(self, min_sz_x=500, min_sz_y=150) main_lo = QVBoxLayout() self.setLayout(main_lo) # Get Add Dialog try: # Read API Spec that I need cls = ECUFactory().get_class(self.ecu_type) self.processor = cls.get_add_plugin(parent) if mapp: self.processor.set_gui(mapp) main_lo.addWidget(self.processor) except: print(traceback.format_exc()) ECULogger().log_traceback() # Ok and Cancel main_lo.addWidget(GBuilder().hor_line(parent)) hl = QHBoxLayout() hl.addWidget(GBuilder().label(parent, "")) ok = GBuilder().pushbutton(parent, "OK", self._ok_hit) ok.setFixedWidth(100) hl.addWidget(ok) canc = GBuilder().pushbutton(parent, "Cancel", self._cancel_hit) canc.setFixedWidth(100) hl.addWidget(canc)
class MainWindow(QtGui.QMainWindow): ''' Main Window of the application ''' def __init__(self, *args, **kwargs): QtGui.QMainWindow.__init__(self, *args, **kwargs) ''' 1. members ''' self.builder = GBuilder() self.monitor = Monitor() self.setWindowTitle('TUMCreate - Automotive Simulator') self.setWindowIcon(QtGui.QIcon(os.path.join(os.path.dirname(__file__), r'../icons/tumcreatelogo2.png'))) ''' 2. initialize the gui factories ''' ViewerPluginFactory().load_classes() SettingsPluginFactory().load_classes() ''' 3. actions ''' self.init_actions() self.create_widgets() def create_widgets(self): ''' 1. Main window ''' self.builder.set_props(self, ctr_lout=True, min_sz_x=1200, min_sz_y=700) ''' 2. Three Group Boxes ''' self.groupb_settings = self.builder.groupbox(self, 'Settings', max_height=200) self.set_settings_group() self.groupb_info = self.builder.groupbox(self, 'Information', max_height=200, max_width=700) self.set_info_group() self.groupb_viewer = self.builder.groupbox(self, 'View') self.set_viewer_group() ''' 3. Init Menubar ''' self.init_menubar(); ''' 4. Toolbar''' self.toolbar_gen_sets = self.builder.toolbar(self, GEnums.T_TOP, actions=self.gen_set_actions) ''' 5. Create Layout''' self.init_layout() def create_aut_env(self): # Spaeter on Button Click z.B. ''' this method creates the simulation''' api_log_path = os.path.join(os.path.dirname(__file__), "../logs/api.log") api.show_logging(logging.INFO, api_log_path, True) my_env = api.create_environment(2500) ecu_spec = SimpleECUSpec([], 200, 200) ecu_group_1 = api.set_ecus(my_env, 10, 'SecureECU', ecu_spec) ecu_spec = SimpleECUSpec(['SEC 1'], 200, 200) ecu_spec.set_ecu_setting('t_ecu_auth_trigger_process', 100) ecu_spec.set_ecu_setting('t_ecu_auth_trigger_intervall', 1000) sec_mod_group = api.set_ecus(my_env, 1, 'SecLwAuthSecurityModule', ecu_spec) bus_spec = SimpleBusSpec(['CAN_0']) bus_group = api.set_busses(my_env, 1, 'StdCANBus', bus_spec) api.connect_bus_by_obj(my_env, 'CAN_0', ecu_group_1 + sec_mod_group) api.register_ecu_groups_to_secmod(my_env, sec_mod_group[0].ecu_id, [ecu_group_1]) certeros = api.create_cert_manager() for ecu in APICore()._ecu_list_from_groups([[ecu_group_1]]): # UNINTENDED HACK api.generate_valid_ecu_cert_cfg(certeros, ecu.ecu_id, CAEnum.CA_L313, 'SEC 1', 0, float('inf')) api.generate_valid_sec_mod_cert_cfg(certeros, 'SEC 1', CAEnum.CA_L313, 0, float('inf')) api.apply_certification(my_env, certeros) stream_1 = MessageStream(my_env.get_env(), 'SecureECU_0', ['SecureECU_1', 'SecureECU_4', 'SecureECU_5'], 13, float('inf'), 0, float('inf')) stream_2 = MessageStream(my_env.get_env(), 'SecureECU_1', ['SecureECU_3', 'SecureECU_2', 'SecureECU_5'], 12, float('inf'), 0, float('inf')) stream_3 = MessageStream(my_env.get_env(), 'SecureECU_0', ['SecureECU_4', 'SecureECU_1', 'SecureECU_5'], 222, float('inf'), 0, float('inf')) stream_4 = MessageStream(my_env.get_env(), 'SecureECU_3', ['SecureECU_0', 'SecureECU_1', 'SecureECU_5'], 11, float('inf'), 0, float('inf')) stream_5 = MessageStream(my_env.get_env(), 'SecureECU_4', ['SecureECU_2', 'SecureECU_1', 'SecureECU_3'], 500, float('inf'), 0, float('inf')) api.add_allowed_stream(my_env, 'SEC 1', stream_1) api.add_allowed_stream(my_env, 'SEC 1', stream_2) api.add_allowed_stream(my_env, 'SEC 1', stream_3) api.add_allowed_stream(my_env, 'SEC 1', stream_4) api.add_allowed_stream(my_env, 'SEC 1', stream_5) t_set = TimingFunctionSet() ecu_func_set = StdSecurLwSecModTimingFunctions(main_library_tag='CyaSSL') t_set.set_mapping_from_function_set('SEC 1', ecu_func_set) api.apply_timing_functions_set(my_env, 'SEC 1', t_set) t_set2 = TimingFunctionSet() ecu_func_set = StdSecurECUTimingFunctions(main_library_tag='CyaSSL') for ecu in APICore()._ecu_list_from_groups([[ecu_group_1]]): # UNINTENDED HACK t_set2.set_mapping_from_function_set(ecu.ecu_id, ecu_func_set) api.apply_timing_functions_set(my_env, ecu.ecu_id, t_set2) api.connect_monitor(my_env, self.monitor, 50) api.build_simulation(my_env) ''' start this in a new thread''' sim = SimulationThread(self, my_env) sim.start() def init_actions(self): ''' 1. Create General Settings''' self.exit_action = QtGui.QAction(QtGui.QIcon(os.path.join(os.path.dirname(__file__), r'../icons/exit.png')), '&Exit', self) self.exit_action.setShortcut('Ctrl+Q') self.exit_action.setStatusTip('Exit application') self.exit_action.triggered.connect(QtGui.qApp.quit) self.help_action = QtGui.QAction(QtGui.QIcon(os.path.join(os.path.dirname(__file__), r'../icons/help.png')), '&Help', self) self.help_action.setShortcut('F3') self.help_action.setStatusTip('Open Help') self.help_action.triggered.connect(QtGui.qApp.quit) self.clear_action = QtGui.QAction(QtGui.QIcon(os.path.join(os.path.dirname(__file__), r'../icons/clear.png')), '&Clear all parameters', self) self.clear_action.setShortcut('Ctrl+Shift+N') self.clear_action.setStatusTip('Open Help') self.clear_action.triggered.connect(QtGui.qApp.quit) ''' 2. define all actions that will appear in the general Toolbar ''' self.gen_set_actions = [self.clear_action, self.help_action] def init_layout(self): ''' Sets the layout for the three main groupboxes ''' main_layout = self.centralWidget().layout() h_layout = QtGui.QHBoxLayout() h_layout.addWidget(self.groupb_settings) h_layout.addWidget(self.groupb_info) main_layout.addLayout(h_layout) main_layout.addWidget(self.groupb_viewer) def init_menubar(self): ''' 1. Create Menubar''' menubar = self.menuBar() ''' 2. add Menus and actions''' # File file_menu = menubar.addMenu('&File') file_menu.addAction(self.clear_action) file_menu.addAction(self.exit_action) # Help help_menu = menubar.addMenu('&Help') help_menu.addAction(self.help_action) def set_settings_group(self): ''' 1. Load Items from settings factory ''' set_fact = SettingsPluginFactory() self.settings_stack = QtGui.QStackedWidget() self.settings_cbox = self.builder.combobox(self.groupb_settings, [], self.set_cb_changed_event_set) for setting_plugin in set_fact.createable_objects(): setting = set_fact.make(setting_plugin) if setting != None: self.settings_stack.addWidget(setting.get_widget(self)) self.settings_cbox.addItem(setting.get_combobox_name()) ''' layout ''' v_layout = QVBoxLayout() self.settings_cbox.setFixedHeight(20) v_layout.addWidget(self.settings_cbox) v_layout.addWidget(self.settings_stack) self.groupb_settings.setLayout(v_layout) def set_cb_changed_event_set(self): self.settings_stack.setCurrentIndex(self.settings_cbox.currentIndex()) def set_info_group(self): ''' 1. Logo''' self.space = QtGui.QLabel() self.info_label = QtGui.QLabel("\nTitle: \t%s \nAuthor: \t%s\nCompany:\t%s\nDepartement:\t%s\nVersion: \t%s" % (__title__, __author__, __enterprise__, __departement__ , __version__)) self.space.setFixedWidth(10) self.info_logo = self.builder.image(self.groupb_info, os.path.join(os.path.dirname(__file__), r'../icons/tumcreatelogo.png', 2.4)) self.info_logo.setMaximumWidth(270) ''' 2. Description Text ''' self.desc_txt = self.builder.label(self.groupb_info, "<b>Description: </b>" + '\n\nThis application simulates an automotive environment. It offers the possibility to perform timing analyses of communication flows between a certain number of ECUs.') ''' 3. Groupbox Layout''' v_layout = QtGui.QVBoxLayout(self.groupb_info) h_layout_one = QtGui.QHBoxLayout() h_layout_one.addWidget(self.space) h_layout_one.addWidget(self.info_label) h_layout_one.addWidget(self.info_logo) v_layout.addLayout(h_layout_one) v_layout.addWidget(self.desc_txt) def set_cb_changed_event_view(self): self.viewer_stack.setCurrentIndex(self.viewer_cbox.currentIndex()) def set_viewer_group(self): ''' 1. Load Items from viewer factory ''' view_fact = ViewerPluginFactory() self.viewer_stack = QtGui.QStackedWidget() self.viewer_cbox = self.builder.combobox(self.groupb_viewer, [], self.set_cb_changed_event_view) self.set_start_button = self.builder.pushbutton(self.groupb_viewer, 'Start Simulation', self.create_aut_env) self.set_start_button.setFixedWidth(200) self.set_start_button.setFixedHeight(25) for viewer_plugin in view_fact.createable_objects(): view = view_fact.make(viewer_plugin) if view != None: view.set_monitor(self.monitor) self.viewer_stack.addWidget(view.get_widget(self)) self.viewer_cbox.addItem(view.get_combobox_name()) ''' layout ''' v_layout = QVBoxLayout() self.viewer_cbox.setFixedHeight(25) v_layout.addWidget(self.viewer_stack) hl = QHBoxLayout() hl.addWidget(self.viewer_cbox) hl.addWidget(self.set_start_button) v_layout.addLayout(hl) self.groupb_viewer.setLayout(v_layout)