Example #1
0
def console_logging(lev, show_output):
    ''' shows logging only in the console 
    
    Input:  lev            int/string    specifies the depth of logging as defined in the logging module
            show_output    bool          specifies if the output is written to the console
    '''
    ECULogger().enabled = True
    if show_output:
        logging.getLogger().setLevel(lev)
    ECULogger().show_outputf(show_output)
Example #2
0
 def wrapped(*args, **kwargs):
     try:
         return fn(*args, **kwargs)
     except Exception as e:            
         try:
             ky = fn.__qualname__.split(".")[0]
             cls = fn.__globals__[ky]
             ECULogger().log_err(401, cls)
         except:
             ECULogger().log_err(401, fn.__qualname__)
         logging.error(format_ex(e))
         ECULogger().log_traceback()    
Example #3
0
    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)
Example #4
0
    def monitor_publish(self):
        ''' 
            information is captured continuously and 
            send to the connected methods once in a while             
        '''

        while True:
            try:

                # get current time
                if self._show_time:
                    print("Current time %s " % self.sim_env.now)

                # if there is new stuff publish it now
                self._input_handler.publish(
                    self.sim_env.now,
                    self._last_run_elements)  # calls all publishers in a chain

                self._last_run_elements.clear()

            except:
                ECULogger().log_traceback()

            # wait
            yield self.sim_env.timeout(self.t_period)
Example #5
0
    def start(self, monitor=False):
        ''' 1. Start application layer of ECU s'''
        for ecu_id in self.ecus:
            if self.ecus[ecu_id].startup_delay:
                self._sim_env.process(self._start_delayed(self.ecus[ecu_id]))
            else:
                self._sim_env.process(self.ecus[ecu_id].ecuSW.app_lay.main())
                self._sim_env.process(
                    self.ecus[ecu_id].ecuSW.comm_mod.datalink_lay.process())
        ''' 2. Start the bus running in parallel to the ECUs '''
        for bus_id in self.buses:
            self._sim_env.process(self.buses[bus_id].process())
        ''' 3. Start the monitor object '''
        if monitor:
            monitor.set_monitor_env(self._sim_env)
            proc = self._sim_env.process(monitor.monitor())
            proc2 = self._sim_env.process(monitor.monitor_publish())
            monitor.set_sim_process(proc)
        ''' 4. Start the environmant'''
        try:
            self._sim_env.run(until=self._sim_env.now + self._app_lifetime)
            del self._sim_env

        except AttributeError:
            pass
        except:
            traceback.print_exc()
            ECULogger().log_traceback()
            logging.info("Simulation terminated")
Example #6
0
 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()
Example #7
0
def show_logging(lev, file_path, show_output):
    ''' shows the logging and saves it to the given
        file 
        
        Input:  lev            int/string    specifies the depth of logging as defined in the logging module
                file_path      string        path to log output file path
                show_output    bool          specifies if the output is written to the file
    '''
    ECULogger().enabled = True    
    if show_output:
        logging.getLogger().setLevel(lev)   
        if not os.path.exists(os.path.dirname(file_path)):
            os.mkdir(os.path.dirname(file_path))  
        if not os.path.exists(file_path):
            open(file_path, 'a').close()
        handler = logging.FileHandler(filename=file_path, mode='w')    
        logging.getLogger().addHandler(handler)
        
    ECULogger().show_outputf(show_output)
Example #8
0
    def publish(self, cur_time, monitor_inputs):

        # emit the signal to all connected receivers then call next publish
        try:
            res = [[monitor_input.time_called, str(monitor_input.mon_id), str(monitor_input.asc_id), str(monitor_input.tag), monitor_input.msg_id, str(monitor_input.message), \
                    monitor_input.msg_size, monitor_input.stream_id, str(monitor_input.unique_id), str(monitor_input.data)] \
                   for monitor_input in monitor_inputs.get() if monitor_input.tag in self._get_tags()]

            self.publish_infos_sig.emit([None, None])
        except:
            ECULogger().log_traceback()

        if self.next != None:
            self.next.publish(cur_time, monitor_inputs)
Example #9
0
    def get_bytes(self):
        ''' returns the sum of the sizes of all elements in
            this buffer
            
            Input:     -
            Output:    size     float        size of all elements inside the buffer
        '''
        if self.diabled_buffer_control: return 0

        try:
            a = sum([(float(it.msg_length_in_bit) / 8.0) for it in self.items])

        except:
            a = 0
            ECULogger().log_traceback()
            print(self.items)
        return a
Example #10
0
 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)
Example #11
0
 def _try_logging_transmission(self, t_propagation, t_sending):
     ''' notes the times that it takes to send the messages
     
         Input:  t_propagation:    float    time it takes to propagate the message
                 t_sending         float    time it takes to send the message
     '''
                     
     try:
         # Log transmission
         L().log(300, self.sim_env.now, self.current_message.sender_id, float(self.current_message_length_bit) / 8.0, \
                 self.current_message_length_bit, self.comp_id, self.current_message.data.get(), t_propagation + t_sending) 
     except:
         
         # Log traceback
         ECULogger().log_traceback()
         try: 
             L().log(300, self.sim_env.now, self.current_message.sender_id, self.current_message.data, \
                     self.current_message_length_bit, self.comp_id, self.current_message.data, t_propagation + t_sending)
         except: pass
Example #12
0
    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
Example #13
0
 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
Example #14
0
 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());
Example #15
0
    def _calc_datarate_export(self, cur_time, last_time, bytes_trans):
        ''' calculates the datarate and writes it to the file'''
        try:
            datarate = {}
            info = {}
            for ky in bytes_trans:
                datarate[ky] = float(bytes_trans[ky]) / (cur_time - last_time)

                info[ky] = [cur_time, ky, datarate[ky] / 1000.0]

                if InterpreterOptions.CSV_DR_FILE in self.export_options:
                    try:
                        self.csv_writer.writerow([
                            "BUS DATARATE", info[ky][0], info[ky][1],
                            info[ky][2]
                        ])
                    except:
                        ECULogger().log_traceback()

            return info
        except:
            pass
Example #16
0
 def mouseDoubleClickEvent(self, e):
     try:                
         self.double_click_func(e.pos() - self.offset, self.ecu_key, self)
     except:
         ECULogger().log_traceback()
Example #17
0
    def lookup(self,
               lib=False,
               mode=False,
               alg=False,
               alg_mode=False,
               keylen=False,
               exp=False,
               param_len=False,
               data_size=False,
               ret_all=False):
        ''' looks for a time value in the database if none found returns none
        Library:    Crypto_Lib_SW, Crypto_Lib_HW, CyaSSL
        Input is Matlab style: var_name, var_value, var_name, var_value, ...        
        Library TEXT, Mode TEXT, Algorithm TEXT, AlgorithmMode TEXT, Keylength INT, Exponent INT, Parameterlength INT, Datasize INT, Time DOUBLE
        
        Input:  lib        string            value of library column in the DB
                mode       string            mode requested of library column in the DB e.g. ENCRYPTION, DECRYPTION,...
                alg        string            name of the algorithm of library column in the DB
                alg_mode   string            name of algorithm mode of library column in the DB (e.g. CTR, ...)
                keylen     integer           length of the key in bit of library column in the DB
                exp        integer           size of the exponent when RSA is used
                param_len  integer           length of the parameter whenn ECC is used (library column in the DB )
                data_size  integer           size of the data of library column in the DB
                ret_all    boolean           if this value is true the values for all data_sizes will be returned
        Output: time       float             time that was requested in the data base given above input values        
        '''
        #         print("ACCESS DATABASE")

        try:
            # build expression
            exc_str = 'SELECT * FROM Measurements WHERE '
            exc_str_b = exc_str
            if lib: exc_str = exc_str + "Library = '" + lib + "' AND "
            if mode: exc_str = exc_str + "Mode = '" + mode + "' AND "
            if alg: exc_str = exc_str + "Algorithm = '" + alg + "' AND "
            if alg_mode:
                exc_str = exc_str + "AlgorithmMode = '" + alg_mode + "' AND "
            if keylen:
                exc_str = exc_str + "Keylength = " + str(keylen) + " AND "
            if exp: exc_str = exc_str + "Exponent = " + str(exp) + " AND "
            if param_len:
                exc_str = exc_str + "Parameterlength = " + str(
                    param_len) + " AND "
            if data_size:
                exc_str = exc_str + "Datasize = " + str(data_size) + " AND "
            exc_str = exc_str[:-4]

            # validate expression
            if exc_str_b != exc_str:
                ioerror = True
                cnt = 0
                while ioerror:
                    try:
                        self.db.execute(exc_str)
                        ioerror = False
                    except sqlite3.OperationalError:
                        cnt = cnt + 1
                        # logging.warn("\tERROR: Database problem. Waiting shortly and trying again")
                        sleep(1)
                        ioerror = True
                        # if cnt > 10:
                        #    logging.warn("\tERROR: Database problem could not be resolved...")

            # receive data
            data = self.db.fetchall()

            # check return all selected
            if data and ret_all:
                return data
            elif data:
                return data[0][-1]
            else:
                return None
        except sqlite3.ProgrammingError:
            self._load_init(
                os.path.join(os.path.dirname(__file__),
                             "data/timingMapping.xml"), "data/measurements.db")
            return self.lookup(lib, mode, alg, alg_mode, keylen, exp,
                               param_len, data_size, ret_all)
        except:
            ECULogger().log_traceback()
            return None