예제 #1
0
파일: PlotTests.py 프로젝트: starling021/uh
    def test_plot(self):
        modulator = Modulator("gfsk")
        modulator.modulation_type = "GFSK"
        modulator.samples_per_symbol = 100
        modulator.sample_rate = 1e6
        modulator.parameters[1] = 20e3
        modulator.parameters[0] = 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, "FSK")
        plt.plot(qad)
        plt.title("Quad Demod")

        plt.show()
예제 #2
0
파일: urh_cli.py 프로젝트: zxc135781/urh
def build_modulator_from_args(arguments: argparse.Namespace):
    if arguments.raw:
        return None
    if arguments.bits_per_symbol is None:
        arguments.bits_per_symbol = 1

    n = 2 ** int(arguments.bits_per_symbol)
    if arguments.parameters is None or len(arguments.parameters) != n:
        raise ValueError("You need to give {} parameters for {} bits per symbol".format(n, int(arguments.bits_per_symbol)))

    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_symbol = int(arguments.samples_per_symbol)
    result.bits_per_symbol = int(arguments.bits_per_symbol)
    result.modulation_type = arguments.modulation_type
    result.sample_rate = arguments.sample_rate

    for i, param in enumerate(arguments.parameters):
        if result.is_amplitude_based and param.endswith("%"):
            result.parameters[i] = float(param[:-1])
        elif result.is_amplitude_based and not param.endswith("%"):
            result.parameters[i] = float(param) * 100
        else:
            result.parameters[i] = float(param)

    return result
예제 #3
0
    def test_cli_modulate_messages(self):
        modulator = Modulator("test")
        modulator.sample_rate = 2e3
        modulator.samples_per_symbol = 100
        modulator.modulation_type = "ASK"
        modulator.parameters[0] = 0
        modulator.parameters[1] = 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.samples_per_symbol = 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)
예제 #4
0
    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)
예제 #5
0
    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)])
예제 #6
0
    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()
예제 #7
0
    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_symbol = self.samples_per_symbol

            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_symbol
            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)
예제 #8
0
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_symbol = 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 = arguments.modulation_type
    result.sample_rate = arguments.sample_rate

    return result
예제 #9
0
    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.complex16s"))
        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.01, 0.1, 5, "FSK", 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_symbol = 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()
예제 #10
0
        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_symbol = 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")