コード例 #1
0
def main():
    def get_val(value, project_params: dict, project_param_key: str, default):
        if value is not None:
            return value
        elif project_param_key in project_params:
            return project_params[project_param_key]
        else:
            return default

    import multiprocessing as mp
    # allow usage of prange (OpenMP) in Processes
    mp.set_start_method("spawn")
    if sys.platform == "win32":
        mp.freeze_support()

    parser = create_parser()
    args = parser.parse_args()
    project_params = parse_project_file(args.project_file)
    for argument in ("device", "frequency", "sample_rate"):
        if getattr(args, argument):
            continue

        if project_params[argument] is not None:
            setattr(args, argument, project_params[argument])
        else:
            print("You must specify a {}.".format(argument))
            sys.exit(1)

    if args.receive and args.transmit:
        print("You cannot use receive and transmit mode at the same time.")
        sys.exit(1)
    if not args.receive and not args.transmit:
        print(
            "You must choose a mode either RX (-rx, --receive) or TX (-tx, --transmit)"
        )
        sys.exit(1)

    args.bandwidth = get_val(args.bandwidth, project_params, "bandwidth", None)
    rx_tx_prefix = "rx_" if args.receive else "tx_"
    args.gain = get_val(args.gain, project_params, rx_tx_prefix + "gain", None)
    args.if_gain = get_val(args.if_gain, project_params,
                           rx_tx_prefix + "if_gain", None)
    args.baseband_gain = get_val(args.baseband_gain, project_params,
                                 rx_tx_prefix + "baseband_gain", None)

    if args.modulation_type is None:
        try:
            if project_params["modulation_type"] is None:
                args.modulation_type = MODULATIONS[int(
                    project_params["modulation_index"])]
            else:
                args.modulation_type = project_params["modulation_type"]
        except:
            pass

    args.bit_length = get_val(args.bit_length, project_params, "bit_len",
                              DEFAULT_BIT_LENGTH)
    args.center = get_val(args.center, project_params, "center",
                          DEFAULT_CENTER)
    args.noise = get_val(args.noise, project_params, "noise", DEFAULT_NOISE)
    args.tolerance = get_val(args.tolerance, project_params, "tolerance",
                             DEFAULT_TOLERANCE)

    args.carrier_frequency = get_val(args.carrier_frequency, project_params,
                                     "carrier_frequency",
                                     DEFAULT_CARRIER_FREQUENCY)
    args.carrier_amplitude = get_val(args.carrier_amplitude, project_params,
                                     "carrier_amplitude",
                                     DEFAULT_CARRIER_AMPLITUDE)
    args.carrier_phase = get_val(args.carrier_phase, project_params,
                                 "carrier_phase", DEFAULT_CARRIER_PHASE)
    args.parameter_zero = get_val(args.parameter_zero, project_params,
                                  "parameter_zero", None)
    args.parameter_one = get_val(args.parameter_one, project_params,
                                 "parameter_one", None)

    if args.verbose is None:
        logger.setLevel(logging.ERROR)
    elif args.verbose == 1:
        logger.setLevel(logging.INFO)
    else:
        logger.setLevel(logging.DEBUG)
    Logger.save_log_level()

    argument_string = "\n".join("{} {}".format(arg, getattr(args, arg))
                                for arg in vars(args))
    logger.debug("Using these parameters\n" + argument_string)

    if args.transmit:
        device = build_device_from_args(args)
        if args.raw:
            if args.filename is None:
                print(
                    "You need to give a file (-file, --filename) where to read samples from."
                )
                sys.exit(1)
            samples_to_send = np.fromfile(args.filename, dtype=np.complex64)
        else:
            modulator = build_modulator_from_args(args)
            messages_to_send = read_messages_to_send(args)
            samples_to_send = modulate_messages(messages_to_send, modulator)
        device.samples_to_send = samples_to_send
        device.start()

        while not device.sending_finished:
            try:
                time.sleep(0.1)
                device.read_messages()
                if device.current_index > 0:
                    cli_progress_bar(device.current_index,
                                     len(device.samples_to_send),
                                     title="Sending")
            except KeyboardInterrupt:
                break

        print()
        device.stop("Sending finished")
    elif args.receive:
        if args.raw:
            if args.filename is None:
                print(
                    "You need to give a file (-file, --filename) to receive into when using raw RX mode."
                )
                sys.exit(1)

            receiver = build_device_from_args(args)
            receiver.start()
        else:
            receiver = build_protocol_sniffer_from_args(args)
            receiver.sniff()

        total_time = 0

        if args.receive_time >= 0:
            print("Receiving for {} seconds...".format(args.receive_time))
        else:
            print("Receiving forever...")

        f = None if args.filename is None else open(args.filename, "w")
        kwargs = dict() if f is None else {"file": f}

        dev = receiver.rcv_device if hasattr(receiver,
                                             "rcv_device") else receiver

        while total_time < abs(args.receive_time):
            try:
                dev.read_messages()
                time.sleep(0.1)
                if args.receive_time >= 0:
                    # smaller zero means infinity
                    total_time += 0.1

                if not args.raw:
                    num_messages = len(receiver.messages)
                    for msg in receiver.messages[:num_messages]:
                        print(
                            msg.decoded_hex_str
                            if args.hex else msg.decoded_bits_str, **kwargs)
                    del receiver.messages[:num_messages]
            except KeyboardInterrupt:
                break

        print("\nStopping receiving...")
        if args.raw:
            receiver.stop("Receiving finished")
            receiver.data[:receiver.current_index].tofile(f)
        else:
            receiver.stop()

        if f is not None:
            f.close()
            print("Received data written to {}".format(args.filename))
コード例 #2
0
ファイル: urh_cli.py プロジェクト: jopohl/urh
def main():
    def get_val(value, project_params: dict, project_param_key: str, default):
        if value is not None:
            return value
        elif project_param_key in project_params:
            return project_params[project_param_key]
        else:
            return default

    import multiprocessing as mp
    # allow usage of prange (OpenMP) in Processes
    mp.set_start_method("spawn")
    if sys.platform == "win32":
        mp.freeze_support()

    parser = create_parser()
    args = parser.parse_args()
    project_params = parse_project_file(args.project_file)
    for argument in ("device", "frequency", "sample_rate"):
        if getattr(args, argument):
            continue

        if project_params[argument] is not None:
            setattr(args, argument, project_params[argument])
        else:
            print("You must specify a {}.".format(argument))
            sys.exit(1)

    if args.receive and args.transmit:
        print("You cannot use receive and transmit mode at the same time.")
        sys.exit(1)
    if not args.receive and not args.transmit:
        print("You must choose a mode either RX (-rx, --receive) or TX (-tx, --transmit)")
        sys.exit(1)

    args.bandwidth = get_val(args.bandwidth, project_params, "bandwidth", None)
    rx_tx_prefix = "rx_" if args.receive else "tx_"
    args.gain = get_val(args.gain, project_params, rx_tx_prefix + "gain", None)
    args.if_gain = get_val(args.if_gain, project_params, rx_tx_prefix + "if_gain", None)
    args.baseband_gain = get_val(args.baseband_gain, project_params, rx_tx_prefix + "baseband_gain", None)

    if args.modulation_type is None:
        try:
            if project_params["modulation_type"] is None:
                args.modulation_type = MODULATIONS[int(project_params["modulation_index"])]
            else:
                args.modulation_type = project_params["modulation_type"]
        except:
            pass

    args.bit_length = get_val(args.bit_length, project_params, "bit_len", DEFAULT_BIT_LENGTH)
    args.center = get_val(args.center, project_params, "center", DEFAULT_CENTER)
    args.noise = get_val(args.noise, project_params, "noise", DEFAULT_NOISE)
    args.tolerance = get_val(args.tolerance, project_params, "tolerance", DEFAULT_TOLERANCE)

    args.carrier_frequency = get_val(args.carrier_frequency, project_params, "carrier_frequency",
                                     DEFAULT_CARRIER_FREQUENCY)
    args.carrier_amplitude = get_val(args.carrier_amplitude, project_params, "carrier_amplitude",
                                     DEFAULT_CARRIER_AMPLITUDE)
    args.carrier_phase = get_val(args.carrier_phase, project_params, "carrier_phase", DEFAULT_CARRIER_PHASE)
    args.parameter_zero = get_val(args.parameter_zero, project_params, "parameter_zero", None)
    args.parameter_one = get_val(args.parameter_one, project_params, "parameter_one", None)

    if args.verbose is None:
        logger.setLevel(logging.ERROR)
    elif args.verbose == 1:
        logger.setLevel(logging.INFO)
    else:
        logger.setLevel(logging.DEBUG)
    Logger.save_log_level()

    argument_string = "\n".join("{} {}".format(arg, getattr(args, arg)) for arg in vars(args))
    logger.debug("Using these parameters\n" + argument_string)

    if args.transmit:
        device = build_device_from_args(args)
        if args.raw:
            if args.filename is None:
                print("You need to give a file (-file, --filename) where to read samples from.")
                sys.exit(1)
            samples_to_send = np.fromfile(args.filename, dtype=np.complex64)
        else:
            modulator = build_modulator_from_args(args)
            messages_to_send = read_messages_to_send(args)
            samples_to_send = modulate_messages(messages_to_send, modulator)
        device.samples_to_send = samples_to_send
        device.start()

        while not device.sending_finished:
            try:
                time.sleep(0.1)
                device.read_messages()
                if device.current_index > 0:
                    cli_progress_bar(device.current_index, len(device.samples_to_send), title="Sending")
            except KeyboardInterrupt:
                break

        print()
        device.stop("Sending finished")
    elif args.receive:
        if args.raw:
            if args.filename is None:
                print("You need to give a file (-file, --filename) to receive into when using raw RX mode.")
                sys.exit(1)

            receiver = build_device_from_args(args)
            receiver.start()
        else:
            receiver = build_protocol_sniffer_from_args(args)
            receiver.sniff()

        total_time = 0

        if args.receive_time >= 0:
            print("Receiving for {} seconds...".format(args.receive_time))
        else:
            print("Receiving forever...")

        f = None if args.filename is None else open(args.filename, "w")
        kwargs = dict() if f is None else {"file": f}

        dev = receiver.rcv_device if hasattr(receiver, "rcv_device") else receiver

        while total_time < abs(args.receive_time):
            try:
                dev.read_messages()
                time.sleep(0.1)
                if args.receive_time >= 0:
                    # smaller zero means infinity
                    total_time += 0.1

                if not args.raw:
                    num_messages = len(receiver.messages)
                    for msg in receiver.messages[:num_messages]:
                        print(msg.decoded_hex_str if args.hex else msg.decoded_bits_str, **kwargs)
                    del receiver.messages[:num_messages]
            except KeyboardInterrupt:
                break

        print("\nStopping receiving...")
        if args.raw:
            receiver.stop("Receiving finished")
            receiver.data[:receiver.current_index].tofile(f)
        else:
            receiver.stop()

        if f is not None:
            f.close()
            print("Received data written to {}".format(args.filename))