def setUp(self): filename = os.path.join(tempfile.gettempdir(), "test.fuzz") mod1 = Modulator("mod 1") mod2 = Modulator("mod 2") mod2.param_for_one = 42 decoders = [ Encoder(["NRZ"]), Encoder(["NRZ-I", constants.DECODING_INVERT]) ] pac = ProtocolAnalyzerContainer([mod1, mod2]) pac.messages.append( Message([True, False, False, True, "A"], 100, decoder=decoders[0], message_type=pac.default_message_type)) pac.messages.append( Message([False, False, False, False, "A"], 200, decoder=decoders[1], message_type=pac.default_message_type)) pac.used_symbols.add(Symbol("A", 1, 1, 100)) pac.create_fuzzing_label(1, 10, 0) pac.to_xml_file(filename)
def test_load_profile(self): filename = os.path.join(tempfile.gettempdir(), "test.fuzz") mod1 = Modulator("mod 1") mod2 = Modulator("mod 2") mod2.param_for_one = 42 decoders = [Encoding(["NRZ"]), Encoding(["NRZ-I", constants.DECODING_INVERT])] pac = ProtocolAnalyzerContainer([mod1, mod2]) pac.messages.append(Message([True, False, False, True], 100, decoder=decoders[0], message_type=pac.default_message_type)) pac.messages.append(Message([False, False, False, False], 200, decoder=decoders[1], message_type=pac.default_message_type)) pac.create_fuzzing_label(1, 10, 0) pac.to_xml_file(filename) self.wait_before_new_file() self.form.add_files([os.path.join(tempfile.gettempdir(), "test.fuzz")]) self.assertEqual(self.form.ui.tabWidget.currentWidget(), self.form.ui.tab_generator) pac = self.form.generator_tab_controller.table_model.protocol self.assertEqual(len(pac.modulators), 2) self.assertEqual(len(pac.messages), 2) self.assertEqual(pac.messages[1][0], False) self.assertEqual(len(pac.protocol_labels), 1)
def test_performance(self): t = time.time() modulator = Modulator("Perf") modulator.modulation_type = 1 modulator.modulate([True] * 1000, pause=10000000) elapsed = time.time() - t self.assertLess(elapsed, 0.5)
def build_modulator_from_args(arguments: argparse.Namespace): if arguments.raw: return None if arguments.parameter_zero is None: raise ValueError("You need to give a modulation parameter for zero (-p0, --parameter-zero)") if arguments.parameter_one is None: raise ValueError("You need to give a modulation parameter for one (-p1, --parameter-one)") result = Modulator("CLI Modulator") result.carrier_freq_hz = float(arguments.carrier_frequency) result.carrier_amplitude = float(arguments.carrier_amplitude) result.carrier_phase_deg = float(arguments.carrier_phase) result.samples_per_bit = int(arguments.bit_length) if arguments.modulation_type == "ASK": if arguments.parameter_zero.endswith("%"): param_zero = float(arguments.parameter_zero[:-1]) else: param_zero = float(arguments.parameter_zero) * 100 if arguments.parameter_one.endswith("%"): param_one = float(arguments.parameter_one[:-1]) else: param_one = float(arguments.parameter_one) * 100 else: param_zero = float(arguments.parameter_zero) param_one = float(arguments.parameter_one) result.param_for_zero = param_zero result.param_for_one = param_one result.modulation_type_str = arguments.modulation_type result.sample_rate = arguments.sample_rate return result
def test_plot(self): modulator = Modulator("gfsk") modulator.modulation_type_str = "GFSK" modulator.samples_per_bit = 100 modulator.sample_rate = 1e6 modulator.param_for_one = 20e3 modulator.param_for_zero = 10e3 modulator.carrier_freq_hz = 15e3 modulator.carrier_phase_deg = 90 modulated_samples = modulator.modulate([True, False, True, False, False], 77) data = copy.deepcopy(modulated_samples) modulated_samples = modulator.modulate([False, True, True, True, True, False, True], 100, start=len(data)) data = np.concatenate((data, modulated_samples)) plt.subplot(2, 1, 1) axes = plt.gca() axes.set_ylim([-2,2]) plt.plot(data.real) plt.title("Modulated Wave") plt.subplot(2, 1, 2) qad = signal_functions.afp_demod(np.ascontiguousarray(data), 0, 1) plt.plot(qad) plt.title("Quad Demod") plt.show()
def test_performance(self): t = time.time() modulator = Modulator("Perf") modulator.modulation_type = 1 modulator.modulate([True] * 1000, pause=10000000) elapsed = time.time() - t self.assertLess(elapsed, 0.5)
def test_psk_detection(self): modulator = Modulator("") modulator.modulation_type_str = "PSK" modulator.param_for_zero = 0 modulator.param_for_one = 180 data = modulator.modulate("10101010111000") mod = AutoInterpretation.detect_modulation(data) self.assertEqual(mod, "PSK")
def test_fsk_performance(): bit_data = "10" * 100 + "0000011111" + "001101011" * 100 + "111111100000" * 100 modulator = Modulator("Perf") modulator.modulation_type_str = "FSK" t = time.time() result = modulator.modulate(bit_data, pause=10000000) elapsed = time.time() - t result.tofile("/tmp/fsk.complex") print("FSK {}ms".format(elapsed * 1000))
def test_fsk_performance(): bit_data = "10" * 100 + "0000011111" + "001101011" * 100 + "111111100000" * 100 modulator = Modulator("Perf") modulator.modulation_type_str = "FSK" t = time.time() result = modulator.modulate(bit_data, pause=10000000) elapsed = time.time() - t result.tofile("/tmp/fsk.complex") print("FSK {}ms".format(elapsed * 1000))
def build_modulator_from_args(arguments: argparse.Namespace): if arguments.raw: return None if arguments.parameter_zero is None: raise ValueError("You need to give a modulation parameter for zero (-p0, --parameter-zero)") if arguments.parameter_one is None: raise ValueError("You need to give a modulation parameter for one (-p1, --parameter-one)") result = Modulator("CLI Modulator") result.carrier_freq_hz = float(arguments.carrier_frequency) result.carrier_amplitude = float(arguments.carrier_amplitude) result.carrier_phase_deg = float(arguments.carrier_phase) result.samples_per_bit = int(arguments.bit_length) if arguments.modulation_type == "ASK": if arguments.parameter_zero.endswith("%"): param_zero = float(arguments.parameter_zero[:-1]) else: param_zero = float(arguments.parameter_zero) * 100 if arguments.parameter_one.endswith("%"): param_one = float(arguments.parameter_one[:-1]) else: param_one = float(arguments.parameter_one) * 100 else: param_zero = float(arguments.parameter_zero) param_one = float(arguments.parameter_one) result.param_for_zero = param_zero result.param_for_one = param_one result.modulation_type_str = arguments.modulation_type result.sample_rate = arguments.sample_rate return result
def test_channels(self): sample_rate = 10 ** 6 channel1_freq = 40 * 10 ** 3 channel2_freq = 240 * 10 ** 3 channel1_data = array.array("B", [1, 0, 1, 0, 1, 0, 0, 1]) channel2_data = array.array("B", [1, 1, 0, 0, 1, 1, 0, 1]) channel3_data = array.array("B", [1, 0, 0, 1, 0, 1, 1, 1]) filter_bw = 0.1 filter_freq1_high = 1.5 * channel1_freq filter_freq1_low = 0.5 * channel1_freq filter_freq2_high = 1.5*channel2_freq filter_freq2_low = 0.5 * channel2_freq modulator1, modulator2, modulator3 = Modulator("test"), Modulator("test2"), Modulator("test3") modulator1.carrier_freq_hz = channel1_freq modulator2.carrier_freq_hz = channel2_freq modulator3.carrier_freq_hz = -channel2_freq modulator1.sample_rate = modulator2.sample_rate = modulator3.sample_rate = sample_rate data1 = modulator1.modulate(channel1_data) data2 = modulator2.modulate(channel2_data) data3 = modulator3.modulate(channel3_data) mixed_signal = data1 + data2 + data3 mixed_signal.tofile("/tmp/three_channels.complex") plt.subplot("221") plt.title("Signal") plt.plot(mixed_signal) spectrogram = Spectrogram(mixed_signal) plt.subplot("222") plt.title("Spectrogram") plt.imshow(np.transpose(spectrogram.data), aspect="auto", cmap="magma") plt.ylim(0, spectrogram.freq_bins) chann1_filtered = Filter.apply_bandpass_filter(mixed_signal, filter_freq1_low / sample_rate, filter_freq1_high / sample_rate, filter_bw) plt.subplot("223") plt.title("Channel 1 Filtered ({})".format("".join(map(str, channel1_data)))) plt.plot(chann1_filtered) chann2_filtered = Filter.apply_bandpass_filter(mixed_signal, filter_freq2_low / sample_rate, filter_freq2_high / sample_rate, filter_bw) plt.subplot("224") plt.title("Channel 2 Filtered ({})".format("".join(map(str, channel2_data)))) plt.plot(chann2_filtered) plt.show()
def test_protocol_sniffer(self): samples_per_symbol = 100 center = 0.0942 noise = 0.1 tolerance = 2 modulation_type = "FSK" sample_rate = 1e6 device_name = NetworkSDRInterfacePlugin.NETWORK_SDR_NAME sniffer = ProtocolSniffer(samples_per_symbol=samples_per_symbol, center=center, center_spacing=0.1, noise=noise, tolerance=tolerance, modulation_type=modulation_type, bits_per_symbol=1, device=device_name, backend_handler=BackendHandler(), network_raw_mode=True) port = self.get_free_port() sniffer.rcv_device.set_server_port(port) self.network_sdr_plugin_sender = NetworkSDRInterfacePlugin(raw_mode=True) self.network_sdr_plugin_sender.client_port = port sniffer.sniff() QTest.qWait(10) data = ["101010", "000111", "1111000"] pause = 10 * samples_per_symbol modulator = Modulator("test") modulator.samples_per_symbol = samples_per_symbol modulator.sample_rate = sample_rate modulator.modulation_type = modulation_type modulator.parameters[1] = 20e3 modulator.parameters[0] = 10e3 packages = [] for d in data: packages.append(modulator.modulate(list(map(int, d)), pause)) # verify modulation was correct pa = ProtocolAnalyzer(None) signal = Signal("", "", sample_rate=sample_rate) signal.iq_array = IQArray.concatenate(packages) signal.modulation_type = modulation_type signal.samples_per_symbol = samples_per_symbol signal.tolerance = tolerance signal.noise_threshold = noise signal.center = center pa.signal = signal pa.get_protocol_from_signal() self.assertEqual(pa.plain_bits_str, data) # send data send_data = IQArray.concatenate(packages) self.network_sdr_plugin_sender.send_raw_data(send_data, 1) time.sleep(1) # Send enough pauses to end sniffing self.network_sdr_plugin_sender.send_raw_data(IQArray(None, np.float32, 10 * 2 * samples_per_symbol), 1) time.sleep(1) sniffer.stop() self.assertEqual(sniffer.plain_bits_str, data)
def test_protocol_sniffer(self): bit_len = 100 center = 0.0942 noise = 0.1 tolerance = 2 modulation_type = 1 sample_rate = 1e6 device_name = NetworkSDRInterfacePlugin.NETWORK_SDR_NAME sniffer = ProtocolSniffer(bit_len=bit_len, center=center, noise=noise, tolerance=tolerance, modulation_type=modulation_type, device=device_name, backend_handler=BackendHandler(), network_raw_mode=True) port = self.get_free_port() sniffer.rcv_device.set_server_port(port) self.network_sdr_plugin_sender = NetworkSDRInterfacePlugin(raw_mode=True) self.network_sdr_plugin_sender.client_port = port sniffer.sniff() QTest.qWait(10) data = ["101010", "000111", "1111000"] pause = 10 * bit_len modulator = Modulator("test") modulator.samples_per_bit = bit_len modulator.sample_rate = sample_rate modulator.modulation_type = modulation_type modulator.param_for_one = 20e3 modulator.param_for_zero = 10e3 packages = [] for d in data: packages.append(modulator.modulate(list(map(int, d)), pause)) # verify modulation was correct pa = ProtocolAnalyzer(None) signal = Signal("", "", sample_rate=sample_rate) signal._fulldata = np.concatenate(packages) signal.modulation_type = modulation_type signal.bit_len = bit_len signal.tolerance = tolerance signal.noise_threshold = noise signal.qad_center = center pa.signal = signal pa.get_protocol_from_signal() self.assertEqual(pa.plain_bits_str, data) # send data send_data = np.concatenate(packages) self.network_sdr_plugin_sender.send_raw_data(send_data, 1) time.sleep(1) # Send enough pauses to end sniffing self.network_sdr_plugin_sender.send_raw_data(np.zeros(10 * bit_len, dtype=np.complex64), 1) time.sleep(1) sniffer.stop() self.assertEqual(sniffer.plain_bits_str, data)
def load_from_xml(self, xml_tag: ET.Element, message_types): assert xml_tag.tag == "simulator_config" items = [] modulators_tag = xml_tag.find("modulators") if modulators_tag: self.project_manager.modulators = Modulator.modulators_from_xml_tag(modulators_tag) participants_tag = xml_tag.find("participants") if participants_tag: for participant in Participant.read_participants_from_xml_tag(participants_tag): if participant not in self.project_manager.participants: self.project_manager.participants.append(participant) self.participants_changed.emit() decodings_tag = xml_tag.find("decodings") if decodings_tag: self.project_manager.decodings = Encoding.read_decoders_from_xml_tag(decodings_tag) rx_config_tag = xml_tag.find("simulator_rx_conf") if rx_config_tag: ProjectManager.read_device_conf_dict(rx_config_tag, self.project_manager.simulator_rx_conf) tx_config_tag = xml_tag.find("simulator_tx_conf") if tx_config_tag: ProjectManager.read_device_conf_dict(tx_config_tag, self.project_manager.simulator_tx_conf) for child_tag in xml_tag.find("items"): items.append(self.load_item_from_xml(child_tag, message_types)) self.add_items(items, pos=0, parent_item=None)
def parse_project_file(file_path: str): import xml.etree.ElementTree as ET from urh.util.ProjectManager import ProjectManager result = defaultdict(lambda: None) if not file_path or not os.path.isfile(file_path): return result try: tree = ET.parse(file_path) root = tree.getroot() except Exception as e: logger.error("Could not read project file {}: {}".format(file_path, e)) return result ProjectManager.read_device_conf_dict(root.find("device_conf"), target_dict=result) result["device"] = result["name"] modulators = Modulator.modulators_from_xml_tag(root) if len(modulators) > 0: modulator = modulators[0] result["carrier_frequency"] = modulator.carrier_freq_hz result["carrier_amplitude"] = modulator.carrier_amplitude result["carrier_phase"] = modulator.carrier_phase_deg result["parameter_zero"] = modulator.param_for_zero result["parameter_one"] = modulator.param_for_one result["modulation_type"] = modulator.modulation_type_str return result
def generate_signal(messages: list, modulator: Modulator, snr_db: int, add_noise=True): result = [] message_powers = [] if isinstance(messages, Message): messages = [messages] for msg in messages: modulated = modulator.modulate(msg.encoded_bits, msg.pause) if add_noise: message_powers.append(np.mean(np.abs(modulated[:len(modulated) - msg.pause]))) result.append(modulated) result = np.concatenate(result) if not add_noise: return result noise = np.random.normal(loc=0, scale=1, size=2 * len(result)).astype(np.float32).view(np.complex64) # https://stackoverflow.com/questions/23690766/proper-way-to-add-noise-to-signal snr_ratio = np.power(10, snr_db / 10) signal_power = np.mean(message_powers) noise_power = signal_power / snr_ratio noise = 1 / np.sqrt(2) * noise_power * noise return result + noise
def __init__(self, compare_frame_controller: CompareFrameController, project_manager: ProjectManager, parent=None): super().__init__(parent) self.ui = Ui_GeneratorTab() self.ui.setupUi(self) self.project_manager = project_manager self.ui.treeProtocols.setHeaderHidden(True) self.tree_model = GeneratorTreeModel(compare_frame_controller) self.tree_model.set_root_item(compare_frame_controller.proto_tree_model.rootItem) self.tree_model.controller = self self.ui.treeProtocols.setModel(self.tree_model) self.table_model = GeneratorTableModel(compare_frame_controller.proto_tree_model.rootItem, [Modulator("Modulation")], compare_frame_controller.decodings) self.table_model.controller = self self.ui.tableMessages.setModel(self.table_model) self.label_list_model = GeneratorListModel(None) self.ui.listViewProtoLabels.setModel(self.label_list_model) self.network_sdr_button_orig_tooltip = self.ui.btnNetworkSDRSend.toolTip() self.set_network_sdr_send_button_visibility() self.set_rfcat_button_visibility() self.network_sdr_plugin = NetworkSDRInterfacePlugin() self.rfcat_plugin = RfCatPlugin() self.init_rfcat_plugin() self.refresh_modulators() self.on_selected_modulation_changed() self.set_fuzzing_ui_status() self.ui.prBarGeneration.hide() self.create_connects(compare_frame_controller)
def show_modulation_info(self): show = not self.has_default_modulation or self.modulators[ 0] != Modulator("Modulation") if not show: self.ui.btnEditModulation.setStyleSheet("background: orange") font = QFont() font.setBold(True) self.ui.btnEditModulation.setFont(font) else: self.ui.btnEditModulation.setStyleSheet("") self.ui.btnEditModulation.setFont(QFont()) cur_ind = self.ui.cBoxModulations.currentIndex() cur_mod = self.modulators[cur_ind] self.ui.lCarrierFreqValue.setText(cur_mod.carrier_frequency_str) self.ui.lCarrierPhaseValue.setText(cur_mod.carrier_phase_str) self.ui.lBitLenValue.setText(cur_mod.bit_len_str) self.ui.lSampleRateValue.setText(cur_mod.sample_rate_str) mod_type = cur_mod.modulation_type_str self.ui.lModTypeValue.setText(mod_type) if mod_type == "ASK": prefix = "Amplitude" elif mod_type == "PSK": prefix = "Phase" elif mod_type in ("FSK", "GFSK"): prefix = "Frequency" else: prefix = "Unknown Modulation Type (This should not happen...)" self.ui.lParamForZero.setText(prefix + " for 0:") self.ui.lParamForZeroValue.setText(cur_mod.param_for_zero_str) self.ui.lParamForOne.setText(prefix + " for 1:") self.ui.lParamForOneValue.setText(cur_mod.param_for_one_str)
def generate_signal(messages: list, modulator: Modulator, snr_db: int, add_noise=True): result = [] message_powers = [] if isinstance(messages, Message): messages = [messages] for msg in messages: modulated = modulator.modulate(msg.encoded_bits, msg.pause) if add_noise: message_powers.append( np.mean(np.abs(modulated[:len(modulated) - msg.pause]))) result.append(modulated) result = np.concatenate(result) if not add_noise: return result noise = np.random.normal(loc=0, scale=1, size=2 * len(result)).astype( np.float32).view(np.complex64) # https://stackoverflow.com/questions/23690766/proper-way-to-add-noise-to-signal snr_ratio = np.power(10, snr_db / 10) signal_power = np.mean(message_powers) noise_power = signal_power / snr_ratio noise = 1 / np.sqrt(2) * noise_power * noise return result + noise
def parse_project_file(file_path: str): import xml.etree.ElementTree as ET from urh.util.ProjectManager import ProjectManager result = defaultdict(lambda: None) if not file_path or not os.path.isfile(file_path): return result try: tree = ET.parse(file_path) root = tree.getroot() except Exception as e: logger.error("Could not read project file {}: {}".format(file_path, e)) return result ProjectManager.read_device_conf_dict(root.find("device_conf"), target_dict=result) result["device"] = result["name"] modulators = Modulator.modulators_from_xml_tag(root) if len(modulators) > 0: modulator = modulators[0] result["carrier_frequency"] = modulator.carrier_freq_hz result["carrier_amplitude"] = modulator.carrier_amplitude result["carrier_phase"] = modulator.carrier_phase_deg result["parameter_zero"] = modulator.param_for_zero result["parameter_one"] = modulator.param_for_one result["modulation_type"] = modulator.modulation_type_str return result
def to_xml_tag(self, decodings, participants, tag_name="protocol", include_message_type=False, write_bits=False, messages=None, modulators=None) -> ET.Element: root = ET.Element(tag_name) messages = self.messages if messages is None else messages # Save modulators if modulators is not None: # For protocol analyzer container root.append(Modulator.modulators_to_xml_tag(modulators)) root.append(Encoding.decodings_to_xml_tag(decodings)) root.append(Participant.participants_to_xml_tag(participants)) # Save data data_tag = ET.SubElement(root, "messages") for i, message in enumerate(messages): message_tag = message.to_xml( decoders=decodings, include_message_type=include_message_type, write_bits=write_bits) data_tag.append(message_tag) # Save message types separatively as not saved in messages already if not include_message_type: message_types_tag = ET.SubElement(root, "message_types") for message_type in self.message_types: message_types_tag.append(message_type.to_xml()) return root
def test_save_modulations(self): self.gframe.modulators[0].name = "Test" amplitude = random.random() self.gframe.modulators[0].carrier_amplitude = amplitude self.gframe.modulators[0].carrier_freq_hz = 1337 self.gframe.modulators[0].carrier_phase_deg = 42 self.gframe.modulators[0].modulation_type = "FSK" self.gframe.modulators[0].sample_rate = 10 ** 3 self.gframe.modulators.append(Modulator("test 2")) self.gframe.modulators = self.gframe.modulators[:2] # Take only the first two self.form.save_project() loaded_mods = self.form.project_manager.read_modulators_from_project_file() self.assertEqual(len(loaded_mods), 2) self.assertEqual(loaded_mods[0].name, "Test") self.assertEqual(loaded_mods[1].name, "test 2") self.assertEqual(loaded_mods[0].carrier_freq_hz, 1337) self.assertEqual(loaded_mods[0].carrier_phase_deg, 42) self.assertEqual(loaded_mods[0].modulation_type, "FSK") self.assertEqual(loaded_mods[0].sample_rate, 10 ** 3) self.gframe.modulators.clear() self.assertEqual(len(self.gframe.modulators), 0) self.form.project_manager.project_file = None # prevent saving of the zero modulators self.form.project_manager.set_project_folder(self.form.project_manager.project_path, close_all=False) self.assertEqual(len(self.gframe.modulators), 2)
def load_from_xml(self, xml_tag: ET.Element, message_types): assert xml_tag.tag == "simulator_config" items = [] modulators_tag = xml_tag.find("modulators") if modulators_tag: self.project_manager.modulators = Modulator.modulators_from_xml_tag(modulators_tag) participants_tag = xml_tag.find("participants") if participants_tag: self.project_manager.participants[:] = Participant.read_participants_from_xml_tag(participants_tag) self.participants_changed.emit() decodings_tag = xml_tag.find("decodings") if decodings_tag: self.project_manager.decodings = Encoding.read_decoders_from_xml_tag(decodings_tag) rx_config_tag = xml_tag.find("simulator_rx_conf") if rx_config_tag: ProjectManager.read_device_conf_dict(rx_config_tag, self.project_manager.simulator_rx_conf) tx_config_tag = xml_tag.find("simulator_tx_conf") if tx_config_tag: ProjectManager.read_device_conf_dict(tx_config_tag, self.project_manager.simulator_tx_conf) for child_tag in xml_tag.find("items"): items.append(self.load_item_from_xml(child_tag, message_types)) self.add_items(items, pos=0, parent_item=None)
def __init__(self, main_controller): super().__init__() self.main_controller = main_controller self.device_conf = dict(frequency=config.DEFAULT_FREQUENCY, sample_rate=config.DEFAULT_SAMPLE_RATE, bandwidth=config.DEFAULT_BANDWIDTH, name="USRP") self.simulator_rx_conf = dict() self.simulator_tx_conf = dict() self.simulator_num_repeat = 1 self.simulator_retries = 10 self.simulator_timeout_ms = 2500 self.simulator_error_handling_index = 2 self.__project_file = None self.__modulators = [Modulator("Modulator")] # type: list[Modulator] self.__decodings = [] # type: list[Encoding] self.load_decodings() self.modulation_was_edited = False self.description = "" self.project_path = "" self.broadcast_address_hex = "ffff" self.participants = [] self.field_types = [] # type: list[FieldType] self.field_types_by_caption = dict() self.reload_field_types()
def to_xml_tag(self, decodings, participants, tag_name="protocol", include_message_type=False, write_bits=False, messages=None, modulators=None) -> ET.Element: root = ET.Element(tag_name) messages = self.messages if messages is None else messages # Save modulators if modulators is not None: # For protocol analyzer container root.append(Modulator.modulators_to_xml_tag(modulators)) root.append(Encoding.decodings_to_xml_tag(decodings)) root.append(Participant.participants_to_xml_tag(participants)) # Save data data_tag = ET.SubElement(root, "messages") for i, message in enumerate(messages): message_tag = message.to_xml(decoders=decodings, include_message_type=include_message_type, write_bits=write_bits) data_tag.append(message_tag) # Save message types separatively as not saved in messages already if not include_message_type: message_types_tag = ET.SubElement(root, "message_types") for message_type in self.message_types: message_types_tag.append(message_type.to_xml()) return root
def read_modulators_from_file(filename: str): if not filename: return [] tree = ET.parse(filename) root = tree.getroot() return Modulator.modulators_from_xml_tag(root)
def read_modulators_from_file(filename: str): if not filename: return [] tree = ET.parse(filename) root = tree.getroot() return Modulator.modulators_from_xml_tag(root)
def test_cli_modulate_messages(self): modulator = Modulator("test") modulator.sample_rate = 2e3 modulator.samples_per_bit = 100 modulator.modulation_type_str = "ASK" modulator.param_for_zero = 0 modulator.param_for_one = 100 bits = "1010111100001" self.assertIsNone(urh_cli.modulate_messages([], modulator)) message = Message.from_plain_bits_str(bits, pause=1000) modulated = urh_cli.modulate_messages([message], modulator) # Demodulate for testing s = Signal("", "", modulation="ASK", sample_rate=2e6) s.bit_len = 100 s.noise_threshold = 0 s.iq_array = modulated pa = ProtocolAnalyzer(s) pa.get_protocol_from_signal() self.assertEqual(len(pa.messages), 1) self.assertEqual(pa.messages[0].plain_bits_str, bits)
def from_xml_tag(self, root: ET.Element, read_bits=False, participants=None, decodings=None): if not root: return None if root.find("modulators") and hasattr(self, "modulators"): self.modulators[:] = [] for mod_tag in root.find("modulators").findall("modulator"): self.modulators.append(Modulator.from_xml(mod_tag)) decoders = self.read_decoders_from_xml_tag( root) if decodings is None else decodings if participants is None: participants = self.read_participants_from_xml_tag(root) if read_bits: self.messages[:] = [] try: message_types = [] for message_type_tag in root.find("message_types").findall( "message_type"): message_types.append(MessageType.from_xml(message_type_tag)) except AttributeError: message_types = [] for message_type in message_types: if message_type not in self.message_types: self.message_types.append(message_type) try: message_tags = root.find("messages").findall("message") for i, message_tag in enumerate(message_tags): if read_bits: message = Message.from_plain_bits_str( bits=message_tag.get("bits")) message.from_xml(tag=message_tag, participants=participants, decoders=decoders, message_types=self.message_types) self.messages.append(message) else: try: self.messages[i].from_xml( tag=message_tag, participants=participants, decoders=decoders, message_types=self.message_types) except IndexError: pass # Part of signal was copied in last session but signal was not saved except AttributeError: pass
def set_project_folder(self, path, ask_for_new_project=True): if path != self.project_path: self.maincontroller.close_all() self.project_path = path self.project_file = os.path.join(self.project_path, constants.PROJECT_FILE) if not os.path.isfile(self.project_file): if ask_for_new_project: reply = QMessageBox.question(self.maincontroller, "Project File", "Do you want to create a Project File for this folder?\n" "If you chose No, you can do it later via File->Convert Folder to Project.", QMessageBox.Yes | QMessageBox.No) if reply == QMessageBox.Yes: dialog = ProjectDialogController(new_project=False, parent=self.maincontroller) dialog.set_path(path) dialog.finished.connect(self.on_dialog_finished) dialog.exec_() else: self.project_file = None if self.project_file is not None: root = ET.Element("UniversalRadioHackerProject") tree = ET.ElementTree(root) tree.write(self.project_file) else: self.read_recording_parameters() self.maincontroller.add_files(self.read_opened_filenames()) self.read_compare_frame_groups() # Labels are read out here cfc = self.maincontroller.compare_frame_controller cfc.load_decodings() cfc.fill_decoding_combobox() for group_id, decoding_index in self.read_decodings().items(): cfc.groups[group_id].decoding = cfc.decodings[decoding_index] #cfc.ui.cbDecoding.setCurrentIndex(index) cfc.refresh_protocol_labels() cfc.updateUI() modulators = self.read_modulators_from_project_file() self.maincontroller.generator_tab_controller.modulators = modulators if modulators else [ Modulator("Modulation")] self.maincontroller.generator_tab_controller.refresh_modulators() if len(self.project_path) > 0 and self.project_file is None: self.maincontroller.ui.actionConvert_Folder_to_Project.setEnabled(True) else: self.maincontroller.ui.actionConvert_Folder_to_Project.setEnabled(False) self.maincontroller.adjustForCurrentFile(path) self.maincontroller.filemodel.setRootPath(path) self.maincontroller.ui.fileTree.setRootIndex( self.maincontroller.file_proxy_model.mapFromSource(self.maincontroller.filemodel.index(path))) self.maincontroller.ui.fileTree.setToolTip(path) self.maincontroller.ui.splitter.setSizes([1, 1]) self.maincontroller.setWindowTitle("Universal Radio Hacker [" + path + "]")
def test_gfsk(self): target_file = os.path.join(tempfile.gettempdir(), "test.complex") modulator = Modulator("gfsk") modulator.modulation_type_str = "FSK" modulator.samples_per_symbol = 100 modulator.sample_rate = 1e6 modulator.param_for_one = 20e3 modulator.param_for_zero = -10e3 data1 = modulator.modulate([True, False, False, True, False], 9437) data2 = modulator.modulate([True, False, True], 9845) #, start=len(s)) data3 = modulator.modulate([True, False, True, False], 8457) #, start=len(s)) s = np.concatenate((data1, data2, data3)) s.tofile(target_file) pa = ProtocolAnalyzer(Signal(target_file, "test", modulation="FSK")) pa.get_protocol_from_signal()
def add_modulator(self): names = [m.name for m in self.modulators] name = "Modulation" number = 1 while name in names: name = "Modulation " + str(number) number += 1 self.modulators.append(Modulator(name)) self.ui.comboBoxCustomModulations.addItem(name) self.ui.comboBoxCustomModulations.setCurrentIndex(len(self.modulators) - 1) self.ui.btnRemoveModulation.setEnabled(True)
def __get_continuous_send_dialog(self): messages = [Message([True]*100, 1000, self.form.compare_frame_controller.active_message_type) for _ in range(10)] modulators = [Modulator("Test")] continuous_send_dialog = ContinuousSendDialogController(self.form.project_manager, messages, modulators, self.form.generator_tab_controller.total_modulated_samples, parent=self.form, testing_mode=True) if self.SHOW: continuous_send_dialog.show() return continuous_send_dialog
def test_cli_modulate_messages(self): modulator = Modulator("test") modulator.sample_rate = 2e3 modulator.samples_per_bit = 100 modulator.modulation_type_str = "ASK" modulator.param_for_zero = 0 modulator.param_for_one = 100 bits = "1010111100001" self.assertIsNone(urh_cli.modulate_messages([], modulator)) message = Message.from_plain_bits_str(bits, pause=1000) modulated = urh_cli.modulate_messages([message], modulator) # Demodulate for testing s = Signal("", "", modulation="ASK", sample_rate=2e6) s.bit_len = 100 s.noise_threshold = 0 s._fulldata = modulated pa = ProtocolAnalyzer(s) pa.get_protocol_from_signal() self.assertEqual(len(pa.messages), 1) self.assertEqual(pa.messages[0].plain_bits_str, bits)
def test_load_profile(self): filename = os.path.join(tempfile.gettempdir(), "test.fuzz.xml") mod1 = Modulator("mod 1") mod2 = Modulator("mod 2") mod2.param_for_one = 42 decoders = [ Encoding(["NRZ"]), Encoding(["NRZ-I", constants.DECODING_INVERT]) ] pac = ProtocolAnalyzerContainer() pac.messages.append( Message([True, False, False, True], 100, decoder=decoders[0], message_type=pac.default_message_type)) pac.messages.append( Message([False, False, False, False], 200, decoder=decoders[1], message_type=pac.default_message_type)) pac.create_fuzzing_label(1, 10, 0) assert isinstance(self.form, MainController) pac.to_xml_file(filename, decoders=decoders, participants=self.form.project_manager.participants) self.wait_before_new_file() self.form.add_files( [os.path.join(tempfile.gettempdir(), "test.fuzz.xml")]) self.assertEqual(self.form.ui.tabWidget.currentWidget(), self.form.ui.tab_generator) pac = self.form.generator_tab_controller.table_model.protocol self.assertEqual(len(pac.messages), 2) self.assertEqual(pac.messages[1][0], False) self.assertEqual(len(pac.protocol_labels), 1)
def test_gfsk(self): target_file = os.path.join(tempfile.gettempdir(), "test.complex") modulator = Modulator("gfsk") modulator.modulation_type_str = "FSK" modulator.samples_per_bit = 100 modulator.sample_rate = 1e6 modulator.param_for_one = 20e3 modulator.param_for_zero = -10e3 data1 = modulator.modulate([True, False, False, True, False], 9437) data2 = modulator.modulate([True, False, True], 9845) #, start=len(s)) data3 = modulator.modulate([True, False, True, False], 8457) #, start=len(s)) s = np.concatenate((data1, data2, data3)) s.tofile(target_file) pa = ProtocolAnalyzer(Signal(target_file, "test", modulation="FSK")) pa.get_protocol_from_signal()
def test_modulate_continuously(self): modulator = Modulator("Test") continuous_modulator = ContinuousModulator(self.__create_messages(), [modulator]) self.assertEqual(continuous_modulator.current_message_index.value, 0) self.assertTrue(continuous_modulator.ring_buffer.is_empty) continuous_modulator.start() self.assertTrue(continuous_modulator.process.is_alive()) time.sleep(1) self.assertFalse(continuous_modulator.ring_buffer.is_empty) continuous_modulator.stop() self.assertFalse(continuous_modulator.process.is_alive())
def test_channels(self): sample_rate = 10**6 channel1_freq = 40 * 10**3 channel2_freq = 240 * 10**3 channel1_data = array.array("B", [1, 0, 1, 0, 1, 0, 0, 1]) channel2_data = array.array("B", [1, 1, 0, 0, 1, 1, 0, 1]) channel3_data = array.array("B", [1, 0, 0, 1, 0, 1, 1, 1]) filter_bw = 0.1 filter_freq1_high = 1.5 * channel1_freq filter_freq1_low = 0.5 * channel1_freq filter_freq2_high = 1.5 * channel2_freq filter_freq2_low = 0.5 * channel2_freq modulator1, modulator2, modulator3 = Modulator("test"), Modulator( "test2"), Modulator("test3") modulator1.carrier_freq_hz = channel1_freq modulator2.carrier_freq_hz = channel2_freq modulator3.carrier_freq_hz = -channel2_freq modulator1.sample_rate = modulator2.sample_rate = modulator3.sample_rate = sample_rate data1 = modulator1.modulate(channel1_data) data2 = modulator2.modulate(channel2_data) data3 = modulator3.modulate(channel3_data) mixed_signal = data1 + data2 + data3 mixed_signal.tofile("/tmp/three_channels.complex") plt.subplot("221") plt.title("Signal") plt.plot(mixed_signal) spectrogram = Spectrogram(mixed_signal) plt.subplot("222") plt.title("Spectrogram") plt.imshow(np.transpose(spectrogram.data), aspect="auto", cmap="magma") plt.ylim(0, spectrogram.freq_bins) chann1_filtered = Filter.apply_bandpass_filter( mixed_signal, filter_freq1_low / sample_rate, filter_freq1_high / sample_rate, filter_bw) plt.subplot("223") plt.title("Channel 1 Filtered ({})".format("".join( map(str, channel1_data)))) plt.plot(chann1_filtered) chann2_filtered = Filter.apply_bandpass_filter( mixed_signal, filter_freq2_low / sample_rate, filter_freq2_high / sample_rate, filter_bw) plt.subplot("224") plt.title("Channel 2 Filtered ({})".format("".join( map(str, channel2_data)))) plt.plot(chann2_filtered) plt.show()
def test_psk_detection(self): modulator = Modulator("") modulator.modulation_type_str = "PSK" modulator.param_for_zero = 0 modulator.param_for_one = 180 data = modulator.modulate("10101010111000") mod = AutoInterpretation.detect_modulation(data) self.assertEqual(mod, "PSK")
def test_psk_detection(self): modulator = Modulator("") modulator.modulation_type = "PSK" modulator.parameters[0] = 0 modulator.parameters[1] = 180 data = modulator.modulate("10101010111000") mod = AutoInterpretation.detect_modulation(data) self.assertEqual(mod, "PSK")
def read_modulators_from_file(self, filename: str): if not filename: return [] tree = ET.parse(filename) root = tree.getroot() result = [] for mod_tag in root.iter("modulator"): mod = Modulator(mod_tag.attrib["name"]) mod.carrier_freq_hz = float(mod_tag.attrib["carrier_freq_hz"]) mod.carrier_amplitude = float(mod_tag.attrib["carrier_amplitude"]) mod.carrier_phase_deg = float(mod_tag.attrib["carrier_phase_deg"]) mod.modulation_type = int(mod_tag.attrib["modulation_type"]) mod.sample_rate = float(mod_tag.attrib["sample_rate"]) mod.param_for_one = float(mod_tag.attrib["param_for_one"]) mod.param_for_zero = float(mod_tag.attrib["param_for_zero"]) result.append(mod) return result
def save_to_xml(self, standalone=False) -> ET.Element: result = ET.Element("simulator_config") if standalone: result.append(Modulator.modulators_to_xml_tag(self.project_manager.modulators)) result.append(Encoding.decodings_to_xml_tag(self.project_manager.decodings)) result.append(Participant.participants_to_xml_tag(self.project_manager.participants)) result.append(self.project_manager.simulator_rx_conf_to_xml()) result.append(self.project_manager.simulator_tx_conf_to_xml()) items_tag = ET.SubElement(result, "items") for item in self.rootItem.children: self.__save_item_to_xml(items_tag, item) return result
def test_segmentation_ask_50(self): modulator = Modulator("ask50") modulator.modulation_type = "ASK" modulator.parameters[0] = 50 modulator.parameters[1] = 100 modulator.samples_per_symbol = 100 msg1 = modulator.modulate("1010101111", pause=10000) msg2 = modulator.modulate("1010101110010101", pause=20000) msg3 = modulator.modulate("1010101010101111", pause=30000) data = IQArray.concatenate((msg1, msg2, msg3)) segments = segment_messages_from_magnitudes(data.magnitudes, noise_threshold=0) self.assertEqual(len(segments), 3) self.assertEqual(segments, [(0, 999), (10999, 12599), (32599, 34199)])
def read_modulators_from_project_file(self): """ :rtype: list of Modulator """ if not self.project_file: return [] tree = ET.parse(self.project_file) root = tree.getroot() result = [] for mod_tag in root.iter("modulator"): result.append(Modulator.from_xml(mod_tag)) return result
def read_modulators_from_project_file(self): """ :rtype: list of Modulator """ if not self.project_file: return [] tree = ET.parse(self.project_file) root = tree.getroot() result = [] for mod_tag in root.iter("modulator"): result.append(Modulator.from_xml(mod_tag)) return result
def write_modulators_to_project_file(self, tree=None): """ :type modulators: list of Modulator :return: """ if self.project_file is None or not self.modulators: return if tree is None: tree = ET.parse(self.project_file) root = tree.getroot() root.append(Modulator.modulators_to_xml_tag(self.modulators)) tree.write(self.project_file)
def write_modulators_to_project_file(self, tree=None): """ :type modulators: list of Modulator :return: """ if self.project_file is None or not self.modulators: return if tree is None: tree = ET.parse(self.project_file) root = tree.getroot() root.append(Modulator.modulators_to_xml_tag(self.modulators)) tree.write(self.project_file)
def from_xml_tag(self, root: ET.Element, read_bits=False, participants=None, decodings=None): if not root: return None if root.find("modulators") and hasattr(self, "modulators"): self.modulators[:] = [] for mod_tag in root.find("modulators").findall("modulator"): self.modulators.append(Modulator.from_xml(mod_tag)) decoders = self.read_decoders_from_xml_tag(root) if decodings is None else decodings if participants is None: participants = self.read_participants_from_xml_tag(root) if read_bits: self.messages[:] = [] try: message_types = [] for message_type_tag in root.find("message_types").findall("message_type"): message_types.append(MessageType.from_xml(message_type_tag)) except AttributeError: message_types = [] for message_type in message_types: if message_type not in self.message_types: self.message_types.append(message_type) try: message_tags = root.find("messages").findall("message") for i, message_tag in enumerate(message_tags): if read_bits: message = Message.from_plain_bits_str(bits=message_tag.get("bits")) message.from_xml(tag=message_tag, participants=participants, decoders=decoders, message_types=self.message_types) self.messages.append(message) else: try: self.messages[i].from_xml(tag=message_tag, participants=participants, decoders=decoders, message_types=self.message_types) except IndexError: pass # Part of signal was copied in last session but signal was not saved except AttributeError: pass
def test_segmentation_ask_50(self): modulator = Modulator("ask50") modulator.modulation_type_str = "ASK" modulator.param_for_zero = 50 modulator.param_for_one = 100 modulator.samples_per_bit = 100 msg1 = modulator.modulate("1010101111", pause=10000) msg2 = modulator.modulate("1010101110010101", pause=20000) msg3 = modulator.modulate("1010101010101111", pause=30000) data = np.concatenate((msg1, msg2, msg3)) segments = segment_messages_from_magnitudes(np.abs(data), noise_threshold=0) print(segments) self.assertEqual(len(segments), 3) self.assertEqual(segments, [(0, 999), (10999, 12599), (32599, 34199)]) print(merge_message_segments_for_ook(segments))
def test_ask_fsk_psk_modulation(self): modulations = ["ASK", "FSK", "PSK"] for i, modulation in enumerate(modulations): modulator = Modulator(modulation) tmp_dir = QDir.tempPath() filename = "{0}_mod.complex".format(modulation) filename = os.path.join(tmp_dir, filename) modulator.modulation_type = i modulator.samples_per_bit = self.samples_per_bit if modulation == "ASK": modulator.param_for_zero = 0 modulator.param_for_one = 100 elif modulation == "FSK": modulator.param_for_zero = 1000 modulator.param_for_one = 2500 elif modulation == "PSK": modulator.param_for_zero = 0 modulator.param_for_one = 180 modulator.modulate(self.modulation_data, self.pause).tofile(filename) signal = Signal(filename, modulation) signal.modulation_type = i signal.bit_len = self.samples_per_bit if modulation == "ASK": signal.qad_center = 0.5 elif modulation == "FSK": signal.qad_center = 0.0097 elif modulation == "PSK": signal.qad_center = 0 self.assertEqual(signal.num_samples, self.total_samples, msg=modulation) pa = ProtocolAnalyzer(signal) pa.get_protocol_from_signal() self.assertEqual(1, len(pa.messages), msg=modulation) self.assertEqual(self.modulation_data, pa.messages[0].plain_bits, msg=modulation)
def test_performance(self): self.form = MainController() self.cfc = self.form.compare_frame_controller self.stc = self.form.simulator_tab_controller self.gtc = self.form.generator_tab_controller self.form.add_signalfile(get_path_for_data_file("esaver.coco")) self.sframe = self.form.signal_tab_controller.signal_frames[0] self.sim_frame = self.form.simulator_tab_controller self.form.ui.tabWidget.setCurrentIndex(3) self.cfc.proto_analyzer.auto_assign_labels() self.network_sdr_plugin_sender = NetworkSDRInterfacePlugin(raw_mode=True) part_a = Participant("Device A", shortname="A", color_index=0) part_b = Participant("Device B", shortname="B", color_index=1) part_b.simulate = True self.form.project_manager.participants.append(part_a) self.form.project_manager.participants.append(part_b) self.form.project_manager.project_updated.emit() sniffer = ProtocolSniffer(100, 0.01, 0.1, 5, 1, NetworkSDRInterfacePlugin.NETWORK_SDR_NAME, BackendHandler(), network_raw_mode=True) sender = EndlessSender(BackendHandler(), NetworkSDRInterfacePlugin.NETWORK_SDR_NAME) simulator = Simulator(self.stc.simulator_config, self.gtc.modulators, self.stc.sim_expression_parser, self.form.project_manager, sniffer=sniffer, sender=sender) pause = 100 msg_a = SimulatorMessage(part_b, [1, 0] * 16 + [1, 1, 0, 0] * 8 + [0, 0, 1, 1] * 8 + [1, 0, 1, 1, 1, 0, 0, 1, 1, 1] * 4, pause=pause, message_type=MessageType("empty_message_type"), source=part_a) msg_b = SimulatorMessage(part_a, [1, 0] * 16 + [1, 1, 0, 0] * 8 + [1, 1, 0, 0] * 8 + [1, 0, 1, 1, 1, 0, 0, 1, 1, 1] * 4, pause=pause, message_type=MessageType("empty_message_type"), source=part_b) self.stc.simulator_config.add_items([msg_a, msg_b], 0, None) self.stc.simulator_config.update_active_participants() port = self.get_free_port() sniffer = simulator.sniffer sniffer.rcv_device.set_server_port(port) self.network_sdr_plugin_sender.client_port = port sender = simulator.sender port = self.get_free_port() sender.device.set_client_port(port) sender.device._VirtualDevice__dev.name = "simulator_sender" current_index = Value("L") elapsed = Value("f") target_num_samples = 13600 + pause receive_process = Process(target=receive, args=(port, current_index, target_num_samples, elapsed)) receive_process.daemon = True receive_process.start() # Ensure receiver is running time.sleep(2) # spy = QSignalSpy(self.network_sdr_plugin_receiver.rcv_index_changed) simulator.start() modulator = Modulator("test_modulator") modulator.samples_per_bit = 100 modulator.carrier_freq_hz = 55e3 # yappi.start() self.network_sdr_plugin_sender.send_raw_data(modulator.modulate(msg_a.encoded_bits), 1) time.sleep(0.5) # send some zeros to simulate the end of a message self.network_sdr_plugin_sender.send_raw_data(np.zeros(self.num_zeros_for_pause, dtype=np.complex64), 1) time.sleep(0.5) receive_process.join(15) logger.info("PROCESS TIME: {0:.2f}ms".format(elapsed.value)) # self.assertEqual(current_index.value, target_num_samples) self.assertLess(elapsed.value, 200) # timeout = spy.wait(2000) # yappi.get_func_stats().print_all() # yappi.get_thread_stats().print_all()
def push_data(self, data: np.ndarray): self.ringbuffer.push(data) if __name__ == '__main__': from urh.dev.BackendHandler import BackendHandler from urh.signalprocessing.Message import Message from urh.signalprocessing.MessageType import MessageType from urh.signalprocessing.Modulator import Modulator from urh.util.Logger import logger import time endless_sender = EndlessSender(BackendHandler(), "HackRF") msg = Message([1, 0] * 16 + [1, 1, 0, 0] * 8 + [0, 0, 1, 1] * 8 + [1, 0, 1, 1, 1, 0, 0, 1, 1, 1] * 4, 0, MessageType("empty_message_type")) modulator = Modulator("test_modulator") modulator.samples_per_bit = 1000 modulator.carrier_freq_hz = 55e3 logger.debug("Starting endless sender") endless_sender.start() time.sleep(1) logger.debug("Pushing data") endless_sender.push_data(modulator.modulate(msg.encoded_bits)) logger.debug("Pushed data") time.sleep(5) logger.debug("Stopping endless sender") endless_sender.stop() time.sleep(1) logger.debug("bye")
# data = np.fromfile("/home/joe/GIT/urh/tests/data/ask.complex", dtype=np.complex64)[462:754] # data = np.fromfile("/home/joe/GIT/urh/tests/data/enocean.complex", dtype=np.complex64)[9724:10228] data = np.fromfile("/home/joe/GIT/publications/ainterpretation/experiments/signals/esaver_test4on.complex", dtype=np.complex64)[86452:115541] # data = np.fromfile("/home/joe/GIT/urh/tests/data/action_ook.complex", dtype=np.complex64)[3780:4300] # data = np.fromfile("/home/joe/GIT/urh/tests/data/ask50.complex", dtype=np.complex64) # Wavelet transform the data # data = np.fromfile("/home/joe/GIT/urh/tests/data/ask.complex", dtype=np.complex64)[0:2 ** 13] # data = np.fromfile("/tmp/generated.complex", dtype=np.complex64) # data = np.fromfile("/tmp/psk.complex", dtype=np.complex64) # data = np.fromfile("/home/joe/GIT/urh/tests/data/psk_generated.complex", dtype=np.complex64)[0:8000] modulator = Modulator("") modulator.modulation_type_str = "PSK" modulator.param_for_zero = 0 modulator.param_for_one = 180 modulator.carrier_freq_hz = 5e3 modulator.sample_rate = 200e3 # data = modulator.modulate("1010", pause=0) # data = np.fromfile("/tmp/ask25.complex", dtype=np.complex64) # data = np.fromfile("/tmp/ask1080.complex", dtype=np.complex64) scale = 4 median_filter_order = 11 data = data[np.abs(data) > 0] # Normalize with max of data to prevent increasing variance for signals with lower amplitude