示例#1
0
    def __init__(self, parent):
        super(WindowSettings, self).__init__(parent)
        self.parent = parent
        self.appIcon = parent.appIcon
        self.w_settings = uic.loadUi('forms/settings.ui')
        self.w_settings.setWindowTitle('Settings')
        self.w_settings.setWindowIcon(self.appIcon)

        self.listInstr = None
        ip_validator = QRegExpValidator(QRegExp(parent.re_ip))
        self.w_settings.ip.setValidator(ip_validator)
        self.w_settings.mask.setValidator(ip_validator)

        self.w_settings.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).clicked.connect(self.is_pressed_ok)
        self.w_settings.buttonBox.button(QtWidgets.QDialogButtonBox.Cancel).clicked.connect(self.is_pressed_cancel)
        self.w_settings.storm_path_btn.clicked.connect(self.select_storm_path)
        self.w_settings.export_btn.clicked.connect(self.export_settings)
        self.w_settings.import_btn.clicked.connect(self.import_settings)

        self.w_settings.combo_gen.currentTextChanged.connect(self.is_generator_changed)
        self.w_settings.combo_sa.currentTextChanged.connect(self.is_analyzer_changed)

        self.db = CobhamDB()
        self.fill_com_ports()
        self.fill_instruments()
        self.load_settings()
        # self.w_settings.exec_()
        self.w_settings.show()
示例#2
0
    def set_assembly(self):
        db = CobhamDB()
        assembly = {}
        for i, j in enumerate(self.bands):
            assembly.update({'rf_type_{}'.format(i + 1): j})
            assembly.update({'rf_asis_{}'.format(i + 1): self.bands_sn.get(j)})
        idobr = self.get_sdr_info()
        assembly.update({'sdr_type_1': idobr.get('master_sdr').get('type')})
        assembly.update({'sdr_asis_1': idobr.get('master_sdr').get('asis')})
        assembly.update({'sdr_type_2': idobr.get('slave_sdr').get('type')})
        assembly.update({'sdr_asis_2': idobr.get('slave_sdr').get('asis')})
        assembly.update({'idobr_type': self.parent.system_type})
        assembly.update({'idobr_asis': self.parent.system_asis})
        assembly.update({'idobr_sn': self.parent.system_sn})
        if len(db.get_idobr_assembly(self.parent.system_asis)) != 0:
            diff = db.compare_assembly(assembly)
            if not diff.get("diff"):
                raise ValueError(
                    'Assembly between DB and system have difference:\n'
                    'System: {}\n'
                    'DB    : {}'.format(diff.get("diff_sys"),
                                        diff.get("diff_db")))

        # assembly.update(self.controller.get_sdr_info())
        # assembly.update({'rf_master': self.sn_list_master})
        # assembly.update({'rf_slave': self.sn_list_slave})
        # assembly.update({'idobr': {'type': self.parent.system_type, 'asis': self.parent.system_asis}})

        if db.set_idobr_assembly(assembly):
            self.controller.log_signal.emit('Creating assembly completed')
        else:
            # ToDo: verify assembly
            self.controller.log_signal_arg.emit(
                'Creating assembly not completed', -1)
示例#3
0
    def __init__(self, parent):
        super(WindowTestJournal, self).__init__(parent)

        self.db = CobhamDB()
        self.parent = parent
        self.assembly = {}
        self.appIcon = parent.appIcon
        self.w_journal = uic.loadUi('forms/journal.ui')
        self.w_journal.setWindowTitle('Test journal')
        self.w_journal.setWindowIcon(self.appIcon)
        self.w_journal.setWindowFlags(QtCore.Qt.WindowSystemMenuHint |
                                       QtCore.Qt.WindowMinMaxButtonsHint |
                                       QtCore.Qt.WindowCloseButtonHint)
        self.w_journal.journal_tab.installEventFilter(self)
        self.w_journal.filter.textChanged.connect(self.filter)
        self.w_journal.print_btn.clicked.connect(self.print_report)
        self.header_journal = ["System type", "System ASIS", "System SN", "Test type", "Test date", "Result"]
        self.header_tests = ["Test name", "Result"]
        self.w_journal.journal_tab.cellDoubleClicked.connect(self.cellDoubleClick)
        self.w_journal.journal_tab.cellClicked.connect(self.cell_select)
        self.w_journal.journal_tab.setSortingEnabled(True)

        self.w_journal.assembly_tree.setHeaderHidden(True)
        curr_date = QtCore.QDate.currentDate()
        self.w_journal.start_date.setDate(curr_date.addDays(-curr_date.day() + 1))
        self.w_journal.stop_date.setDate(curr_date.addDays(curr_date.daysInMonth() - curr_date.day()))
        self.w_journal.start_date.dateChanged.connect(self.fill_tab_row)
        self.w_journal.stop_date.dateChanged.connect(self.fill_tab_row)

        self.fill_tab_header()
        self.fill_tab_row()
        # self.fill_temp_combo()

        self.w_journal.exec_()
示例#4
0
 def __init__(self, parent=None, **kwargs):
     QtCore.QThread.__init__(self, parent)
     self.startTime = datetime.datetime.now().timestamp()
     self.curr_parent = kwargs.get('curr_parent')
     self.type_test = kwargs.get('type_test')
     self.settings = CobhamDB().get_all_data('settings')
     self.login_msg = self.curr_parent.login_msg
     self.isSystemBoot = False
     self.curr_test = None
     self.db = CobhamDB()
示例#5
0
 def genPreset(self, **kwargs):
     self.gen = self.getInstr(
         CobhamDB().get_all_data('settings').get('combo_gen'))
     self.gen.write("*RST")
     self.gen.write(":POW:OFFS -{} dB".format(
         CobhamDB().get_all_data('settings').get('atten_gen')))
     self.gen.write(":OUTP:STAT OFF")
     self.gen.write(":OUTP:MOD:STAT OFF")
     if kwargs.get('freq'):
         self.gen.write(":FREQ:FIX {} MHz".format(kwargs.get('freq')))
     return self.gen
示例#6
0
 def __init__(self, controller, bands):
     self.controller = controller
     self.bands = bands
     self.test_status = True
     self.instr = Instruments(controller=self.controller)
     self.db = CobhamDB()
     self.instr.genPreset()
     # self.instr.saPreset()
     # {band_number: [UL, DL]}
     self.band_uldl = {}
     self.band_fft = {1: [2, 3], 2: [0, 1], 3: [6, 7], 4: [4, 5]}
示例#7
0
 def get_connection():
     db = CobhamDB()
     tmp = db.get_port_baud()
     port = tmp.get('port')
     baud = tmp.get('baud')
     try:
         ser = serial.Serial(port, baud, timeout=False)
         ser.reset_input_buffer()
         ser.reset_output_buffer()
         return ser
     except Exception as e:
         raise e
示例#8
0
    def __init__(self, parent=None):
        # logging.debug('This message should go to the log file')
        # logging.info('So should this')
        # logging.warning('And this, too')

        super(MainApp, self).__init__(parent)
        self.db = CobhamDB()
        self.cfg = Config(self)

        self.system_type = ''
        self.system_asis = ''
        self.system_sn = ''

        self.wk_dir = os.path.dirname(os.path.realpath('__file__'))
        self.appIcon = QtGui.QIcon("img/cobham_c_64x64.ico")
        self.w_main = uic.loadUi('forms/mainwindow.ui')
        self.w_main.setWindowTitle('CobhamUtils {}'.format(VERSION))
        self.w_main.setWindowIcon(self.appIcon)

        self.login_msg = 'root@AxellShell[root]'
        self.answer = None
        self.controller_thread = None
        self.calibration_thread = None
        self.tests_queue = {}
        self.test_type = ''

        self.passImg = QtGui.QPixmap('Img/pass.png').scaled(30, 30)
        self.failImg = QtGui.QPixmap('Img/fail.png').scaled(30, 30)
        self.warningImg = QtGui.QPixmap('Img/warning.png').scaled(30, 30)
        self.greenLedMovie = QMovie('Img/greenLed.gif')
        self.blueLedMovie = QMovie('Img/blueLed.gif')
        self.redLedMovie = QMovie('Img/redLed.gif')

        self.w_main.start_test_btn.clicked.connect(self.test)
        self.w_main.selectall_chbox.clicked.connect(self.select_all)
        self.w_main.calibration_btn.clicked.connect(self.calibration)
        self.w_main.new_test_btn.clicked.connect(self.new_test)
        self.w_main.menu_Settings.triggered.connect(self.window_settings)
        self.w_main.menu_TestJournal.triggered.connect(self.window_test_journal)
        self.w_main.menu_test.triggered.connect(self.send_img_msg)
        self.w_main.menu_Quit.triggered.connect(self.w_main.close)
        self.w_main.menu_Quit.setShortcut('Ctrl+Q')

        self.check_com(False)
        self.set_progress_bar(1, 0)

        self.w_main.show()

        self.stop_event = threading.Event()
        self.c_thread = EventListener(self)
        self.c_thread.timer_signal.connect(self.set_timer, QtCore.Qt.QueuedConnection)
        self.c_thread.start()
示例#9
0
 def saPreset(self, **kwargs):
     self.sa = self.getInstr(
         CobhamDB().get_all_data('settings').get('combo_sa'))
     self.sa_send_cmd(":SYST:PRES")
     self.sa_send_cmd(":CAL:AUTO OFF")
     if kwargs.get('freq'):
         self.sa_send_cmd(":SENSE:FREQ:center {} MHz".format(
             kwargs.get('freq')))
     self.sa_send_cmd(":SENSE:FREQ:span 100 kHz")
     self.sa_send_cmd("DISP:WIND:TRAC:Y:RLEV:OFFS {}".format(
         CobhamDB().get_all_data('settings').get('atten_sa')))
     # self.sa_send_cmd(":BAND:VID 27 KHz")
     return self.sa
示例#10
0
 def check_instr(self):
     addr_gen = CobhamDB().get_all_data('settings').get('addr_gen')
     name_gen = CobhamDB().get_all_data('settings').get('combo_gen')
     addr_sa = CobhamDB().get_all_data('settings').get('addr_sa')
     name_sa = CobhamDB().get_all_data('settings').get('combo_sa')
     is_instrument_present = True
     list_instr = self.getListInstrument()
     if addr_gen not in list_instr.keys(
     ) or list_instr.get(addr_gen) != name_gen:
         self.controller.log_signal_arg.emit(
             "Generator {} not found".format(name_gen), -1)
         is_instrument_present = False
     if addr_sa not in list_instr.keys(
     ) or list_instr.get(addr_sa) != name_sa:
         self.controller.log_signal_arg.emit(
             "Signal analyzer {} not found".format(name_sa), -1)
         is_instrument_present = False
     return is_instrument_present
示例#11
0
    def __init__(self, parent):
        super(WindowCalibration, self).__init__(parent)
        self.parent = parent
        self.appIcon = parent.appIcon
        self.w_calibration = uic.loadUi('forms/calibration.ui')
        self.w_calibration.setWindowTitle('Calibration')
        self.w_calibration.setWindowIcon(self.appIcon)
        self.db = CobhamDB()

        self.w_calibration.start_btn.clicked.connect(self.run_calibration)

        self.w_calibration.exec_()
示例#12
0
    def __init__(self, parent, assembly):
        super(WindowAssembly, self).__init__(parent)
        self.db = CobhamDB()
        self.parent = parent
        self.appIcon = parent.appIcon
        self.w_assembly = uic.loadUi('forms/assembly.ui')
        self.w_assembly.setWindowTitle('Assembly')
        self.w_assembly.setWindowIcon(self.appIcon)

        self.w_assembly.tree.setHeaderHidden(True)
        self.fill_tree(assembly)
        self.w_assembly.tree.expandToDepth(1)
        self.w_assembly.exec_()
示例#13
0
 def __init__(self, controller, parent=None):
     QtCore.QThread.__init__(self, parent)
     self._stopFlag = False
     self.controller = controller
     self.parent = controller.curr_parent
     self.db = CobhamDB()
     self.db.set_test_type(self.__class__.__name__)
     self.asis = self.parent.w_main.asis_lbl.text()
     self.test_time = datetime.datetime.now().strftime(
         "%Y/%m/%d/, %H:%M:%S")
     self.bands = None
     self.bands_sn = None
     self.sn_list_master = {}
     self.sn_list_slave = {}
     self.filters = {
         'ABCD08': [806, 5, 847],
         'ABCD09': [942.5, 5, 897.5],
         'ABCD18': [1842.5, 5, 1747.5],
         'ABCD21': [2140, 5, 1950]
     }
     self.test_result = {}
     self.current_test_name = None
示例#14
0
    def __init__(self, **kwargs):
        self.controller = kwargs.get('controller')
        self.parent = kwargs.get('parent')
        self.db = CobhamDB()
        # if not self.controller is None:
        #     gen_offset = self.db.get_gen_offset()[0]
        #     sa_offset = self.db.get_sa_offset()[0]
        #     self.gen_calibr = self.controller.str_to_dict(gen_offset)
        #     self.sa_calibr = self.controller.str_to_dict(sa_offset)

        self.sa = None
        self.gen = None
        try:
            self.rm = visa.ResourceManager()
            self.rm.timeout = 50000
        except Exception as e:
            self.controller.msg_signal.emit('w',
                                            'Instrument initialisation error',
                                            str(e), 1)
            raise e
示例#15
0
 def __init__(self, **kwargs):
     self.controller = kwargs.get('controller')
     self.instr = Instruments(controller=self.controller)
     self.db = CobhamDB()
示例#16
0
class Calibration:
    log_signal = QtCore.pyqtSignal(str)
    log_signal_arg = QtCore.pyqtSignal(str, int)
    timer_signal = QtCore.pyqtSignal(float)
    msg_signal = QtCore.pyqtSignal(str, str, str, int)
    input_signal = QtCore.pyqtSignal(str)
    set_label_signal = QtCore.pyqtSignal(str, str)

    def __init__(self, **kwargs):
        self.controller = kwargs.get('controller')
        self.instr = Instruments(controller=self.controller)
        self.db = CobhamDB()

    def run_calibration(self):
        self.instr.genPreset()
        self.instr.saPreset()
        self.controller.log_signal.emit("Start calibration")
        answer = self.controller.send_msg(
            'i', 'Calibration', "Connect generator to analyzer using "
            "cable with attenuator. And press OK.", 2)

        if answer != QMessageBox.Ok:
            return

        self.db.clear_calibration()
        list_gen2sa = self.loop_calibration('gen2sa')

        answer = self.controller.send_msg(
            'i', 'Calibration', "Connect analyzer to generator using "
            "cable with attenuator. And press OK.", 2)
        if answer != QMessageBox.Ok:
            return
        list_sa2gen = self.loop_calibration('sa2gen')
        calibr = {}
        for i in list_gen2sa.keys():
            val = {'gen2sa': list_gen2sa.get(i), 'sa2gen': list_sa2gen.get(i)}
            calibr.update({i: val})
        self.db.set_calibration(calibr)
        self.controller.log_signal.emit('Calibration complete')
        self.controller.curr_parent.check_calibration()

    def loop_calibration(self, type):
        list_val = {}
        # time_now = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
        time_now = time.strftime("%Y-%m-%d", time.gmtime())
        steep = int(self.db.get_all_data('settings').get('cal_steep'))
        start = int(self.db.get_all_data('settings').get('cal_start'))
        stop = int(self.db.get_all_data('settings').get('cal_stop'))

        self.instr.gen.write("POW:AMPL -20 dBm")
        gen_pow = float(self.instr.gen.query("POW:AMPL?"))
        if type == 'Gen2Sa':
            atten = float(self.db.get_all_data('settings').get('atten_gen'))
        elif type == 'Sa2Gen':
            atten = float(self.db.get_all_data('settings').get('atten_sa'))
        else:
            atten = 0
        self.instr.sa_send_cmd("DISP:WIND:TRAC:Y:RLEV:OFFS {}".format(atten))
        self.instr.gen.write(":OUTP:STAT ON")
        time.sleep(1)
        for i in range(start, stop + steep, steep):
            if i % 50 == 0:
                self.instr.sa_calibration_settings(i)
            self.instr.gen.write(":FREQ:FIX {} MHz".format(i))
            self.instr.sa_send_cmd(":CALC:MARK1:X {} MHz".format(i))
            # self.instr.sa_send_cmd(":TRAC1:MODE VIEW")
            gain = round(float(self.instr.sa_send_query("CALC:MARK1:Y?")), 2)
            offset = round(gen_pow - gain, 2)
            list_val.update({i: offset})
            # self.instr.sa_send_cmd(":TRAC1:MODE WRIT")
            # self.db.set_calibration(column=type, freq=i, val=offset)
            self.controller.log_signal.emit('Freq {} MHz: offset = {}'.format(
                i, offset))
        self.instr.gen.write(":OUTP:STAT OFF")
        return list_val
示例#17
0
class TestController(QtCore.QThread):
    LOG_FILENAME = './Log/cobham_utils.log'
    # # logging.basicConfig(filename=LOG_FILENAME, level=logging.ERROR)
    # logger = logging.FileHandler(LOG_FILENAME)
    # logger.setLevel(logging.DEBUG)
    # # logger = logging.getLogger('cobham_utils')

    # create logger with 'spam_application'
    logger = logging.getLogger('cobham_utils')
    logger.setLevel(logging.DEBUG)
    # create file handler which logs even debug messages
    fh = logging.FileHandler(LOG_FILENAME)
    fh.setLevel(logging.DEBUG)
    # create console handler with a higher log level
    ch = logging.StreamHandler()
    ch.setLevel(logging.ERROR)
    # create formatter and add it to the handlers
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    fh.setFormatter(formatter)
    ch.setFormatter(formatter)
    # add the handlers to the logger
    logger.addHandler(fh)
    logger.addHandler(ch)

    log_signal = QtCore.pyqtSignal(str)
    log_signal_arg = QtCore.pyqtSignal(str, int)
    timer_signal = QtCore.pyqtSignal(float)
    msg_signal = QtCore.pyqtSignal(str, str, str, int)
    msg_img_signal = QtCore.pyqtSignal(str, str)
    input_signal = QtCore.pyqtSignal(str)
    set_label_signal = QtCore.pyqtSignal(str, str)
    check_com_signal = QtCore.pyqtSignal(bool)
    test_result_signal = QtCore.pyqtSignal(int, bool)
    progress_bar_signal = QtCore.pyqtSignal(int, int)

    def __init__(self, parent=None, **kwargs):
        QtCore.QThread.__init__(self, parent)
        self.startTime = datetime.datetime.now().timestamp()
        self.curr_parent = kwargs.get('curr_parent')
        self.type_test = kwargs.get('type_test')
        self.settings = CobhamDB().get_all_data('settings')
        self.login_msg = self.curr_parent.login_msg
        self.isSystemBoot = False
        self.curr_test = None
        self.db = CobhamDB()

    """
    Run selected tests or calibration
    """

    def run(self):
        test_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        try:
            # if not Instruments(controller=self).check_instr():
            #     return

            if self.type_test == 'FufuiDOBR':
                # if not self.curr_parent.check_calibration():
                #     return
                if not self.system_login():
                    self.send_msg('w', 'CobhamUtils', 'System login fail', 1)
                    return
                self.send_com_command('axsh SET NIC eth0 DYNAMIC')
                self.get_ip()

                self.curr_test = FufuiDOBR(self)
                self.db.set_test_type(self.type_test)
                count = self.curr_parent.w_main.tests_tab.rowCount()
                tests_queue = self.curr_parent.tests_queue
                for x in range(0, count):
                    tmp = self.curr_parent.w_main.tests_tab.item(x, 1).text()
                    for i in list(tests_queue.values()):
                        if i[0] == tmp:
                            test = i[1]
                            break
                    is_enable = self.curr_parent.w_main.tests_tab.item(
                        x, 0).checkState()
                    if is_enable == 2:
                        curr_test = self.curr_parent.w_main.tests_tab.item(
                            x, 1).text()
                        while True:
                            result = self.curr_test.start_current_test(test)
                            for_save = {
                                'type_test':
                                self.type_test,
                                'system_asis':
                                self.curr_parent.w_main.asis_lbl.text(),
                                'date_test':
                                test_date,
                                'meas_name':
                                curr_test,
                                'meas_func':
                                test,
                                'status':
                                result
                            }
                            if not result or type(result) == Exception:
                                q = self.send_msg('w', 'Error',
                                                  'Test {} fail'.format(test),
                                                  3)
                                if q == QMessageBox.Ignore:
                                    break
                                if q == QMessageBox.Retry:
                                    result = None
                                    self.progress_bar_signal.emit(0, 0)
                                    continue
                                if q == QMessageBox.Cancel:
                                    self.db.save_test_result(for_save)
                                    self.test_result_signal.emit(x, result)
                                    return
                            else:
                                break
                        self.db.save_test_result(for_save)
                        self.test_result_signal.emit(x, result)

            if self.type_test == 'FufuMtdi':
                if not self.system_login():
                    self.send_msg('w', 'CobhamUtils', 'System login fail', 1)
                    return
                self.send_com_command('axsh SET NIC eth0 DYNAMIC')
                self.get_ip()
                self.curr_test = FufuMtdi(controller=self)
                self.db.set_test_type(self.type_test)
                count = self.curr_parent.w_main.tests_tab.rowCount()
                tests_queue = self.curr_parent.tests_queue
                for x in range(0, count):
                    tmp = self.curr_parent.w_main.tests_tab.item(x, 1).text()
                    for i in list(tests_queue.values()):
                        if i[0] == tmp:
                            test = i[1]
                            break
                    is_enable = self.curr_parent.w_main.tests_tab.item(
                        x, 0).checkState()
                    if is_enable == 2:
                        curr_test = self.curr_parent.w_main.tests_tab.item(
                            x, 1).text()
                        while True:
                            try:
                                result = self.curr_test.start_current_test(
                                    test)
                            except serial.serialutil.SerialException as e:
                                q = self.send_msg('w', 'COM port error',
                                                  str(e), 5)
                                if q == QMessageBox.Retry:
                                    continue
                                # self.logger.info(str(e))
                                return

                            for_save = {
                                'type_test':
                                self.type_test,
                                'system_asis':
                                self.curr_parent.w_main.asis_lbl.text(),
                                'system_type':
                                self.curr_parent.system_type,
                                'date_test':
                                test_date,
                                'meas_name':
                                curr_test,
                                'meas_func':
                                test,
                                'status':
                                result
                            }
                            if not result or type(result) == Exception:
                                q = self.send_msg('w', 'Error',
                                                  'Test {} fail'.format(test),
                                                  3)
                                if q == QMessageBox.Ignore:
                                    break
                                if q == QMessageBox.Retry:
                                    result = None
                                    self.progress_bar_signal.emit(0, 0)
                                    continue
                                if q == QMessageBox.Cancel:
                                    self.db.save_test_result(for_save)
                                    self.test_result_signal.emit(x, result)
                                    return
                            else:
                                break
                        print(for_save)
                        # self.db.save_FufuMtdi_result(for_save)
                        self.test_result_signal.emit(x, result)

            if self.type_test == 'calibration':
                self.curr_test = Calibration(controller=self)
                self.curr_test.run_calibration()
        # except ValueError as e:
        #     if str(e) == 'com_port': return
        #     self.send_msg('w', 'CobhamUtils', str(e), 1)
        #     return

        # except serial.serialutil.SerialException as e:
        #     self.send_msg('w', 'COM port error', str(e), 1)
        #     self.logger.info(str(e))
        #     return
        except Exception as e:
            traceback_str = ''.join(traceback.format_tb(e.__traceback__))
            self.log_signal_arg.emit(traceback_str, -1)
            self.send_msg('c', 'Error', str(e), 1)
            self.logger.error(str(e))
            self.logger.info(traceback_str)
            return

    def system_up_check(self):
        res = self.send_com_command('')
        if not self.login_msg in res:
            match = re.search(r'(Axell-Controller-)(\w{4}\s)(login:)', res)
            if match:
                self.system_login()
            else:
                t = threading.Thread(target=self.axell_boot)
                t.start()
                start = datetime.datetime.now().timestamp()
                while not self.isSystemBoot:
                    delta = datetime.datetime.now().timestamp() - start
                    self.timer_signal.emit(delta)
                    time.sleep(1)
        # ToDo: add timeout( return False)
        return True

    def axell_boot(self):
        self.log_signal_arg.emit("Waiting End of Axell boot", 0)
        with ComPort.get_connection() as ser:
            while ser.is_open:
                try:
                    try:
                        out = str(ser.readline(), 'utf-8').replace("\n", "")
                    except:
                        out = ser.readline()
                    if len(out) != 0:
                        # if out not string
                        if not isinstance(out, str):
                            continue
                        self.set_label_signal.emit('console_lbl', out)
                        if 'End of Axell boot' in out:
                            self.isSystemBoot = True
                            self.curr_parent.send_log("Done")
                            time.sleep(3)
                            self.system_login()
                except serial.SerialException as e:
                    return e

    def system_login(self):
        res = self.send_com_command('')
        print("login -> {}".format(res))
        re_string = '({})@[\S]+\[{}\]'.format(self.settings.get('user_name'),
                                              self.settings.get('user_name'))
        if res is None:
            return
        if re.search(re_string, res):
            self.log_signal.emit('System already login ...')
            return True
        else:
            self.log_signal.emit('Login in system ...')
            self.send_com_command(self.settings.get('user_name'))
            time.sleep(1)
            res = self.send_com_command(self.settings.get('user_pass'))
            if re.search(re_string, res):
                self.log_signal.emit('Login in system complete')
                return True
            else:
                raise ValueError('Login fail. Fix the problem and try again.')

    def send_com_command(self, cmd):
        if cmd == self.settings.get('user_name') or \
                cmd == self.settings.get('user_pass') or \
                    len(cmd) == 0:
            is_login = True
        else:
            is_login = False

        with ComPort.get_connection() as ser:
            try:
                cmd = cmd + '\r'
                ser.write(cmd.encode('utf-8'))
                res = ser.read()
                self.check_com_signal.emit(ser.is_open)
                repeat = 0
                while 1:
                    time.sleep(.5)
                    data_left = ser.inWaiting()
                    res += ser.read(data_left)
                    if data_left == 0:
                        if len(res) == (len(cmd) + 1) and repeat < 20:
                            repeat += 1
                            continue
                        else:
                            break
                res = str(res, 'utf-8')
                # print(res)
                # if 'timeout end with no input' in res or 'ERROR' in res:
                #     ser.close()
                #     self.send_com_command(cmd_tmp)
                if '-sh:' in res:
                    # self.send_msg('w', 'Error', res, 1)
                    raise ValueError(res)
                if res is None:
                    q = self.send_msg(
                        'q', 'Cobham utils',
                        'Command "{}" received None.'.format(cmd))
                    if q == QMessageBox.Retry:
                        self.send_com_command(cmd)
                    if q == QMessageBox.Cancel:
                        pass
                if not is_login:
                    res = str(res).replace(cmd, '').replace(
                        'root@AxellShell[root]>', '')
                return res
            except Exception as e:
                # q = self.send_msg('q', 'Cobham utils', str(e), 5)
                q = self.send_img_msg('Cobham utils', str(e))
                if q == QMessageBox.Retry:
                    self.send_com_command(cmd)
                if q == QMessageBox.Cancel:
                    raise e

    def get_ip(self):
        cmd = 'axsh get nic eth0'
        res = self.send_com_command(cmd).strip().split(' ')
        ip = res[1]
        self.set_label_signal.emit('ip_lbl', ip)
        self.log_signal.emit('ip = {}'.format(ip))
        return res

    def get_bands(self):
        bands = []
        q = self.send_com_command('udp_bridge1 list').split('\n')
        for i in q:
            r = re.search('(ABCD\d\d)', i)
            if r is not None:
                bands.append(r.group(0))
        # if len(bands) != 4:
        #     self.send_msg('w', 'Error', 'Found only {} bands'.format(len(bands)), 1)
        #     self.log_signal.emit(self.send_com_command('udp_bridge1 list'))
        #     input('Press Enter for return...')
        return bands

    def get_bands_sn(self):
        bands = self.get_bands()
        bands_sn = {}
        for i, val in enumerate(bands):
            self.log_signal.emit(
                'Getting serial for board with SnapId = {}'.format(val))
            if i / 2 < 1:
                bands_sn.update({val: self.get_band_serial(True, i + 1)})
            else:
                bands_sn.update({val: self.get_band_serial(False, i - 1)})
            self.log_signal.emit('Serial number: {}'.format(bands_sn.get(val)))

    def get_band_serial(self, master, n):
        print(n)
        if master:
            res = self.send_com_command('dobr_partNum GET {}'.format(n))
        else:
            res = self.send_com_command(
                'send_msg -d 172.24.30.2 -c dobr_partNum GET {}'.format(n))
        match = re.search(r'(part\snumber\s=\s)\w{4}', res)
        print(res)
        if match:
            for_return = match.group().split('=')[1].strip()
            if for_return is None:
                self.get_band_serial(master, n)
            return for_return
        else:
            self.get_band_serial(master, n)

    def send_msg(self, icon, msgTitle, msgText, typeQestions):
        self.msg_signal.emit(icon, msgTitle, msgText, typeQestions)
        while self.curr_parent.answer is None:
            time.sleep(.5)
        else:
            for_return = self.curr_parent.answer
            self.curr_parent.answer = None
            return for_return

    def send_img_msg(self, msgText, msgImage):
        self.msg_img_signal.emit(msgText, msgImage)
        while self.curr_parent.answer is None:
            time.sleep(.05)
        else:
            for_return = self.curr_parent.answer
            self.curr_parent.answer = None
            return for_return

    @staticmethod
    def str_to_dict(val):
        start = val.find('{')
        stop = 0
        for i, j in enumerate(val):
            if j == '}':
                stop = i
        return ast.literal_eval(val[start:stop + 1])

    def send_test_name(self, name, status):
        if status == 'completed':
            status = status + '\n'
        self.log_signal.emit('*** {} *** {}'.format(name, status))

    @staticmethod
    def true_to_pass(val):
        if val:
            return 'PASS'
        return 'FAIL'

    def test(self):
        print(self.curr_test)

        with futures.ThreadPoolExecutor(1) as executor:
            print(self.curr_test)
            executor.submit(self.curr_test.stop_test)
示例#18
0
class WindowTestJournal(QDialog):
    def __init__(self, parent):
        super(WindowTestJournal, self).__init__(parent)

        self.db = CobhamDB()
        self.parent = parent
        self.assembly = {}
        self.appIcon = parent.appIcon
        self.w_journal = uic.loadUi('forms/journal.ui')
        self.w_journal.setWindowTitle('Test journal')
        self.w_journal.setWindowIcon(self.appIcon)
        self.w_journal.setWindowFlags(QtCore.Qt.WindowSystemMenuHint |
                                       QtCore.Qt.WindowMinMaxButtonsHint |
                                       QtCore.Qt.WindowCloseButtonHint)
        self.w_journal.journal_tab.installEventFilter(self)
        self.w_journal.filter.textChanged.connect(self.filter)
        self.w_journal.print_btn.clicked.connect(self.print_report)
        self.header_journal = ["System type", "System ASIS", "System SN", "Test type", "Test date", "Result"]
        self.header_tests = ["Test name", "Result"]
        self.w_journal.journal_tab.cellDoubleClicked.connect(self.cellDoubleClick)
        self.w_journal.journal_tab.cellClicked.connect(self.cell_select)
        self.w_journal.journal_tab.setSortingEnabled(True)

        self.w_journal.assembly_tree.setHeaderHidden(True)
        curr_date = QtCore.QDate.currentDate()
        self.w_journal.start_date.setDate(curr_date.addDays(-curr_date.day() + 1))
        self.w_journal.stop_date.setDate(curr_date.addDays(curr_date.daysInMonth() - curr_date.day()))
        self.w_journal.start_date.dateChanged.connect(self.fill_tab_row)
        self.w_journal.stop_date.dateChanged.connect(self.fill_tab_row)

        self.fill_tab_header()
        self.fill_tab_row()
        # self.fill_temp_combo()

        self.w_journal.exec_()

    def print_report(self):
        selected = self.w_journal.journal_tab.selectedIndexes()
        if len(selected) == 0:
            self.parent.send_msg('i', 'Print report', 'You have to choice report for print', 1)
            return
        else:
            row = selected[0].row()
            asis = self.w_journal.journal_tab.item(row, 1).text()
            test_type = self.w_journal.journal_tab.item(row, 3).text()
            date = self.w_journal.journal_tab.item(row, 4).text()

        try:
            report_data = self.db.get_current_system_tests(asis=asis, date=date)
            assembly = self.db.get_idobr_assembly(asis)
            report = Report(date=date, data=report_data, assembly=assembly, test_type=test_type)
            report.generate_report()
        except Exception as e:
            self.parent.send_msg('w', 'Generate report error', str(e), 1)

    def fill_temp_combo(self):
        workbook = xlrd.open_workbook('templates/template.xls', formatting_info=True, on_demand=True)
        for k in workbook.sheet_names():
            self.w_journal.templ_combo.addItem(k)

    def fill_tab_header(self):
        """
        Tests journal table
        """
        self.w_journal.journal_tab.setSelectionMode(QAbstractItemView.SingleSelection)
        self.w_journal.journal_tab.setEditTriggers(QAbstractItemView.NoEditTriggers)

        self.w_journal.journal_tab.setRowCount(0)
        self.w_journal.journal_tab.setColumnCount(len(self.header_journal))
        self.w_journal.journal_tab.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
        self.w_journal.journal_tab.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
        self.w_journal.journal_tab.horizontalHeader().setSectionResizeMode(2, QHeaderView.Stretch)
        self.w_journal.journal_tab.horizontalHeader().setSectionResizeMode(3, QHeaderView.Stretch)
        self.w_journal.journal_tab.horizontalHeader().setSectionResizeMode(4, QHeaderView.ResizeToContents)
        self.w_journal.journal_tab.horizontalHeader().setSectionResizeMode(5, QHeaderView.ResizeToContents)

        self.w_journal.journal_tab.setHorizontalHeaderLabels(self.header_journal)

        """
        Tests result table
        """
        self.w_journal.tests_tab.setSelectionMode(QAbstractItemView.SingleSelection)
        self.w_journal.tests_tab.setEditTriggers(QAbstractItemView.NoEditTriggers)

        self.w_journal.tests_tab.setRowCount(0)
        self.w_journal.tests_tab.setColumnCount(len(self.header_tests))
        self.w_journal.tests_tab.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
        self.w_journal.tests_tab.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeToContents)

        self.w_journal.tests_tab.setHorizontalHeaderLabels(self.header_tests)

    """
    Function fill test result table
    and statistic
    """
    def fill_tab_row(self, **kwargs):
        start = self.w_journal.start_date.date().toPyDate()
        stop = self.w_journal.stop_date.date().toPyDate()
        self.w_journal.journal_tab.setRowCount(0)
        rows = self.db.get_test_journal(filter_key=kwargs.get('f_key'),filter_val=kwargs.get('f_val'),
                                        date_start=start, date_stop=stop)
        total_system = {}
        pass_count = 0
        fail_count = 0
        partial_count = 0
        total_tests = len(rows)

        for row in rows:
            total_system.update({row.get('asis'): None})

            curr_sys = self.db.get_idobr_by_asis(row.get('asis'))
            type_test = self.get_type_test(asis=curr_sys.get('asis'), date_test=row.get('date'))

            res = row.get('result')
            if res == 'PASS' and 'partial' not in type_test.lower():
                pass_count += 1
            else:
                partial_count += 1
            if res == 'FAIL':
                fail_count += 1

            if row.get('result') == 'PASS' and 'partial' in type_test.lower():
                result = QTableWidgetItem(QtGui.QIcon(self.parent.warningImg), "")
            elif row.get('result') == 'PASS':
                result = QTableWidgetItem(QtGui.QIcon(self.parent.passImg), "")
            if row.get('result') == 'FAIL':
                result = QTableWidgetItem(QtGui.QIcon(self.parent.failImg), "")
            rowPosition = self.w_journal.journal_tab.rowCount()
            self.w_journal.journal_tab.insertRow(rowPosition)
            self.w_journal.journal_tab.setItem(rowPosition, 0, QTableWidgetItem(curr_sys.get('type')))
            self.w_journal.journal_tab.setItem(rowPosition, 1, QTableWidgetItem(curr_sys.get('asis')))
            self.w_journal.journal_tab.setItem(rowPosition, 2, QTableWidgetItem(curr_sys.get('sn')))
            self.w_journal.journal_tab.setItem(rowPosition, 3, QTableWidgetItem(type_test))
            self.w_journal.journal_tab.setItem(rowPosition, 4, QTableWidgetItem(row.get('date')))
            self.w_journal.journal_tab.setItem(rowPosition, 5, result)
            # self.w_journal.journal_tab.resizeRowsToContents()

        self.w_journal.total_test_stat.setText(str(total_tests))
        self.w_journal.total_system_stat.setText(str(len(total_system.keys())))
        try:
            self.w_journal.pass_stat.setText("{}({}%)".format(str(pass_count),
                                                              str(round(pass_count * 100 / int(total_tests), 1))))
            self.w_journal.partial_stat.setText("{}({}%)".format(str(partial_count),
                                                              str(round(partial_count * 100 / int(total_tests), 1))))
            self.w_journal.fail_stat.setText("{}({}%)".format(str(fail_count),
                                                              str(round(fail_count * 100 / int(total_tests), 1))))
        except ZeroDivisionError:
            self.w_journal.pass_stat.setText("{}({}%)".format('0', '0'))
            self.w_journal.fail_stat.setText("{}({}%)".format('0', '0'))

    """
    Function return type of current test
    Partial or Complete
    """
    def get_type_test(self, **kwargs):
        asis = kwargs.get('asis')
        date = kwargs.get('date_test')
        tests = len(self.db.get_current_system_tests(date=date, asis=asis))
        # ToDo: select test type (FufuiDOBR... etc)
        queue = len(self.parent.get_tests_queue(FufuiDOBR))
        type_test = "Partial test" if tests != queue else "Complete test"
        return type_test

    """
    Function open in new window
    assembly of current system
    """
    def cellDoubleClick(self, row, column):
        if self.header_journal[column] in ["System ASIS", "System SN"]:
            by_asis = self.db.get_idobr_by_asis(self.w_journal.journal_tab.item(row, column).text())
            by_sn = self.db.get_idobr_by_sn(self.w_journal.journal_tab.item(row, column).text())
            system = by_asis if by_asis is not None else by_sn
            assembly = self.db.get_idobr_assembly(system.get('asis'))
            if len(assembly) != 0:
                WindowAssembly(parent=self.parent, assembly=assembly)

    """
    Function show in journal window 
    tests result of current system test
    """
    def cell_select(self, row, column):
        self.w_journal.tests_tab.setRowCount(0)
        date = self.w_journal.journal_tab.item(row, 4).text()
        asis = self.w_journal.journal_tab.item(row, 1).text()
        rows = self.db.get_current_system_tests(date=date, asis=asis)
        for row in rows:
            if row.get('result') == 'PASS':
                result = QTableWidgetItem(QtGui.QIcon(self.parent.passImg), "")
            else:
                result = QTableWidgetItem(QtGui.QIcon(self.parent.failImg), "")
            rowPosition = self.w_journal.tests_tab.rowCount()
            self.w_journal.tests_tab.insertRow(rowPosition)
            self.w_journal.tests_tab.setItem(rowPosition, 0, QTableWidgetItem(row.get('meas')))
            self.w_journal.tests_tab.setItem(rowPosition, 1, QTableWidgetItem(result))


        system = self.db.get_idobr_by_asis(asis=asis)
        # by_sn = self.db.get_idobr_by_sn(self.w_journal.journal_tab.item(row, 2).text())
        # system = by_asis if by_asis is not None else by_sn
        assembly = self.db.get_idobr_assembly(system.get('asis'))
        if len(assembly) != 0:
            self.fill_assembly(assembly)
        self.w_journal.assembly_tree.expandToDepth(1)

    """
    Function build and fill
    assembly tree
    """
    def fill_assembly(self, assembly):
        self.w_journal.assembly_tree.clear()
        system = "{} ASIS: {} SN: {}".format(assembly.get('idobr_type'), assembly.get('idobr_asis'), assembly.get('idobr_sn'))
        root = QTreeWidgetItem(self.w_journal.assembly_tree, [system], 1)
        sub_item_m = QTreeWidgetItem(root, ["master SDR %s ASIS: %s" % (assembly.get('sdr_type_1'), assembly.get('sdr_asis_1'))])
        sub_item_s = QTreeWidgetItem(root, ["slave SDR %s ASIS: %s" % (assembly.get('sdr_type_2'), assembly.get('sdr_asis_2'))])
        QTreeWidgetItem(sub_item_m, ["rf: {} ASIS: {}".format(assembly.get('rf_type_1'), assembly.get('rf_asis_1'))])
        QTreeWidgetItem(sub_item_m, ["rf: {} ASIS: {}".format(assembly.get('rf_type_3'), assembly.get('rf_asis_3'))])
        QTreeWidgetItem(sub_item_s, ["rf: {} ASIS: {}".format(assembly.get('rf_type_2'), assembly.get('rf_asis_2'))])
        QTreeWidgetItem(sub_item_s, ["rf: {} ASIS: {}".format(assembly.get('rf_type_4'), assembly.get('rf_asis_4'))])

    def filter(self):
        f_val = self.w_journal.filter.text().upper()
        self.fill_tab_row(f_val=f_val)

    def eventFilter(self, source, event):
        # ToDo: need fix
        if event.type() == QtCore.QEvent.KeyPress:
            row = self.w_journal.journal_tab.selectedIndexes()[0].row() - 1
            if row >= 0:
                self.cell_select(row, 1)
        return False
示例#19
0
class WindowSettings(QDialog):
    def __init__(self, parent):
        super(WindowSettings, self).__init__(parent)
        self.parent = parent
        self.appIcon = parent.appIcon
        self.w_settings = uic.loadUi('forms/settings.ui')
        self.w_settings.setWindowTitle('Settings')
        self.w_settings.setWindowIcon(self.appIcon)

        self.listInstr = None
        ip_validator = QRegExpValidator(QRegExp(parent.re_ip))
        self.w_settings.ip.setValidator(ip_validator)
        self.w_settings.mask.setValidator(ip_validator)

        self.w_settings.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).clicked.connect(self.is_pressed_ok)
        self.w_settings.buttonBox.button(QtWidgets.QDialogButtonBox.Cancel).clicked.connect(self.is_pressed_cancel)
        self.w_settings.storm_path_btn.clicked.connect(self.select_storm_path)
        self.w_settings.export_btn.clicked.connect(self.export_settings)
        self.w_settings.import_btn.clicked.connect(self.import_settings)

        self.w_settings.combo_gen.currentTextChanged.connect(self.is_generator_changed)
        self.w_settings.combo_sa.currentTextChanged.connect(self.is_analyzer_changed)

        self.db = CobhamDB()
        self.fill_com_ports()
        self.fill_instruments()
        self.load_settings()
        # self.w_settings.exec_()
        self.w_settings.show()

    def is_pressed_ok(self):
        self.save_settings()
        self.w_settings.close()

    def is_pressed_cancel(self):
        self.w_settings.close()

    '''
    Get available COM ports
    '''
    def fill_com_ports(self):
        com_ports = ComPort()
        for i in com_ports.get_port_list():
            self.w_settings.combo_com.addItem(i[0])
        for i in com_ports.get_baud_list():
            self.w_settings.combo_baud.addItem(str(i))

    def fill_instruments(self):
        instr = Instruments(parent=self.parent)
        self.listInstr = instr.getListInstrument()
        instr.rm.close()
        self.w_settings.combo_gen.addItem('', '')
        self.w_settings.combo_sa.addItem('', '')
        for key in self.listInstr.keys():
            self.w_settings.combo_gen.addItem(self.listInstr.get(key))
            self.w_settings.combo_sa.addItem(self.listInstr.get(key))



    def load_settings(self):
        self.gui_write(self.db.get_all_data('settings'))

    def save_settings(self):
        for_query = {}
        values = self.gui_read()
        for _v in values.keys():
            print(_v)
            for_query.update({_v: values.get(_v)[0]})
        self.db.save_settings(for_query)
        self.parent.check_com(False)
        self.parent.check_calibration()
        self.w_settings.close()

    def verify_settings(self):
        return False


    ''''
    Write to the gui values from data base
    '''
    def gui_write(self, for_write):
        struct = self.gui_read()
        for _v in for_write.keys():
            _v = _v.lower()
            try:
                obj = struct.get(_v)[2]
                if obj.__class__ is QComboBox:
                    index = obj.findText(for_write.get(_v), QtCore.Qt.MatchFixedString)
                    if index != -1:
                        obj.setCurrentIndex(index)
                    else:
                        obj.addItem('')
                        obj.setCurrentIndex(obj.count()-1)
                if obj.__class__ is QLineEdit:
                    obj.setText(for_write.get(_v))
                if obj.__class__ is QRadioButton:
                    if for_write.get(_v).lower() == '1':
                        obj.setChecked(True)
            except Exception as e:
                raise e
        self.parent.check_com(False)


    '''
    Fill dictionary with checked values
    '''
    def gui_read(self):
        for_return = {}
        struct = inspect.getmembers(self.w_settings, lambda a:not(inspect.isroutine(a)))
        for i in struct:
            try:
                if i[1].__class__ is QComboBox:
                    for_return.update({i[0]: [i[1].currentText(), i[1].__class__.__name__, i[1]]})
                if i[1].__class__ is QLineEdit:
                    for_return.update({i[0]: [i[1].text(), i[1].__class__.__name__, i[1]]})
                if i[1].__class__ is QRadioButton:
                    n = 1 if i[1].isChecked() else 0
                    for_return.update({i[0]: [n, i[1].__class__.__name__, i[1]]})
            except:
                continue
        return for_return

    def is_generator_changed(self):
        for i in self.listInstr.keys():
            if self.listInstr.get(i) == self.w_settings.combo_gen.currentText():
                self.w_settings.addr_gen.setText(i)
                break
        if self.w_settings.combo_gen.currentText() == self.w_settings.combo_sa.currentText():
            self.w_settings.combo_sa.setCurrentText('')

    def is_analyzer_changed(self):
        for i in self.listInstr.keys():
            if self.listInstr.get(i) == self.w_settings.combo_sa.currentText():
                self.w_settings.addr_sa.setText(i)
                break
        if self.w_settings.combo_gen.currentText() == self.w_settings.combo_sa.currentText():
            self.w_settings.combo_gen.setCurrentText('')

    def select_storm_path(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getOpenFileName(self, "Select Storm Interface file", "", "Executable Files (*.exe)",
                                                  options=options)
        if fileName:
            self.w_settings.storm_path.setText(fileName)

    def export_settings(self):
        cfg = Config(self.parent)
        cfg.cfg_write(self.gui_read())

    def import_settings(self):
        cfg = Config(self.parent)
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getOpenFileName(self, "Select configuration file", "", "Configuration Files (*.ini)",
                                                  options=options)
        tmp = cfg.cfg_read(file=fileName)
        if not tmp is None:
            self.gui_write(tmp)
            self.parent.send_msg('i', 'Import settings', 'Import settings complete', 1)
示例#20
0
class FufuiDOBR(QtCore.QThread):
    def __init__(self, controller, parent=None):
        QtCore.QThread.__init__(self, parent)
        self._stopFlag = False
        self.controller = controller
        self.parent = controller.curr_parent
        self.db = CobhamDB()
        self.db.set_test_type(self.__class__.__name__)
        self.asis = self.parent.w_main.asis_lbl.text()
        self.test_time = datetime.datetime.now().strftime(
            "%Y/%m/%d/, %H:%M:%S")
        self.bands = None
        self.bands_sn = None
        self.sn_list_master = {}
        self.sn_list_slave = {}
        self.filters = {
            'ABCD08': [806, 5, 847],
            'ABCD09': [942.5, 5, 897.5],
            'ABCD18': [1842.5, 5, 1747.5],
            'ABCD21': [2140, 5, 1950]
        }
        self.test_result = {}
        self.current_test_name = None

    def stop_test(self):
        self._stopFlag = True
        print('>>> ', self._stopFlag)

    def set_test_name(self, name):
        self.controller.send_test_name(name, 'Started')
        self.current_test_name = name

    def start_current_test(self, test):
        test_result = getattr(self, test)()
        self.controller.send_test_name(self.current_test_name, 'Completed\n')
        return test_result

    def run_test_check_bands_10(self):
        self.set_test_name('Check bands')
        self.bands = self.get_bands()
        self.bands_sn = self.get_bands_sn()

        status = True
        doubles = {}
        for i in self.bands:
            if i in doubles:
                doubles.update({i: False})
            else:
                doubles.update({i: True})
        if not all(doubles.values()):
            status = False
            self.controller.log_signal.emit(
                'Bands has same names: {}'.format(doubles))
        if not status:
            q = self.controller.send_msg(
                'w', 'Error', 'Bands has same names: {}'.format(doubles), 3)
            if q == QMessageBox.Retry:
                self.check_bands()
        self.controller.log_signal.emit('Check bands: {}'.format(
            self.controller.true_to_pass(status)))
        self.set_assembly()
        # self.db.set_test_result(self.__class__.__name__, inspect.currentframe().f_code.co_name, self.asis,
        #                         self.test_time, self.controller.true_to_pass(status))
        return status

    def run_test_verify_connections_20(self):
        self.set_test_name('Verify connections')
        status = True
        master = True if 'DOBR-M' in self.controller.send_com_command(
            'axsh get MDL') else False
        slave = True if 'DOBR-S' in self.controller.send_com_command(
            'send_msg -d 172.24.30.2 -c "axsh get mdl"') else False
        if not master or not slave:
            status = False
        self.controller.log_signal.emit(
            "Verify connections to both SDR'S: {}".format(
                self.controller.true_to_pass(status)))
        # self.db.set_test_result(self.__class__.__name__, inspect.currentframe().f_code.co_name, self.asis,
        #                         self.test_time, self.controller.true_to_pass(status))
        return status

    def run_test_save_set_file_30(self):
        self.set_test_name('Save set file')
        path = self.parent.wk_dir + '\\!Backup\\{}\\Rev_{}\\{}\\*.csv'.format(
            self.parent.w_main.art_lbl.text(),
            self.parent.w_main.rev_lbl.text(),
            self.parent.w_main.asis_lbl.text())

        self.check_bands()
        self.check_bands_sn()
        is_files_exist = True
        for band in self.bands:
            if not os.path.exists(
                    path.replace("*", "{}_{}".format(
                        band, self.bands_sn.get(band)))):
                is_files_exist = False
        if is_files_exist:
            q = self.controller.send_msg(
                'q', 'Cobham utils', 'All set files already exist.\n'
                'Continue save set files?', 2)
            if q == QMessageBox.Cancel:
                return True

        self.controller.send_com_command('udp_bridge1 restart')
        self.controller.log_signal.emit("Starting udp_bridge")
        storm = Storm(controller=self.controller,
                      bands=self.bands,
                      bands_sn=self.bands_sn)
        for place, band in enumerate(self.bands):
            storm.save_setfile(place=place, band=band)

        paths = ''
        for i in glob.glob(path):
            paths += i
        status = True
        for band in self.bands:
            if not '{}_{}'.format(band, self.bands_sn.get(band)) in paths:
                self.controller.log_signal.emit(
                    'Set file for RF board {} with ASIS: {} not found'.format(
                        band, self.bands_sn.get(band)))
                status = False
        self.controller.send_com_command('udp_bridge1 stop')
        self.controller.log_signal.emit("Stoping udp_bridge")
        return status

    def run_test_band_status_40(self):
        self.set_test_name('Band status')
        tmp = self.controller.send_com_command('dobrstatus --json')
        res = self.controller.str_to_dict(tmp)
        res_list = []
        result = True
        for val in res.get('Bands'):
            if not int(val.get('No')):
                result = False
            if not int(val.get('Band')):
                result = False
            if val.get('Installed').upper() != 'YES':
                result = False
            res_list.append(result)
            self.controller.log_signal.emit('Band {} status = {}'.format(
                val.get('Band'), self.controller.true_to_pass(result)))
        status = all(res_list)
        self.controller.log_signal.emit('Band status: {}'.format(
            self.controller.true_to_pass(status)))
        # self.db.set_test_result(self.__class__.__name__, inspect.currentframe().f_code.co_name, self.asis,
        #                         self.test_time, self.controller.true_to_pass(status))
        return status

    def run_test_set_filters_50(self):
        self.set_test_name('Set filters')
        return self.set_filters(1)

    def run_test_composite_power_60(self):
        self.set_test_name('Composite power')
        test_status = True
        try:
            q = self.controller.send_msg(
                'i', 'DL composite power test',
                'Connect Generator to Base, Spectrum to Mobile using attenuators 30 dB',
                2)
            if q == QMessageBox.Cancel:
                return
            self.check_bands()
            instr = Instruments(controller=self.controller)
            instr.genPreset()
            instr.saPreset()
            for n in range(1, len(self.bands) + 1):
                band_info = self.controller.str_to_dict(
                    self.controller.send_com_command(
                        'dobr_filters GET {} --json'.format(n)))
                band_name = list(band_info.keys())[0]
                start = float(band_info.get(band_name)[0].get('DL_start_freq'))
                stop = float(band_info.get(band_name)[0].get('DL_end_freq'))
                center = start + (stop - start) / 2
                offset = self.db.get_offset(center)
                gen_offset = offset.get('gen')
                sa_offset = offset.get('sa')

                instr.sa.write(
                    "DISP:WIND:TRAC:Y:RLEV:OFFS {}".format(30 + sa_offset))
                instr.sa.write(":SENSE:FREQ:center {} MHz".format(center))
                instr.gen.write(":FREQ:FIX {} MHz".format(center))
                instr.gen.write("POW:AMPL {} dBm".format(-60 + gen_offset))
                instr.gen.write(":OUTP:STAT ON")
                instr.sa.write(":CALC:MARK1:STAT ON")
                time.sleep(3)
                instr.sa.write("CALC:MARK1:MAX")
                time.sleep(1)
                gain = round(float(instr.sa.query("CALC:MARK1:Y?")), 2)
                if gain > 16 or gain < 10:
                    status = 'FAIL'
                    test_status = False
                else:
                    status = 'PASS'
                self.controller.log_signal.emit(
                    '{} DL composite power = {} dB : {}'.format(
                        band_name, gain, status))
                instr.gen.write(":OUTP:STAT OFF")
            self.controller.log_signal.emit('DL composite power: {}'.format(
                self.controller.true_to_pass(test_status)))
            return test_status
        except Exception as e:
            raise e

    def run_test_fft_calibrate_70(self):
        self.set_test_name('FFT calibration')
        self.check_bands()
        fft = FftCalibrate(self.controller, self.bands)
        return fft.run_calibrate()

    def run_test_sw_verification_80(self):
        self.set_test_name('SW version verification')
        need_sw = self.db.get_all_data('settings').get('sw_version').split(';')
        need_patch = self.db.get_all_data('settings').get(
            'patch_version').split(';')

        master_model = self.controller.send_com_command('axsh get mdl')
        master_versions = self.controller.send_com_command('axsh get swv')
        master_patch = self.controller.send_com_command('get_patches.sh')
        status_master = True
        if not self.check_sw(need_sw, master_versions) or not self.check_sw(
                need_patch, master_patch):
            status_master = False
        self.controller.log_signal.emit(
            'SW ver. verification on board {}: {}'.format(
                master_model.strip(),
                self.controller.true_to_pass(status_master)))

        slave_model = self.controller.send_com_command(
            'send_msg -d 172.24.30.2 -c "axsh get mdl"').strip()
        slave_versions = self.controller.send_com_command(
            'send_msg -d 172.24.30.2 -c "axsh get swv"')
        slave_path = self.controller.send_com_command(
            'send_msg -d 172.24.30.2 -c "get_patches.sh"')
        status_slave = True
        if not self.check_sw(need_sw, slave_versions) or not self.check_sw(
                need_patch, slave_path):
            status_slave = False
        self.controller.log_signal.emit(
            'SW ver. verification on board {}: {}'.format(
                slave_model.strip(),
                self.controller.true_to_pass(status_slave)))
        return any([status_master, status_slave])

    def run_test_mute_90(self):
        self.set_test_name('System mute')
        status = True
        self.check_bands()
        for band in range(1, len(self.bands) + 1):
            self.controller.log_signal.emit(
                'Set band {} Transmission: Disable'.format(self.bands[band -
                                                                      1]))
            self.controller.send_com_command(
                'dobr_pa_control SET {} {}'.format(band, 0))

        self.set_filters(0)

        answer = self.controller.send_msg(
            'i', 'Mute test', 'Is all leds on the rf boards are RED?', 2)
        if answer != QMessageBox.Ok:
            status = False

        for band in range(1, len(self.bands) + 1):
            self.controller.log_signal.emit(
                'Set band {} Transmission: Enable'.format(self.bands[band -
                                                                     1]))
            self.controller.send_com_command(
                'dobr_pa_control SET {} {}'.format(band, 1))
        self.set_filters(1)

        answer = self.controller.send_msg(
            'i', 'Mute test', 'Is all leds on the rf boards are GREEN?', 2)
        if answer != QMessageBox.Ok:
            status = False
        return status

    def run_test_ext_alarm_100(self):
        self.set_test_name('External alarms')
        self.controller.send_com_command('axsh SET EXT 0 0 0 0')
        keys = ['7', '6', '5', '4']
        res_list = []
        for n, pin in enumerate(keys):
            counter = 3
            while True:
                alarms = self.get_ext_alarm()
                if alarms.get(pin) == '0':
                    curr_status = True
                    res_list.append(curr_status)
                    self.controller.log_signal.emit(
                        'EXT{} alarm: PASS'.format(pin))
                    break
                else:
                    # self.controller.send_msg('i', 'Alarms test', 'Short pin {} to the chassis'.format(pin), 1)
                    counter -= 1
                    if counter < 0:
                        res_list.append(False)
                        self.controller.log_signal.emit(
                            'EXT{} alarm: FAIL'.format(pin))
                        break
            self.controller.progress_bar_signal.emit(len(keys), n + 1)
        status = self.controller.true_to_pass(all(res_list))
        self.controller.log_signal.emit('External alarms: {}'.format(status))
        # self.db.set_test_result(self.__class__.__name__, inspect.currentframe().f_code.co_name, self.asis,
        #                         self.test_time, self.controller.true_to_pass(status))

        return all(res_list)

    def run_test_gpr_gps_110(self):
        gps_status = False
        modem_status = False
        is_modem_printed = False
        is_gps_printed = False
        ip = ''

        self.set_test_name('GPS & GPRS')
        self.controller.send_msg(
            'i', 'GPR & GPS',
            'Connect GPS and GPR antenna, and insert sim card', 1)
        test_start = datetime.datetime.now().timestamp()
        self.controller.log_signal.emit(
            'Enable Remote and Modem Communication: {}'.format(
                self.set_remote_communication(1)))

        gde = int(
            self.controller.send_com_command('axsh GET CDE').split(' ')[0])
        gpr = int(self.controller.send_com_command('axsh GET GPR ENB'))
        apn = self.controller.send_com_command('axsh GET GPR APN').strip()

        if gde != 1 or gpr != 1 or apn != self.db.get_all_data('settings').get(
                'apn_name'):
            self.controller.log_signal.emit(
                'gpr_gps_test: initialisation FAIL')
            return
        else:
            self.controller.log_signal.emit(
                'gpr_gps_test: initialisation PASS')

        self.controller.log_signal.emit('Checking USB devices...')
        printed_device = []
        while True:
            tmp = self.controller.send_com_command('lsusb').replace(
                '\r', '').split('\n')
            delta = datetime.datetime.now().timestamp() - test_start
            tmp = list(filter(lambda x: x != '', tmp))

            if len(tmp) > 2:
                for i in tmp:
                    self.controller.log_signal_arg.emit(i, -1)
                return False
            if len(tmp) > 0:
                for i in tmp:
                    if i not in printed_device:
                        self.controller.log_signal.emit(
                            'Found USB device: {}'.format(i))
                        printed_device.append(i)
            if len(tmp) == 2:
                break
            if delta > 180 and len(tmp) < 2:
                self.controller.log_signal.emit(
                    'Checking USB devices: found only {} USB device'.format(
                        len(tmp)))
                return False
            time.sleep(3)

        while True:
            time_wait = int(
                self.db.get_all_data('settings').get('modem_timeout'))
            cur_time = time.time()
            delta_time = int(cur_time - test_start)
            if delta_time % 5 == 0:
                if int(self.controller.send_com_command(
                        'axsh GET GPR STATUS')) == 1 and not modem_status:
                    modem_status = True
                    if not is_modem_printed:
                        self.controller.log_signal.emit(
                            'Modem test: {}'.format(modem_status))
                        ip = self.get_ip_by_iface('wwan0')
                        self.controller.log_signal.emit(
                            'IP address: {}'.format(ip))
                        is_modem_printed = True

                tmp = self.controller.send_com_command(
                    'read_gps_coordinates.sh')
                gps_arr = self.controller.str_to_dict(tmp)['coordinates'][0]
                if gps_arr['x'] != 0.0 and gps_arr[
                        'y'] != 0.0 and not gps_status:
                    gps_status = True
                    if not is_gps_printed:
                        self.controller.log_signal.emit(
                            'GPS test: {}'.format(gps_status))
                        self.controller.log_signal.emit(
                            'Coordinates: {} : {}'.format(
                                gps_arr['x'], gps_arr['y']))
                        is_gps_printed = True
                if gps_status and modem_status:
                    break
            if delta_time // 60 >= time_wait:
                break
            time.sleep(.5)
        result = all([gps_status, modem_status])
        if result:
            self.controller.log_signal.emit(
                'Disable Remote and Modem Communication: {}'.format(
                    self.set_remote_communication(0)))
            self.controller.send_msg(
                'i', 'GPR & GPS',
                'Disconnect GPS and GPR antenna, and replace sim card', 1)
        return result

    def run_test_set_static_ip_120(self):
        self.set_test_name('Set static IP')
        ip = self.db.get_all_data('settings').get('ip')
        mask = self.db.get_all_data('settings').get('mask')
        tmp = re.search('^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}',
                        mask).group(0)
        gtw = tmp + '254'
        # ToDo: check ip
        self.controller.send_com_command(
            'axsh SET NIC eth0 STATIC {} {} {}'.format(ip, mask, gtw))
        self.controller.send_com_command(
            'ifconfig eth0 {} netmask {} up'.format(ip, mask))
        curr_ip = self.controller.get_ip()
        if ip != curr_ip[1] or curr_ip[0] != 'STATIC':
            self.controller.send_msg('w', 'Cobham FuFu',
                                     'Trying set static ip is FAIL', 1)
            for_return = False
        else:
            for_return = True
        self.controller.log_signal.emit('Setting static IP: {}'.format(
            self.controller.true_to_pass(for_return)))
        return for_return

    def run_test_clear_log_130(self):
        self.set_test_name('Clear system log')
        logs = self.controller.send_com_command('alarms numoflogs --json')
        logs = self.controller.str_to_dict(logs)
        num_logs = logs.get('NumOfLogs')[0].get('NUM')
        self.controller.log_signal.emit(
            'Found {} logs in system'.format(num_logs))
        if num_logs == '0':
            return True
        self.controller.log_signal.emit('Deleting logs')
        self.controller.send_com_command('alarms logsclear')
        time.sleep(3)
        logs = self.controller.send_com_command('alarms numoflogs --json')
        logs = self.controller.str_to_dict(logs)
        num_logs = logs.get('NumOfLogs')[0].get('NUM')
        self.controller.log_signal.emit(
            'Found {} logs in system'.format(num_logs))
        if num_logs != '0':
            q = self.controller.send_msg('w', 'Clear logs',
                                         'Not all logs deleted.', 3)
            if q == QMessageBox.Retry:
                self.run_test_clear_log_130()
            elif q == QMessageBox.Cancel:
                return False
        else:
            return True

    def get_sdr_info(self):
        info = {}
        for i in ['master_sdr', 'slave_sdr']:
            if i == 'master_sdr':
                pref = ''
            else:
                pref = 'send_msg -d 172.24.30.2 -c '
            val = self.controller.send_com_command(pref +
                                                   'axsh get sis').split(' ')
            info.update({i: {'type': val[2], 'asis': val[3]}})
        return info

    def set_assembly(self):
        db = CobhamDB()
        assembly = {}
        for i, j in enumerate(self.bands):
            assembly.update({'rf_type_{}'.format(i + 1): j})
            assembly.update({'rf_asis_{}'.format(i + 1): self.bands_sn.get(j)})
        idobr = self.get_sdr_info()
        assembly.update({'sdr_type_1': idobr.get('master_sdr').get('type')})
        assembly.update({'sdr_asis_1': idobr.get('master_sdr').get('asis')})
        assembly.update({'sdr_type_2': idobr.get('slave_sdr').get('type')})
        assembly.update({'sdr_asis_2': idobr.get('slave_sdr').get('asis')})
        assembly.update({'idobr_type': self.parent.system_type})
        assembly.update({'idobr_asis': self.parent.system_asis})
        assembly.update({'idobr_sn': self.parent.system_sn})
        if len(db.get_idobr_assembly(self.parent.system_asis)) != 0:
            diff = db.compare_assembly(assembly)
            if not diff.get("diff"):
                raise ValueError(
                    'Assembly between DB and system have difference:\n'
                    'System: {}\n'
                    'DB    : {}'.format(diff.get("diff_sys"),
                                        diff.get("diff_db")))

        # assembly.update(self.controller.get_sdr_info())
        # assembly.update({'rf_master': self.sn_list_master})
        # assembly.update({'rf_slave': self.sn_list_slave})
        # assembly.update({'idobr': {'type': self.parent.system_type, 'asis': self.parent.system_asis}})

        if db.set_idobr_assembly(assembly):
            self.controller.log_signal.emit('Creating assembly completed')
        else:
            # ToDo: verify assembly
            self.controller.log_signal_arg.emit(
                'Creating assembly not completed', -1)

    def get_bands(self):
        bands = []
        q = self.controller.send_com_command('udp_bridge1 list').split('\n')
        for i in q:
            r = re.search('(ABCD\d\d)', i)
            if r is not None:
                snap = r.group(0)
                tmp = str(int(re.search('\d{2}$', snap).group(0))) + '00'
                if i.find(tmp) == -1:
                    freq = re.search('\d{3,4}', i).group(0)
                    self.controller.log_signal.emit(
                        'Band {}: incorrect SnapId: {}'.format(freq, snap))
                else:
                    self.controller.log_signal.emit(
                        'Band {} detected: SnapId: {}'.format(tmp, snap))
                bands.append(snap)
        if len(bands) != 4:
            q = self.controller.send_msg(
                'w', 'Error', 'Found only {} bands'.format(len(bands)), 3)
            if q == QMessageBox.Retry:
                self.get_bands()
            return None
        return bands

    def get_bands_sn(self):
        sn_list = {}
        self.check_bands()
        for i, j in enumerate(self.bands):
            n = i % 2
            while 1:
                q = self.get_sn(i, n)
                if q.get('is_err') is not None or q.get('None') is not None:
                    self.controller.log_signal.emit(
                        'Get band {} ASIS error. Retrying'.format(j))
                    time.sleep(1)
                    continue
                else:
                    sn = q.get('sn')
                    break
            sn_list.update({j: sn})
            if i < 2:
                self.sn_list_master.update({j: sn})
            else:
                self.sn_list_slave.update({j: sn})
            self.controller.log_signal.emit('Band {} ASIS = {}'.format(j, sn))
        return sn_list

    def get_sn(self, i, n):
        sn = None
        if i < 2:
            tmp = self.controller.send_com_command(
                'dobr_partNum GET {}'.format(n + 1))
        else:
            tmp = self.controller.send_com_command(
                'send_msg -d 172.24.30.2 -c dobr_partNum GET {}'.format(n + 1))
        is_err = re.search('(ERROR)', tmp)
        is_sn = re.search('[A-Z0-9]{4}', tmp)
        if is_sn is None or is_sn.group(0) is None:
            self.get_sn(i, n)
        else:
            sn = is_sn.group(0)
        return {'is_err': is_err, 'sn': sn}

    def set_test_result(self):
        # ToDo: save test result
        # self.db.set_test_result(test_type=inspect.currentframe().f_code.co_name,
        #                         asis=self.asis,
        #                         date_test=self.test_time,
        #                         meas=
        #                         )
        # self.db.set_test_result(, , self.asis,
        #                         , self.controller.true_to_pass(status))
        pass

    def check_sw(self, need, current):
        for ver in need:
            if str(ver).upper() not in current.upper():
                self.controller.log_signal.emit(
                    'Software version {} not equal current version {}'.format(
                        need, current))
                return False
        return True

    def get_ext_alarm(self):
        alarms = {}
        tmp = self.controller.send_com_command('get_ext_alarm.sh').split(
            '\r\n')
        for i in tmp:
            if re.search(r'(EXT_ALM)', i) is None or i == '':
                continue
            alarms.update({
                re.search(r'(^\d)', i).group():
                re.search(r'(\d$)', i).group()
            })
        print(alarms)
        return alarms

    def set_filters(self, enable_filter):
        self.check_bands()
        val = 'ENABLE' if enable_filter == 1 else 'DISABLE'
        test_status = True
        self.controller.log_signal.emit('Filters: {}'.format(val))
        # dobr_filters SET |band_index| |filter_num| |Tag| |Enable| |Tech| |DL_start_freq|
        #                  |DL_stop_freq| |DL_max_power| |DL_max_gain| |power_delta| |Gain_delta|
        for n, band in enumerate(self.bands):
            self.controller.log_signal.emit(
                'Setting filter for {}'.format(band))
            conf_filter = self.filters.get(band)
            band_index = n + 1
            tech = 'GSM'
            center = float(conf_filter[0])
            bw = float(conf_filter[1])
            DL_start_freq = center - (bw / 2)
            DL_stop_freq = center + (bw / 2)

            res = self.controller.send_com_command(
                'dobr_filters SET {} 1 1 {} {} {} {} 24 73 3 0'.format(
                    band_index, enable_filter, tech, DL_start_freq,
                    DL_stop_freq))
            res = self.controller.str_to_dict(res)
            self.controller.send_com_command(
                'dobr_pa_control SET {} {}'.format(band_index, enable_filter))
            self.set_imop_status(n + 1, 0)
            res_filter = res['DOBR FILTER'][0]['Status']
            self.controller.log_signal.emit('Set filter {}: {}'.format(
                band, res_filter))
            if res_filter != 'SUCCESS':
                self.controller.log_signal.emit(res['DOBR FILTER'][0]['Info'])
                test_status = False
            self.controller.progress_bar_signal.emit(len(self.bands), n + 1)
        return test_status

    def set_imop_status(self, band, status):
        self.controller.send_com_command('imop_control SET {} {}'.format(
            band, status))

    def set_remote_communication(self, status):
        # Remote Communication:    axsh SET CDE 1
        # Enable Modem Connection: axsh SET GPR ENB 0
        # Check Modem Connection: asch GET GPR STATUS
        self.controller.send_com_command('axsh SET CDE {}'.format(status))
        self.controller.send_com_command('axsh SET GPR ENB {}'.format(status))
        if status == 1:
            self.controller.send_com_command('axsh SET GPR APN {}'.format(
                self.db.get_all_data('settings').get('apn_name')))
        else:
            self.controller.send_com_command("axsh SET GPR APN ''")

        comm = int(
            self.controller.send_com_command(
                'axsh GET CDE'.format(status)).split(' ')[0])
        modem = int(self.controller.send_com_command('axsh GET GPR ENB'))
        test = [int(comm), int(modem)]
        apn = self.controller.send_com_command('axsh GET GPR APN').strip()

        if status == 0 and apn == '':
            test.append(0)
        if status == 1 and apn == self.db.get_all_data('settings').get(
                'apn_name'):
            test.append(1)

        if status == 0 and sum(test) == 0:
            return True
        elif status == 1 and sum(test) == 3:
            return True
        else:
            return False

    def check_bands(self):
        if self.bands is None:
            self.bands = self.get_bands()

    def check_bands_sn(self):
        if self.bands_sn is None:
            self.bands_sn = self.get_bands_sn()

    def get_ip_by_iface(self, iface):
        tmp = self.controller.send_com_command(
            "ifconfig {} | grep 'inet addr:' | cut -d: -f2".format(
                iface)).replace('Bcast', '')
        return tmp
示例#21
0
class FftCalibrate:
    def __init__(self, controller, bands):
        self.controller = controller
        self.bands = bands
        self.test_status = True
        self.instr = Instruments(controller=self.controller)
        self.db = CobhamDB()
        self.instr.genPreset()
        # self.instr.saPreset()
        # {band_number: [UL, DL]}
        self.band_uldl = {}
        self.band_fft = {1: [2, 3], 2: [0, 1], 3: [6, 7], 4: [4, 5]}

    def run_calibrate(self):
        all_bands = self.controller.str_to_dict(
            self.controller.send_com_command('bands --json')).get('bands')
        for n, band in enumerate(self.bands):
            n = n + 1
            band_info = self.controller.str_to_dict(
                self.controller.send_com_command(
                    'dobr_filters GET {} --json'.format(n)))
            band_name = list(band_info.keys())[0]
            band_name_freq = re.search('(\d){3,4}', band_name).group(0)
            start = float(band_info.get(band_name)[0].get('DL_start_freq'))
            stop = float(band_info.get(band_name)[0].get('DL_end_freq'))
            dl_center = start + (stop - start) / 2
            for band in all_bands:
                if band.get('Band') == band_name_freq:
                    '''
                    get data for calculate uplink freq
                    '''
                    apac = int(band.get('APAC'))
                    duplex = int(band.get('Duplex')) / 1000000
                    if apac == 1:
                        ul_center = dl_center - duplex
                    elif apac == 0:
                        ul_center = dl_center + duplex
                    else:
                        raise ValueError()
                    self.band_uldl.update({n: [ul_center, dl_center]})
        q = self.controller.send_msg(
            'i', 'FFT calibration',
            'Connect Generator to the Base port using attenuators 30 dB', 1)
        if q == QMessageBox.Ok:
            for i in self.band_uldl.keys():
                self.get_peak(i, 1)
        q = self.controller.send_msg(
            'i', 'FFT calibration',
            'Connect Generator to the Mobile port using attenuators 30 dB', 1)
        if q == QMessageBox.Ok:
            for i in self.band_uldl.keys():
                self.get_peak(i, 0)
        self.controller.log_signal.emit('FFT calibration: {}'.format(
            self.controller.true_to_pass(self.test_status)))
        return self.test_status

    def get_peak(self, band_number, uldl):
        try:
            if uldl == 0:
                uldl_name = 'Uplink'
            else:
                uldl_name = 'Downlink'
            center_freq = self.band_uldl.get(band_number)[uldl]
            offset = self.db.get_offset(center_freq)
            # self.instr.sa.write(":SENSE:FREQ:center {} MHz".format(center_freq))
            self.instr.gen.write(":FREQ:FIX {} MHz".format(center_freq))
            self.instr.gen.write("POW:AMPL {} dBm".format(-60 +
                                                          offset.get('gen')))
            self.instr.gen.write(":OUTP:STAT ON")
            self.controller.send_com_command('axsh SET fft {} -195'.format(
                self.band_fft[band_number][uldl]))
            time.sleep(1)
            tmp_gain = self.controller.send_com_command(
                'fft.lua json {} 0 1'.format(
                    self.band_fft[band_number][uldl])).strip()
            res = self.controller.str_to_dict(tmp_gain)
            curr_fft = (int(max(res['data'])) + 60) * (-1)
            self.controller.send_com_command('axsh SET fft {} {}'.format(
                self.band_fft[band_number][uldl], curr_fft))
            # ToDo: every time res.get('band') is 800 ???????
            print(res.get('band'))
            fft = self.controller.send_com_command('axsh GET fft {}'.format(
                self.band_fft[band_number][uldl])).strip()
            gain = int(fft) + int(max(res['data']))

            fft_delta = abs(202 - abs(curr_fft))
            if fft_delta > 10:
                self.test_status = False
            self.controller.log_signal.emit('{} {} FFT = {} Gain = {} '.format(
                res.get('band'), uldl_name, fft, gain))
            self.instr.gen.write(":OUTP:STAT OFF")
        except Exception as e:
            print(e)
            self.controller.log_signal.emit('Get peak error, retrying')
            self.get_peak(band_number, uldl)
示例#22
0
class MainApp(QMainWindow, QObject):
    LOG_FILENAME = './Log/cobham_utils.log'
    logging.basicConfig(filename=LOG_FILENAME, level=logging.ERROR)
    re_ip = r"^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.)){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"

    def __init__(self, parent=None):
        # logging.debug('This message should go to the log file')
        # logging.info('So should this')
        # logging.warning('And this, too')

        super(MainApp, self).__init__(parent)
        self.db = CobhamDB()
        self.cfg = Config(self)

        self.system_type = ''
        self.system_asis = ''
        self.system_sn = ''

        self.wk_dir = os.path.dirname(os.path.realpath('__file__'))
        self.appIcon = QtGui.QIcon("img/cobham_c_64x64.ico")
        self.w_main = uic.loadUi('forms/mainwindow.ui')
        self.w_main.setWindowTitle('CobhamUtils {}'.format(VERSION))
        self.w_main.setWindowIcon(self.appIcon)

        self.login_msg = 'root@AxellShell[root]'
        self.answer = None
        self.controller_thread = None
        self.calibration_thread = None
        self.tests_queue = {}
        self.test_type = ''

        self.passImg = QtGui.QPixmap('Img/pass.png').scaled(30, 30)
        self.failImg = QtGui.QPixmap('Img/fail.png').scaled(30, 30)
        self.warningImg = QtGui.QPixmap('Img/warning.png').scaled(30, 30)
        self.greenLedMovie = QMovie('Img/greenLed.gif')
        self.blueLedMovie = QMovie('Img/blueLed.gif')
        self.redLedMovie = QMovie('Img/redLed.gif')

        self.w_main.start_test_btn.clicked.connect(self.test)
        self.w_main.selectall_chbox.clicked.connect(self.select_all)
        self.w_main.calibration_btn.clicked.connect(self.calibration)
        self.w_main.new_test_btn.clicked.connect(self.new_test)
        self.w_main.menu_Settings.triggered.connect(self.window_settings)
        self.w_main.menu_TestJournal.triggered.connect(self.window_test_journal)
        self.w_main.menu_test.triggered.connect(self.send_img_msg)
        self.w_main.menu_Quit.triggered.connect(self.w_main.close)
        self.w_main.menu_Quit.setShortcut('Ctrl+Q')

        self.check_com(False)
        self.set_progress_bar(1, 0)

        self.w_main.show()

        self.stop_event = threading.Event()
        self.c_thread = EventListener(self)
        self.c_thread.timer_signal.connect(self.set_timer, QtCore.Qt.QueuedConnection)
        self.c_thread.start()

    def fill_test_tab(self):
        self.w_main.tests_tab.setSelectionMode(QAbstractItemView.SingleSelection)
        self.w_main.tests_tab.setEditTriggers(QAbstractItemView.NoEditTriggers)

        self.w_main.tests_tab.setRowCount(0)
        self.w_main.tests_tab.setColumnCount(3)
        self.w_main.tests_tab.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeToContents)
        self.w_main.tests_tab.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
        self.w_main.tests_tab.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeToContents)

        self.w_main.tests_tab.setHorizontalHeaderLabels(["", "Test name", ""])
        # self.w_main.tests_tab.horizontalHeaderItem(0).setToolTip("Column 1 ")
        # self.w_main.tests_tab.horizontalHeaderItem(1).setToolTip("Column 2 ")

        test_dict = self.get_tests_queue(getattr(sys.modules[__name__], self.test_type))
        keys = sorted(list(test_dict.keys()))
        for key in keys:
            rowPosition = self.w_main.tests_tab.rowCount()
            chkBoxItem = QTableWidgetItem()
            chkBoxItem.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
            chkBoxItem.setCheckState(QtCore.Qt.Checked)

            self.w_main.tests_tab.insertRow(rowPosition)
            self.w_main.tests_tab.setItem(rowPosition, 0, chkBoxItem)
            self.w_main.tests_tab.setItem(rowPosition, 1, QTableWidgetItem(test_dict.get(key)[0]))
            self.w_main.tests_tab.setItem(rowPosition, 2, None)
            self.w_main.tests_tab.resizeRowsToContents()

    def set_test_status(self, rowPosition, status):
        if status:
            result = QTableWidgetItem(QtGui.QIcon(self.passImg), "")
        else:
            result = QTableWidgetItem(QtGui.QIcon(self.failImg), "")
        self.w_main.tests_tab.setItem(rowPosition, 2, result)

    def get_tests_queue(self, object):
        methods = [method_name for method_name in dir(object) if callable(getattr(object, method_name))]
        self.tests_queue = {}
        for i in methods:
            if 'run_test_' in i:
                try:
                    n = re.search('[\d]+$', i).group(0)
                    name = i.replace('run_test_', '').replace('_{}'.format(n), '').replace('_', ' ').upper()
                    tests_names = [name, i]
                    self.tests_queue.update({int(n): tests_names})
                except:
                    self.send_msg('c', 'CobhamUtils', 'Not found queue number in method {}'.format(i), 1)
                    return
        return self.tests_queue

    def select_all(self):
        state = self.w_main.selectall_chbox.checkState()
        count = self.w_main.tests_tab.rowCount()
        for x in range(0, count):
            self.w_main.tests_tab.item(x, 0).setCheckState(state)

    def check_com(self, val):
        self.w_main.port_lbl.setText(self.db.get_settings_by_name('combo_com'))
        self.w_main.baud_lbl.setText(self.db.get_settings_by_name('combo_baud'))
        self.greenLedMovie.setScaledSize(QSize(13, 13))
        isPortPresent = False
        for i in ComPort.get_port_list():
            if self.db.get_settings_by_name('combo_com') == i[0]:
                isPortPresent = True
        if isPortPresent:
            if val:
                self.w_main.comstat_lbl.setMovie(self.greenLedMovie)
                self.greenLedMovie.start()
            else:
                self.w_main.comstat_lbl.setMovie(self.blueLedMovie)
                self.blueLedMovie.start()
        else:
            self.w_main.comstat_lbl.setMovie(self.redLedMovie)
            self.redLedMovie.start()

    def check_calibration(self):
        icon = self.passImg
        is_calibrated = False
        try:
            # ToDo: modify check calibration algorithm
            cal_date = self.db.get_settings_by_name('last_calibr')
            start = int(self.db.get_settings_by_name('cal_start'))
            stop = int(self.db.get_settings_by_name('cal_stop'))
            step = int(self.db.get_settings_by_name('cal_steep'))
            # for i in range(start, stop, step):
            #     tmp = self.db.get_offset(i)
            #     print(tmp)
            # print(datetime.strptime(cal_date, '%Y-%m-%d'))
            self.w_main.calstat_lbl.setToolTip('Calibration date: {}'.format(cal_date))
            is_calibrated = True
        except:
            icon = self.failImg
        finally:
            self.w_main.start_test_btn.setEnabled(is_calibrated)
            self.w_main.calstat_lbl.setPixmap(icon)
            return is_calibrated

    def test(self):
        if self.w_main.start_test_btn.text() == 'START':
            self.run_controller(type_test=self.test_type)
        else:
            if self.send_msg('i', 'CobhamUtils', 'Are you want stop test?', 2) == QMessageBox.Ok:
                # with futures.ThreadPoolExecutor(1) as executor:
                #     executor.submit(self.controller_thread.test)
                self.controller_thread.curr_test = None
                # self.controller_thread.curr_test.stop_test()


    def calibration(self):
        WindowCalibration(self)
        # Calibration(self)
        # self.run_controller(type_test='calibration')
        # self.check_calibration()

    def run_controller(self, **kwargs):
        # self.w_main.art_lbl.setText('')
        # self.w_main.rev_lbl.setText('')
        # self.w_main.asis_lbl.setText('')
        # self.w_main.ip_lbl.setText('')
        self.w_main.list_log.clear()
        count = self.w_main.tests_tab.rowCount()
        for rowPosition in range(0, count):
            self.w_main.tests_tab.setItem(rowPosition, 2, None)

        # if kwargs.get('type_test') == 'test':
        #     val = self.input_msg('Scan SN:')


        self.controller_thread = TestController(curr_parent=self, type_test=kwargs.get('type_test'))
        self.controller_thread.log_signal.connect(self.send_log, QtCore.Qt.QueuedConnection)
        self.controller_thread.log_signal_arg.connect(self.send_log, QtCore.Qt.QueuedConnection)
        self.controller_thread.timer_signal.connect(self.set_timer, QtCore.Qt.QueuedConnection)
        self.controller_thread.msg_signal.connect(self.send_msg, QtCore.Qt.QueuedConnection)
        self.controller_thread.input_signal.connect(self.input_msg, QtCore.Qt.QueuedConnection)
        self.controller_thread.set_label_signal.connect(self.set_label_text, QtCore.Qt.QueuedConnection)
        self.controller_thread.check_com_signal.connect(self.check_com, QtCore.Qt.QueuedConnection)
        self.controller_thread.test_result_signal.connect(self.set_test_status, QtCore.Qt.QueuedConnection)
        self.controller_thread.progress_bar_signal.connect(self.set_progress_bar, QtCore.Qt.QueuedConnection)

        self.controller_thread.started.connect(self.on_started)
        self.controller_thread.finished.connect(self.on_finished)

        self.controller_thread.start()

    def on_started(self):
        self.set_progress_bar(0, 0)

    def on_finished(self):
        self.set_progress_bar(1, 1)

    def set_progress_bar(self, pmax, pval):
        self.w_main.progressBar.setMaximum(pmax)
        self.w_main.progressBar.setValue(pval)

    def window_settings(self):
        WindowSettings(self)

    def window_test_journal(self):
        WindowTestJournal(self)

    def send_log(self, *args):
        self.w_main.list_log.addItem(args[0])
        if len(args) > 1:
            numrows = len(self.w_main.list_log)
            if args[1] == 1:
                self.w_main.list_log.item(numrows - 1).setForeground(QtCore.Qt.green)
            if args[1] == -1:
                self.w_main.list_log.item(numrows - 1).setForeground(QtCore.Qt.red)
        self.w_main.list_log.scrollToBottom()

    def send_log_same_line(self, *args):
        numrows = len(self.w_main.list_log)
        try:
            print(self.w_main.list_log.currentRow())
        except Exception as e:
            print(e)
        self.w_main.list_log.addItem(args[0])
        self.w_main.list_log.scrollToBottom()

    def set_timer(self, val):
        # val should be in ms
        timer = time.strftime('%M:%S', time.gmtime(val))
        self.w_main.timer_label.setText(str(timer))

    def set_label_text(self, label, value):
        obj = self.w_main.__dict__.get(label)
        obj.setText(value)

    def send_msg(self, icon, msgTitle, msgText, typeQuestion):
        msg = QMessageBox()
        if icon == 'q':
            msg.setIcon(QMessageBox.Question)
        elif icon == 'i':
            msg.setIcon(QMessageBox.Information)
        elif icon == 'w':
            msg.setIcon(QMessageBox.Warning)
        elif icon == 'c':
            msg.setIcon(QMessageBox.Critical)
        msg.setText(msgText)
        msg.setWindowTitle(msgTitle)
        msg.setWindowIcon(self.appIcon)
        if typeQuestion == 1:
            msg.setStandardButtons(QMessageBox.Ok)
        elif typeQuestion == 2:
            msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
        elif typeQuestion == 3:
            msg.setStandardButtons(QMessageBox.Ignore | QMessageBox.Retry | QMessageBox.Cancel)
        elif typeQuestion == 4:
            msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        elif typeQuestion == 5:
            msg.setStandardButtons(QMessageBox.Retry | QMessageBox.Cancel)
        self.answer = msg.exec_()
        return self.answer

    def send_img_msg(self, title, image_text, image):
        # title = 'DL composite power test'
        # image_text = 'Connect Generator to Base, Spectrum to Mobile using attenuators 30 dB'
        # image = 'test.png'
        self.answer = ImageMessage(self, title=title, text=image_text, image=image).get_answer()
        print(self.answer)
        return self.answer


    def new_test(self):
        # ToDo: temporary
        val = self.input_msg('Scan system barcode:')
        # val = 'DOBR0292/NUER'
        if not val:
            return
        else:
            tmp = val.split('/')
            if len(tmp) != 2:
                self.send_msg('w', 'Warning', 'Entered incorrect number', 1)

            self.system_type = tmp[0]
            self.system_asis = tmp[1]
            tests = self.cfg.cfg_read(file='./systems_config.ini', section='systems')
            val = tests.get(self.system_type.upper())

            if val is not None:
                # ToDo: temporary
                sn = self.input_msg('Input system SN:')
                # sn = '112018000030'
                self.system_sn = sn
                if sn is None:
                    return
                match = re.search('^(0[1-9])|(1[0-2])20((1[8-9])|(2[0-9]))[0-9]{6}$', sn)
                if not match:
                    match = re.search('^[0-9]{8}$', sn)
                if not match:
                    self.send_msg('i', 'CobhamUtils', 'Incorrect SN', 1)
                    return False
                else:
                    res = True
                    idobr = self.db.get_idobr_by_asis(self.system_asis)
                    if idobr and idobr.get('sn') not in match.group(0):
                        res = False
                        self.send_msg('i', 'CobhamUtils', 'Found iDOBR {}\nwith ASIS: {}\n'
                                                              'and another SN: {}'
                                          .format(idobr.get('type'), idobr.get('asis'), idobr.get('sn')), 1)
                    idobr = self.db.get_idobr_by_sn(sn)
                    if idobr and idobr.get('asis') != self.system_asis:
                        res = False
                        self.send_msg('i', 'CobhamUtils', 'Found iDOBR {}\nwith SN: {}\n'
                                                          'and another ASIS: {}'
                                      .format(idobr.get('type'), idobr.get('sn'), idobr.get('asis')), 1)
                    if not res:
                        return res


                test_list = []
                for i in val.split(';'):
                    test_list.append(i)
                self.test_type = WindowTestSelect(parent=self, tests=test_list).test_type
                if self.test_type == '':
                    return
                if not self.check_calibration():
                    self.w_main.start_test_btn.setEnabled(False)
            else:
                self.send_msg('i', 'CobhamUtils', 'Tests for system {} is not available'.format(self.system_type), 1)
                return

            l = len(tmp[0])
            self.w_main.art_lbl.setText(tmp[0][:l - 1])
            self.w_main.rev_lbl.setText(tmp[0][l - 1:])
            self.w_main.asis_lbl.setText(tmp[1])

        try:
            self.fill_test_tab()
        except:
            self.send_msg('c', 'CobhamUtils', '{} class not found'.format(self.test_type), 1)
            self.w_main.art_lbl.setText("")
            self.w_main.rev_lbl.setText("")
            self.w_main.asis_lbl.setText("")
            return

    def input_msg(self, msg):
        input = QInputDialog()
        input.setWindowIcon(self.appIcon)
        text, okPressed = input.getText(self, 'Input', msg)
        if okPressed and text != '':
            return text
        return None