Ejemplo n.º 1
0
 def test_save_wav(self):
     temp_dir = tempfile.gettempdir()
     os.chdir(temp_dir)
     self.assertFalse(os.path.isfile("test.wav"))
     FileOperator.save_data(bytearray([1, 2]), "test.wav")
     self.assertTrue(os.path.isfile("test.wav"))
     os.remove("test.wav")
Ejemplo n.º 2
0
    def on_save_clicked(self):
        data = self.device.data[:self.device.current_index]

        dev = self.device
        big_val = Formatter.big_value_with_suffix
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        initial_name = "{0}-{1}-{2}Hz-{3}Sps".format(dev.name, timestamp,
                                                     big_val(dev.frequency),
                                                     big_val(dev.sample_rate))

        if dev.bandwidth_is_adjustable:
            initial_name += "-{}Hz.wav".format(big_val(dev.bandwidth))

        initial_name = initial_name.replace(
            Formatter.local_decimal_seperator(), "_").replace("_000", "")

        FileOperator.save_data(data,
                               initial_name,
                               sample_rate=20e6,
                               long_record=True)
        # filename = FileOperator.save_data_dialog(initial_name, data,
        #                                          sample_rate=dev.sample_rate)
        # filename = self.recorded_files

        self.already_saved = True

        # if filename is not None and filename not in self.recorded_files:
        #     self.recorded_files.append(filename)

        self.close()
Ejemplo n.º 3
0
    def show_open_dialog(self, directory=False):
        dialog = FileOperator.get_open_dialog(directory_mode=directory,
                                              parent=self,
                                              name_filter="full")
        if dialog.exec_():
            try:
                file_names = dialog.selectedFiles()
                folders = [
                    folder for folder in file_names if os.path.isdir(folder)
                ]

                if len(folders) > 0:
                    folder = folders[0]
                    for f in self.signal_tab_controller.signal_frames:
                        self.close_signal_frame(f)

                    self.project_manager.set_project_folder(folder)
                else:
                    self.setCursor(Qt.WaitCursor)
                    file_names = FileOperator.uncompress_archives(
                        file_names, QDir.tempPath())
                    self.add_files(file_names)
                    self.unsetCursor()
            except Exception as e:
                Errors.generic_error(self.tr("Failed to open"), str(e),
                                     traceback.format_exc())
                self.unsetCursor()
Ejemplo n.º 4
0
Archivo: Signal.py Proyecto: jopohl/urh
 def save_as(self, filename: str):
     QApplication.instance().setOverrideCursor(Qt.WaitCursor)
     self.filename = filename
     FileOperator.save_signal(self)
     self.name = os.path.splitext(os.path.basename(filename))[0]
     self.changed = False
     QApplication.instance().restoreOverrideCursor()
Ejemplo n.º 5
0
 def save_as(self, filename: str):
     QApplication.instance().setOverrideCursor(Qt.WaitCursor)
     self.filename = filename
     FileOperator.save_signal(self)
     self.name = os.path.splitext(os.path.basename(filename))[0]
     self.changed = False
     QApplication.instance().restoreOverrideCursor()
Ejemplo n.º 6
0
 def generate_file(self):
     try:
         total_samples = self.total_modulated_samples
         buffer = self.prepare_modulation_buffer(total_samples,
                                                 show_error=False)
         if buffer is None:
             Errors.generic_error(
                 self.tr("File too big"),
                 self.tr("This file would get too big to save."))
             self.unsetCursor()
             return
         modulated_samples = self.modulate_data(buffer)
         try:
             sample_rate = self.modulators[0].sample_rate
         except Exception as e:
             logger.exception(e)
             sample_rate = 1e6
         FileOperator.save_data_dialog("generated.complex",
                                       modulated_samples,
                                       sample_rate=sample_rate,
                                       parent=self)
     except Exception as e:
         Errors.generic_error(self.tr("Failed to generate data"), str(e),
                              traceback.format_exc())
         self.unsetCursor()
Ejemplo n.º 7
0
 def generate_file(self):
     try:
         modulated_samples = self.modulate_data()
         FileOperator.save_data_dialog("", modulated_samples, parent=self)
     except Exception as e:
         Errors.generic_error(self.tr("Failed to generate data"), str(e), traceback.format_exc())
         self.unsetCursor()
Ejemplo n.º 8
0
 def test_save_wav(self):
     temp_dir = tempfile.gettempdir()
     os.chdir(temp_dir)
     self.assertFalse(os.path.isfile("test.wav"))
     FileOperator.save_data(bytearray([1, 2]), "test.wav")
     self.assertTrue(os.path.isfile("test.wav"))
     os.remove("test.wav")
Ejemplo n.º 9
0
 def generate_file(self):
     try:
         total_samples = self.total_modulated_samples
         buffer = self.prepare_modulation_buffer(total_samples, show_error=False)
         if buffer is None:
             Errors.generic_error(self.tr("File too big"), self.tr("This file would get too big to save."))
             self.unsetCursor()
             return
         modulated_samples = self.modulate_data(buffer)
         FileOperator.save_data_dialog("", modulated_samples, parent=self)
     except Exception as e:
         Errors.generic_error(self.tr("Failed to generate data"), str(e), traceback.format_exc())
         self.unsetCursor()
Ejemplo n.º 10
0
 def on_btn_save_clicked(self):
     filename = FileOperator.get_save_file_name("profile.fuzz.xml", caption="Save fuzz profile")
     if filename:
         self.table_model.protocol.to_xml_file(filename,
                                               decoders=self.project_manager.decodings,
                                               participants=self.project_manager.participants,
                                               modulators=self.modulators)
Ejemplo n.º 11
0
 def on_btn_save_rx_clicked(self):
     rx_device = self.simulator.sniffer.rcv_device
     if isinstance(rx_device.data, np.ndarray):
         filename = FileOperator.get_save_file_name("simulation_capture.complex")
         if filename:
             rx_device.data[:rx_device.current_index].tofile(filename)
             self.rx_file_saved.emit(filename)
Ejemplo n.º 12
0
 def on_btn_save_rx_clicked(self):
     rx_device = self.simulator.sniffer.rcv_device
     if isinstance(rx_device.data, np.ndarray):
         filename = FileOperator.get_save_file_name(
             "simulation_capture.complex")
         if filename:
             rx_device.data[:rx_device.current_index].tofile(filename)
Ejemplo n.º 13
0
 def on_graphics_view_save_as_clicked(self):
     filename = FileOperator.get_save_file_name("signal.complex")
     if filename:
         try:
             self.scene_manager.signal.save_as(filename)
         except Exception as e:
             QMessageBox.critical(self, self.tr("Error saving signal"), e.args[0])
Ejemplo n.º 14
0
 def on_btn_save_clicked(self):
     filename = FileOperator.get_save_file_name("profile.fuzz.xml", caption="Save fuzz profile")
     if filename:
         self.table_model.protocol.to_xml_file(filename,
                                               decoders=self.project_manager.decodings,
                                               participants=self.project_manager.participants,
                                               modulators=self.modulators)
Ejemplo n.º 15
0
    def open(self):
        fip = FileIconProvider()
        self.dialog = QFileDialog(self)
        #tree = self.dialog.findChild(QTreeView)
        #""":type: QTreeView """
        #tree.setRootIsDecorated(True)
        #tree.setItemsExpandable(True)

        # Damit SignalClick Behavior auch geht. Nachteil: Man muss immer den Open Button drücken
        #tree.blockSignals(True)
        self.dialog.setIconProvider(fip)
        self.dialog.setDirectory(FileOperator.RECENT_PATH)
        self.dialog.setWindowTitle("Open Folder")
        self.dialog.setFileMode(QFileDialog.ExistingFiles)
        self.dialog.setOptions(QFileDialog.DontUseNativeDialog | QFileDialog.DontResolveSymlinks)
        self.dialog.setViewMode(QFileDialog.Detail)
        self.dialog.setNameFilter(
            "All files (*);;Complex Files *.complex (*.complex);;Wav Files *.wav (*.wav);;Protocols *.txt (*.txt);;"
            "Tar Archives (*.tar *.tar.gz *.tar.bz2);;Zip Archives (*.zip)")

        self.dialog.currentChanged.connect(self.handle_dialog_selection_changed)

        if self.dialog.exec_():
            fileNames = self.dialog.selectedFiles()
            folders = [folder for folder in fileNames if os.path.isdir(folder)]

            if len(folders) > 0:
                folder = folders[0]
                for f in self.signal_tab_controller.signal_frames:
                    self.close_signal_frame(f)

                self.project_manager.set_project_folder(folder)
            else:
                fileNames = FileOperator.uncompress_archives(fileNames, QDir.tempPath())
                self.add_files(fileNames)
Ejemplo n.º 16
0
    def show_open_dialog(self, directory=False):
        fip = FileIconProvider()
        self.dialog = QFileDialog(self)
        self.dialog.setIconProvider(fip)
        self.dialog.setDirectory(FileOperator.RECENT_PATH)
        self.dialog.setWindowTitle("Open Folder")
        if directory:
            self.dialog.setFileMode(QFileDialog.Directory)
        else:
            self.dialog.setFileMode(QFileDialog.ExistingFiles)
            self.dialog.setNameFilter(
                "All files (*);;Complex (*.complex);;Complex16 unsigned (*.complex16u);;Complex16 signed (*.complex16s);;Wave (*.wav);;Protocols (*.proto);;"
                "Fuzzprofiles (*.fuzz);;Tar Archives (*.tar *.tar.gz *.tar.bz2);;Zip Archives (*.zip)")

        self.dialog.setOptions(QFileDialog.DontResolveSymlinks)
        self.dialog.setViewMode(QFileDialog.Detail)

        if self.dialog.exec_():
            try:
                file_names = self.dialog.selectedFiles()
                folders = [folder for folder in file_names if os.path.isdir(folder)]

                if len(folders) > 0:
                    folder = folders[0]
                    for f in self.signal_tab_controller.signal_frames:
                        self.close_signal_frame(f)

                    self.project_manager.set_project_folder(folder)
                else:
                    file_names = FileOperator.uncompress_archives(file_names, QDir.tempPath())
                    self.add_files(file_names)
            except Exception as e:
                Errors.generic_error(self.tr("Failed to open"), str(e), traceback.format_exc())
                QApplication.instance().restoreOverrideCursor()
Ejemplo n.º 17
0
 def on_graphics_view_save_as_clicked(self):
     filename = FileOperator.get_save_file_name("signal.complex")
     if filename:
         try:
             self.scene_manager.signal.save_as(filename)
         except Exception as e:
             QMessageBox.critical(self, self.tr("Error saving signal"), e.args[0])
Ejemplo n.º 18
0
 def on_btn_open_clicked(self):
     dialog = FileOperator.get_open_dialog(directory_mode=False,
                                           parent=self,
                                           name_filter="fuzz")
     if dialog.exec_():
         for filename in dialog.selectedFiles():
             self.load_from_file(filename)
Ejemplo n.º 19
0
 def save_signal_as(self):
     filename = FileOperator.get_save_file_name(self.signal.filename, wav_only=self.signal.wav_mode)
     if filename:
         try:
             self.signal.save_as(filename)
         except Exception as e:
             QMessageBox.critical(self, self.tr("Error saving signal"), e.args[0])
Ejemplo n.º 20
0
 def on_compare_frame_controller_load_protocol_clicked(self):
     dialog = FileOperator.get_open_dialog(directory_mode=False,
                                           parent=self,
                                           name_filter="proto")
     if dialog.exec_():
         for filename in dialog.selectedFiles():
             self.add_protocol_file(filename)
Ejemplo n.º 21
0
 def save_signal_as(self):
     filename = FileOperator.get_save_file_name(self.signal.filename, wav_only=self.signal.wav_mode)
     if filename:
         try:
             self.signal.save_as(filename)
         except Exception as e:
             QMessageBox.critical(self, self.tr("Error saving signal"), e.args[0])
Ejemplo n.º 22
0
    def handle_files_dropped(self, files, group_id=0):
        """
        :type files: list of QtCore.QUrl
        """
        localfiles = [fileurl.path() for fileurl in files if fileurl.isLocalFile()]

        if len(localfiles) > 0:
            self.add_files(FileOperator.uncompress_archives(localfiles, QDir.tempPath()), group_id)
Ejemplo n.º 23
0
 def on_btn_save_rx_clicked(self):
     rx_device = self.simulator.sniffer.rcv_device
     if isinstance(rx_device.data, np.ndarray) or isinstance(rx_device.data, IQArray):
         data = IQArray(rx_device.data[:rx_device.current_index])
         filename = FileOperator.ask_signal_file_name_and_save("simulation_capture", data,
                                                               sample_rate=rx_device.sample_rate, parent=self)
         if filename:
             data.tofile(filename)
             self.rx_file_saved.emit(filename)
Ejemplo n.º 24
0
 def __add_urls_to_group(self, file_urls, group_id=0):
     local_files = [
         file_url.toLocalFile() for file_url in file_urls
         if file_url.isLocalFile()
     ]
     if len(local_files) > 0:
         self.add_files(FileOperator.uncompress_archives(
             local_files, QDir.tempPath()),
                        group_id=group_id)
Ejemplo n.º 25
0
 def on_open_recent_action_triggered(self):
     action = self.sender()
     try:
         if os.path.isdir(action.data()):
             self.project_manager.set_project_folder(action.data())
         elif os.path.isfile(action.data()):
             self.add_files(FileOperator.uncompress_archives([action.data()], QDir.tempPath()))
     except Exception as e:
         Errors.generic_error(self.tr("Failed to open"), str(e), traceback.format_exc())
         self.unsetCursor()
 def on_open_recent_action_triggered(self):
     action = self.sender()
     try:
         if os.path.isdir(action.data()):
             self.project_manager.set_project_folder(action.data())
         elif os.path.isfile(action.data()):
             self.setCursor(Qt.WaitCursor)
             self.add_files(FileOperator.uncompress_archives([action.data()], QDir.tempPath()))
             self.unsetCursor()
     except Exception as e:
         Errors.exception(e)
         self.unsetCursor()
Ejemplo n.º 27
0
    def save_signal_as(self):
        if self.signal.filename:
            initial_name = self.signal.filename
        else:
            initial_name = self.signal.name.replace(" ", "-").replace(",", ".").replace(".", "_") + ".complex"

        filename = FileOperator.get_save_file_name(initial_name, wav_only=self.signal.wav_mode)
        if filename:
            try:
                self.signal.save_as(filename)
            except Exception as e:
                QMessageBox.critical(self, self.tr("Error saving signal"), e.args[0])
Ejemplo n.º 28
0
    def show_open_dialog(self, directory=False):
        dialog = FileOperator.get_open_dialog(directory_mode=directory, parent=self, name_filter="full")
        if dialog.exec_():
            try:
                file_names = dialog.selectedFiles()
                folders = [folder for folder in file_names if os.path.isdir(folder)]

                if len(folders) > 0:
                    folder = folders[0]
                    for f in self.signal_tab_controller.signal_frames:
                        self.close_signal_frame(f)

                    self.project_manager.set_project_folder(folder)
                else:
                    self.setCursor(Qt.WaitCursor)
                    file_names = FileOperator.uncompress_archives(file_names, QDir.tempPath())
                    self.add_files(file_names)
                    self.unsetCursor()
            except Exception as e:
                Errors.generic_error(self.tr("Failed to open"), str(e), traceback.format_exc())
                self.unsetCursor()
Ejemplo n.º 29
0
 def on_open_recent_action_triggered(self):
     action = self.sender()
     try:
         if os.path.isdir(action.data()):
             self.project_manager.set_project_folder(action.data())
         elif os.path.isfile(action.data()):
             self.setCursor(Qt.WaitCursor)
             self.add_files(FileOperator.uncompress_archives([action.data()], QDir.tempPath()))
             self.unsetCursor()
     except Exception as e:
         Errors.generic_error(self.tr("Failed to open"), str(e), traceback.format_exc())
         self.unsetCursor()
Ejemplo n.º 30
0
    def record_markered_diapazone(self, my_sel_freq):
        try:
            bw = abs(my_sel_freq[1] - my_sel_freq[0])
        except:
            return
        old_freq = self.device.frequency
        old_gain = self.device.gain
        self.on_stop_clicked()
        self.device = VirtualDevice(BackendHandler(),
                                    self.selected_device_name, Mode.receive)
        self.device.frequency = my_sel_freq[0] + bw / 2
        sample_rate = 20e6
        self.device.sample_rate = sample_rate
        self.device.bandwidth = bw
        self.device.start()
        time.sleep(0.1)
        while self.device.data[:self.device.
                               current_index].size < 1 * sample_rate:
            pass
        self.device.stop('lol_1')
        data = self.device.data[:self.device.current_index]
        dev = self.device
        big_val = Formatter.big_value_with_suffix
        timestamp = datetime.now().strftime("%Y-%m-%d_%H:%M:%S")
        freq = 6800e6 + self.status_k - my_sel_freq[0] + bw / 2
        initial_name = "{0}-{1}-{2}Hz-{3}Sps".format(dev.name, timestamp,
                                                     big_val(freq),
                                                     big_val(dev.sample_rate))
        if dev.bandwidth_is_adjustable:
            initial_name += "-{}Hz.wav".format(big_val(dev.bandwidth))

        initial_name = initial_name.replace(
            Formatter.local_decimal_seperator(), "_").replace("_000", "")
        FileOperator.save_data(data, initial_name, sample_rate=sample_rate)
        self.files_recorded.emit(initial_name)
        self.init_device()
        self.device.frequency = old_freq
        self.device.gain = old_gain
        self.device.sample_rate = 20e6
        self.change_tab.emit()
Ejemplo n.º 31
0
    def stop_iq_read(self):
        self.on_stop_clicked()
        data = self.device.data[:self.device.current_index]
        dev = self.device
        big_val = Formatter.big_value_with_suffix
        timestamp = datetime.now().strftime("%Y-%m-%d_%H:%M:%S")
        initial_name = "{0}-{1}-{2}Hz-{3}Sps".format(dev.name, timestamp,
                                                     big_val(dev.frequency),
                                                     big_val(dev.sample_rate))
        if dev.bandwidth_is_adjustable:
            initial_name += "-{}Hz.wav".format(big_val(dev.bandwidth))

        initial_name = initial_name.replace(
            Formatter.local_decimal_seperator(), "_").replace("_000", "")

        FileOperator.save_data(data, initial_name, sample_rate=dev.sample_rate)
        self.files_recorded.emit(initial_name)
        self.init_device()
        self.device.frequency = self.old_freq
        self.old_freq = None
        self.on_start_clicked()
        self.change_tab.emit()
Ejemplo n.º 32
0
    def on_save_clicked(self):
        data = self.device.data[:self.device.current_index]

        dev = self.device
        big_val = Formatter.big_value_with_suffix
        initial_name = "{0} {1}Hz {2}Sps {3}Hz.complex".format(dev.name, big_val(dev.frequency),
                                                               big_val(dev.sample_rate),
                                                               big_val(dev.bandwidth)).replace(
            Formatter.local_decimal_seperator(), "_").replace("_000", "")

        filename = FileOperator.save_data_dialog(initial_name, data, parent=self)
        self.already_saved = True
        if filename is not None and filename not in self.recorded_files:
            self.recorded_files.append(filename)
Ejemplo n.º 33
0
    def read_opened_filenames(self):
        if self.project_file is not None:
            tree = ET.parse(self.project_file)
            root = tree.getroot()
            fileNames = []

            for ftag in root.findall("open_file"):
                pos = int(ftag.attrib["position"])
                filename = os.path.join(self.project_path, ftag.attrib["name"])
                fileNames.insert(pos, filename)

            fileNames = FileOperator.uncompress_archives(fileNames, QDir.tempPath())
            return fileNames
        return []
Ejemplo n.º 34
0
 def generate_file(self):
     try:
         total_samples = self.total_modulated_samples
         buffer = self.prepare_modulation_buffer(total_samples,
                                                 show_error=False)
         if buffer is None:
             Errors.generic_error(
                 self.tr("File too big"),
                 self.tr("This file would get too big to save."))
             self.unsetCursor()
             return
         modulated_samples = self.modulate_data(buffer)
         try:
             sample_rate = self.modulators[0].sample_rate
         except Exception as e:
             logger.exception(e)
             sample_rate = 1e6
         FileOperator.ask_signal_file_name_and_save("generated",
                                                    modulated_samples,
                                                    sample_rate=sample_rate,
                                                    parent=self)
     except Exception as e:
         Errors.exception(e)
         self.unsetCursor()
Ejemplo n.º 35
0
    def test_uncompress_archives(self):
        temp_dir = tempfile.gettempdir()
        os.chdir(temp_dir)

        with tarfile.open("test.tar.gz", "w:gz") as tar:
            for name in ["1.complex", "2.complex", "3.complex"]:
                data = np.ones(10, dtype=np.complex64)
                data.tofile(name)
                tar.add(name)

        with ZipFile('test.zip', 'w') as zip:
            for name in ["4.complex", "5.complex"]:
                data = np.ones(20, dtype=np.complex64)
                data.tofile(name)
                zip.write(name)

        QApplication.instance().processEvents()
        QTest.qWait(self.WAIT_TIMEOUT_BEFORE_NEW)
        self.form.add_files(
            FileOperator.uncompress_archives(["test.tar.gz", "test.zip"],
                                             QDir.tempPath()))
        self.assertEqual(len(self.form.signal_tab_controller.signal_frames), 5)

        tar_md5 = hashlib.md5(
            open(os.path.join(temp_dir, "test.tar.gz"),
                 'rb').read()).hexdigest()
        self.form.signal_tab_controller.signal_frames[
            0].signal._fulldata = np.ones(5, dtype=np.complex64)
        self.form.signal_tab_controller.signal_frames[0].signal.changed = True
        self.form.signal_tab_controller.signal_frames[
            0].ui.btnSaveSignal.click()

        tar_md5_after_save = hashlib.md5(
            open(os.path.join(temp_dir, "test.tar.gz"),
                 'rb').read()).hexdigest()
        self.assertNotEqual(tar_md5, tar_md5_after_save)

        zip_md5 = hashlib.md5(
            open(os.path.join(temp_dir, "test.zip"), 'rb').read()).hexdigest()
        self.form.signal_tab_controller.signal_frames[
            4].signal._fulldata = np.ones(5, dtype=np.complex64)
        self.form.signal_tab_controller.signal_frames[4].signal.changed = True
        self.form.signal_tab_controller.signal_frames[
            4].ui.btnSaveSignal.click()

        zip_md5_after_save = hashlib.md5(
            open(os.path.join(temp_dir, "test.zip"), 'rb').read()).hexdigest()
        self.assertNotEqual(zip_md5, zip_md5_after_save)
Ejemplo n.º 36
0
    def read_opened_filenames(self):
        if self.project_file is not None:
            tree = ET.parse(self.project_file)
            root = tree.getroot()
            file_names = []

            for file_tag in root.findall("open_file"):
                pos = int(file_tag.attrib["position"])
                filename = os.path.normpath(os.path.join(self.project_path, file_tag.attrib["name"]))
                file_names.insert(pos, filename)

            QApplication.setOverrideCursor(Qt.WaitCursor)
            file_names = FileOperator.uncompress_archives(file_names, QDir.tempPath())
            QApplication.restoreOverrideCursor()
            return file_names
        return []
Ejemplo n.º 37
0
    def read_opened_filenames(self):
        if self.project_file is not None:
            tree = ET.parse(self.project_file)
            root = tree.getroot()
            file_names = []

            for ftag in root.findall("open_file"):
                pos = int(ftag.attrib["position"])
                filename = os.path.join(self.project_path, ftag.attrib["name"])
                file_names.insert(pos, filename)

            QApplication.setOverrideCursor(Qt.WaitCursor)
            file_names = FileOperator.uncompress_archives(file_names, QDir.tempPath())
            QApplication.restoreOverrideCursor()
            return file_names
        return []
Ejemplo n.º 38
0
    def on_save_clicked(self):
        data = self.device.data[:self.device.current_index]

        dev = self.device
        big_val = Formatter.big_value_with_suffix
        initial_name = "{0}-{1}Hz-{2}Sps".format(dev.name, big_val(dev.frequency), big_val(dev.sample_rate))

        if dev.bandwidth_is_adjustable:
            initial_name += "-{}Hz".format(big_val(dev.bandwidth))

        initial_name = initial_name.replace(Formatter.local_decimal_seperator(), "_").replace("_000", "")

        filename = FileOperator.save_data_dialog(initial_name + ".complex", data, parent=self)
        self.already_saved = True
        if filename is not None and filename not in self.recorded_files:
            self.recorded_files.append(filename)
Ejemplo n.º 39
0
    def on_save_clicked(self):
        data = self.device.data[:self.device.current_index]

        dev = self.device
        big_val = Formatter.big_value_with_suffix
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        initial_name = "{0}-{1}-{2}Hz-{3}Sps".format(dev.name, timestamp,
                                                     big_val(dev.frequency),
                                                     big_val(dev.sample_rate))

        if dev.bandwidth_is_adjustable:
            initial_name += "-{}Hz".format(big_val(dev.bandwidth))

        initial_name = initial_name.replace(
            Formatter.local_decimal_seperator(), "_").replace("_000", "")

        filename = FileOperator.ask_signal_file_name_and_save(
            initial_name, data, sample_rate=dev.sample_rate, parent=self)
        self.already_saved = True
        if filename is not None and filename not in self.recorded_files:
            self.recorded_files.append(filename)
Ejemplo n.º 40
0
    def test_uncompress_archives(self):
        temp_dir = tempfile.gettempdir()
        os.chdir(temp_dir)

        with tarfile.open("test.tar.gz", "w:gz") as tar:
            for name in ["1.complex", "2.complex", "3.complex"]:
                data = np.ndarray(10, dtype=np.complex64)
                data.tofile(name)
                tar.add(name)

        with ZipFile('test.zip', 'w') as zip:
            for name in ["4.complex", "5.complex"]:
                data = np.ndarray(10, dtype=np.complex64)
                data.tofile(name)
                zip.write(name)

        tests.utils_testing.short_wait()
        form = MainController()
        tests.utils_testing.short_wait()
        form.add_files(FileOperator.uncompress_archives(["test.tar.gz", "test.zip"], QDir.tempPath()))
        self.assertEqual(len(form.signal_tab_controller.signal_frames), 5)

        tar_md5 = hashlib.md5(open(os.path.join(temp_dir, "test.tar.gz"), 'rb').read()).hexdigest()
        form.signal_tab_controller.signal_frames[0].signal._fulldata = np.ones(5, dtype=np.complex64)
        form.signal_tab_controller.signal_frames[0].signal.changed = True
        form.signal_tab_controller.signal_frames[0].ui.btnSaveSignal.click()

        tar_md5_after_save = hashlib.md5(open(os.path.join(temp_dir, "test.tar.gz"), 'rb').read()).hexdigest()
        self.assertNotEqual(tar_md5, tar_md5_after_save)

        zip_md5 = hashlib.md5(open(os.path.join(temp_dir, "test.zip"), 'rb').read()).hexdigest()
        form.signal_tab_controller.signal_frames[4].signal._fulldata = np.ones(5, dtype=np.complex64)
        form.signal_tab_controller.signal_frames[4].signal.changed = True
        form.signal_tab_controller.signal_frames[4].ui.btnSaveSignal.click()

        zip_md5_after_save = hashlib.md5(open(os.path.join(temp_dir, "test.zip"), 'rb').read()).hexdigest()
        self.assertNotEqual(zip_md5, zip_md5_after_save)
Ejemplo n.º 41
0
    def show_open_dialog(self, directory=False):
        fip = FileIconProvider()
        self.dialog = QFileDialog(self)
        self.dialog.setIconProvider(fip)
        self.dialog.setDirectory(FileOperator.RECENT_PATH)
        self.dialog.setWindowTitle("Open Folder")
        if directory:
            self.dialog.setFileMode(QFileDialog.Directory)
        else:
            self.dialog.setFileMode(QFileDialog.ExistingFiles)
            self.dialog.setNameFilter(
                "All files (*);;Complex (*.complex);;Complex16 unsigned (*.complex16u);;Complex16 signed (*.complex16s);;Wave (*.wav);;Protocols (*.proto);;"
                "Fuzzprofiles (*.fuzz);;Tar Archives (*.tar *.tar.gz *.tar.bz2);;Zip Archives (*.zip)")

        self.dialog.setOptions(QFileDialog.DontResolveSymlinks)
        self.dialog.setViewMode(QFileDialog.Detail)

        if self.dialog.exec_():
            try:
                file_names = self.dialog.selectedFiles()
                folders = [folder for folder in file_names if os.path.isdir(folder)]

                if len(folders) > 0:
                    folder = folders[0]
                    for f in self.signal_tab_controller.signal_frames:
                        self.close_signal_frame(f)

                    self.project_manager.set_project_folder(folder)
                else:
                    self.setCursor(Qt.WaitCursor)
                    file_names = FileOperator.uncompress_archives(file_names, QDir.tempPath())
                    self.add_files(file_names)
                    self.unsetCursor()
            except Exception as e:
                Errors.generic_error(self.tr("Failed to open"), str(e), traceback.format_exc())
                QApplication.instance().restoreOverrideCursor()
Ejemplo n.º 42
0
    def test_uncompress_archives(self):
        temp_dir = tempfile.gettempdir()
        os.chdir(temp_dir)

        with tarfile.open("test.tar.gz", "w:gz") as tar:
            for name in ["1.complex", "2.complex", "3.complex"]:
                data = np.ndarray(10, dtype=np.complex64)
                data.tofile(name)
                tar.add(name)

        with ZipFile('test.zip', 'w') as zip:
            for name in ["4.complex", "5.complex"]:
                data = np.ndarray(10, dtype=np.complex64)
                data.tofile(name)
                zip.write(name)

        QApplication.instance().processEvents()
        QTest.qWait(self.WAIT_TIMEOUT_BEFORE_NEW)
        self.form.add_files(FileOperator.uncompress_archives(["test.tar.gz", "test.zip"], QDir.tempPath()))
        self.assertEqual(len(self.form.signal_tab_controller.signal_frames), 5)

        tar_md5 = hashlib.md5(open(os.path.join(temp_dir, "test.tar.gz"), 'rb').read()).hexdigest()
        self.form.signal_tab_controller.signal_frames[0].signal._fulldata = np.ones(5, dtype=np.complex64)
        self.form.signal_tab_controller.signal_frames[0].signal.changed = True
        self.form.signal_tab_controller.signal_frames[0].ui.btnSaveSignal.click()

        tar_md5_after_save = hashlib.md5(open(os.path.join(temp_dir, "test.tar.gz"), 'rb').read()).hexdigest()
        self.assertNotEqual(tar_md5, tar_md5_after_save)

        zip_md5 = hashlib.md5(open(os.path.join(temp_dir, "test.zip"), 'rb').read()).hexdigest()
        self.form.signal_tab_controller.signal_frames[4].signal._fulldata = np.ones(5, dtype=np.complex64)
        self.form.signal_tab_controller.signal_frames[4].signal.changed = True
        self.form.signal_tab_controller.signal_frames[4].ui.btnSaveSignal.click()

        zip_md5_after_save = hashlib.md5(open(os.path.join(temp_dir, "test.zip"), 'rb').read()).hexdigest()
        self.assertNotEqual(zip_md5, zip_md5_after_save)
Ejemplo n.º 43
0
 def on_btn_load_clicked(self):
     dialog = FileOperator.get_open_dialog(False,
                                           parent=self,
                                           name_filter="simulator")
     if dialog.exec_():
         self.load_simulator_file(dialog.selectedFiles()[0])
Ejemplo n.º 44
0
 def on_btn_save_clicked(self):
     filename = FileOperator.get_save_file_name("profile.fuzz", caption="Save fuzz profile")
     if filename:
         self.table_model.protocol.to_xml_file(filename)
Ejemplo n.º 45
0
    def test_get_open_dialog(self):
        d1 = FileOperator.get_open_dialog(directory_mode=False)
        self.assertEqual(d1.fileMode(), QFileDialog.ExistingFiles)

        d2 = FileOperator.get_open_dialog(directory_mode=True)
        self.assertEqual(d2.fileMode(), QFileDialog.Directory)
Ejemplo n.º 46
0
 def on_btn_open_clicked(self):
     dialog = FileOperator.get_open_dialog(directory_mode=False, parent=self, name_filter="fuzz")
     if dialog.exec_():
         for filename in dialog.selectedFiles():
             self.load_from_file(filename)
Ejemplo n.º 47
0
 def on_btn_save_clicked(self):
     filename = FileOperator.get_save_file_name(initial_name="myprofile.sim.xml", caption="Save simulator profile")
     if filename:
         self.save_simulator_file(filename)
Ejemplo n.º 48
0
 def on_btn_load_clicked(self):
     dialog = FileOperator.get_open_dialog(False, parent=self, name_filter="simulator")
     if dialog.exec_():
         self.load_simulator_file(dialog.selectedFiles()[0])
Ejemplo n.º 49
0
 def on_btn_select_path_clicked(self):
     directory = FileOperator.get_directory()
     if directory:
         self.set_path(directory)
Ejemplo n.º 50
0
 def on_compare_frame_controller_load_protocol_clicked(self):
     dialog = FileOperator.get_open_dialog(directory_mode=False, parent=self, name_filter="proto")
     if dialog.exec_():
         for filename in dialog.selectedFiles():
             self.add_protocol_file(filename)
Ejemplo n.º 51
0
 def __add_urls_to_group(self, file_urls, group_id=0):
     local_files = [file_url.toLocalFile() for file_url in file_urls if file_url.isLocalFile()]
     if len(local_files) > 0:
         self.setCursor(Qt.WaitCursor)
         self.add_files(FileOperator.uncompress_archives(local_files, QDir.tempPath()), group_id=group_id)
         self.unsetCursor()