def test_open_simulator_dialog_and_send_mismatching_message(self): stc = self.form.simulator_tab_controller assert isinstance(stc, SimulatorTabController) self.__setup_project() self.add_all_signals_to_simulator() stc.simulator_scene.select_all_items() for msg in stc.simulator_scene.get_selected_messages(): msg.destination = self.dennis stc.ui.gvSimulator.message_updated.emit(msg) list_model = stc.ui.listViewSimulate.model() self.assertEqual(list_model.rowCount(), 2) list_model.setData(list_model.createIndex(1, 0), Qt.Checked, role=Qt.CheckStateRole) dialog = stc.get_simulator_dialog() network_sdr_name = NetworkSDRInterfacePlugin.NETWORK_SDR_NAME dialog.device_settings_tx_widget.ui.cbDevice.setCurrentText( network_sdr_name) dialog.device_settings_rx_widget.ui.cbDevice.setCurrentText( network_sdr_name) send_port = self.get_free_port() dialog.simulator.sender.device.set_client_port(send_port) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) s.bind(("", send_port)) s.listen(1) rcv_port = self.get_free_port() dialog.simulator.sniffer.rcv_device.set_server_port(rcv_port) dialog.ui.btnStartStop.click() QTest.qWait(100) modulator = dialog.project_manager.modulators[0] # type: Modulator sender = NetworkSDRInterfacePlugin(raw_mode=True, sending=True) sender.client_port = rcv_port sender.send_raw_data(modulator.modulate("1" * 352), 1) sender.send_raw_data(np.zeros(1000, dtype=np.complex64), 1) sender.send_raw_data(modulator.modulate("10" * 176), 1) sender.send_raw_data(np.zeros(1000, dtype=np.complex64), 1) QTest.qWait(1000) simulator_log = dialog.ui.textEditSimulation.toPlainText() self.assertIn("Received message 1", simulator_log) self.assertIn("preamble: 11111111", simulator_log) self.assertIn("Mismatch for label: preamble", simulator_log) dialog.close() s.close()
class TestSimulatorPerfomance(QtTestCase): def setUp(self): super().setUp() self.num_zeros_for_pause = 1000 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()
class TestSimulator(QtTestCase): TIMEOUT = 0.25 def setUp(self): super().setUp() settings.OVERWRITE_RECEIVE_BUFFER_SIZE = 50000 Modulator.FORCE_DTYPE = np.float32 self.num_zeros_for_pause = 1000 def test_simulation_flow(self): """ test a simulation flow with an increasing sequence number :return: """ if sys.platform == "win32" and struct.calcsize("P") * 8 == 32: print("Skipping test on 32 Bit windows as CI is slow.") self.assertTrue(True) return profile = self.get_path_for_filename("testprofile.sim.xml") self.form.add_files([profile]) self.assertEqual( len(self.form.simulator_tab_controller.simulator_scene. get_all_message_items()), 6) port = self.get_free_port() self.alice = NetworkSDRInterfacePlugin(raw_mode=True) self.alice.client_port = port dialog = self.form.simulator_tab_controller.get_simulator_dialog( ) # type: SimulatorDialog dialog.project_manager.simulator_timeout_ms = 999999999 name = NetworkSDRInterfacePlugin.NETWORK_SDR_NAME dialog.device_settings_rx_widget.ui.cbDevice.setCurrentText(name) dialog.device_settings_tx_widget.ui.cbDevice.setCurrentText(name) simulator = dialog.simulator simulator.sniffer.rcv_device.set_server_port(port) port = self.get_free_port() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) s.bind(("", port)) s.listen(1) simulator.sender.device.set_client_port(port) dialog.ui.btnStartStop.click() while not any("Waiting for message" in msg for msg in dialog.simulator.log_messages): logger.debug("Waiting for simulator to wait for message") time.sleep(self.TIMEOUT) conn, addr = s.accept() msg = next(msg for msg in dialog.simulator_config.get_all_messages() if msg.source.name == "Alice") checksum_label = next( lbl for lbl in msg.message_type if lbl.is_checksum_label).label # type: ChecksumLabel modulator = dialog.project_manager.modulators[0] # type: Modulator preamble_str = "10101010" sync_str = "1001" preamble = list(map(int, preamble_str)) sync = list(map(int, sync_str)) seq = list(map(int, "00000010")) data = list(map(int, "11001101")) seq_num = int("".join(map(str, seq)), 2) checksum = list(checksum_label.calculate_checksum(seq + data)) msg1 = preamble + sync + seq + data + checksum self.alice.send_raw_data(modulator.modulate(msg1), 1) time.sleep(self.TIMEOUT) self.alice.send_raw_data( IQArray(None, np.float32, self.num_zeros_for_pause), 1) while not any("Sending message 2" in msg for msg in dialog.simulator.log_messages): logger.debug("Waiting for simulator to send message 2") time.sleep(self.TIMEOUT) bits = self.__demodulate(conn) self.assertEqual(len(bits), 1) bits = bits[0] self.assertTrue(bits.startswith(preamble_str + sync_str), msg=bits) bits = bits.replace(preamble_str + sync_str, "") self.assertEqual(int(bits, 2), seq_num + 1) seq = list(map(int, "{0:08b}".format(seq_num + 2))) checksum = list(checksum_label.calculate_checksum(seq + data)) msg2 = preamble + sync + seq + data + checksum self.alice.send_raw_data(modulator.modulate(msg2), 1) time.sleep(self.TIMEOUT) self.alice.send_raw_data( IQArray(None, np.float32, self.num_zeros_for_pause), 1) while not any("Sending message 4" in msg for msg in dialog.simulator.log_messages): logger.debug("Waiting for simulator to send message 4") time.sleep(self.TIMEOUT) bits = self.__demodulate(conn) self.assertEqual(len(bits), 1) bits = bits[0] self.assertTrue(bits.startswith(preamble_str + sync_str)) bits = bits.replace(preamble_str + sync_str, "") self.assertEqual(int(bits, 2), seq_num + 3) seq = list(map(int, "{0:08b}".format(seq_num + 4))) checksum = list(checksum_label.calculate_checksum(seq + data)) msg3 = preamble + sync + seq + data + checksum self.alice.send_raw_data(modulator.modulate(msg3), 1) time.sleep(self.TIMEOUT) self.alice.send_raw_data( IQArray(None, np.float32, self.num_zeros_for_pause), 1) while not any("Sending message 6" in msg for msg in dialog.simulator.log_messages): logger.debug("Waiting for simulator to send message 6") time.sleep(self.TIMEOUT) bits = self.__demodulate(conn) self.assertEqual(len(bits), 1) bits = bits[0] self.assertTrue(bits.startswith(preamble_str + sync_str)) bits = bits.replace(preamble_str + sync_str, "") self.assertEqual(int(bits, 2), seq_num + 5) NetworkSDRInterfacePlugin.shutdown_socket(conn) NetworkSDRInterfacePlugin.shutdown_socket(s) def test_external_program_simulator(self): if sys.platform == "win32" and struct.calcsize("P") * 8 == 32: print("Skipping test on 32 Bit windows as CI is slow.") self.assertTrue(True) return stc = self.form.simulator_tab_controller # type: SimulatorTabController stc.ui.btnAddParticipant.click() stc.ui.btnAddParticipant.click() stc.project_manager.simulator_timeout_ms = 999999999 stc.simulator_scene.add_counter_action(None, 0) action = next(item for item in stc.simulator_scene.items() if isinstance(item, CounterActionItem)) action.model_item.start = 3 action.model_item.step = 2 counter_item_str = "item" + str( action.model_item.index()) + ".counter_value" stc.ui.gvSimulator.add_empty_message(42) stc.ui.gvSimulator.add_empty_message(42) stc.ui.cbViewType.setCurrentIndex(0) stc.create_simulator_label(0, 10, 20) stc.create_simulator_label(1, 10, 20) messages = stc.simulator_config.get_all_messages() messages[0].source = stc.project_manager.participants[0] messages[0].destination = stc.project_manager.participants[1] messages[0].destination.simulate = True messages[1].source = stc.project_manager.participants[1] messages[1].destination = stc.project_manager.participants[0] stc.simulator_scene.add_trigger_command_action(None, 200) stc.simulator_scene.add_sleep_action(None, 200) lbl1 = messages[0].message_type[0] # type: SimulatorProtocolLabel lbl2 = messages[1].message_type[0] # type: SimulatorProtocolLabel ext_program = get_path_for_data_file( "external_program_simulator.py") + " " + counter_item_str if sys.platform == "win32": ext_program = sys.executable + " " + ext_program lbl1.value_type_index = 3 lbl1.external_program = ext_program lbl2.value_type_index = 3 lbl2.external_program = ext_program action = next(item for item in stc.simulator_scene.items() if isinstance(item, SleepActionItem)) action.model_item.sleep_time = 0.000000001 stc.simulator_scene.clearSelection() action = next(item for item in stc.simulator_scene.items() if isinstance(item, TriggerCommandActionItem)) action.setSelected(True) self.assertEqual(stc.ui.detail_view_widget.currentIndex(), 4) file_name = os.path.join(tempfile.gettempdir(), "external_test") if os.path.isfile(file_name): os.remove(file_name) self.assertFalse(os.path.isfile(file_name)) external_command = "cmd.exe /C copy NUL {}".format( file_name) if os.name == "nt" else "touch {}".format(file_name) stc.ui.lineEditTriggerCommand.setText(external_command) self.assertEqual(action.model_item.command, external_command) port = self.get_free_port() self.alice = NetworkSDRInterfacePlugin(raw_mode=True) self.alice.client_port = port dialog = stc.get_simulator_dialog() name = NetworkSDRInterfacePlugin.NETWORK_SDR_NAME dialog.device_settings_rx_widget.ui.cbDevice.setCurrentText(name) dialog.device_settings_tx_widget.ui.cbDevice.setCurrentText(name) simulator = dialog.simulator simulator.sniffer.rcv_device.set_server_port(port) port = self.get_free_port() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) s.bind(("", port)) s.listen(1) simulator.sender.device.set_client_port(port) dialog.ui.btnStartStop.click() while not any("Waiting for message" in msg for msg in dialog.simulator.log_messages): logger.debug("Waiting for simulator to wait for message") time.sleep(self.TIMEOUT) conn, addr = s.accept() modulator = dialog.project_manager.modulators[0] # type: Modulator self.alice.send_raw_data(modulator.modulate("100" + "10101010" * 42), 1) time.sleep(self.TIMEOUT) self.alice.send_raw_data( IQArray(None, np.float32, 2 * self.num_zeros_for_pause), 1) while not any("Sending message" in msg for msg in dialog.simulator.log_messages): logger.debug("Waiting for simulator to send message") time.sleep(self.TIMEOUT) time.sleep(self.TIMEOUT) bits = self.__demodulate(conn) self.assertEqual(bits[0].rstrip("0"), "101010101") while simulator.is_simulating: logger.debug("Wait for simulator to finish") time.sleep(self.TIMEOUT) NetworkSDRInterfacePlugin.shutdown_socket(conn) NetworkSDRInterfacePlugin.shutdown_socket(s) self.assertTrue(os.path.isfile(file_name)) 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
def test_open_simulator_dialog_and_send_mismatching_message(self): def __wait_for_simulator_log_message(dialog, log_message): n = 0 while not any(log_message in msg for msg in dialog.simulator.log_messages): if n < 50: time.sleep(0.5) else: self.fail("Did not receive log message \"{}\"".format( log_message)) n += 1 stc = self.form.simulator_tab_controller assert isinstance(stc, SimulatorTabController) self.__setup_project() self.add_all_signals_to_simulator() stc.simulator_scene.select_all_items() stc.simulator_config.project_manager.simulator_timeout_ms = 999999999 for msg in stc.simulator_scene.get_selected_messages(): msg.destination = self.dennis stc.ui.gvSimulator.message_updated.emit(msg) list_model = stc.ui.listViewSimulate.model() self.assertEqual(list_model.rowCount(), 2) list_model.setData(list_model.createIndex(1, 0), Qt.Checked, role=Qt.CheckStateRole) dialog = stc.get_simulator_dialog() network_sdr_name = NetworkSDRInterfacePlugin.NETWORK_SDR_NAME dialog.device_settings_rx_widget.ui.cbDevice.setCurrentText( network_sdr_name) rcv_port = util.get_free_port() dialog.simulator.sniffer.rcv_device.set_server_port(rcv_port) dialog.simulator.sniffer.adaptive_noise = False dialog.simulator.sniffer.automatic_center = False dialog.ui.btnStartStop.click() __wait_for_simulator_log_message(dialog, "Waiting for message 1") modulator = dialog.project_manager.modulators[0] # type: Modulator sender = NetworkSDRInterfacePlugin(raw_mode=True, sending=True) sender.client_port = rcv_port sender.send_raw_data(modulator.modulate("1" * 352), 1) time.sleep(0.5) sender.send_raw_data(IQArray(None, np.float32, 2000), 1) __wait_for_simulator_log_message(dialog, "Waiting for message 2") sender.send_raw_data(modulator.modulate("10" * 176), 1) time.sleep(0.5) sender.send_raw_data(IQArray(None, np.float32, 2000), 1) __wait_for_simulator_log_message(dialog, "Mismatch for label:") dialog.on_timer_timeout() # enforce writing to text view simulator_log = dialog.ui.textEditSimulation.toPlainText() self.assertIn("Received message 1", simulator_log) self.assertIn("preamble: 11111111", simulator_log) self.assertIn("Mismatch for label: preamble", simulator_log) dialog.close()
class TestSimulator(QtTestCase): def setUp(self): super().setUp() SettingsProxy.OVERWRITE_RECEIVE_BUFFER_SIZE = 10 * 10**6 self.num_zeros_for_pause = 1000 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.complex")) 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 = 100000 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 = 113600 - 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) QTest.qWait(10) # 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) QTest.qWait(100) receive_process.join(10) 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 test_simulation_flow(self): """ test a simulation flow with an increasing sequence number :return: """ profile = self.get_path_for_filename("testprofile.sim.xml") self.form.add_files([profile]) self.assertEqual( len(self.form.simulator_tab_controller.simulator_scene. get_all_message_items()), 6) port = self.get_free_port() self.alice = NetworkSDRInterfacePlugin(raw_mode=True) self.alice.client_port = port dialog = self.form.simulator_tab_controller.get_simulator_dialog() name = NetworkSDRInterfacePlugin.NETWORK_SDR_NAME dialog.device_settings_rx_widget.ui.cbDevice.setCurrentText(name) dialog.device_settings_tx_widget.ui.cbDevice.setCurrentText(name) QTest.qWait(10) simulator = dialog.simulator simulator.sniffer.rcv_device.set_server_port(port) port = self.get_free_port() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) s.bind(("", port)) s.listen(1) QTest.qWait(10) simulator.sender.device.set_client_port(port) dialog.ui.btnStartStop.click() QTest.qWait(1500) conn, addr = s.accept() msg = next(msg for msg in dialog.simulator_config.get_all_messages() if msg.source.name == "Alice") checksum_label = next( lbl for lbl in msg.message_type if lbl.is_checksum_label).label # type: ChecksumLabel modulator = dialog.project_manager.modulators[0] # type: Modulator preamble_str = "10101010" sync_str = "1001" preamble = list(map(int, preamble_str)) sync = list(map(int, sync_str)) seq = list(map(int, "00000010")) data = list(map(int, "11001101")) seq_num = int("".join(map(str, seq)), 2) checksum = list(checksum_label.calculate_checksum(seq + data)) msg1 = preamble + sync + seq + data + checksum self.alice.send_raw_data(modulator.modulate(msg1), 1) self.alice.send_raw_data( np.zeros(self.num_zeros_for_pause, dtype=np.complex64), 1) bits = self.__demodulate(conn) self.assertEqual(len(bits), 1) bits = bits[0] self.assertTrue(bits.startswith(preamble_str + sync_str)) bits = bits.replace(preamble_str + sync_str, "") self.assertEqual(int(bits, 2), seq_num + 1) seq = list(map(int, "{0:08b}".format(seq_num + 2))) checksum = list(checksum_label.calculate_checksum(seq + data)) msg2 = preamble + sync + seq + data + checksum self.alice.send_raw_data(modulator.modulate(msg2), 1) self.alice.send_raw_data( np.zeros(self.num_zeros_for_pause, dtype=np.complex64), 1) bits = self.__demodulate(conn) self.assertEqual(len(bits), 1) bits = bits[0] self.assertTrue(bits.startswith(preamble_str + sync_str)) bits = bits.replace(preamble_str + sync_str, "") self.assertEqual(int(bits, 2), seq_num + 3) seq = list(map(int, "{0:08b}".format(seq_num + 4))) checksum = list(checksum_label.calculate_checksum(seq + data)) msg3 = preamble + sync + seq + data + checksum self.alice.send_raw_data(modulator.modulate(msg3), 1) self.alice.send_raw_data( np.zeros(self.num_zeros_for_pause, dtype=np.complex64), 1) bits = self.__demodulate(conn) self.assertEqual(len(bits), 1) bits = bits[0] self.assertTrue(bits.startswith(preamble_str + sync_str)) bits = bits.replace(preamble_str + sync_str, "") self.assertEqual(int(bits, 2), seq_num + 5) QTest.qWait(50) self.assertTrue(simulator.simulation_is_finished()) time.sleep(1) conn.close() s.close() QTest.qWait(100) def test_external_program_simulator(self): stc = self.form.simulator_tab_controller stc.ui.btnAddParticipant.click() stc.ui.btnAddParticipant.click() stc.simulator_scene.add_counter_action(None, 0) action = next(item for item in stc.simulator_scene.items() if isinstance(item, CounterActionItem)) action.model_item.start = 3 action.model_item.step = 2 counter_item_str = "item" + str( action.model_item.index()) + ".counter_value" stc.ui.gvSimulator.add_empty_message(42) stc.ui.gvSimulator.add_empty_message(42) stc.ui.cbViewType.setCurrentIndex(0) stc.create_simulator_label(0, 10, 20) stc.create_simulator_label(1, 10, 20) messages = stc.simulator_config.get_all_messages() messages[0].source = stc.project_manager.participants[0] messages[0].destination = stc.project_manager.participants[1] messages[0].destination.simulate = True messages[1].source = stc.project_manager.participants[1] messages[1].destination = stc.project_manager.participants[0] stc.simulator_scene.add_trigger_command_action(None, 200) stc.simulator_scene.add_sleep_action(None, 200) lbl1 = messages[0].message_type[0] # type: SimulatorProtocolLabel lbl2 = messages[1].message_type[0] # type: SimulatorProtocolLabel lbl1.value_type_index = 3 lbl1.external_program = get_path_for_data_file( "external_program_simulator.py") + " " + counter_item_str lbl2.value_type_index = 3 lbl2.external_program = get_path_for_data_file( "external_program_simulator.py") + " " + counter_item_str action = next(item for item in stc.simulator_scene.items() if isinstance(item, SleepActionItem)) action.model_item.sleep_time = 0.001 stc.simulator_scene.clearSelection() action = next(item for item in stc.simulator_scene.items() if isinstance(item, TriggerCommandActionItem)) action.setSelected(True) self.assertEqual(stc.ui.detail_view_widget.currentIndex(), 4) fname = tempfile.mktemp() self.assertFalse(os.path.isfile(fname)) external_command = "cmd.exe /C copy NUL {}".format( fname) if os.name == "nt" else "touch {}".format(fname) stc.ui.lineEditTriggerCommand.setText(external_command) self.assertEqual(action.model_item.command, external_command) port = self.get_free_port() self.alice = NetworkSDRInterfacePlugin(raw_mode=True) self.alice.client_port = port dialog = stc.get_simulator_dialog() name = NetworkSDRInterfacePlugin.NETWORK_SDR_NAME dialog.device_settings_rx_widget.ui.cbDevice.setCurrentText(name) dialog.device_settings_tx_widget.ui.cbDevice.setCurrentText(name) QTest.qWait(10) simulator = dialog.simulator simulator.sniffer.rcv_device.set_server_port(port) port = self.get_free_port() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) s.bind(("", port)) s.listen(1) QTest.qWait(10) simulator.sender.device.set_client_port(port) dialog.ui.btnStartStop.click() QTest.qWait(1500) conn, addr = s.accept() modulator = dialog.project_manager.modulators[0] # type: Modulator self.alice.send_raw_data(modulator.modulate("100" + "10101010" * 42), 1) self.alice.send_raw_data( np.zeros(self.num_zeros_for_pause, dtype=np.complex64), 1) bits = self.__demodulate(conn) self.assertEqual(bits[0], "101010101") QTest.qWait(500) self.assertTrue(simulator.simulation_is_finished()) conn.close() s.close() QTest.qWait(100) self.assertTrue(os.path.isfile(fname)) def __demodulate(self, connection): QTest.qWait(100) data = connection.recv(65536) while len(data) % 8 != 0: data += connection.recv(65536) arr = np.array(np.frombuffer(data, dtype=np.complex64)) signal = Signal("", "") signal._fulldata = arr pa = ProtocolAnalyzer(signal) pa.get_protocol_from_signal() return pa.plain_bits_str
class TestProtocolSniffer(QtTestCase): def setUp(self): super().setUp() SettingsProxy.OVERWRITE_RECEIVE_BUFFER_SIZE = 50000 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_symbol = 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.iq_array = IQArray.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 = 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 * bit_len), 1) time.sleep(1) sniffer.stop() self.assertEqual(sniffer.plain_bits_str, data)
class TestProtocolSniffer(QtTestCase): def setUp(self): super().setUp() SettingsProxy.OVERWRITE_RECEIVE_BUFFER_SIZE = 50000 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 test_open_simulator_dialog_and_send_mismatching_message(self): stc = self.form.simulator_tab_controller assert isinstance(stc, SimulatorTabController) self.__setup_project() self.add_all_signals_to_simulator() stc.simulator_scene.select_all_items() stc.simulator_config.project_manager.simulator_timeout_ms = 999999999 for msg in stc.simulator_scene.get_selected_messages(): msg.destination = self.dennis stc.ui.gvSimulator.message_updated.emit(msg) list_model = stc.ui.listViewSimulate.model() self.assertEqual(list_model.rowCount(), 2) list_model.setData(list_model.createIndex(1, 0), Qt.Checked, role=Qt.CheckStateRole) dialog = stc.get_simulator_dialog() network_sdr_name = NetworkSDRInterfacePlugin.NETWORK_SDR_NAME dialog.device_settings_rx_widget.ui.cbDevice.setCurrentText(network_sdr_name) rcv_port = self.get_free_port() dialog.simulator.sniffer.rcv_device.set_server_port(rcv_port) dialog.simulator.sniffer.adaptive_noise = False dialog.simulator.sniffer.automatic_center = False dialog.ui.btnStartStop.click() while not any("Waiting for message 1" in msg for msg in dialog.simulator.log_messages): logger.debug("Waiting for simulator to wait for message 1") time.sleep(1) modulator = dialog.project_manager.modulators[0] # type: Modulator sender = NetworkSDRInterfacePlugin(raw_mode=True, sending=True) sender.client_port = rcv_port sender.send_raw_data(modulator.modulate("1" * 352), 1) time.sleep(0.5) sender.send_raw_data(np.zeros(1000, dtype=np.complex64), 1) while not any("Waiting for message 2" in msg for msg in dialog.simulator.log_messages): logger.debug("Waiting for simulator wait for message 2") time.sleep(1) sender.send_raw_data(modulator.modulate("10" * 176), 1) time.sleep(0.5) sender.send_raw_data(np.zeros(1000, dtype=np.complex64), 1) while not any("Mismatch for label:" in msg for msg in dialog.simulator.log_messages): logger.debug("Waiting for mismatching message") time.sleep(1) dialog.on_timer_timeout() # enforce writing to text view simulator_log = dialog.ui.textEditSimulation.toPlainText() self.assertIn("Received message 1", simulator_log) self.assertIn("preamble: 11111111", simulator_log) self.assertIn("Mismatch for label: preamble", simulator_log) dialog.close()
class TestSimulator(QtTestCase): TIMEOUT = 0.5 def setUp(self): super().setUp() SettingsProxy.OVERWRITE_RECEIVE_BUFFER_SIZE = 50000 self.num_zeros_for_pause = 1000 def test_simulation_flow(self): """ test a simulation flow with an increasing sequence number :return: """ profile = self.get_path_for_filename("testprofile.sim.xml") self.form.add_files([profile]) self.assertEqual(len(self.form.simulator_tab_controller.simulator_scene.get_all_message_items()), 6) port = self.get_free_port() self.alice = NetworkSDRInterfacePlugin(raw_mode=True) self.alice.client_port = port dialog = self.form.simulator_tab_controller.get_simulator_dialog() # type: SimulatorDialog dialog.project_manager.simulator_timeout_ms = 999999999 name = NetworkSDRInterfacePlugin.NETWORK_SDR_NAME dialog.device_settings_rx_widget.ui.cbDevice.setCurrentText(name) dialog.device_settings_tx_widget.ui.cbDevice.setCurrentText(name) simulator = dialog.simulator simulator.sniffer.rcv_device.set_server_port(port) port = self.get_free_port() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) s.bind(("", port)) s.listen(1) simulator.sender.device.set_client_port(port) dialog.ui.btnStartStop.click() QTest.qWait(250) while not any("Waiting for message" in msg for msg in dialog.simulator.log_messages): logger.debug("Waiting for simulator to wait for message") time.sleep(1) conn, addr = s.accept() msg = next(msg for msg in dialog.simulator_config.get_all_messages() if msg.source.name == "Alice") checksum_label = next(lbl for lbl in msg.message_type if lbl.is_checksum_label).label # type: ChecksumLabel modulator = dialog.project_manager.modulators[0] # type: Modulator preamble_str = "10101010" sync_str = "1001" preamble = list(map(int, preamble_str)) sync = list(map(int, sync_str)) seq = list(map(int, "00000010")) data = list(map(int, "11001101")) seq_num = int("".join(map(str, seq)), 2) checksum = list(checksum_label.calculate_checksum(seq + data)) msg1 = preamble + sync + seq + data + checksum self.alice.send_raw_data(modulator.modulate(msg1), 1) time.sleep(self.TIMEOUT) self.alice.send_raw_data(np.zeros(self.num_zeros_for_pause, dtype=np.complex64), 1) while not any("Sending message 2" in msg for msg in dialog.simulator.log_messages): logger.debug("Waiting for simulator to send message 2") time.sleep(1) bits = self.__demodulate(conn) self.assertEqual(len(bits), 1) bits = bits[0] self.assertTrue(bits.startswith(preamble_str + sync_str), msg=bits) bits = bits.replace(preamble_str + sync_str, "") self.assertEqual(int(bits, 2), seq_num + 1) seq = list(map(int, "{0:08b}".format(seq_num + 2))) checksum = list(checksum_label.calculate_checksum(seq + data)) msg2 = preamble + sync + seq + data + checksum self.alice.send_raw_data(modulator.modulate(msg2), 1) time.sleep(self.TIMEOUT) self.alice.send_raw_data(np.zeros(self.num_zeros_for_pause, dtype=np.complex64), 1) while not any("Sending message 4" in msg for msg in dialog.simulator.log_messages): logger.debug("Waiting for simulator to send message 4") time.sleep(1) bits = self.__demodulate(conn) self.assertEqual(len(bits), 1) bits = bits[0] self.assertTrue(bits.startswith(preamble_str + sync_str)) bits = bits.replace(preamble_str + sync_str, "") self.assertEqual(int(bits, 2), seq_num + 3) seq = list(map(int, "{0:08b}".format(seq_num + 4))) checksum = list(checksum_label.calculate_checksum(seq + data)) msg3 = preamble + sync + seq + data + checksum self.alice.send_raw_data(modulator.modulate(msg3), 1) time.sleep(self.TIMEOUT) self.alice.send_raw_data(np.zeros(self.num_zeros_for_pause, dtype=np.complex64), 1) while not any("Sending message 6" in msg for msg in dialog.simulator.log_messages): logger.debug("Waiting for simulator to send message 6") time.sleep(1) bits = self.__demodulate(conn) self.assertEqual(len(bits), 1) bits = bits[0] self.assertTrue(bits.startswith(preamble_str + sync_str)) bits = bits.replace(preamble_str + sync_str, "") self.assertEqual(int(bits, 2), seq_num + 5) NetworkSDRInterfacePlugin.shutdown_socket(conn) NetworkSDRInterfacePlugin.shutdown_socket(s) def test_external_program_simulator(self): stc = self.form.simulator_tab_controller # type: SimulatorTabController stc.ui.btnAddParticipant.click() stc.ui.btnAddParticipant.click() stc.project_manager.simulator_timeout_ms = 999999999 stc.simulator_scene.add_counter_action(None, 0) action = next(item for item in stc.simulator_scene.items() if isinstance(item, CounterActionItem)) action.model_item.start = 3 action.model_item.step = 2 counter_item_str = "item" + str(action.model_item.index()) + ".counter_value" stc.ui.gvSimulator.add_empty_message(42) stc.ui.gvSimulator.add_empty_message(42) stc.ui.cbViewType.setCurrentIndex(0) stc.create_simulator_label(0, 10, 20) stc.create_simulator_label(1, 10, 20) messages = stc.simulator_config.get_all_messages() messages[0].source = stc.project_manager.participants[0] messages[0].destination = stc.project_manager.participants[1] messages[0].destination.simulate = True messages[1].source = stc.project_manager.participants[1] messages[1].destination = stc.project_manager.participants[0] stc.simulator_scene.add_trigger_command_action(None, 200) stc.simulator_scene.add_sleep_action(None, 200) lbl1 = messages[0].message_type[0] # type: SimulatorProtocolLabel lbl2 = messages[1].message_type[0] # type: SimulatorProtocolLabel ext_program = get_path_for_data_file("external_program_simulator.py") + " " + counter_item_str if sys.platform == "win32": ext_program = sys.executable + " " + ext_program lbl1.value_type_index = 3 lbl1.external_program = ext_program lbl2.value_type_index = 3 lbl2.external_program = ext_program action = next(item for item in stc.simulator_scene.items() if isinstance(item, SleepActionItem)) action.model_item.sleep_time = 0.000000001 stc.simulator_scene.clearSelection() action = next(item for item in stc.simulator_scene.items() if isinstance(item, TriggerCommandActionItem)) action.setSelected(True) self.assertEqual(stc.ui.detail_view_widget.currentIndex(), 4) file_name = os.path.join(tempfile.gettempdir(), "external_test") if os.path.isfile(file_name): os.remove(file_name) self.assertFalse(os.path.isfile(file_name)) external_command = "cmd.exe /C copy NUL {}".format(file_name) if os.name == "nt" else "touch {}".format(file_name) stc.ui.lineEditTriggerCommand.setText(external_command) self.assertEqual(action.model_item.command, external_command) port = self.get_free_port() self.alice = NetworkSDRInterfacePlugin(raw_mode=True) self.alice.client_port = port dialog = stc.get_simulator_dialog() name = NetworkSDRInterfacePlugin.NETWORK_SDR_NAME dialog.device_settings_rx_widget.ui.cbDevice.setCurrentText(name) dialog.device_settings_tx_widget.ui.cbDevice.setCurrentText(name) QTest.qWait(100) simulator = dialog.simulator simulator.sniffer.rcv_device.set_server_port(port) port = self.get_free_port() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) s.bind(("", port)) s.listen(1) simulator.sender.device.set_client_port(port) dialog.ui.btnStartStop.click() QTest.qWait(250) while not any("Waiting for message" in msg for msg in dialog.simulator.log_messages): logger.debug("Waiting for simulator to wait for message") time.sleep(1) conn, addr = s.accept() modulator = dialog.project_manager.modulators[0] # type: Modulator self.alice.send_raw_data(modulator.modulate("100" + "10101010" * 42), 1) time.sleep(self.TIMEOUT) self.alice.send_raw_data(np.zeros(self.num_zeros_for_pause, dtype=np.complex64), 1) while not any("Sending message" in msg for msg in dialog.simulator.log_messages): logger.debug("Waiting for simulator to send message") time.sleep(1) time.sleep(self.TIMEOUT) bits = self.__demodulate(conn) self.assertEqual(bits[0].rstrip("0"), "101010101") while simulator.is_simulating: logger.debug("Wait for simulator to finish") time.sleep(1) NetworkSDRInterfacePlugin.shutdown_socket(conn) NetworkSDRInterfacePlugin.shutdown_socket(s) self.assertTrue(os.path.isfile(file_name)) def __demodulate(self, connection: socket.socket): connection.settimeout(0.1) 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 = np.array(np.frombuffer(b"".join(total_data), dtype=np.complex64)) signal = Signal("", "") signal._fulldata = arr pa = ProtocolAnalyzer(signal) pa.get_protocol_from_signal() return pa.plain_bits_str
class TestSimulatorPerfomance(QtTestCase): def setUp(self): super().setUp() self.num_zeros_for_pause = 1000 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()
class TestProtocolSniffer(QtTestCase): def setUp(self): super().setUp() SettingsProxy.OVERWRITE_RECEIVE_BUFFER_SIZE = 100 * 10**6 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) chunk_size = 128 for i in range(0, len(send_data), chunk_size): self.network_sdr_plugin_sender.send_raw_data( send_data[i:i + chunk_size], 1) QTest.qWait(10) # Send enough pauses to end sniffing for i in range(10): self.network_sdr_plugin_sender.send_raw_data( np.zeros(bit_len, dtype=np.complex64), 1) QTest.qWait(10) sniffer.stop() self.assertEqual(sniffer.plain_bits_str, data) # needed to prevent crash on windows QTest.qWait(10)
def test_open_simulator_dialog_and_send_mismatching_message(self): stc = self.form.simulator_tab_controller assert isinstance(stc, SimulatorTabController) self.__setup_project() self.add_all_signals_to_simulator() stc.simulator_scene.select_all_items() stc.simulator_config.project_manager.simulator_timeout_ms = 999999999 for msg in stc.simulator_scene.get_selected_messages(): msg.destination = self.dennis stc.ui.gvSimulator.message_updated.emit(msg) list_model = stc.ui.listViewSimulate.model() self.assertEqual(list_model.rowCount(), 2) list_model.setData(list_model.createIndex(1, 0), Qt.Checked, role=Qt.CheckStateRole) dialog = stc.get_simulator_dialog() network_sdr_name = NetworkSDRInterfacePlugin.NETWORK_SDR_NAME dialog.device_settings_rx_widget.ui.cbDevice.setCurrentText( network_sdr_name) rcv_port = self.get_free_port() dialog.simulator.sniffer.rcv_device.set_server_port(rcv_port) dialog.simulator.sniffer.adaptive_noise = False dialog.simulator.sniffer.automatic_center = False dialog.ui.btnStartStop.click() while not any("Waiting for message 1" in msg for msg in dialog.simulator.log_messages): logger.debug("Waiting for simulator to wait for message 1") time.sleep(1) modulator = dialog.project_manager.modulators[0] # type: Modulator sender = NetworkSDRInterfacePlugin(raw_mode=True, sending=True) sender.client_port = rcv_port sender.send_raw_data(modulator.modulate("1" * 352), 1) time.sleep(0.5) sender.send_raw_data(np.zeros(1000, dtype=np.complex64), 1) while not any("Waiting for message 2" in msg for msg in dialog.simulator.log_messages): logger.debug("Waiting for simulator wait for message 2") time.sleep(1) sender.send_raw_data(modulator.modulate("10" * 176), 1) time.sleep(0.5) sender.send_raw_data(np.zeros(1000, dtype=np.complex64), 1) while not any("Mismatch for label:" in msg for msg in dialog.simulator.log_messages): logger.debug("Waiting for mismatching message") time.sleep(1) QTest.qWait(250) QApplication.processEvents() QTest.qWait(100) simulator_log = dialog.ui.textEditSimulation.toPlainText() self.assertIn("Received message 1", simulator_log) self.assertIn("preamble: 11111111", simulator_log) self.assertIn("Mismatch for label: preamble", simulator_log) dialog.close()
class TestSimulator(QtTestCase): def setUp(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.complex")) 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() SettingsProxy.OVERWRITE_RECEIVE_BUFFER_SIZE = 100 * 10**6 self.network_sdr_plugin_sender = NetworkSDRInterfacePlugin( raw_mode=True) def test_performance(self): 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.001, 5, 1, NetworkSDRInterfacePlugin.NETWORK_SDR_NAME, BackendHandler(), network_raw_mode=True, real_time=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) 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, 100000, 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, 100000, 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 = 113600 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(1) # 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 modulator.modulate(msg_a.encoded_bits) # yappi.start() self.network_sdr_plugin_sender.send_raw_data( modulator.modulated_samples, 1) QTest.qWait(100) receive_process.join(10) print("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 __get_free_port(self): import socket s = socket.socket() s.bind(("", 0)) port = s.getsockname()[1] s.close() return port