def create_protocol_sniff_dialog(self, testing_mode=False): pm = self.project_manager signal = next( (proto.signal for proto in self.compare_frame_controller.protocol_list), None) signals = [ f.signal for f in self.signal_tab_controller.signal_frames if f.signal ] psd = ProtocolSniffDialog(project_manager=pm, signal=signal, signals=signals, testing_mode=testing_mode, parent=self) if psd.has_empty_device_list: Errors.no_device() psd.close() return None else: psd.device_parameters_changed.connect(pm.set_device_parameters) psd.protocol_accepted.connect( self.compare_frame_controller.add_sniffed_protocol_messages) return psd
def __send_messages(self, messages, sample_rates): if len(messages): self.is_sending = True else: return False # Open and configure RfCat if not self.open_rfcat(): return False modulation = self.modulators[ messages[0].modulator_index].modulation_type if modulation == "ASK": modulation = "MOD_ASK_OOK" elif modulation == "FSK": modulation = "MOD_2FSK" elif modulation == "GFSK": modulation = "MOD_GFSK" elif modulation == "PSK": modulation = "MOD_MSK" else: # Fallback modulation = "MOD_ASK_OOK" self.configure_rfcat( modulation=modulation, freq=self.project_manager.device_conf["frequency"], sample_rate=sample_rates[0], samples_per_symbol=messages[0].samples_per_symbol) repeats_from_settings = settings.read('num_sending_repeats', type=int) repeats = repeats_from_settings if repeats_from_settings > 0 else -1 while (repeats > 0 or repeats == -1) and self.__sending_interrupt_requested == False: logger.debug("Start iteration ({} left)".format( repeats if repeats > 0 else "infinite")) for i, msg in enumerate(messages): if self.__sending_interrupt_requested: break assert isinstance(msg, Message) wait_time = msg.pause / sample_rates[i] self.current_send_message_changed.emit(i) error = self.send_data( self.bit_str_to_bytearray(msg.encoded_bits_str)) if not error: logger.debug("Sent message {0}/{1}".format( i + 1, len(messages))) logger.debug( "Waiting message pause: {0:.2f}s".format(wait_time)) if self.__sending_interrupt_requested: break time.sleep(wait_time) else: self.is_sending = False Errors.generic_error("Could not connect to {0}:{1}".format( self.client_ip, self.client_port), msg=error) break if repeats > 0: repeats -= 1 logger.debug("Sending finished") self.is_sending = False
def __send_messages(self, messages, sample_rates): """ :type messages: list of Message :type sample_rates: list of int :param sample_rates: Sample Rate for each messages, this is needed to calculate the wait time, as the pause for a message is given in samples :return: """ self.is_sending = True for i, msg in enumerate(messages): if self.__sending_interrupt_requested: break assert isinstance(msg, Message) wait_time = msg.pause / sample_rates[i] self.current_send_message_changed.emit(i) error = self.send_data( self.bit_str_to_bytearray(msg.encoded_bits_str)) if not error: logger.debug("Sent message {0}/{1}".format( i + 1, len(messages))) logger.debug( "Waiting message pause: {0:.2f}s".format(wait_time)) if self.__sending_interrupt_requested: break time.sleep(wait_time) else: self.is_sending = False Errors.generic_error("Could not connect to {0}:{1}".format( self.client_ip, self.client_port), msg=error) break logger.debug("Sending finished") self.is_sending = False
def add_files(self, filepaths, group_id=0, enforce_sample_rate=None): num_files = len(filepaths) if num_files == 0: return for i, filename in enumerate(filepaths): if not os.path.exists(filename): continue if os.path.isdir(filename): for f in self.signal_tab_controller.signal_frames: self.close_signal_frame(f) FileOperator.RECENT_PATH = filename self.project_manager.set_project_folder(filename) return FileOperator.RECENT_PATH = os.path.split(filename)[0] if filename.endswith(".complex"): self.add_signalfile(filename, group_id, enforce_sample_rate=enforce_sample_rate) elif filename.endswith(".coco"): self.add_signalfile(filename, group_id, enforce_sample_rate=enforce_sample_rate) elif filename.endswith(".proto") or filename.endswith( ".proto.xml"): self.add_protocol_file(filename) elif filename.endswith(".wav"): try: import wave w = wave.open(filename) w.close() except wave.Error as e: Errors.generic_error( "Unsupported WAV type", "Only uncompressed WAVs (PCM) are supported.", str(e)) continue self.add_signalfile(filename, group_id, enforce_sample_rate=enforce_sample_rate) elif filename.endswith(".fuzz") or filename.endswith(".fuzz.xml"): self.add_fuzz_profile(filename) elif filename.endswith(".txt"): self.add_plain_bits_from_txt(filename) elif filename.endswith(".csv"): self.__import_csv(filename, group_id) continue elif os.path.basename(filename) == constants.PROJECT_FILE: self.project_manager.set_project_folder( os.path.split(filename)[0]) else: self.add_signalfile(filename, group_id, enforce_sample_rate=enforce_sample_rate) if self.project_manager.project_file is None: self.adjust_for_current_file(filename)
def on_btn_simulate_clicked(self): if not self.simulator_config.protocol_valid(): QMessageBox.critical(self, self.tr("Invalid protocol configuration"), self.tr( "There are some problems with your protocol configuration. Please fix them first.")) return if not len(self.simulator_config.get_all_messages()): QMessageBox.critical(self, self.tr("No messages found"), self.tr("Please add at least one message.")) return num_simulated = len([p for p in self.project_manager.participants if p.simulate]) if num_simulated == 0: if self.ui.listViewSimulate.model().rowCount() == 0: QMessageBox.critical(self, self.tr("No active participants"), self.tr("You have no active participants.<br>" "Please add a participant in the <i>Participants tab</i> and " "assign it to at least one message as <i>source</i> or <i>destination.</i>")) return else: QMessageBox.critical(self, self.tr("No participant for simulation selected"), self.tr("Please check at least one participant from the " "<i>Simulate these participants</i> list.")) return try: self.get_simulator_dialog().exec_() except Exception as e: Errors.generic_error("An error occurred", str(e))
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()
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()
def on_btn_send_clicked(self): try: modulated_data = self.modulate_data() try: dialog = SendDialogController(self.project_manager.frequency, self.project_manager.sample_rate, self.project_manager.bandwidth, self.project_manager.gain, self.project_manager.device, modulated_data=modulated_data, parent=self) except OSError as e: logger.error(repr(e)) return if dialog.has_empty_device_list: Errors.no_device() dialog.close() return dialog.recording_parameters.connect( self.project_manager.set_recording_parameters) dialog.show() dialog.graphics_view.show_full_scene(reinitialize=True) except Exception as e: Errors.generic_error(self.tr("Failed to generate data"), str(e), traceback.format_exc()) self.unsetCursor()
def show_proto_sniff_dialog(self): pm = self.project_manager signal = None for proto in self.compare_frame_controller.protocol_list: signal = proto.signal if signal: break if signal: bit_len = signal.bit_len mod_type = signal.modulation_type tolerance = signal.tolerance noise = signal.noise_threshold center = signal.qad_center else: bit_len = 100 mod_type = 1 tolerance = 5 noise = 0.001 center = 0.02 psd = ProtocolSniffDialogController(pm, noise, center, bit_len, tolerance, mod_type, parent=self) if psd.has_empty_device_list: Errors.no_device() psd.close() else: psd.protocol_accepted.connect( self.compare_frame_controller.add_sniffed_protocol_messages) psd.show()
def on_selected_device_changed(self): dev_name = self.ui.cbDevice.currentText() if dev_name == NetworkSDRInterfacePlugin.NETWORK_SDR_NAME: self.ui.cbDevice.blockSignals(True) self.ui.cbDevice.setCurrentText(self.device.name) self.ui.cbDevice.blockSignals(False) Errors.network_sdr_send_is_elsewhere() return nrep = self.ui.spinBoxNRepeat.value() sts = self.device.samples_to_send self.device.free_data() # gc.collect() # Cant do GC here, because the SencRecvDialog itself would be deleted (see https://github.com/jopohl/urh/issues/83) self.device = VirtualDevice(self.backend_handler, dev_name, self.device.mode, self.device.bandwidth, self.device.frequency, self.device.gain, self.device.sample_rate, sts, self.device.ip, nrep, self) self.__create_device_connects() if hasattr(self.scene_manager, "plot_data"): del self.scene_manager.plot_data if self.mode == Mode.receive: self.scene_manager = LiveSceneManager(np.array([]), parent=self) self.graphics_view.scene_manager = self.scene_manager self.graphics_view.setScene(self.scene_manager.scene) self.ui.lineEditIP.setVisible(dev_name == "USRP") self.ui.labelIP.setVisible(dev_name == "USRP")
def close_signal_frame(self, signal_frame: SignalFrameController): try: self.project_manager.write_signal_information_to_project_file( signal_frame.signal) try: proto = self.signal_protocol_dict[signal_frame] except KeyError: proto = None if proto is not None: self.close_protocol(proto) del self.signal_protocol_dict[signal_frame] if self.signal_tab_controller.ui.scrlAreaSignals.minimumHeight( ) > signal_frame.height(): self.signal_tab_controller.ui.scrlAreaSignals.setMinimumHeight( self.signal_tab_controller.ui.scrlAreaSignals. minimumHeight() - signal_frame.height()) if signal_frame.signal is not None: # Non-Empty Frame (when a signal and not a protocol is opened) self.file_proxy_model.open_files.discard( signal_frame.signal.filename) signal_frame.eliminate() self.compare_frame_controller.ui.treeViewProtocols.expandAll() self.set_frame_numbers() self.refresh_main_menu() except Exception as e: Errors.generic_error(self.tr("Failed to close"), str(e), traceback.format_exc()) self.unsetCursor()
def save_data(data, filename: str): if filename.endswith(".wav"): f = wave.open(filename, "w") f.setnchannels(1) f.setsampwidth(1) f.setframerate(1000000) f.writeframes(data) f.close() elif filename.endswith(".coco"): with tarfile.open(filename, 'w:bz2') as tar_write: tmp_name = os.path.join(QDir.tempPath(), "tmpfile") data.tofile(tmp_name) tar_write.add(tmp_name) os.remove(tmp_name) else: try: data.tofile(filename) except Exception as e: Errors.write_error(e) if filename in archives.keys(): archive = archives[filename] if archive.endswith("zip"): rewrite_zip(archive) elif archive.endswith("tar") or archive.endswith("bz2") or archive.endswith("gz"): rewrite_tar(archive)
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()
def on_btn_simulate_clicked(self): if not self.simulator_config.protocol_valid(): QMessageBox.critical(self, self.tr("Invalid protocol configuration"), self.tr( "There are some problems with your protocol configuration. Please fix them first.")) return if not len(self.simulator_config.get_all_messages()): QMessageBox.critical(self, self.tr("No messages found"), self.tr("Please add at least one message.")) return num_simulated = len([p for p in self.project_manager.participants if p.simulate]) if num_simulated == 0: if self.ui.listViewSimulate.model().rowCount() == 0: QMessageBox.critical(self, self.tr("No active participants"), self.tr("You have no active participants.<br>" "Please add a participant in the <i>Participants tab</i> and " "assign it to at least one message as <i>source</i> or <i>destination.</i>")) return else: QMessageBox.critical(self, self.tr("No participant for simulation selected"), self.tr("Please check at least one participant from the " "<i>Simulate these participants</i> list.")) return try: self.get_simulator_dialog().exec_() except Exception as e: Errors.exception(e)
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()
def save_data(data, filename: str): if filename.endswith(".wav"): f = wave.open(filename, "w") f.setnchannels(1) f.setsampwidth(1) f.setframerate(1000000) f.writeframes(data) f.my_close() elif filename.endswith(".coco"): with tarfile.open(filename, 'w:bz2') as tarwrite: tmp_name = os.path.join(QDir.tempPath(), "tmpfile") data.tofile(tmp_name) tarwrite.add(tmp_name) os.remove(tmp_name) else: try: data.tofile(filename) except Exception as e: Errors.write_error(e) if filename in archives.keys(): archive = archives[filename] if archive.endswith("zip"): rewrite_zip(archive) elif archive.endswith("tar") or archive.endswith("bz2") or archive.endswith("gz"): rewrite_tar(archive)
def show_proto_sniff_dialog(self): pm = self.project_manager signal = next( (proto.signal for proto in self.compare_frame_controller.protocol_list), None) bit_len = signal.bit_len if signal else 100 mod_type = signal.modulation_type if signal else 1 tolerance = signal.tolerance if signal else 5 noise = signal.noise_threshold if signal else 0.001 center = signal.qad_center if signal else 0.02 psd = ProtocolSniffDialogController( pm, noise, center, bit_len, tolerance, mod_type, self.compare_frame_controller.decodings, encoding_index=self.compare_frame_controller.ui.cbDecoding. currentIndex(), parent=self) if psd.has_empty_device_list: Errors.no_device() psd.close() else: psd.recording_parameters.connect(pm.set_recording_parameters) psd.protocol_accepted.connect( self.compare_frame_controller.add_sniffed_protocol_messages) psd.show()
def close_signal_frame(self, signal_frame: SignalFrame): try: self.project_manager.write_signal_information_to_project_file(signal_frame.signal) try: proto = self.signal_protocol_dict[signal_frame] except KeyError: proto = None if proto is not None: self.close_protocol(proto) del self.signal_protocol_dict[signal_frame] if self.signal_tab_controller.ui.scrlAreaSignals.minimumHeight() > signal_frame.height(): self.signal_tab_controller.ui.scrlAreaSignals.setMinimumHeight( self.signal_tab_controller.ui.scrlAreaSignals.minimumHeight() - signal_frame.height()) if signal_frame.signal is not None: # Non-Empty Frame (when a signal and not a protocol is opened) self.file_proxy_model.open_files.discard(signal_frame.signal.filename) signal_frame.eliminate() self.compare_frame_controller.ui.treeViewProtocols.expandAll() self.set_frame_numbers() self.refresh_main_menu() except Exception as e: Errors.generic_error(self.tr("Failed to close"), str(e), traceback.format_exc()) self.unsetCursor()
def on_btn_add_separator_clicked(self): sep, ok = QInputDialog.getText(self, "Enter Separator", "Separator:", text=",") if ok and sep not in (self.ui.comboBoxCSVSeparator.itemText(i) for i in range(self.ui.comboBoxCSVSeparator.count())): if len(sep) == 1: self.ui.comboBoxCSVSeparator.addItem(sep) else: Errors.generic_error("Invalid Separator", "Separator must be exactly one character.")
def prepare_modulation_buffer(self, total_samples: int, show_error=True) -> np.ndarray: memory_size_for_buffer = total_samples * 8 logger.debug("Allocating {0:.2f}MB for modulated samples".format(memory_size_for_buffer / (1024 ** 2))) try: return np.zeros(total_samples, dtype=np.complex64) except MemoryError: if show_error: Errors.not_enough_ram_for_sending_precache(memory_size_for_buffer) return None
def on_selected_tx_device_changed(self): old_name = self.simulator.sender.device_name try: dev_name = self.device_settings_tx_widget.ui.cbDevice.currentText() self.simulator.sender.device_name = dev_name self.device_settings_tx_widget.device = self.simulator.sender.device except Exception as e: self.device_settings_tx_widget.ui.cbDevice.setCurrentText(old_name) Errors.generic_error("Error occurred", str(e))
def on_spectrum_analyzer_link_activated(self, link: str): if link == "open_spectrum_analyzer": r = SpectrumDialogController(ProjectManager(None), parent=self) if r.has_empty_device_list: Errors.no_device() r.close() return r.device_parameters_changed.connect(self.set_recording_params_from_spectrum_analyzer_link) r.show()
def on_show_spectrum_dialog_action_triggered(self): pm = self.project_manager r = SpectrumDialogController(pm, parent=self) if r.has_empty_device_list: Errors.no_device() r.close() return r.device_parameters_changed.connect(pm.set_device_parameters) r.show()
def on_show_spectrum_dialog_action_triggered(self): pm = self.project_manager r = SpectrumDialogController(pm, parent=self) if r.has_empty_device_list: Errors.no_device() r.close() return r.recording_parameters.connect(pm.set_recording_parameters) r.show()
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_show_spectrum_dialog_action_triggered(self): pm = self.project_manager r = SendRecvDialogController(pm.frequency, pm.sample_rate, pm.bandwidth, pm.gain, pm.device, Mode.spectrum, parent=self) if r.has_empty_device_list: Errors.no_device() r.close() return r.recording_parameters.connect(pm.set_recording_parameters) r.show()
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()
def on_btn_replay_clicked(self): pmngr = self.project_manager dialog = SendRecvDialogController(pmngr.frequency, pmngr.sample_rate, pmngr.bandwidth, pmngr.gain, pmngr.device, Mode.send, modulated_data=self.signal.data, parent=self) if dialog.has_empty_device_list: Errors.no_device() dialog.close() return dialog.recording_parameters.connect(pmngr.set_recording_parameters) dialog.show()
def show_spectrum_dialog(self): pm = self.project_manager r = SendRecvDialogController(pm.frequency, pm.sample_rate, pm.bandwidth, pm.gain, pm.device, Mode.spectrum, parent=self) if r.has_empty_device_list: Errors.no_device() r.close() return r.device_parameters_changed.connect(pm.set_device_parameters) r.show()
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()
def add_files(self, filepaths, group_id=0, enforce_sample_rate=None): num_files = len(filepaths) if num_files == 0: return for i, filename in enumerate(filepaths): if not os.path.exists(filename): continue if os.path.isdir(filename): for f in self.signal_tab_controller.signal_frames: self.close_signal_frame(f) FileOperator.RECENT_PATH = filename self.project_manager.set_project_folder(filename) return FileOperator.RECENT_PATH = os.path.split(filename)[0] if filename.endswith(".complex"): self.add_signalfile(filename, group_id, enforce_sample_rate=enforce_sample_rate) elif filename.endswith(".coco"): self.add_signalfile(filename, group_id, enforce_sample_rate=enforce_sample_rate) elif filename.endswith(".proto") or filename.endswith(".proto.xml") or filename.endswith(".bin"): self.add_protocol_file(filename) elif filename.endswith(".wav"): try: import wave w = wave.open(filename) w.close() except wave.Error as e: Errors.generic_error("Unsupported WAV type", "Only uncompressed WAVs (PCM) are supported.", str(e)) continue self.add_signalfile(filename, group_id, enforce_sample_rate=enforce_sample_rate) elif filename.endswith(".fuzz") or filename.endswith(".fuzz.xml"): self.add_fuzz_profile(filename) elif filename.endswith(".sim") or filename.endswith(".sim.xml"): self.add_simulator_profile(filename) elif filename.endswith(".txt"): self.add_plain_bits_from_txt(filename) elif filename.endswith(".csv"): self.__import_csv(filename, group_id) continue elif os.path.basename(filename) == constants.PROJECT_FILE: self.project_manager.set_project_folder(os.path.split(filename)[0]) else: self.add_signalfile(filename, group_id, enforce_sample_rate=enforce_sample_rate) if self.project_manager.project_file is None: self.adjust_for_current_file(filename) self.refresh_main_menu()
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()
def on_show_record_dialog_action_triggered(self): pm = self.project_manager r = ReceiveDialogController(pm.frequency, pm.sample_rate, pm.bandwidth, pm.gain, pm.device, parent=self) if r.has_empty_device_list: Errors.no_device() r.close() return r.recording_parameters.connect(pm.set_recording_parameters) r.files_recorded.connect(self.on_signals_recorded) r.show()
def on_btn_replay_clicked(self): project_manager = self.project_manager dialog = SendDialogController(project_manager.frequency, project_manager.sample_rate, project_manager.bandwidth, project_manager.gain, project_manager.device, modulated_data=self.signal.data, parent=self) if dialog.has_empty_device_list: Errors.no_device() dialog.close() return dialog.recording_parameters.connect(project_manager.set_recording_parameters) dialog.show() dialog.graphics_view.show_full_scene(reinitialize=True)
def show_proto_sniff_dialog(self): pm = self.project_manager signal = next((proto.signal for proto in self.compare_frame_controller.protocol_list), None) psd = ProtocolSniffDialog(project_manager=pm, signal=signal, parent=self) if psd.has_empty_device_list: Errors.no_device() psd.close() else: psd.device_parameters_changed.connect(pm.set_device_parameters) psd.protocol_accepted.connect(self.compare_frame_controller.add_sniffed_protocol_messages) psd.show()
def prepare_modulation_buffer(self, total_samples: int, show_error=True) -> np.ndarray: memory_size_for_buffer = total_samples * 8 logger.debug("Allocating {0:.2f}MB for modulated samples".format(memory_size_for_buffer / (1024 ** 2))) try: # allocate it three times as we need the same amount for the sending process np.zeros(3*total_samples, dtype=np.complex64) except MemoryError: # will go into continuous mode in this case if show_error: Errors.not_enough_ram_for_sending_precache(3*memory_size_for_buffer) return None return np.zeros(total_samples, dtype=np.complex64)
def __parse_error_messages(self, messages): messages = messages.lower() if "no devices found for" in messages: self.device.stop_on_error("Could not establish connection to USRP") Errors.usrp_found() self.on_clear_clicked() elif any(e in messages for e in ("hackrf_error_not_found", "hackrf_error_libusb")): self.device.stop_on_error( "Could not establish connection to HackRF") Errors.hackrf_not_found() self.on_clear_clicked() elif "no module named gnuradio" in messages: self.device.stop_on_error("Did not find gnuradio.") Errors.gnuradio_not_installed() self.on_clear_clicked() elif "rtlsdr-open: error code: -1" in messages: self.device.stop_on_error("Could not open a RTL-SDR device.") self.on_clear_clicked() elif "rtlsdr-open: error code: -12" in messages: self.device.stop_on_error("Could not open a RTL-SDR device") Errors.rtlsdr_sdr_driver() self.on_clear_clicked() elif "Address already in use" in messages: self._restart_device_thread()
def __parse_error_messages(self, messages): messages = messages.lower() if "no devices found for" in messages: self.device.stop_on_error("Could not establish connection to USRP") Errors.usrp_found() self.on_clear_clicked() elif any(e in messages for e in ("hackrf_error_not_found", "hackrf_error_libusb")): self.device.stop_on_error("Could not establish connection to HackRF") Errors.hackrf_not_found() self.on_clear_clicked() elif "no module named gnuradio" in messages: self.device.stop_on_error("Did not find gnuradio.") Errors.gnuradio_not_installed() self.on_clear_clicked() elif "rtlsdr-open: error code: -1" in messages: self.device.stop_on_error("Could not open a RTL-SDR device.") self.on_clear_clicked() elif "rtlsdr-open: error code: -12" in messages: self.device.stop_on_error("Could not open a RTL-SDR device") Errors.rtlsdr_sdr_driver() self.on_clear_clicked() elif "Address already in use" in messages: self._restart_device_thread()
def show_record_dialog(self): pm = self.project_manager r = SendRecvDialogController(pm.frequency, pm.sample_rate, pm.bandwidth, pm.gain, pm.device, Mode.receive, parent=self) if r.has_empty_device_list: Errors.no_device() r.close() return r.recording_parameters.connect(pm.set_recording_parameters) r.files_recorded.connect(self.load_recorded_signals) r.show()
def __send_messages(self, messages, sample_rates): if len(messages): self.is_sending = True else: return False # Open and configure RfCat if not self.open_rfcat(): return False modulation = self.modulators[messages[0].modulator_index].modulation_type if modulation == 0: # ASK modulation = "MOD_ASK_OOK" elif modulation == 1: # FSK modulation = "MOD_2FSK" elif modulation == 2: # GFSK modulation = "MOD_GFSK" elif modulation == 3: # PSK modulation = "MOD_MSK" else: # Fallback modulation = "MOD_ASK_OOK" self.configure_rfcat(modulation=modulation, freq=self.project_manager.device_conf["frequency"], sample_rate=sample_rates[0], bit_len=messages[0].bit_len) repeats_from_settings = constants.SETTINGS.value('num_sending_repeats', type=int) repeats = repeats_from_settings if repeats_from_settings > 0 else -1 while (repeats > 0 or repeats == -1) and self.__sending_interrupt_requested == False: logger.debug("Start iteration ({} left)".format(repeats if repeats > 0 else "infinite")) for i, msg in enumerate(messages): if self.__sending_interrupt_requested: break assert isinstance(msg, Message) wait_time = msg.pause / sample_rates[i] self.current_send_message_changed.emit(i) error = self.send_data(self.bit_str_to_bytearray(msg.encoded_bits_str)) if not error: logger.debug("Sent message {0}/{1}".format(i+1, len(messages))) logger.debug("Waiting message pause: {0:.2f}s".format(wait_time)) if self.__sending_interrupt_requested: break time.sleep(wait_time) else: self.is_sending = False Errors.generic_error("Could not connect to {0}:{1}".format(self.client_ip, self.client_port), msg=error) break if repeats > 0: repeats -= 1 logger.debug("Sending finished") self.is_sending = False
def on_button_box_accepted(self): self.path = os.path.realpath(self.path) if not os.path.exists(self.path): try: os.makedirs(self.path) except Exception: pass # Path should be created now, if not raise Error if not os.path.exists(self.path): Errors.invalid_path(self.path) return self.committed = True self.accept()
def create_protocol_sniff_dialog(self, testing_mode=False): pm = self.project_manager signal = next((proto.signal for proto in self.compare_frame_controller.protocol_list), None) signals = [f.signal for f in self.signal_tab_controller.signal_frames if f.signal] psd = ProtocolSniffDialog(project_manager=pm, signal=signal, signals=signals, testing_mode=testing_mode, parent=self) if psd.has_empty_device_list: Errors.no_device() psd.close() return None else: psd.device_parameters_changed.connect(pm.set_device_parameters) psd.protocol_accepted.connect(self.compare_frame_controller.add_sniffed_protocol_messages) return psd
def on_show_record_dialog_action_triggered(self): pm = self.project_manager try: r = ReceiveDialog(pm, parent=self) except OSError as e: logger.error(repr(e)) return if r.has_empty_device_list: Errors.no_device() r.close() return r.device_parameters_changed.connect(pm.set_device_parameters) r.files_recorded.connect(self.on_signals_recorded) r.show()
def on_btn_replay_clicked(self): project_manager = self.project_manager try: dialog = SendDialogController(project_manager, modulated_data=self.signal.data, parent=self) except OSError as e: logger.error(repr(e)) return if dialog.has_empty_device_list: Errors.no_device() dialog.close() return dialog.recording_parameters.connect(project_manager.set_recording_parameters) dialog.show() dialog.graphics_view.show_full_scene(reinitialize=True)
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()
def show_proto_sniff_dialog(self): pm = self.project_manager signal = next((proto.signal for proto in self.compare_frame_controller.protocol_list), None) bit_len = signal.bit_len if signal else 100 mod_type = signal.modulation_type if signal else 1 tolerance = signal.tolerance if signal else 5 noise = signal.noise_threshold if signal else 0.001 center = signal.qad_center if signal else 0.02 psd = ProtocolSniffDialogController(pm, noise, center, bit_len, tolerance, mod_type, self.compare_frame_controller.decodings, encoding_index=self.compare_frame_controller.ui.cbDecoding.currentIndex(), parent=self) if psd.has_empty_device_list: Errors.no_device() psd.close() else: psd.recording_parameters.connect(pm.set_recording_parameters) psd.protocol_accepted.connect(self.compare_frame_controller.add_sniffed_protocol_messages) psd.show()
def __send_messages(self, messages, sample_rates): """ :type messages: list of Message :type sample_rates: list of int :param sample_rates: Sample Rate for each messages, this is needed to calculate the wait time, as the pause for a message is given in samples :return: """ self.is_sending = True sock = self.prepare_send_connection() if sock is None: return try: for i, msg in enumerate(messages): if self.__sending_interrupt_requested: break assert isinstance(msg, Message) wait_time = msg.pause / sample_rates[i] self.current_send_message_changed.emit(i) error = self.send_data(self.bit_str_to_bytearray(msg.encoded_bits_str) + b"\n", sock) if not error: logger.debug("Sent message {0}/{1}".format(i + 1, len(messages))) logger.debug("Waiting message pause: {0:.2f}s".format(wait_time)) if self.__sending_interrupt_requested: break time.sleep(wait_time) else: self.is_sending = False Errors.generic_error("Could not connect to {0}:{1}".format(self.client_ip, self.client_port), msg=error) break logger.debug("Sending finished") self.is_sending = False finally: self.shutdown_socket(sock)
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()
def update_view(self): try: self.ui.sliderYscale.setValue(int(self.graphics_view.transform().m22())) except AttributeError: return txt = self.ui.txtEditErrors.toPlainText() new_messages = self.device.read_messages() if "No devices found for" in new_messages: self.device.stop_on_error("Could not establish connection to USRP") Errors.usrp_found() self.on_clear_clicked() elif any(e in new_messages for e in ("HACKRF_ERROR_NOT_FOUND", "HACKRF_ERROR_LIBUSB")): self.device.stop_on_error("Could not establish connection to HackRF") Errors.hackrf_not_found() self.on_clear_clicked() elif "No module named gnuradio" in new_messages: self.device.stop_on_error("Did not find gnuradio.") Errors.gnuradio_not_installed() self.on_clear_clicked() elif "RTLSDR-open: Error Code: -1" in new_messages: self.device.stop_on_error("Could not open a RTL-SDR device.") self.on_clear_clicked() elif "Address already in use" in new_messages: self._restart_device_thread() if len(new_messages) > 1: self.ui.txtEditErrors.setPlainText(txt + new_messages) self.ui.progressBar.setValue(self.device.current_index) self.ui.lSamplesCaptured.setText("{0:n}".format(self.device.current_index)) self.ui.lSignalSize.setText(locale.format_string("%.2f", (8 * self.device.current_index) / (1024 ** 2))) self.ui.lTime.setText(locale.format_string("%.2f", self.device.current_index / self.device.sample_rate)) if self.is_rx and self.device.data is not None and len(self.device.data) > 0: self.ui.labelReceiveBufferFull.setText("{0}%".format(int(100 * self.device.current_index / len(self.device.data)))) if self.device.current_index == 0: return False return True
def on_btn_send_clicked(self): try: total_samples = self.total_modulated_samples buffer = self.prepare_modulation_buffer(total_samples) if buffer is not None: modulated_data = self.modulate_data(buffer) else: # Enter continuous mode modulated_data = None try: if modulated_data is not None: try: dialog = SendDialog(self.project_manager, modulated_data=modulated_data, modulation_msg_indices=self.modulation_msg_indices, parent=self) except MemoryError: # Not enough memory for device buffer so we need to create a continuous send dialog del modulated_data Errors.not_enough_ram_for_sending_precache(None) dialog = ContinuousSendDialog(self.project_manager, self.table_model.protocol.messages, self.modulators, total_samples, parent=self) else: dialog = ContinuousSendDialog(self.project_manager, self.table_model.protocol.messages, self.modulators, total_samples, parent=self) except OSError as e: logger.exception(e) return if dialog.has_empty_device_list: Errors.no_device() dialog.close() return dialog.device_parameters_changed.connect(self.project_manager.set_device_parameters) dialog.show() dialog.graphics_view.show_full_scene(reinitialize=True) except Exception as e: Errors.generic_error(self.tr("Failed to generate data"), str(e), traceback.format_exc()) self.unsetCursor()
def create_new_signal(self, start, end): if start != end: new_signal = self.signal.create_new(start, end) self.signal_created.emit(new_signal) else: Errors.empty_selection()