Пример #1
0
def demodulate(signal_data,
               mod_type: str,
               bit_length,
               center,
               noise,
               tolerance,
               decoding=None,
               pause_threshold=8):
    signal = Signal("", "")
    if isinstance(signal_data, IQArray):
        signal.iq_array = signal_data
    else:
        if signal_data.dtype == np.complex64:
            signal.iq_array = IQArray(signal_data.view(np.float32))
        else:
            signal.iq_array = IQArray(signal_data)
    signal.modulation_type = mod_type
    signal.bit_len = bit_length
    signal.qad_center = center
    signal.noise_threshold = noise
    signal.pause_threshold = pause_threshold
    if tolerance is not None:
        signal.tolerance = tolerance
    pa = ProtocolAnalyzer(signal)
    if decoding is not None:
        pa.decoder = decoding
    pa.get_protocol_from_signal()
    return pa.decoded_hex_str
Пример #2
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)
Пример #3
0
    def modulate(self, data=None, pause=0, start=0) -> IQArray:
        assert pause >= 0
        if data is None:
            data = self.data
        else:
            self.data = data

        if isinstance(data, str):
            data = array.array("B", map(int, data))
        elif isinstance(data, list):
            data = array.array("B", data)

        if len(data) == 0:
            return IQArray(None, np.float32, 0)

        dtype = self.get_dtype()
        a = self.carrier_amplitude * IQArray.min_max_for_dtype(dtype)[1]

        type_code = "b" if dtype == np.int8 else "h" if dtype == np.int16 else "f"
        type_val = array.array(type_code, [0])[0]

        parameters = self.parameters
        if self.modulation_type == "ASK":
            parameters = array.array("f", [a * p / 100 for p in parameters])
        elif self.modulation_type == "PSK":
            parameters = array.array("f",
                                     [p * (math.pi / 180) for p in parameters])

        result = signal_functions.modulate_c(
            data, self.samples_per_symbol, self.modulation_type, parameters,
            self.bits_per_symbol, a, self.carrier_freq_hz,
            self.carrier_phase_deg * (np.pi / 180), self.sample_rate, pause,
            start, type_val, self.gauss_bt, self.gauss_filter_width)
        return IQArray(result)
Пример #4
0
    def test_4_psk(self):
        bits = array.array("B", [1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1])
        angles_degree = [-135, -45, 45, 135]

        parameters = array.array("f", [np.pi*a/180 for a in angles_degree])
        result = modulate_c(bits, 100, "PSK", parameters, 2, 1, 40e3, 0, 1e6, 1000, 0)

        signal = Signal("")
        signal.iq_array = IQArray(result)
        signal.bits_per_symbol = 2
        signal.center = 0
        signal.center_spacing = 1
        signal.modulation_type = "PSK"

        proto_analyzer = ProtocolAnalyzer(signal)
        proto_analyzer.get_protocol_from_signal()
        demod_bits = proto_analyzer.plain_bits_str[0]
        self.assertEqual(len(demod_bits), len(bits))
        self.assertTrue(demod_bits.startswith("10101010"))

        np.random.seed(42)
        noised = result + 0.1 * np.random.normal(loc=0, scale=np.sqrt(2)/2, size=(len(result), 2))
        signal.iq_array = IQArray(noised.astype(np.float32))
        signal.center_spacing = 1.5
        signal.noise_threshold = 0.2
        signal._qad = None
        proto_analyzer.get_protocol_from_signal()
        demod_bits = proto_analyzer.plain_bits_str[0]
        self.assertEqual(len(demod_bits), len(bits))
        self.assertTrue(demod_bits.startswith("10101010"))
Пример #5
0
 def on_btn_save_rx_clicked(self):
     rx_device = self.simulator.sniffer.rcv_device
     if isinstance(rx_device.data, np.ndarray) or isinstance(rx_device.data, IQArray):
         data = IQArray(rx_device.data[:rx_device.current_index])
         filename = FileOperator.ask_signal_file_name_and_save("simulation_capture", data,
                                                               sample_rate=rx_device.sample_rate, parent=self)
         if filename:
             data.tofile(filename)
             self.rx_file_saved.emit(filename)
Пример #6
0
    def test_continuous_pop(self):
        ring_buffer = RingBuffer(size=10)
        values = IQArray(np.array(list(range(10)), dtype=np.complex64))
        ring_buffer.push(values)
        retrieved = np.empty(0, dtype=np.float32)

        for i in range(10):
            retrieved = np.append(retrieved, ring_buffer.pop(1))

        self.assertEqual(values, IQArray(retrieved))
Пример #7
0
    def __init__(self,
                 filename: str,
                 name="Signal",
                 modulation: str = None,
                 sample_rate: float = 1e6,
                 parent=None):
        super().__init__(parent)
        self.__name = name
        self.__tolerance = 5
        self.__samples_per_symbol = 100
        self.__pause_threshold = 8
        self.__message_length_divisor = 1
        self.__costas_loop_bandwidth = 0.1
        self._qad = None
        self.__center = 0
        self._noise_threshold = 0
        self.__sample_rate = sample_rate
        self.noise_min_plot = 0
        self.noise_max_plot = 0
        self.block_protocol_update = False

        self.iq_array = IQArray(None, np.int8, 1)

        self.wav_mode = filename.endswith(".wav")
        self.__changed = False
        if modulation is None:
            modulation = "FSK"
        self.__modulation_type = modulation
        self.__bits_per_symbol = 1
        self.__center_spacing = 1  # required for higher order modulations

        self.__parameter_cache = {
            mod: {
                "center": None,
                "samples_per_symbol": None
            }
            for mod in self.MODULATION_TYPES
        }

        self.__already_demodulated = False

        if len(filename) > 0:
            if self.wav_mode:
                self.__load_wav_file(filename)
            elif filename.endswith(".coco"):
                self.__load_compressed_complex(filename)
            else:
                self.__load_complex_file(filename)

            self.filename = filename
            self.noise_threshold = AutoInterpretation.detect_noise_level(
                self.iq_array.magnitudes)
        else:
            self.filename = ""
Пример #8
0
    def modulate(self, data=None, pause=0, start=0) -> IQArray:
        assert pause >= 0
        if data is None:
            data = self.data
        else:
            self.data = data

        if isinstance(data, str):
            data = array.array("B", map(int, data))
        elif isinstance(data, list):
            data = array.array("B", data)

        if len(data) == 0:
            return IQArray(None, np.float32, 0)

        mod_type = self.MODULATION_TYPES[self.modulation_type]

        dtype = self.get_dtype()
        a = self.carrier_amplitude * IQArray.min_max_for_dtype(dtype)[1]

        # add a variable here to prevent it from being garbage collected in multithreaded cases (Python 3.4)
        result = np.zeros(0, dtype=dtype)

        type_code = "b" if dtype == np.int8 else "h" if dtype == np.int16 else "f"
        type_val = array.array(type_code, [0])[0]

        if mod_type == "FSK":
            result = signal_functions.modulate_fsk(
                data, pause, start, a, self.param_for_zero, self.param_for_one,
                self.carrier_phase_deg * (np.pi / 180), self.sample_rate,
                self.samples_per_bit, type_val)
        elif mod_type == "ASK":
            a0 = a * (self.param_for_zero / 100)
            a1 = a * (self.param_for_one / 100)
            result = signal_functions.modulate_ask(
                data, pause, start, a0, a1, self.carrier_freq_hz,
                self.carrier_phase_deg * (np.pi / 180), self.sample_rate,
                self.samples_per_bit, type_val)
        elif mod_type == "PSK":
            phi0 = self.param_for_zero * (np.pi / 180)
            phi1 = self.param_for_one * (np.pi / 180)
            result = signal_functions.modulate_psk(data, pause, start, a,
                                                   self.carrier_freq_hz, phi0,
                                                   phi1, self.sample_rate,
                                                   self.samples_per_bit,
                                                   type_val)
        elif mod_type == "GFSK":
            result = signal_functions.modulate_gfsk(
                data, pause, start, a, self.param_for_zero, self.param_for_one,
                self.carrier_phase_deg * (np.pi / 180), self.sample_rate,
                self.samples_per_bit, self.gauss_bt, self.gauss_filter_width,
                type_val)

        return IQArray(result)
Пример #9
0
    def __init__(self,
                 samples_per_symbol: int,
                 center: float,
                 center_spacing: float,
                 noise: float,
                 tolerance: int,
                 modulation_type: str,
                 bits_per_symbol: int,
                 device: str,
                 backend_handler: BackendHandler,
                 network_raw_mode=False):
        signal = Signal("", "LiveSignal")
        signal.samples_per_symbol = samples_per_symbol
        signal.center = center
        signal.center_spacing = center_spacing
        signal.noise_threshold = noise
        signal.tolerance = tolerance
        signal.silent_set_modulation_type(modulation_type)
        signal.bits_per_symbol = bits_per_symbol
        ProtocolAnalyzer.__init__(self, signal)
        QObject.__init__(self, None)

        self.network_raw_mode = network_raw_mode
        self.backend_handler = backend_handler
        self.rcv_device = VirtualDevice(self.backend_handler,
                                        device,
                                        Mode.receive,
                                        resume_on_full_receive_buffer=True,
                                        raw_mode=network_raw_mode)

        signal.iq_array = IQArray(None, self.rcv_device.data_type, 0)

        self.sniff_thread = Thread(target=self.check_for_data, daemon=True)

        self.rcv_device.started.connect(self.__emit_started)
        self.rcv_device.stopped.connect(self.__emit_stopped)

        self.__buffer = IQArray(None, np.float32, 0)
        self.__init_buffer()
        self.__current_buffer_index = 0

        self.reading_data = False
        self.adaptive_noise = False
        self.automatic_center = False

        self.pause_length = 0
        self.is_running = False

        self.store_messages = True

        self.__sniff_file = ""
        self.__store_data = True
Пример #10
0
    def __load_wav_file(self, filename: str):
        wav = wave.open(filename, "r")
        num_channels, sample_width, sample_rate, num_frames, comptype, compname = wav.getparams(
        )

        if sample_width == 1:
            params = {"min": 0, "max": 255, "fmt": np.uint8}  # Unsigned Byte
        elif sample_width == 2:
            params = {"min": -32768, "max": 32767, "fmt": np.int16}
        elif sample_width == 3:
            params = {"min": -8388608, "max": 8388607, "fmt": np.int32}
        elif sample_width == 4:
            params = {"min": -2147483648, "max": 2147483647, "fmt": np.int32}
        else:
            raise ValueError(
                "Can't handle sample width {0}".format(sample_width))

        params["center"] = (params["min"] + params["max"]) / 2

        byte_frames = wav.readframes(num_frames * num_channels)
        if sample_width == 3:
            num_samples = len(byte_frames) // (sample_width * num_channels)
            arr = np.empty((num_samples, num_channels, 4), dtype=np.uint8)
            raw_bytes = np.frombuffer(byte_frames, dtype=np.uint8)
            arr[:, :, :sample_width] = raw_bytes.reshape(
                -1, num_channels, sample_width)
            arr[:, :, sample_width:] = (
                arr[:, :, sample_width - 1:sample_width] >> 7) * 255
            data = arr.view(np.int32).flatten()
        else:
            data = np.frombuffer(byte_frames, dtype=params["fmt"])

        self.iq_array = IQArray(None, np.float32, n=num_frames)
        if num_channels == 1:
            self.iq_array.real = np.multiply(
                1 / params["max"], np.subtract(data, params["center"]))
            self.__already_demodulated = True
        elif num_channels == 2:
            self.iq_array.real = np.multiply(
                1 / params["max"], np.subtract(data[0::2], params["center"]))
            self.iq_array.imag = np.multiply(
                1 / params["max"], np.subtract(data[1::2], params["center"]))
        else:
            raise ValueError(
                "Can't handle {0} channels. Only 1 and 2 are supported.".
                format(num_channels))

        wav.close()

        self.sample_rate = sample_rate
Пример #11
0
    def test_push(self):
        ring_buffer = RingBuffer(size=10)
        self.assertEqual(0, ring_buffer.left_index)

        add1 = IQArray(np.array([1, 2, 3, 4, 5], dtype=np.complex64))
        ring_buffer.push(add1)
        self.assertEqual(5, ring_buffer.right_index)
        self.assertTrue(np.array_equal(ring_buffer.data[0:5], add1))

        add2 = IQArray(np.array([10, 20, 30, 40, 50, 60], dtype=np.complex64))
        self.assertFalse(ring_buffer.will_fit(len(add2)))
        ring_buffer.push(add2[:-1])
        self.assertTrue(np.array_equal(ring_buffer.data[5:10], add2[:-1]))
        self.assertTrue(np.array_equal(ring_buffer.data[0:5], add1))
Пример #12
0
    def create_new(self, start=0, end=0, new_data=None):
        new_signal = Signal("", "New " + self.name)

        if new_data is None:
            new_signal.iq_array = IQArray(self.iq_array[start:end])
        else:
            new_signal.iq_array = IQArray(new_data)

        new_signal._noise_threshold = self.noise_threshold
        new_signal.noise_min_plot = self.noise_min_plot
        new_signal.noise_max_plot = self.noise_max_plot
        new_signal.__bit_len = self.bit_len
        new_signal.__qad_center = self.qad_center
        new_signal.changed = True
        return new_signal
Пример #13
0
    def test_uncompress_archives(self):
        temp_dir = tempfile.gettempdir()
        os.chdir(temp_dir)

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

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

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

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

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

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

        zip_md5_after_save = hashlib.md5(
            open(os.path.join(temp_dir, "test.zip"), 'rb').read()).hexdigest()
        self.assertNotEqual(zip_md5, zip_md5_after_save)
Пример #14
0
    def __init__(self, data_array, parent):
        super().__init__(parent)
        self.plot_data = data_array
        self.end = 0

        self.minimum, self.maximum = IQArray.min_max_for_dtype(
            data_array.dtype)
Пример #15
0
 def test_big_buffer(self):
     ring_buffer = RingBuffer(size=5)
     try:
         ring_buffer.push(IQArray(np.array([1, 2, 3, 4, 5, 6, 7], dtype=np.complex64)))
         self.assertTrue(False)
     except ValueError:
         self.assertTrue(True)
Пример #16
0
 def init_recv_buffer(self):
     if self.receive_buffer is None:
         num_samples = SettingsProxy.get_receive_buffer_size(
             self.resume_on_full_receive_buffer, self.is_in_spectrum_mode)
         self.receive_buffer = IQArray(None,
                                       dtype=self.DATA_TYPE,
                                       n=int(num_samples))
Пример #17
0
    def prepare_modulation_buffer(self, total_samples: int, show_error=True) -> IQArray:
        dtype = Modulator.get_dtype()
        n = 2 if dtype == np.int8 else 4 if dtype == np.int16 else 8

        memory_size_for_buffer = total_samples * n
        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
            IQArray(None, dtype=dtype, n=3*total_samples)
        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 IQArray(None, dtype=dtype, n=total_samples)
Пример #18
0
    def __demodulate(self, connection: socket.socket):
        connection.settimeout(self.TIMEOUT)
        time.sleep(self.TIMEOUT)

        total_data = []
        while True:
            try:
                data = connection.recv(65536)
                if data:
                    total_data.append(data)
                else:
                    break
            except socket.timeout:
                break

        if len(total_data) == 0:
            logger.error("Did not receive any data from socket.")

        arr = IQArray(
            np.array(np.frombuffer(b"".join(total_data), dtype=np.complex64)))
        signal = Signal("", "")
        signal.iq_array = arr
        pa = ProtocolAnalyzer(signal)
        pa.get_protocol_from_signal()
        return pa.plain_bits_str
Пример #19
0
    def draw_sine_wave(self):
        if self.dialog_ui.graphicsViewSineWave.scene_manager:
            self.dialog_ui.graphicsViewSineWave.scene_manager.clear_path()

        QApplication.instance().setOverrideCursor(Qt.WaitCursor)
        self.__set_status_of_editable_elements(enabled=False)

        t = np.arange(0, self.num_samples) / self.sample_rate
        arg = 2 * np.pi * self.frequency * t + self.phase

        self.complex_wave = np.empty(len(arg), dtype=np.complex64)
        self.complex_wave.real = np.cos(arg)
        self.complex_wave.imag = np.sin(arg)
        self.complex_wave = IQArray(self.amplitude *
                                    self.complex_wave).convert_to(
                                        self.original_data.dtype)

        self.draw_data = np.insert(self.original_data[:, 0], self.position,
                                   self.complex_wave[:, 0])
        y, h = self.dialog_ui.graphicsViewSineWave.view_rect().y(
        ), self.dialog_ui.graphicsViewSineWave.view_rect().height()
        self.insert_indicator.setRect(self.position, y - h, self.num_samples,
                                      2 * h + abs(y))

        self.__set_status_of_editable_elements(enabled=True)
        QApplication.instance().restoreOverrideCursor()
        self.dialog_ui.graphicsViewSineWave.plot_data(self.draw_data)
        self.dialog_ui.graphicsViewSineWave.show_full_scene()
Пример #20
0
    def change_acess_to_iq_record(self):
        self.__dev.my_acess_record_iq = True if self.__dev.my_acess_record_iq == False else False

        if self.__dev.my_acess_record_iq == False:

            self.__dev.my_receive_buffer = IQArray(None, dtype=np.float32, n=int(SettingsProxy.get_receive_buffer_size(False, False)))
            self.__dev.my_current_recv_index = 0
Пример #21
0
    def __init__(self, modulators, tree_model=None, parent=None):
        """
        :type modulators: list of Modulator
        """
        super().__init__(parent)

        self.ui = Ui_DialogModulation()
        self.ui.setupUi(self)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setWindowFlags(Qt.Window)

        self.lock_samples_in_view = False

        if tree_model is not None:
            self.ui.treeViewSignals.setModel(tree_model)
            self.ui.treeViewSignals.expandAll()
            self.ui.gVOriginalSignal.signal_tree_root = tree_model.rootItem

        self.ui.comboBoxCustomModulations.clear()
        for modulator in modulators:
            self.ui.comboBoxCustomModulations.addItem(modulator.name)
        if len(modulators) == 1:
            self.ui.btnRemoveModulation.setDisabled(True)

        self.modulators = modulators

        for graphic_view in (self.ui.gVCarrier, self.ui.gVData):
            graphic_view.scene_y_min = -1
            graphic_view.scene_y_max = 1
            graphic_view.scene_x_zoom_stretch = 1.1

        min_max_mod = IQArray.min_max_for_dtype(self.current_modulator.get_dtype())
        self.ui.gVModulated.scene_y_min = min_max_mod[0]
        self.ui.gVModulated.scene_y_max = min_max_mod[1]
        self.ui.gVModulated.scene_x_zoom_stretch = 1.1

        self.set_ui_for_current_modulator()

        self.ui.cbShowDataBitsOnly.setText(self.tr("Show Only Data Sequence\n"))
        self.ui.cbShowDataBitsOnly.setEnabled(False)
        self.protocol = None  # type: ProtocolAnalyzer
        self.search_results = []
        self.ui.cbShowDataBitsOnly.setEnabled(False)
        self.ui.btnSearchNext.setEnabled(False)
        self.ui.btnSearchPrev.setEnabled(False)

        self.ui.chkBoxLockSIV.setDisabled(True)

        self.original_bits = ""
        self.ui.btnRestoreBits.setEnabled(False)

        self.create_connects()

        try:
            self.restoreGeometry(constants.SETTINGS.value("{}/geometry".format(self.__class__.__name__)))
        except TypeError:
            pass

        self.set_modulation_profile_status()
Пример #22
0
    def __init__(self, ring_buffer: RingBuffer, parent):
        super().__init__(parent)
        self.ring_buffer = ring_buffer
        self.__start = 0
        self.__end = 0

        self.minimum, self.maximum = IQArray.min_max_for_dtype(
            self.ring_buffer.dtype)
Пример #23
0
    def auto_fit_view(self):
        super().auto_fit_view()

        plot_min, plot_max = util.minmax(self.signal.real_plot_data)
        data_min, data_max = IQArray.min_max_for_dtype(self.signal.real_plot_data.dtype)
        self.scale(1, (data_max - data_min) / (plot_max-plot_min))

        self.centerOn(self.view_rect().x() + self.view_rect().width() / 2, self.y_center)
Пример #24
0
    def create_new(self, start=0, end=0, new_data=None):
        new_signal = Signal("", "New " + self.name)

        if new_data is None:
            new_signal.iq_array = IQArray(self.iq_array[start:end])
        else:
            new_signal.iq_array = IQArray(new_data)

        new_signal._noise_threshold = self.noise_threshold
        new_signal.noise_min_plot = self.noise_min_plot
        new_signal.noise_max_plot = self.noise_max_plot
        new_signal.__samples_per_symbol = self.samples_per_symbol
        new_signal.__bits_per_symbol = self.bits_per_symbol
        new_signal.__center = self.center
        new_signal.wav_mode = self.wav_mode
        new_signal.__already_demodulated = self.__already_demodulated
        new_signal.changed = True
        return new_signal
Пример #25
0
    def samples(self, value):
        if isinstance(value, IQArray):
            value = value.as_complex64()
        elif isinstance(value, np.ndarray) and value.dtype != np.complex64:
            value = IQArray(value).as_complex64()
        elif value is None:
            value = np.zeros(1, dtype=np.complex64)

        self.__samples = value
Пример #26
0
 def test_will_fit(self):
     ring_buffer = RingBuffer(size=8)
     self.assertEqual(ring_buffer.space_left, 8)
     self.assertTrue(ring_buffer.will_fit(4))
     self.assertTrue(ring_buffer.will_fit(8))
     self.assertFalse(ring_buffer.will_fit(9))
     ring_buffer.push(IQArray(np.array([1, 2, 3, 4], dtype=np.complex64)))
     self.assertEqual(ring_buffer.space_left, 4)
     self.assertTrue(ring_buffer.will_fit(3))
     self.assertTrue(ring_buffer.will_fit(4))
     self.assertFalse(ring_buffer.will_fit(5))
Пример #27
0
    def init_send_parameters(self, samples_to_send: IQArray = None, repeats: int = None, resume=False):
        if samples_to_send is not None:
            if isinstance(samples_to_send, IQArray):
                samples_to_send = samples_to_send.convert_to(self.DATA_TYPE)
            else:
                samples_to_send = IQArray(samples_to_send).convert_to(self.DATA_TYPE)

            self.samples_to_send = samples_to_send
            self.send_buffer = None

        if self.send_buffer is None:
            if isinstance(self.samples_to_send, IQArray):
                self.send_buffer = self.iq_to_bytes(self.samples_to_send.data)
            else:
                self.send_buffer = self.iq_to_bytes(self.samples_to_send)
        elif not resume:
            self.current_sending_repeat = 0

        if repeats is not None:
            self.sending_repeats = repeats
Пример #28
0
    def device_name(self, value: str):
        if value != self.rcv_device.name:
            self.rcv_device.free_data()
            self.rcv_device = VirtualDevice(self.backend_handler, value, Mode.receive, device_ip="192.168.10.2",
                                            resume_on_full_receive_buffer=True, raw_mode=self.network_raw_mode)
            self.rcv_device.started.connect(self.__emit_started)
            self.rcv_device.stopped.connect(self.__emit_stopped)

            self.signal.iq_array = IQArray(None, self.rcv_device.data_type, 0)

            self.__init_buffer()
Пример #29
0
    def init_scene(self):
        if self.num_samples == 0:
            return

        minimum, maximum = IQArray.min_max_for_dtype(self.plot_data.dtype)
        self.scene.setSceneRect(0, minimum, self.num_samples,
                                maximum - minimum)
        self.scene.setBackgroundBrush(settings.BGCOLOR)

        if self.line_item is not None:
            self.line_item.setLine(0, 0, self.num_samples, 0)
Пример #30
0
    def read_receiving_queue(self):

        my_num_samples = SettingsProxy.get_receive_buffer_size(False, False)
        self.my_receive_buffer = IQArray(None,
                                         dtype=self.DATA_TYPE,
                                         n=int(my_num_samples))
        self.my_current_recv_index = 0

        while self.is_receiving:
            try:
                byte_buffer = self.parent_data_conn.recv_bytes()

                samples = self.bytes_to_iq(byte_buffer)
                n_samples = len(samples)
                if n_samples == 0:
                    continue

                if self.apply_dc_correction:
                    samples = samples - np.mean(samples, axis=0)

            except OSError as e:
                logger.exception(e)
                continue
            except EOFError:
                logger.info("EOF Error: Ending receive thread")
                break

            if self.current_recv_index + n_samples >= len(self.receive_buffer):
                if self.resume_on_full_receive_buffer:
                    self.current_recv_index = 0
                    if n_samples >= len(self.receive_buffer):
                        n_samples = len(self.receive_buffer) - 1
                else:
                    self.stop_rx_mode(
                        "Receiving buffer is full {0}/{1}".format(
                            self.current_recv_index + n_samples,
                            len(self.receive_buffer)))
                    return

            self.receive_buffer[self.
                                current_recv_index:self.current_recv_index +
                                n_samples] = samples[:n_samples]
            self.current_recv_index += n_samples

            if self.my_acess_record_iq:

                self.my_receive_buffer[self.my_current_recv_index:self.
                                       my_current_recv_index +
                                       n_samples] = samples[:n_samples]
                self.my_current_recv_index += n_samples

        logger.debug("Exiting read_receive_queue thread.")