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
def run(self): self.initialize_process() len_data = len(self.data) self.current_iteration = self.current_iteration if self.current_iteration is not None else 0 time.sleep(1) try: while self.current_index < len_data and not self.isInterruptionRequested(): time.sleep(0.1 * (self.samples_per_transmission / self.MAX_SAMPLES_PER_TRANSMISSION)) self.socket.send(self.data[self.current_index:self.current_index + self.samples_per_transmission].tostring()) self.current_index += self.samples_per_transmission if self.current_index >= len_data: self.current_iteration += 1 else: continue if self.repeat_endless or self.current_iteration < self.sending_repeats: self.current_index = 0 self.current_index = len_data - 1 self.current_iteration = None self.stop("FIN - All data was sent successfully") except RuntimeError: logger.error("Sender thread crashed.")
def parse_project_file(file_path: str): import xml.etree.ElementTree as ET from urh.util.ProjectManager import ProjectManager result = defaultdict(lambda: None) if not file_path or not os.path.isfile(file_path): return result try: tree = ET.parse(file_path) root = tree.getroot() except Exception as e: logger.error("Could not read project file {}: {}".format(file_path, e)) return result ProjectManager.read_device_conf_dict(root.find("device_conf"), target_dict=result) result["device"] = result["name"] modulators = Modulator.modulators_from_xml_tag(root) if len(modulators) > 0: modulator = modulators[0] result["carrier_frequency"] = modulator.carrier_freq_hz result["carrier_amplitude"] = modulator.carrier_amplitude result["carrier_phase"] = modulator.carrier_phase_deg result["parameter_zero"] = modulator.param_for_zero result["parameter_one"] = modulator.param_for_one result["modulation_type"] = modulator.modulation_type_str return result
def duplicate_lines(self, rows: list): for row in reversed(rows): try: self.messages.insert(max(rows) + 1, copy.deepcopy(self.messages[row])) except Exception as e: logger.error("Duplicating line ", str(e)) self.qt_signals.line_duplicated.emit()
def stop(self): self.is_running = False self.rcv_device.stop("Stopping receiving due to user interaction") if self.sniff_thread.is_alive(): self.sniff_thread.join(0.1) if self.sniff_thread.is_alive(): logger.error("Sniff thread is still alive")
def run_command(command, param: str = None, use_stdin=False, detailed_output=False, return_rc=False): cmd, arg = parse_command(command) if shutil.which(cmd) is None: logger.error("Could not find {}".format(cmd)) return "" startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW if "." in cmd: default_app = get_default_windows_program_for_extension(cmd.split(".")[-1]) if default_app: arg.insert(0, cmd) cmd = default_app call_list = [cmd] + arg try: if detailed_output: if param is not None: call_list.append(param) p = subprocess.Popen(call_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo) out, err = p.communicate() result = "{} exited with {}".format(" ".join(call_list), p.returncode) if out.decode(): result += " stdout: {}".format(out.decode()) if err.decode(): result += " stderr: {}".format(err.decode()) if return_rc: return result, p.returncode else: return result elif use_stdin: p = subprocess.Popen(call_list, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo) param = param.encode() if param is not None else None out, _ = p.communicate(param) if return_rc: return out.decode(), p.returncode else: return out.decode() else: if param is not None: call_list.append(param) if return_rc: raise ValueError("Return Code not supported for this configuration") return subprocess.check_output(call_list, stderr=subprocess.PIPE, startupinfo=startupinfo).decode() except Exception as e: msg = "Could not run {} ({})".format(cmd, e) logger.error(msg) if detailed_output: return msg else: return ""
def decimal2bit(number: str, num_bits: int) -> array.array: try: number = int(number) except ValueError as e: logger.error(e) return array.array("B", []) fmt_str = "{0:0" + str(num_bits) + "b}" return array.array("B", map(int, fmt_str.format(number)))
def read_decoders_from_xml_tag(root: ET.Element): try: decoders = [] for decoding_tag in root.find("decodings").findall("decoding"): conf = [d.strip().replace("'", "") for d in decoding_tag.text.split(",") if d.strip().replace("'", "")] decoders.append(Encoding(conf)) return decoders except AttributeError: logger.error("no decodings found in xml") return []
def load_from_file(self, filename: str): try: self.table_model.protocol.from_xml_file(filename) self.refresh_pause_list() self.refresh_estimated_time() self.refresh_modulators() self.show_modulation_info() self.refresh_table() self.set_fuzzing_ui_status() except: logger.error("You done something wrong to the xml fuzzing profile.")
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 from_xml_file(self, filename: str, read_bits=False): try: tree = ET.parse(filename) except FileNotFoundError: logger.error("Could not find file " + filename) return except ET.ParseError: logger.error("Could not parse file " + filename) return root = tree.getroot() self.from_xml_tag(root, read_bits=read_bits)
def ascii2bit(ascii_str: str) -> array.array: if not isinstance(ascii_str, str): return array.array("B", []) try: bitstring = "".join("{0:08b}".format(ord(c)) for c in ascii_str) return array.array("B", [True if x == "1" else False for x in bitstring]) except (TypeError, ValueError) as e: logger.error(e) result = array.array("B", []) return result
def prepare_send_connection(self): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.connect((self.client_ip, self.client_port)) self.send_connection_established.emit() return sock except Exception as e: msg = "Could not establish connection " + str(e) self.error_occurred.emit(msg) logger.error(msg) return None
def __fill_counter_values(self, command: str): result = [] regex = "(item[0-9]+\.counter_value)" for token in re.split(regex, command): if re.match(regex, token) is not None: try: result.append(str(self.simulator_config.item_dict[token].value)) except (KeyError, ValueError, AttributeError): logger.error("Could not get counter value for " + token) else: result.append(token) return "".join(result)
def to_xml(self) -> ET.Element: result = ET.Element("message_type", attrib={"name": self.name, "id": self.id, "assigned_by_ruleset": "1" if self.assigned_by_ruleset else "0", "assigned_by_logic_analyzer": "1" if self.assigned_by_logic_analyzer else "0"}) for lbl in self: try: result.append(lbl.to_xml()) except TypeError: logger.error("Could not save label: " + str(lbl)) result.append(self.ruleset.to_xml()) return result
def build_image(imagename: str): if imagename not in SUPPORTED_IMAGES: logger.error("{} is not a supported docker image".format(imagename)) sys.exit(1) cmd = ["sudo"] if USE_SUDO else [] cmd.extend(["docker", "build", "--force-rm", "--no-cache", "--tag", "urh/"+imagename, "."]) print(" ".join(cmd)) script = __file__ if not os.path.islink(__file__) else os.readlink(__file__) os.chdir(os.path.realpath(os.path.join(script, "..", imagename))) call(cmd)
def hex2bit(hex_str: str) -> array.array: if not isinstance(hex_str, str): return array.array("B", []) if hex_str[:2] == "0x": hex_str = hex_str[2:] try: bitstring = "".join("{0:04b}".format(int(h, 16)) for h in hex_str) return array.array("B", [True if x == "1" else False for x in bitstring]) except (TypeError, ValueError) as e: logger.error(e) result = array.array("B", []) return result
def configure_special_config_tabs(self): self.ui.tabWidgetAdvancedSettings.clear() for lbl in self.model.message_type: # type: ProtocolLabel if lbl.field_type is not None and lbl.field_type.function in self.SPECIAL_CONFIG_TYPES: if isinstance(lbl, ChecksumLabel): w = ChecksumWidgetController(lbl, self.model.message, self.model.proto_view) self.ui.tabWidgetAdvancedSettings.addTab(w, lbl.name) else: logger.error("No Special Config Dialog for field type " + lbl.field_type.caption) if self.ui.tabWidgetAdvancedSettings.count() > 0: self.ui.tabWidgetAdvancedSettings.setCurrentIndex(0) self.ui.tabWidgetAdvancedSettings.setFocus() self.ui.groupBoxAdvancedSettings.setVisible(self.ui.tabWidgetAdvancedSettings.count() > 0)
def stop(self, msg: str): if self.backend == Backends.grc: self.__dev.stop(msg) # Already connected to stopped in constructor elif self.backend == Backends.native: if self.mode == Mode.send: self.__dev.stop_tx_mode(msg) else: self.__dev.stop_rx_mode(msg) self.emit_stopped_signal() elif self.backend == Backends.network: self.__dev.stop_tcp_server() self.emit_stopped_signal() elif self.backend == Backends.none: pass else: logger.error("Stop device: Unsupported backend " + str(self.backend))
def on_show_record_dialog_action_triggered(self): pm = self.project_manager try: r = ReceiveDialog(pm, parent=self) except OSError as e: logger.error(repr(e)) return if r.has_empty_device_list: Errors.no_device() r.close() return r.device_parameters_changed.connect(pm.set_device_parameters) r.files_recorded.connect(self.on_signals_recorded) r.show()
def on_btn_replay_clicked(self): project_manager = self.project_manager try: dialog = SendDialogController(project_manager, modulated_data=self.signal.data, parent=self) except OSError as e: logger.error(repr(e)) return if dialog.has_empty_device_list: Errors.no_device() dialog.close() return dialog.recording_parameters.connect(project_manager.set_recording_parameters) dialog.show() dialog.graphics_view.show_full_scene(reinitialize=True)
def on_combobox_crc_function_current_index_changed(self, index: int): poly_str = self.ui.comboBoxCRCFunction.itemText(index) if poly_str in GenericCRC.DEFAULT_POLYNOMIALS: self.checksum_label.checksum.polynomial = self.checksum_label.checksum.choose_polynomial(poly_str) self.checksum_label.checksum.start_value = array.array("B", [0] * (self.checksum_label.checksum.poly_order - 1)) self.checksum_label.checksum.final_xor = array.array("B", [0] * (self.checksum_label.checksum.poly_order - 1)) elif poly_str in self.SPECIAL_CRCS: self.checksum_label.checksum = copy.deepcopy(self.SPECIAL_CRCS[poly_str]) else: logger.error("Unknown CRC") return self.ui.lineEditCRCPolynomial.setText(self.checksum_label.checksum.polynomial_as_hex_str) self.ui.lineEditStartValue.setText(util.bit2hex(self.checksum_label.checksum.start_value)) self.ui.lineEditFinalXOR.setText(util.bit2hex(self.checksum_label.checksum.final_xor)) self.ui.lineEditCRCPolynomial.editingFinished.emit()
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 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 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 generate_message_from_template(self, template_msg: SimulatorMessage): new_message = Message(template_msg.plain_bits, pause=template_msg.pause, rssi=0, message_type=template_msg.message_type, decoder=template_msg.decoder) for lbl in template_msg.children: # type: SimulatorProtocolLabel if lbl.value_type_index == 2: # formula valid, _, node = self.expression_parser.validate_expression(lbl.formula) assert valid result = self.expression_parser.evaluate_node(node) elif lbl.value_type_index == 3: transcript = self.transcript.get_for_participant(template_msg.source if template_msg.source.simulate else template_msg.destination) if template_msg.destination.simulate: direction = "->" if template_msg.source.simulate else "<-" transcript += "\n" + direction + new_message.plain_bits_str + "\n" cmd = self.__fill_counter_values(lbl.external_program) result = util.run_command(cmd, transcript, use_stdin=True) if len(result) != lbl.end - lbl.start: log_msg = "Result value of external program {}: {} ({}) does not match label length {}" logger.error(log_msg.format(cmd, result, len(result), lbl.end - lbl.start)) continue try: new_message[lbl.start:lbl.end] = array.array("B", (map(bool, map(int, result)))) except Exception as e: log_msg = "Could not assign {} to range because {}".format(result, e) logger.error(log_msg) continue elif lbl.value_type_index == 4: # random value result = numpy.random.randint(lbl.random_min, lbl.random_max + 1) else: continue self.set_label_value(new_message, lbl, result) return new_message
def configure_special_config_tabs(self): self.ui.tabWidgetAdvancedSettings.clear() for lbl in self.model.message_type: # type: ProtocolLabel if isinstance(lbl, SimulatorProtocolLabel): lbl = lbl.label if lbl.field_type is not None and lbl.field_type.function in self.SPECIAL_CONFIG_TYPES: if isinstance(lbl, ChecksumLabel): w = ChecksumWidget(lbl, self.model.message, self.model.proto_view) self.ui.tabWidgetAdvancedSettings.addTab(w, lbl.name) else: logger.error("No Special Config Dialog for field type " + lbl.field_type.caption) if self.ui.tabWidgetAdvancedSettings.count() > 0: self.ui.tabWidgetAdvancedSettings.setCurrentIndex(0) self.ui.tabWidgetAdvancedSettings.setFocus() self.ui.groupBoxAdvancedSettings.setVisible( self.ui.tabWidgetAdvancedSettings.count() > 0)
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: logger.info("{0}-{1} ({2}): Success".format( type(self).__name__, action, msg)) else: logger.info("{0}-{1}: Success".format( type(self).__name__, action)) else: if msg: err = "{0}-{1} ({4}): {2} ({3})".format( type(self).__name__, action, error_code_msg, retcode, msg) else: err = "{0}-{1}: {2} ({3})".format( type(self).__name__, action, error_code_msg, retcode) self.errors.add(err) logger.error(err)
def to_xml(self) -> ET.Element: result = ET.Element("message_type", attrib={ "name": self.name, "id": self.id, "assigned_by_ruleset": "1" if self.assigned_by_ruleset else "0", "assigned_by_logic_analyzer": "1" if self.assigned_by_logic_analyzer else "0" }) for lbl in self: try: result.append(lbl.to_xml(-1)) except TypeError: logger.error("Could not save label: " + str(lbl)) result.append(self.ruleset.to_xml()) return result
def create_image(data: np.ndarray, colormap, data_min=None, data_max=None, normalize=True) -> QImage: """ Create QImage from ARGB array. The ARGB must have shape (width, height, 4) and dtype=ubyte. NOTE: The order of values in the 3rd axis must be (blue, green, red, alpha). :return: """ image_data = Spectrogram.apply_bgra_lookup(data, colormap, data_min, data_max, normalize) if not image_data.flags['C_CONTIGUOUS']: logger.debug("Array was not C_CONTIGUOUS. Converting it.") image_data = np.ascontiguousarray(image_data) try: # QImage constructor needs inverted row/column order image = QImage(image_data.ctypes.data, image_data.shape[1], image_data.shape[0], QImage.Format_ARGB32) except Exception as e: logger.error("could not create image " + str(e)) return QImage() image.data = image_data return image
def set_gnuradio_installed_status(self): if self.use_gnuradio_install_dir: # We are probably on windows with a bundled gnuradio installation bin_dir = os.path.join(self.gnuradio_install_dir, "bin") site_packages_dir = os.path.join(self.gnuradio_install_dir, "lib", "site-packages") if all(os.path.isdir(dir) for dir in [self.gnuradio_install_dir, bin_dir, site_packages_dir]): self.gnuradio_is_installed = True else: self.gnuradio_is_installed = False else: if os.path.isfile(self.python2_exe) and os.access(self.python2_exe, os.X_OK): try: # Use shell=True to prevent console window popping up on windows self.gnuradio_is_installed = call('"{0}" -c "import gnuradio"'.format(self.python2_exe), shell=True, stderr=DEVNULL) == 0 except OSError as e: logger.error("Could not determine GNU Radio install status. Assuming true. Error: " + str(e)) self.gnuradio_is_installed = True else: self.gnuradio_is_installed = False constants.SETTINGS.setValue("gnuradio_is_installed", int(self.gnuradio_is_installed))
def generate_message_from_template(self, template_msg: SimulatorMessage): new_message = Message(template_msg.plain_bits, pause=template_msg.pause, rssi=0, message_type=template_msg.message_type, decoder=template_msg.decoder) for lbl in template_msg.children: # type: SimulatorProtocolLabel if lbl.value_type_index == 2: # formula valid, _, node = self.expression_parser.validate_expression(lbl.formula) assert valid result = self.expression_parser.evaluate_node(node) elif lbl.value_type_index == 3: transcript = self.get_transcript(template_msg.source if template_msg.source.simulate else template_msg.destination) direction = "->" if template_msg.source.simulate else "<-" transcript += direction + new_message.plain_bits_str + "\n" cmd = self.__fill_counter_values(lbl.external_program) result = util.run_command(cmd, transcript, use_stdin=True) if len(result) != lbl.end - lbl.start: log_msg = "Result value of external program {} ({}) does not match label length {}" logger.error(log_msg.format(result, len(result), lbl.end - lbl.start)) continue try: new_message[lbl.start:lbl.end] = array.array("B", (map(bool, map(int, result)))) except Exception as e: log_msg = "Could not assign {} to range because {}".format(result, e) logger.error(log_msg) continue elif lbl.value_type_index == 4: # random value result = numpy.random.randint(lbl.random_min, lbl.random_max + 1) else: continue self.set_label_value(new_message, lbl, result) return new_message
def on_btn_send_clicked(self): try: total_samples = self.total_modulated_samples buffer = self.prepare_modulation_buffer(total_samples) if buffer is not None: modulated_data = self.modulate_data(buffer) else: # Enter continuous mode modulated_data = None try: if modulated_data is not None: try: dialog = SendDialogController(self.project_manager, modulated_data=modulated_data, modulation_msg_indices=self.modulation_msg_indices, parent=self) except MemoryError: # Not enough memory for device buffer so we need to create a continuous send dialog del modulated_data Errors.not_enough_ram_for_sending_precache(None) dialog = ContinuousSendDialogController(self.project_manager, self.table_model.protocol.messages, self.modulators, total_samples, parent=self) else: dialog = ContinuousSendDialogController(self.project_manager, self.table_model.protocol.messages, self.modulators, total_samples, parent=self) except OSError as e: logger.error(repr(e)) return if dialog.has_empty_device_list: Errors.no_device() dialog.close() return dialog.recording_parameters.connect(self.project_manager.set_recording_parameters) dialog.show() dialog.graphics_view.show_full_scene(reinitialize=True) except Exception as e: Errors.generic_error(self.tr("Failed to generate data"), str(e), traceback.format_exc()) self.unsetCursor()
def set_gnuradio_installed_status(self): if self.use_gnuradio_install_dir: # We are probably on windows with a bundled gnuradio installation bin_dir = os.path.join(self.gnuradio_install_dir, "bin") site_packages_dir = os.path.join(self.gnuradio_install_dir, "lib", "site-packages") if all(os.path.isdir(dir) for dir in [self.gnuradio_install_dir, bin_dir, site_packages_dir]): self.gnuradio_is_installed = True else: self.gnuradio_is_installed = False else: if os.path.isfile(self.python2_exe) and os.access(self.python2_exe, os.X_OK): try: # Use shell=True to prevent console window popping up on windows self.gnuradio_is_installed = call('"{0}" -c "import gnuradio"'.format(self.python2_exe), shell=True, stderr=DEVNULL) == 0 except OSError as e: logger.error("Could not determine GNU Radio install status. Assuming true. Error: "+str(e)) self.gnuradio_is_installed = True else: self.gnuradio_is_installed = False constants.SETTINGS.setValue("gnuradio_is_installed", int(self.gnuradio_is_installed))
def stop_rx_mode(self, msg): self.is_receiving = False self.parent_conn.send("stop") logger.info("RTLSDR: Stopping RX Mode: " + msg) if hasattr(self, "receive_process"): self.receive_process.join(0.3) if self.receive_process.is_alive(): logger.warning( "RTLSDR: Receive process is still alive, terminating it") self.receive_process.terminate() self.receive_process.join() self.parent_conn, self.child_conn = Pipe() 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("RTLSDR: Joined read_queue_thread") except RuntimeError: logger.error("RTLSDR: Could not join read_queue_thread")
def evaluate_node(self, node): if isinstance(node, ast.BinOp): return self.operators[type(node.op)](self.evaluate_node(node.left), self.evaluate_node(node.right)) elif isinstance(node, ast.UnaryOp): return self.operators[type(node.op)](self.evaluate_node(node.operand)) elif isinstance(node, ast.Compare): to_string = isinstance(node.comparators[0], ast.Str) return self.operators[type(node.ops[0])](self.evaluate_attribute_node(node.left, to_string), self.evaluate_node(node.comparators[0])) elif isinstance(node, ast.BoolOp): func = all if isinstance(node.op, ast.And) else any return func(self.evaluate_node(value) for value in node.values) elif isinstance(node, ast.Str): return node.s elif isinstance(node, ast.Attribute): return self.evaluate_attribute_node(node) elif isinstance(node, ast.Num): return node.n else: logger.error("Error during parsing")
def on_btn_send_clicked(self): try: total_samples = self.total_modulated_samples buffer = self.prepare_modulation_buffer(total_samples) if buffer is not None: modulated_data = self.modulate_data(buffer) else: # Enter continuous mode modulated_data = None try: if modulated_data is not None: try: dialog = SendDialogController(self.project_manager, modulated_data=modulated_data, parent=self) except MemoryError: # Not enough memory for device buffer so we need to create a continuous send dialog del modulated_data Errors.not_enough_ram_for_sending_precache(None) dialog = ContinuousSendDialogController(self.project_manager, self.table_model.protocol.messages, self.modulators, total_samples, parent=self) else: dialog = ContinuousSendDialogController(self.project_manager, self.table_model.protocol.messages, self.modulators, total_samples, parent=self) except OSError as e: logger.error(repr(e)) return if dialog.has_empty_device_list: Errors.no_device() dialog.close() return dialog.recording_parameters.connect(self.project_manager.set_recording_parameters) dialog.show() dialog.graphics_view.show_full_scene(reinitialize=True) except Exception as e: Errors.generic_error(self.tr("Failed to generate data"), str(e), traceback.format_exc()) self.unsetCursor()
def on_btn_replay_clicked(self): project_manager = self.project_manager try: dialog = SendDialogController(project_manager.frequency, project_manager.sample_rate, project_manager.bandwidth, project_manager.gain, project_manager.device, modulated_data=self.signal.data, parent=self) except OSError as e: logger.error(repr(e)) return if dialog.has_empty_device_list: Errors.no_device() dialog.close() return dialog.recording_parameters.connect( project_manager.set_recording_parameters) dialog.show() dialog.graphics_view.show_full_scene(reinitialize=True)
def on_btn_send_clicked(self): try: modulated_data = self.modulate_data() try: dialog = SendDialogController(self.project_manager, modulated_data=modulated_data, parent=self) except OSError as e: logger.error(repr(e)) return if dialog.has_empty_device_list: Errors.no_device() dialog.close() return dialog.recording_parameters.connect( self.project_manager.set_recording_parameters) dialog.show() dialog.graphics_view.show_full_scene(reinitialize=True) except Exception as e: Errors.generic_error(self.tr("Failed to generate data"), str(e), traceback.format_exc()) self.unsetCursor()
def on_combobox_crc_function_current_index_changed(self, index: int): poly_str = self.ui.comboBoxCRCFunction.itemText(index) if poly_str in GenericCRC.DEFAULT_POLYNOMIALS: self.checksum_label.checksum.polynomial = self.checksum_label.checksum.choose_polynomial( poly_str) self.checksum_label.checksum.start_value = array.array( "B", [0] * (self.checksum_label.checksum.poly_order - 1)) self.checksum_label.checksum.final_xor = array.array( "B", [0] * (self.checksum_label.checksum.poly_order - 1)) elif poly_str in self.SPECIAL_CRCS: self.checksum_label.checksum = copy.deepcopy( self.SPECIAL_CRCS[poly_str]) else: logger.error("Unknown CRC") return self.ui.lineEditCRCPolynomial.setText( self.checksum_label.checksum.polynomial_as_hex_str) self.ui.lineEditStartValue.setText( util.bit2hex(self.checksum_label.checksum.start_value)) self.ui.lineEditFinalXOR.setText( util.bit2hex(self.checksum_label.checksum.final_xor)) self.ui.lineEditCRCPolynomial.editingFinished.emit()
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 __demodulate(self, connection: socket.socket): connection.settimeout(0.5) 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
def bcd2bit(value: str) -> array.array: try: return array.array("B", map(int, "".join(BCD_REVERSE_LUT[c] for c in value))) except Exception as e: logger.error(e) return array.array("B", [])
def duplicate_line(self, row: int): try: self.messages.insert(row + 1, copy.deepcopy(self.messages[row])) self.qt_signals.line_duplicated.emit() except Exception as e: logger.error("Duplicating line ", str(e))
def dropMimeData(self, mimedata, action, row, column, parentIndex): if action == Qt.IgnoreAction: return True data_str = str(mimedata.text()) indexes = list(reversed(data_str.split("/")[:-1])) drag_nodes = [] # Ensure we only drop groups or files contains_groups = False contains_files = False for index in indexes: row, column, parent = map(int, index.split(",")) if parent == -1: parent = self.rootItem else: parent = self.rootItem.child(parent) node = parent.child(row) try: if node.is_group: contains_groups = True else: contains_files = True except AttributeError: logger.error( "Could not perform drop for index {}".format(index)) continue if contains_files and contains_groups: QMessageBox.information( QWidget(), self.tr("Drag not supported"), self. tr("You can only drag/drop groups or protocols, no mixtures of both." )) return False drag_nodes.append(node) drop_node = self.getItem(parentIndex) if drop_node == self.rootItem: # Append to Last Group when dropped on root try: drop_node = self.rootItem.children[-1] except IndexError: return False if not drop_node.is_group: parent_node = drop_node.parent() dropped_on_group = False else: parent_node = drop_node dropped_on_group = True if parent_node is None: return False if dropped_on_group and contains_groups: parent_node = drop_node.parent() pos = parent_node.index_of(drop_node) parent_node.bringChildsToIndex(pos, drag_nodes) elif dropped_on_group: if parent_node.containsChilds(drag_nodes): # "Nodes on parent folder Dropped" parent_node.bringChildsToFront(drag_nodes) else: # "Nodes on distinct folder dropped" for dragNode in drag_nodes: parent_node.appendChild(dragNode) self.proto_to_group_added.emit( self.rootItem.index_of(parent_node)) else: # Dropped on file if contains_groups: # Can't drop groups on files return False elif parent_node.containsChilds( drag_nodes) and drop_node in parent_node.children: # "Nodes on node in parent folder dropped" pos = parent_node.index_of(drop_node) parent_node.bringChildsToIndex(pos, drag_nodes) elif parent_node.containsChilds(drag_nodes): parent_node.bringChildsToFront(drag_nodes) else: # "Nodes on node in distinct folder dropped" pos = parent_node.index_of(drop_node) for dragNode in drag_nodes: dragNode.setParent(parent_node) parent_node.insertChild(pos, dragNode) self.proto_to_group_added.emit( self.rootItem.index_of(parent_node)) self.item_dropped.emit() return True
def run_command(command, param: str = None, use_stdin=False, detailed_output=False, return_rc=False): cmd, arg = parse_command(command) if shutil.which(cmd) is None: logger.error("Could not find {}".format(cmd)) return "" startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW if "." in cmd: default_app = get_default_windows_program_for_extension( cmd.split(".")[-1]) if default_app: arg.insert(0, cmd) cmd = default_app call_list = [cmd] + arg try: if detailed_output: if param is not None: call_list.append(param) p = subprocess.Popen(call_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo) out, err = p.communicate() result = "{} exited with {}".format(" ".join(call_list), p.returncode) if out.decode(): result += " stdout: {}".format(out.decode()) if err.decode(): result += " stderr: {}".format(err.decode()) if return_rc: return result, p.returncode else: return result elif use_stdin: p = subprocess.Popen(call_list, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo) param = param.encode() if param is not None else None out, _ = p.communicate(param) if return_rc: return out.decode(), p.returncode else: return out.decode() else: if param is not None: call_list.append(param) if return_rc: raise ValueError( "Return Code not supported for this configuration") return subprocess.check_output(call_list, stderr=subprocess.PIPE, startupinfo=startupinfo).decode() except Exception as e: msg = "Could not run {} ({})".format(cmd, e) logger.error(msg) if detailed_output: return msg else: return ""
def run(self): logger.debug("Spectrum Thread: Init Process") self.initialize_process() logger.debug("Spectrum Thread: Process Intialized") self.init_recv_socket() logger.debug("Spectrum Thread: Socket initialized") recv = self.socket.recv rcvd = b"" try: logger.debug("Spectrum Thread: Enter main loop") 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, because no data transmitted anymore" ) return if len(rcvd) % 8 != 0: continue try: tmp = np.fromstring(rcvd, dtype=np.complex64) len_tmp = len(tmp) if self.data is None: self.data = np.zeros( self.buf_size, dtype=np.complex64) # type: np.ndarray if self.current_index + len_tmp >= len(self.data): self.data[self. current_index:] = tmp[:len(self.data) - self.current_index] tmp = tmp[len(self.data) - self.current_index:] w = np.abs(np.fft.fft(self.data)) freqs = np.fft.fftfreq(len(w), 1 / self.sample_rate) idx = np.argsort(freqs) self.x = freqs[idx].astype(np.float32) self.y = w[idx].astype(np.float32) self.data = np.zeros(len(self.data), dtype=np.complex64) self.data[0:len(tmp)] = tmp self.current_index = len(tmp) continue self.data[self.current_index:self.current_index + len_tmp] = tmp self.current_index += len_tmp return rcvd rcvd = b"" except ValueError: self.stop("Could not receive data. Is your Hardware ok?") except RuntimeError as e: logger.error("Spectrum thread crashed", str(e.args))