def stop_tx_mode(self, msg): try: self.parent_ctrl_conn.send(self.Command.STOP.name) except (BrokenPipeError, OSError) as e: logger.debug("Closing parent control connection: " + str(e)) logger.info("{0}: Stopping TX Mode: {1}".format(self.__class__.__name__, msg)) if hasattr(self, "transmit_process") and self.transmit_process.is_alive(): self.transmit_process.join(self.JOIN_TIMEOUT) if self.transmit_process.is_alive(): logger.warning("{0}: Transmit process is still alive, terminating it".format(self.__class__.__name__)) self.transmit_process.terminate() self.transmit_process.join() self.is_transmitting = False try: self.parent_ctrl_conn.close() except OSError as e: logger.exception(e) try: self.child_ctrl_conn.close() except OSError as e: logger.exception(e)
def read_receiving_queue(self): while self.is_receiving: try: byte_buffer = self.parent_data_conn.recv_bytes() samples = self.unpack_complex(byte_buffer) n_samples = len(samples) if n_samples == 0: continue 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.emit_data_received_signal: self.data_received.emit(samples) logger.debug("Exiting read_receive_queue thread.")
def configure_rfcat(self, modulation = "MOD_ASK_OOK", freq = 433920000, sample_rate = 2000000, bit_len = 500): self.set_parameter("d.setMdmModulation({})".format(modulation), log=False) self.set_parameter("d.setFreq({})".format(int(freq)), log=False) self.set_parameter("d.setMdmSyncMode(0)", log=False) self.set_parameter("d.setMdmDRate({})".format(int(sample_rate // bit_len)), log=False) self.set_parameter("d.setMaxPower()", log=False) logger.info("Configured RfCat to Modulation={}, Freqency={} Hz, Datarate={} baud".format(modulation, int(freq), int(sample_rate // bit_len)))
def initialize_process(self): self.started.emit() if not hasattr(sys, 'frozen'): rp = os.path.realpath(os.path.join(os.path.dirname(__file__), "scripts")) else: rp = os.path.realpath(os.path.dirname(sys.executable)) suffix = "_recv.py" if self._receiving else "_send.py" filename = self.device.lower().split(" ")[0] + suffix if not self.python2_interpreter: raise Exception("Could not find python 2 interpreter. Make sure you have a running gnuradio installation.") options = [self.python2_interpreter, os.path.join(rp, filename), "--samplerate", str(self.sample_rate), "--freq", str(self.freq), "--gain", str(self.gain), "--bandwidth", str(self.bandwidth), "--port", str(self.gr_port)] if self.device.upper() == "HACKRF": options.extend(["--if-gain", str(self.if_gain), "--baseband-gain", str(self.baseband_gain)]) if self.device.upper() == "RTL-SDR": options.extend(["--freq-correction", str(self.freq_correction), "--direct-sampling", str(self.direct_sampling_mode)]) logger.info("Starting Gnuradio") logger.debug(" ".join(options)) self.tb_process = Popen(options, stdout=PIPE, stderr=PIPE, stdin=PIPE, bufsize=1) logger.info("Started Gnuradio") t = Thread(target=self.enqueue_output, args=(self.tb_process.stderr, self.queue)) t.daemon = True # thread dies with the program t.start()
def set_parameter(self, param: str, log=True): # returns error (True/False) try: self.write_to_rfcat(param) self.ready = False if log: logger.debug(param) except OSError as e: logger.info("Could not set parameter {0}:{1} ({2})".format(param, e)) return True return False
def run(self): if self.data is None: self.init_recv_buffer() self.initialize_process() logger.info("Initialize receive socket") self.init_recv_socket() recv = self.socket.recv rcvd = b"" try: while not self.isInterruptionRequested(): try: rcvd += recv(32768) # Receive Buffer = 32768 Byte except zmq.error.Again: # timeout continue except (zmq.error.ContextTerminated, ConnectionResetError): self.stop("Stopped receiving, because connection was reset.") return except OSError as e: # https://github.com/jopohl/urh/issues/131 logger.warning("Error occurred", str(e)) if len(rcvd) < 8: self.stop("Stopped receiving: No data received anymore") return if len(rcvd) % 8 != 0: continue try: tmp = np.fromstring(rcvd, dtype=np.complex64) num_samples = len(tmp) if self.data is None: # seems to be sometimes None in rare cases self.init_recv_buffer() if self.current_index + num_samples >= len(self.data): if self.resume_on_full_receive_buffer: self.current_index = 0 if num_samples >= len(self.data): self.stop("Receiving buffer too small.") else: self.stop("Receiving Buffer is full.") return self.data[self.current_index:self.current_index + num_samples] = tmp self.current_index += num_samples rcvd = b"" except ValueError: self.stop("Could not receive data. Is your Hardware ok?") except RuntimeError: logger.error("Receiver Thread crashed.")
def run_image(imagename: str, rebuild=False): if not is_image_there(imagename) or rebuild: build_image(imagename) cmd = ["sudo"] if USE_SUDO else [] call(cmd + ["xhost", "+"]) # Allow docker to connect to hosts X Server cmd.extend(["docker", "run", "-e", "DISPLAY=$DISPLAY", "-v", "/tmp/.X11-unix:/tmp/.X11-unix", "urh/"+imagename]) logger.info("call {}".format(" ".join(cmd))) rc = call(" ".join(cmd), shell=True) return rc == 0
def set_parameter(self, param: str, value: int, ctrl_connection): # returns error (True/False) if self.socket_is_open: msg = self.RTL_TCP_CONSTS.index(param).to_bytes(1, self.ENDIAN) # Set param at bits 0-7 msg += value.to_bytes(4, self.ENDIAN) # Set value at bits 8-39 try: self.sock.sendall(msg) # Send data to rtl_tcp except OSError as e: self.sock.close() logger.info("Could not set parameter {0}:{1} ({2})".format(param, value, e)) ctrl_connection.send("Could not set parameter {0} {1} ({2}):1".format(param, value, e)) return True return False
def get_receive_buffer_size(resume_on_full_receive_buffer: bool, spectrum_mode: bool) -> int: if resume_on_full_receive_buffer: if spectrum_mode: num_samples = constants.SPECTRUM_BUFFER_SIZE else: num_samples = constants.SNIFF_BUFFER_SIZE else: # Take 60% of avail memory threshold = constants.SETTINGS.value('ram_threshold', 0.6, float) num_samples = threshold * (psutil.virtual_memory().available / 8) logger.info("Initializing receive buffer with size {0}B".format(Formatter.big_value_with_suffix(num_samples*8))) return int(num_samples)
def start_tx_mode(self, samples_to_send: np.ndarray = None, repeats=None, resume=False): self.is_transmitting = True self.parent_ctrl_conn, self.child_ctrl_conn = Pipe() self.init_send_parameters(samples_to_send, repeats, resume=resume) logger.info("{0}: Starting TX Mode".format(self.__class__.__name__)) self.transmit_process = Process(target=self.send_process_function, args=self.send_process_arguments) self.transmit_process.daemon = True self._start_read_message_thread() self.transmit_process.start()
def start_rx_mode(self): self.init_recv_buffer() self.parent_data_conn, self.child_data_conn = Pipe(duplex=False) self.parent_ctrl_conn, self.child_ctrl_conn = Pipe() self.is_receiving = True logger.info("{0}: Starting RX Mode".format(self.__class__.__name__)) self.receive_process = Process(target=self.receive_process_function, args=self.receive_process_arguments) self.receive_process.daemon = True self._start_read_rcv_buffer_thread() self._start_read_message_thread() try: self.receive_process.start() except OSError as e: logger.error(repr(e)) self.device_messages.append(repr(e))
def read_device_messages(self): while self.is_receiving or self.is_transmitting: try: message = self.parent_ctrl_conn.recv() try: splitted = message.split(":") action = ":".join(splitted[:-1]) return_code = splitted[-1] self.log_retcode(int(return_code), action) except ValueError: self.device_messages.append("{0}: {1}".format(self.__class__.__name__, message)) except (EOFError, UnpicklingError, OSError, ConnectionResetError) as e: logger.info("Exiting read device message thread due to " + str(e)) break self.is_transmitting = False self.is_receiving = False logger.debug("Exiting read device errors thread")
def log_retcode(self, retcode: int, action: str, msg=""): msg = str(msg) error_code_msg = self.error_codes[retcode] if retcode in self.error_codes else "Error Code: " + str(retcode) if retcode == self.success: if msg: formatted_message = "{0}-{1} ({2}): Success".format(type(self).__name__, action, msg) else: formatted_message = "{0}-{1}: Success".format(type(self).__name__, action) logger.info(formatted_message) else: if msg: formatted_message = "{0}-{1} ({4}): {2} ({3})".format(type(self).__name__, action, error_code_msg, retcode, msg) else: formatted_message = "{0}-{1}: {2} ({3})".format(type(self).__name__, action, error_code_msg, retcode) logger.error(formatted_message) self.device_messages.append(formatted_message)
def get_receive_buffer_size(resume_on_full_receive_buffer: bool, spectrum_mode: bool) -> int: if SettingsProxy.OVERWRITE_RECEIVE_BUFFER_SIZE: return SettingsProxy.OVERWRITE_RECEIVE_BUFFER_SIZE if resume_on_full_receive_buffer: if spectrum_mode: num_samples = constants.SPECTRUM_BUFFER_SIZE else: num_samples = constants.SNIFF_BUFFER_SIZE else: # Take 60% of avail memory threshold = constants.SETTINGS.value('ram_threshold', 0.6, float) num_samples = threshold * (psutil.virtual_memory().available / 8) # Do not let it allocate too much memory on 32 bit if 8 * 2 * num_samples > sys.maxsize: num_samples = sys.maxsize // (8 * 2 * 1.5) logger.info("Correcting buffer size to {}".format(num_samples)) logger.info("Allocate receive buffer with {0}B".format(Formatter.big_value_with_suffix(num_samples * 8))) return int(num_samples)
def find_field(self, messages): """ Wrapper method selecting the backend to assign the protocol field. Various strategies are possible e.g.: 1) Heuristics e.g. for Preamble 2) Scoring based e.g. for Length 3) Fulltext search for addresses based on participant subgroups :param messages: messages a field shall be searched for :type messages: list of Message """ try: if self.backend == self.Backend.python: self._py_find_field(messages) elif self.backend == self.Backend.cython: self._cy_find_field(messages) elif self.backend == self.Backend.plainc: self._c_find_field(messages) else: raise ValueError("Unsupported backend {}".format(self.backend)) except NotImplementedError: logger.info("Skipped {} because not implemented yet".format(self.__class__.__name__))
def open(self, ctrl_connection, hostname="127.0.0.1", port=1234): if not self.socket_is_open: try: # Create socket and connect self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) # self.sock.settimeout(1.0) # Timeout 1s self.sock.connect((hostname, port)) except Exception as e: self.socket_is_open = False logger.info("Could not connect to rtl_tcp at {0}:{1} ({2})".format(hostname, port, e)) ctrl_connection.send("Could not connect to rtl_tcp at {0} [{1}] ({2}):1".format(hostname, port, e)) return False try: # Receive rtl_tcp initial data init_data = self.sock.recv(self.MAXDATASIZE) if len(init_data) != 12: return False if init_data[0:4] != b'RTL0': return False # Extract tuner name tuner_number = int.from_bytes(init_data[4:8], self.ENDIAN) if tuner_number == 1: self.tuner = "E4000" elif tuner_number == 2: self.tuner = "FC0012" elif tuner_number == 3: self.tuner = "FC0013" elif tuner_number == 4: self.tuner = "FC2580" elif tuner_number == 5: self.tuner = "R820T" elif tuner_number == 6: self.tuner = "R828D" else: self.tuner = "Unknown" # Extract IF and RF gain self.if_gain = int.from_bytes(init_data[8:10], self.ENDIAN) self.rf_gain = int.from_bytes(init_data[10:12], self.ENDIAN) logger.info( "Connected to rtl_tcp at {0}:{1} (Tuner: {2}, RF-Gain: {3}, IF-Gain: {4})".format(hostname, port, self.tuner, self.rf_gain, self.if_gain)) ctrl_connection.send( "Connected to rtl_tcp at {0}[{1}] (Tuner={2}, RF-Gain={3}, IF-Gain={4}):0".format(hostname, port, self.tuner, self.rf_gain, self.if_gain)) except Exception as e: self.socket_is_open = False logger.info("This is not a valid rtl_tcp server at {0}:{1} ({2})".format(hostname, port, e)) return False self.socket_is_open = True
def init_recv_socket(self): logger.info("Initalizing receive socket") self.context = zmq.Context() self.socket = self.context.socket(zmq.PULL) logger.info("Initalized receive socket") while not self.isInterruptionRequested(): try: time.sleep(0.1) logger.info("Trying to get a connection to gnuradio...") self.socket.connect("tcp://{0}:{1}".format(self.ip, self.gr_port)) logger.info("Got connection") break except (ConnectionRefusedError, ConnectionResetError): continue except Exception as e: logger.error("Unexpected error", str(e))
def stop(self, msg: str): if msg and not msg.startswith("FIN"): self.requestInterruption() if self.tb_process: logger.info("Kill grc process") self.tb_process.kill() logger.info("Term grc process") self.tb_process.terminate() self.tb_process = None logger.info(msg) self.stopped.emit()
def stop(self, msg: str): if msg and not msg.startswith("FIN"): self.requestInterruption() if self.tb_process: logger.info("Kill grc process") self.tb_process.kill() logger.info("Term grc process") self.tb_process.terminate() self.tb_process = None logger.info(msg) self.stopped.emit()
def process_command(command): logger.debug("RTLSDR: {}".format(command)) if command == "stop": return "stop" tag, value = command.split(":") if tag == "center_freq": logger.info("RTLSDR: Set center freq to {0}".format(int(value))) return rtlsdr.set_center_freq(int(value)) elif tag == "tuner_gain": logger.info("RTLSDR: Set tuner gain to {0}".format(int(value))) return rtlsdr.set_tuner_gain(int(value)) elif tag == "sample_rate": logger.info("RTLSDR: Set sample_rate to {0}".format(int(value))) return rtlsdr.set_sample_rate(int(value)) elif tag == "tuner_bandwidth": logger.info("RTLSDR: Set bandwidth to {0}".format(int(value))) return rtlsdr.set_tuner_bandwidth(int(value))
def process_command(rtlsdrtcp, command): logger.debug("RTLSDRTCP: {}".format(command)) if command == "stop": return "stop" tag, value = command.split(":") if tag == "center_freq": logger.info("RTLSDR: Set center freq to {0}".format(int(value))) return rtlsdrtcp.set_parameter("centerFreq", int(value)) elif tag == "tuner_gain": logger.info("RTLSDR: Set tuner gain to {0}".format(int(value))) return rtlsdrtcp.set_parameter("tunerGain", int(value)) elif tag == "sample_rate": logger.info("RTLSDR: Set sample_rate to {0}".format(int(value))) return rtlsdrtcp.set_parameter("sampleRate", int(value)) elif tag == "tuner_bandwidth": logger.info("RTLSDR: Set bandwidth to {0}".format(int(value))) return rtlsdrtcp.set_parameter("bandwidth", int(value))
def process_command(command): if command == "stop": return "stop" tag, value = command.split(":") if tag == "center_freq": logger.info("[RTLSDR] setting center freq to {}".format(int(value))) rtlsdr.set_center_freq(int(value)) elif tag == "tuner_gain": logger.info("[RTLSDR] setting tuner_gain to {}".format(int(value))) rtlsdr.set_tuner_gain(int(value)) elif tag == "sample_rate": logger.info("[RTLSDR] setting sample rate to {}".format(int(value))) rtlsdr.set_sample_rate(int(value))
def process_command(command): if command == "stop": return "stop" tag, value = command.split(":") if tag == "center_freq": logger.info("[RTLSDR] setting center freq to {}".format(int(value))) rtlsdr.set_center_freq(int(value)) elif tag == "tuner_gain": logger.info("[RTLSDR] setting tuner_gain to {}".format(int(value))) rtlsdr.set_tuner_gain(int(value)) elif tag == "sample_rate": logger.info("[RTLSDR] setting sample rate to {}".format(int(value))) rtlsdr.set_sample_rate(int(value))
def stop(self, msg: str): if msg and not msg.startswith("FIN"): self.requestInterruption() time.sleep(0.1) try: logger.info("Kill grc process") self.tb_process.kill() logger.info("Term grc process") self.tb_process.terminate() self.tb_process = None except AttributeError: pass logger.info(msg) self.stopped.emit()
def stop(self, msg: str): if msg and not msg.startswith("FIN"): self.requestInterruption() time.sleep(0.1) try: logger.info("Kill grc process") self.tb_process.kill() logger.info("Term grc process") self.tb_process.terminate() self.tb_process = None except AttributeError: pass logger.info(msg) self.stopped.emit()
def process_command(command): logger.debug("HackRF: {}".format(command)) if command == "stop": return "stop" tag, value = command.split(":") if tag == "center_freq": logger.info("HackRF: Set center freq to {0}".format(int(value))) return hackrf.set_freq(int(value)) elif tag == "gain": logger.info("HackRF: Set gain to {0}".format(int(value))) hackrf.set_lna_gain(int(value)) hackrf.set_vga_gain(int(value)) hackrf.set_txvga_gain(int(value)) elif tag == "sample_rate": logger.info("HackRF: Set sample_rate to {0}".format(int(value))) return hackrf.set_sample_rate(int(value)) elif tag == "bandwidth": logger.info("HackRF: Set bandwidth to {0}".format(int(value))) return hackrf.set_baseband_filter_bandwidth(int(value))
def stop_rx_mode(self, msg): self.is_receiving = False logger.info("HackRF: Stopping RX Mode: " + msg) if hasattr(self, "read_queue_thread") and self.read_recv_buffer_thread.is_alive(): try: self.read_recv_buffer_thread.join(0.001) logger.info("HackRF: Joined read_queue_thread") except RuntimeError: logger.error("HackRF: Could not join read_queue_thread") if self.is_open: logger.info("stopping HackRF rx mode ({0})".format(msg)) logger.warning( "closing because stop_rx_mode of HackRF is bugged and will not allow re receive without close") self.close(exit=False)
def stop_rx_mode(self, msg): self.is_receiving = False self.is_receiving_p.value = 0 logger.info("RTLSDR: Stopping RX Mode: " + msg) if hasattr(self, "read_queue_thread") and self.read_queue_thread.is_alive(): try: self.read_queue_thread.join(0.001) logger.info("RTLSDR: Joined read_queue_thread") except RuntimeError: logger.error("RTLSDR: Could not join read_queue_thread") if hasattr(self, "receive_process") and self.receive_process.is_alive(): if self.receive_process.is_alive(): self.receive_process.join() if not self.receive_process.is_alive(): logger.info("RTLSDR: Terminated async read process") else: logger.warning("RTLSDR: Could not terminate async read process")
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 remove_containers(): logger.info("removing containers") cmd = ["sudo"] if USE_SUDO else [] cmd.extend(["docker", "rm", "-f", "$({}docker ps -aq)".format("sudo " if USE_SUDO else "")]) call(" ".join(cmd), shell=True)
def reset_send_buffer(self): try: self.send_buffer_reader.seek(0) self.current_sent_sample = 0 except ValueError: logger.info("Send buffer was already closed. Cant reset it.")
def process_command(self, command, ctrl_connection, is_tx=False): logger.debug("RTLSDRTCP: {}".format(command)) if command == self.Command.STOP.name: return self.Command.STOP tag, value = command if tag == self.Command.SET_FREQUENCY.name: logger.info("RTLSDRTCP: Set center freq to {0}".format(int(value))) return self.set_parameter("centerFreq", int(value), ctrl_connection) elif tag == self.Command.SET_RF_GAIN.name: logger.info("RTLSDRTCP: Set tuner gain to {0}".format(int(value))) return self.set_parameter("tunerGain", 10 * int(value), ctrl_connection) # calculate *10 for API elif tag == self.Command.SET_IF_GAIN.name: logger.info("RTLSDRTCP: Set if gain to {0}".format(int(value))) return self.set_parameter("tunerIFGain", 10 * int(value), ctrl_connection) # calculate *10 for API elif tag == self.Command.SET_SAMPLE_RATE.name: logger.info("RTLSDRTCP: Set sample_rate to {0}".format(int(value))) return self.set_parameter("sampleRate", int(value), ctrl_connection) elif tag == self.Command.SET_BANDWIDTH.name: logger.info("RTLSDRTCP: Set bandwidth to {0}".format(int(value))) return self.set_parameter("bandwidth", int(value), ctrl_connection) elif tag == self.Command.SET_FREQUENCY_CORRECTION.name: logger.info("RTLSDRTCP: Set ppm correction to {0}".format( int(value))) return self.set_parameter("freqCorrection", int(value), ctrl_connection) elif tag == self.Command.SET_DIRECT_SAMPLING_MODE.name: logger.info("RTLSDRTCP: Set direct sampling mode to {0}".format( int(value))) return self.set_parameter("directSampling", int(value), ctrl_connection)
def open(self, ctrl_connection, hostname="127.0.0.1", port=1234): if not self.socket_is_open: try: # Create socket and connect self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) # self.sock.settimeout(1.0) # Timeout 1s self.sock.connect((hostname, port)) except Exception as e: self.socket_is_open = False logger.info( "Could not connect to rtl_tcp at {0}:{1} ({2})".format( hostname, port, e)) ctrl_connection.send( "Could not connect to rtl_tcp at {0} [{1}] ({2}):1".format( hostname, port, e)) return False try: # Receive rtl_tcp initial data init_data = self.sock.recv(self.MAXDATASIZE) if len(init_data) != 12: return False if init_data[0:4] != b'RTL0': return False # Extract tuner name tuner_number = int.from_bytes(init_data[4:8], self.ENDIAN) if tuner_number == 1: self.tuner = "E4000" elif tuner_number == 2: self.tuner = "FC0012" elif tuner_number == 3: self.tuner = "FC0013" elif tuner_number == 4: self.tuner = "FC2580" elif tuner_number == 5: self.tuner = "R820T" elif tuner_number == 6: self.tuner = "R828D" else: self.tuner = "Unknown" # Extract IF and RF gain self.if_gain = int.from_bytes(init_data[8:10], self.ENDIAN) self.rf_gain = int.from_bytes(init_data[10:12], self.ENDIAN) logger.info( "Connected to rtl_tcp at {0}:{1} (Tuner: {2}, RF-Gain: {3}, IF-Gain: {4})" .format(hostname, port, self.tuner, self.rf_gain, self.if_gain)) ctrl_connection.send( "Connected to rtl_tcp at {0}[{1}] (Tuner={2}, RF-Gain={3}, IF-Gain={4}):0" .format(hostname, port, self.tuner, self.rf_gain, self.if_gain)) except Exception as e: self.socket_is_open = False logger.info( "This is not a valid rtl_tcp server at {0}:{1} ({2})". format(hostname, port, e)) return False self.socket_is_open = True
def process_command(self, command, ctrl_connection): logger.debug("RTLSDRTCP: {}".format(command)) if command == "stop": return "stop" tag, value = command.split(":") if tag == "center_freq": logger.info("RTLSDRTCP: Set center freq to {0}".format(int(value))) return self.set_parameter("centerFreq", int(value), ctrl_connection) elif tag == "rf_gain": logger.info("RTLSDRTCP: Set tuner gain to {0}".format(int(value))) return self.set_parameter("tunerGain", 10 * int(value), ctrl_connection) # calculate *10 for API elif tag == "if_gain": logger.info("RTLSDRTCP: Set if gain to {0}".format(int(value))) return self.set_parameter("tunerIFGain", 10 * int(value), ctrl_connection) # calculate *10 for API elif tag == "sample_rate": logger.info("RTLSDRTCP: Set sample_rate to {0}".format(int(value))) return self.set_parameter("sampleRate", int(value), ctrl_connection) elif tag == "tuner_bandwidth": logger.info("RTLSDRTCP: Set bandwidth to {0}".format(int(value))) return self.set_parameter("bandwidth", int(value), ctrl_connection) elif tag == "freq_correction": logger.info("RTLSDRTCP: Set ppm correction to {0}".format( int(value))) return self.set_parameter("freqCorrection", int(value), ctrl_connection) elif tag == "direct_sampling_mode": logger.info("RTLSDRTCP: Set direct sampling mode to {0}".format( int(value))) return self.set_parameter("directSampling", int(value), ctrl_connection)
def process_command(self, command, ctrl_connection, is_tx=False): logger.debug("RTLSDRTCP: {}".format(command)) if command == self.Command.STOP.name: return self.Command.STOP tag, value = command if tag == self.Command.SET_FREQUENCY.name: logger.info("RTLSDRTCP: Set center freq to {0}".format(int(value))) return self.set_parameter("centerFreq", int(value), ctrl_connection) elif tag == self.Command.SET_RF_GAIN.name: logger.info("RTLSDRTCP: Set tuner gain to {0}".format(int(value))) return self.set_parameter("tunerGain", 10 * int(value), ctrl_connection) # calculate *10 for API elif tag == self.Command.SET_IF_GAIN.name: logger.info("RTLSDRTCP: Set if gain to {0}".format(int(value))) return self.set_parameter("tunerIFGain", 10 * int(value), ctrl_connection) # calculate *10 for API elif tag == self.Command.SET_SAMPLE_RATE.name: logger.info("RTLSDRTCP: Set sample_rate to {0}".format(int(value))) return self.set_parameter("sampleRate", int(value), ctrl_connection) elif tag == self.Command.SET_BANDWIDTH.name: logger.info("RTLSDRTCP: Set bandwidth to {0}".format(int(value))) return self.set_parameter("bandwidth", int(value), ctrl_connection) elif tag == self.Command.SET_FREQUENCY_CORRECTION.name: logger.info("RTLSDRTCP: Set ppm correction to {0}".format(int(value))) return self.set_parameter("freqCorrection", int(value), ctrl_connection) elif tag == self.Command.SET_DIRECT_SAMPLING_MODE.name: logger.info("RTLSDRTCP: Set direct sampling mode to {0}".format(int(value))) return self.set_parameter("directSampling", int(value), ctrl_connection)
def increase_gr_port(self): if self.backend == Backends.grc: self.__dev.gr_port += 1 logger.info("Retry with port " + str(self.__dev.gr_port)) else: raise ValueError("Only for GR backend")
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()
def increase_gr_port(self): if self.backend == Backends.grc: self.__dev.gr_port += 1 logger.info("Retry with port " + str(self.__dev.gr_port)) else: raise ValueError("Only for GR backend")
def process_command(command): logger.debug("RTLSDR: {}".format(command)) if command == "stop": return "stop" tag, value = command.split(":") if tag == "center_freq": logger.info("RTLSDR: Set center freq to {0}".format(int(value))) return rtlsdr.set_center_freq(int(value)) elif tag == "rf_gain": logger.info("RTLSDR: Set tuner gain to {0}".format(int(value))) return rtlsdr.set_tuner_gain(10 * int(value)) # calculate *10 for API elif tag == "sample_rate": logger.info("RTLSDR: Set sample_rate to {0}".format(int(value))) return rtlsdr.set_sample_rate(int(value)) elif tag == "tuner_bandwidth": logger.info("RTLSDR: Set bandwidth to {0}".format(int(value))) return rtlsdr.set_tuner_bandwidth(int(value)) elif tag == "freq_correction": logger.info("RTLSDR: Set freq_correction to {0}".format( int(value))) return rtlsdr.set_freq_correction(int(value)) elif tag == "direct_sampling_mode": logger.info("RTLSDR: Set direct_sampling_mode to {0}".format( int(value))) return rtlsdr.set_direct_sampling(int(value))