Beispiel #1
0
 def resume(self):
     log.debug('Supervision is finished.')
     self.start_supervision_pushbutton.setText('开始监控')
     self.open_serial_pushbutton.setEnabled(True)
     self.look_result_pushbutton.setEnabled(True)
     # Copy log.txt to result dir
     shutil.copy(conf.LOG_FILE, self.base_dir)
Beispiel #2
0
    def refresh_camera_table(self):
        """
        Refresh main window's camera table.

        Warning: Once camera is open or supervision starts, Adding new camera
        devices will cause app crash which means the application don't
        support hot plug.
        :return: None
        """
        self.cameras = camera_handler.get_cameras()
        self.cameratable_tablewidget.clearContents()
        if not camera_handler.check_camera_availability():
            warning(self, '提示', '无可用摄像头')
            return
        camera_num = len(self.cameras)
        self.cameratable_tablewidget.setRowCount(camera_num)
        if camera_num > 1:
            log.debug('There are %s cameras available.' % camera_num)
        else:
            log.debug('There is 1 camera available.')
        for i, cam in enumerate(self.cameras):
            cam.set_tag('camera%s' % i)
            tag = QtWidgets.QTableWidgetItem(cam.tag())
            camera_name = QtWidgets.QTableWidgetItem(cam.name())
            camera_id = QtWidgets.QTableWidgetItem(cam.id())
            self.cameratable_tablewidget.setItem(i, 0, tag)
            self.cameratable_tablewidget.setItem(i, 1, camera_name)
            self.cameratable_tablewidget.setItem(i, 2, camera_id)
Beispiel #3
0
 def open_port(self):
     if self.open_serial_pushbutton.text() == '关闭COM':
         self.serial_port.close()
         log.debug('Close %s successfully.' % self.serial_port.port)
         information(self, '提示', '成功关闭%s' % self.serial_port.port)
         self.open_serial_pushbutton.setText('打开COM')
         self.refresh_serial_pushbutton.setEnabled(True)
         self.serial_port_combobox.setEnabled(True)
     else:
         try:
             port_name = self.serial_port_combobox.currentText()
             if port_name == '':
                 log.error('Invalid port name.')
                 critical(self, '提示', '无效的串口名')
                 return
             self.serial_port.port = port_name  # configure initialized port
             self.serial_port.baudrate = int(
                 self.serial_baudrate_combobox.currentText())
             self.serial_port.bytesize = int(
                 self.serial_databits_combobox.currentText())
             parity = self.serial_parity_combobox.currentText()
             self.serial_port.parity = comport_handler.PARITY_NAME[parity]
             self.serial_port.stopbits = float(
                 self.serial_stopbits_combobox.currentText())
             self.serial_port.open()
             log.debug('Open %s successfully.' % port_name)
             information(self, '提示', '成功打开%s' % port_name)
             self.open_serial_pushbutton.setText('关闭COM')
             self.refresh_serial_pushbutton.setEnabled(False)
             # self.serial_port_combobox.setEnabled(False)
         except Exception as e:
             log.critical("Open port fail, please check configurations.")
             critical(self, '提示', '无法打开串口,请检查参数配置')
Beispiel #4
0
    def __init__(self):
        self.serial_port = serial.Serial()
        self.cameras = camera_handler.get_cameras()
        self.current_snap_times = 0
        self.current_cam = None
        self.base_dir = None
        self.camera_reports = []
        self.summary_report = None
        self.worker = None
        self.supervision_thread = QtCore.QThread()
        super(MainWindow, self).__init__()
        self.setupUi(self)
        log.debug('App starts.')
        log.debug('Window size: %s * %s.' % (self.width(), self.height()))

        # self.setMinimumSize(400, 300)

        # All connections between signals and slots are defined here.
        self.refreshcamera_pushbutton.clicked.connect(
            self.refresh_camera_table)
        self.opencamera_pushbutton.clicked.connect(self.open_camera)
        self.capturestd_pushbutton.clicked.connect(self.capture_std)
        self.refresh_serial_pushbutton.clicked.connect(self.refresh_serial)
        self.open_serial_pushbutton.clicked.connect(self.open_port)
        self.resultdir_pushbutton.clicked.connect(self.choose_resultdir)
        self.start_supervision_pushbutton.clicked.connect(
            self.start_supervision)
        self.look_result_pushbutton.clicked.connect(self.look_result)

        self.init_data()
Beispiel #5
0
 def choose_resultdir(self):
     result_dir = QtWidgets.QFileDialog.getExistingDirectory(
         self, '选择结果路径', self.resultdir_linedit.text(),
         QtWidgets.QFileDialog.ShowDirsOnly)
     if result_dir == '':
         return
     else:
         self.resultdir_linedit.setText(result_dir)
     log.debug('Result directory is %s.' % result_dir)
Beispiel #6
0
    def snap_and_diff(self):
        event_loop = QtCore.QEventLoop()

        if self.current_cam.get_image_capture().isReadyForCapture():
            self.current_cam.get_image_capture().imageCaptured.connect(
                self.capture_curr)
            self.current_cam.get_image_capture().imageCaptured.connect(
                event_loop.quit)
            log.debug('Snap current image.')
            self.current_cam.capture()
            event_loop.exec()
        self.diff()
Beispiel #7
0
 def capture_std(self):
     for cam in self.cameras:
         if self.get_table_camera_info()[2] != cam.id():
             continue
         if not cam.is_open():
             log.warning('%s not opened yet.' % cam.tag())
             warning(self, '提示', '请先打开摄像头%s' % cam.tag())
             return
         if cam.get_image_capture().isReadyForCapture():
             cam.get_image_capture().imageCaptured.connect(
                 self.display_image)
             self.current_cam = cam
             cam.capture()
             log.debug("Start %s's standard image capturing..." %
                       cam.name())
Beispiel #8
0
 def diff(self):
     standard_image = image_proc.qimage2cv(self.current_cam.standard_img())
     current_image = image_proc.qimage2cv(self.current_cam.current_frame())
     diff_result, diff_percent = image_proc.diff(standard_image,
                                                 current_image,
                                                 self.image_diff_rate)
     diff_percent = str(round(diff_percent, 2)) + '%'
     self.diff_finished.emit(self.current_cam.name(),
                             str(self.curr_supervision_count),
                             str(self.current_snap_time), str(diff_result),
                             str(diff_percent))
     log.debug("%s's %s_%s diff result is %s, diff percent is %s" %
               (self.current_cam.name(), self.curr_supervision_count,
                self.current_snap_time, diff_result, diff_percent))
     self.save_report(diff_result, diff_percent)
Beispiel #9
0
    def open_camera(self):
        if self.cameratable_tablewidget.rowCount() == 0:
            log.warning('Not available cameras.')
            warning(self, '提示', '无可用摄像头')
            return

        for cam in self.cameras:
            if self.get_table_camera_info()[2] != cam.id():
                continue
            if cam.is_open():
                log.warning('%s is already open' % cam.name())
                information(self, '提示', '%s已打开' % cam.tag())
                return
            cam.get_viewfinder().setWindowTitle(cam.tag())
            cam.get_viewfinder().installEventFilter(self)
            cam.show_camera_window()
            cam.open()
            log.debug('%s opened successfully.' % cam.name())
Beispiel #10
0
    def eventFilter(self, obj, event):
        """
        Object obj installed event filter and is watched by main window.

        :param obj: installed event filter and by watched.
        :param event: obj's event type
        :return: stop being handled further return True, otherwise return False.
        """
        if type(obj) == QtMultimediaWidgets.QCameraViewfinder:
            if event.type() == QtCore.QEvent.Close:
                for item in self.cameras:
                    if obj != item.get_viewfinder():
                        continue
                    log.debug('%s has been closed.' % item.name())
                    item.close()
                    return True
            else:
                return False
        return MainWindow.eventFilter(self, obj, event)
Beispiel #11
0
 def start_supervision(self):
     while self.curr_supervision_count < self.supervision_count:
         if not self.supervision_control:
             break
         self.curr_supervision_count += 1
         log.debug('Power off and sleep %ss.' % self.off_time)
         self.serial_port.write(self.power_key)
         self.thread().sleep(self.off_time)
         log.debug('Power on and start snap.')
         self.serial_port.write(self.power_key)
         for i in range(self.snap_count):
             self.thread().sleep(self.snap_interval)
             for cam in self.cameras:
                 if not cam.is_open():
                     continue
                 self.current_cam = cam
                 self.current_snap_time = i + 1
                 self.snap_and_diff()
     self.summary_report.update()
     self.supervision_finished.emit()
Beispiel #12
0
 def start(self):
     if not self.check_and_prepare():
         return
     self.start_supervision_pushbutton.setText('结束监控')
     self.open_serial_pushbutton.setEnabled(False)
     self.look_result_pushbutton.setEnabled(False)
     # if self.powertype_combobox.currentText() == '电源箱交流':
     #     pass
     if self.powertype_combobox.currentText() == '电源箱交流':
         log.debug('Start powerbox supervision.')
         self.worker = supervision_worker.PowerboxWorker()
     elif self.powertype_combobox.currentText() == '红外直流':
         log.debug('Start direct supervision.')
         self.worker = supervision_worker.DirectWorker()
     else:
         log.debug('Start cross supervision.')
         self.worker = supervision_worker.CrossWorker()
     self.init_worker(self.worker)
     self.worker.moveToThread(self.supervision_thread)
     self.supervision_thread.started.connect(self.worker.start_supervision)
     self.worker.diff_finished.connect(self.update_result_table)
     self.worker.supervision_finished.connect(self.supervision_thread.quit)
     self.worker.supervision_finished.connect(self.resume)
     self.supervision_thread.finished.connect(self.worker.deleteLater)
     self.supervision_thread.start()
Beispiel #13
0
 def display_image(self, id, image):
     # Hold standard img for cam
     self.current_cam.set_standard_img(image)
     tab_text = self.current_cam.tag()
     for i in range(self.standardimg_tabwidget.count()):
         if self.standardimg_tabwidget.tabText(i) == tab_text:
             self.standardimg_tabwidget.widget(i).setPixmap(
                 QtGui.QPixmap.fromImage(image))
             return
     image_label = QtWidgets.QLabel()
     image_label.setAlignment(QtCore.Qt.AlignCenter)
     image_label.setSizePolicy(QtWidgets.QSizePolicy.Expanding,
                               QtWidgets.QSizePolicy.Expanding)
     screen_geometry = QtWidgets.QApplication.desktop().screenGeometry(self)
     image_label.setMinimumSize(screen_geometry.width() // 8,
                                screen_geometry.height() // 8)
     self.standardimg_tabwidget.addTab(image_label, tab_text)
     self.update_label_image(image_label, QtGui.QPixmap.fromImage(image))
     log.debug("Capturing %s's standard image is finished." %
               self.current_cam.name())
     self.current_cam.get_image_capture().imageCaptured.disconnect(
         self.display_image)
Beispiel #14
0
 def closeEvent(self, event):
     if self.supervision_thread.isRunning():
         log.warning('Supervision is still running.')
         button = warning(
             self, '提示', '电视监控正在运行,确定要关闭?',
             QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
         if button == QtWidgets.QMessageBox.Yes:
             self.supervision_thread.quit()
         else:
             event.ignore()
             return
     if self.serial_port.is_open:
         log.debug('Close %s.' % self.serial_port.name)
         self.serial_port.close()
     for cam in self.cameras:
         if cam.is_open():
             log.debug('Close %s.' % cam.name())
             cam.get_viewfinder().close()
             cam.close()
     log.debug('Close App.')
     event.accept()
Beispiel #15
0
    def check_and_prepare(self):
        """Check preconditions is ready.

        Check:
            1. Camera is open.
            2. Comport is open.
            3. Test result dir is valid.
            4. Any config parm is ready to use.
            ...

        Prepare:
            1. Initialize current test result dir.

        :return: True for all conditions are ready, False for not.
        """
        # Check if any camera has open
        for cam in self.cameras:
            if cam.is_open():
                break
        else:
            log.warning("Haven't opened any cameras.")
            critical(self, '提示', '未打开任何摄像头')
            return False

        # Check if standard image has been captured
        for cam in self.cameras:
            if not cam.is_open():
                continue
            if cam.standard_img() is None:
                log.warning("%s didn't capture standard image." % cam.name())
                critical(self, '提示', '未截取标准图')
                return False

        # Check if com_port is open
        if self.powertype_combobox.currentText() != '电源箱交流':
            if not self.serial_port.is_open:
                log.warning("Haven't opened cam port.")
                critical(self, '提示', '未打开串口')
                return False

        # Check result dir is valid
        if not os.path.isdir(self.resultdir_linedit.text()):
            log.warning('Result base dir is invalid.')
            critical(self, '提示', '路径错误')
            return False

        # Check all parameters have been configured.
        for item in self.powertype_stackedwidget.currentWidget().children():
            if type(item) != QtWidgets.QLineEdit:
                continue
            if not item.text():
                log.warning('Configuration params is missing.')
                critical(self, '提示', '配置参数未填写')
                return False

        # Initialize test result dir
        current_time = time.strftime('%Y-%m-%d_%H-%M-%S', time.localtime())
        self.base_dir = os.path.join(self.resultdir_linedit.text(),
                                     current_time)
        if not os.path.exists(self.base_dir):
            os.mkdir(self.base_dir)
            shutil.copy(conf.SUMMARY_REPORT_XSL, self.base_dir)
            shutil.copy(conf.CAMERA_REPORT_XSL, self.base_dir)
            shutil.copy(conf.STYLE_CSS, self.base_dir)

        log.debug('Current base dir is %s' % self.base_dir)
        for cam in self.cameras:
            if not cam.is_open():
                continue
            camera_report = report.CameraReport(cam, self.base_dir)
            log.debug("%s's result dir is %s" %
                      (cam.name(), camera_report.result_dir))
            # Save standard img to cam's dir
            camera_report.save_standard_img()
            # Initialize each open camera's report
            self.camera_reports.append(camera_report)
        # Initialize summary report
        summary_report_name = os.path.join(self.base_dir, conf.SUMMARY_REPORT)
        self.summary_report = report.SummaryReport(self.camera_reports,
                                                   summary_report_name,
                                                   current_time)

        # Initialize result table
        for cam in self.cameras:
            if not cam.is_open():
                continue
            result_cam_table = QtWidgets.QTableWidget()
            result_cam_table.setColumnCount(4)
            result_cam_table.setHorizontalHeaderLabels(
                ['当前轮次', '对比轮次', '对比结果', '误差值'])
            self.result_tabwidget.addTab(result_cam_table, cam.name())
        return True
Beispiel #16
0
 def start_supervision(self):
     if self.start_supervision_pushbutton.text() == "开始监控":
         log.debug('Start supervision, first check param configurations.')
         self.start()
     else:
         self.stop()
Beispiel #17
0
 def stop(self):
     log.debug('Stop supervision.')
     self.worker.supervision_control = False