예제 #1
0
int UHD_SAFE_MAIN(int argc, char *argv[]){
    uhd::set_thread_priority_safe();

    //variables to be set by po
    std::string args;

    //setup the program options
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help", "help message")
        ("args", po::value<std::string>(&args)->default_value(""), "single uhd device address args")
    ;
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    //print the help message
    if (vm.count("help")){
        std::cout << boost::format("UHD Test Timed Commands %s") % desc << std::endl;
        return ~0;
    }

    //create a usrp device
    std::cout << std::endl;
    std::cout << boost::format("Creating the usrp device with: %s...") % args << std::endl;
    uhd::usrp::multi_usrp::sptr usrp = uhd::usrp::multi_usrp::make(args);
    std::cout << boost::format("Using Device: %s") % usrp->get_pp_string() << std::endl;

    //check if timed commands are supported
    std::cout << std::endl;
    std::cout << "Testing support for timed commands on this hardware... " << std::flush;
    try{
        usrp->set_command_time(uhd::time_spec_t(0.0));
        usrp->clear_command_time();
    }
    catch (const std::exception &e){
        std::cout << "fail" << std::endl;
        std::cerr << "Got exception: " << e.what() << std::endl;
        std::cerr << "Timed commands are not supported on this hardware." << std::endl;
        return ~0;
    }
    std::cout << "pass" << std::endl;

    //readback time really fast, time diff is small
    std::cout << std::endl;
    std::cout << "Perform fast readback of registers:" << std::endl;
    uhd::time_spec_t total_time;
    for (size_t i = 0; i < 100; i++){
        const uhd::time_spec_t t0 = usrp->get_time_now();
        const uhd::time_spec_t t1 = usrp->get_time_now();
        total_time += (t1-t0);
    }
    std::cout << boost::format(
        "Difference between paired reads: %f us"
    ) % (total_time.get_real_secs()/100*1e6) << std::endl;

    //use a timed command to start a stream at a specific time
    //this is not the right way start streaming at time x,
    //but it should approximate it within control RTT/2
    //setup streaming
    std::cout << std::endl;
    std::cout << "About to start streaming using timed command:" << std::endl;
    
    //create a receive streamer
    uhd::stream_args_t stream_args("fc32"); //complex floats
    uhd::rx_streamer::sptr rx_stream = usrp->get_rx_stream(stream_args);
    
    uhd::stream_cmd_t stream_cmd(uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE);
    stream_cmd.num_samps = 100;
    stream_cmd.stream_now = true;
    const uhd::time_spec_t stream_time = usrp->get_time_now() + uhd::time_spec_t(0.1);
    usrp->set_command_time(stream_time);
    rx_stream->issue_stream_cmd(stream_cmd);
    usrp->clear_command_time();

    //meta-data will be filled in by recv()
    uhd::rx_metadata_t md;

    //allocate buffer to receive with samples
    std::vector<std::complex<float> > buff(stream_cmd.num_samps);

    const size_t num_rx_samps = rx_stream->recv(&buff.front(), buff.size(), md, 1.0);
    if (md.error_code != uhd::rx_metadata_t::ERROR_CODE_NONE){
        throw std::runtime_error(str(boost::format(
            "Unexpected error code 0x%x"
        ) % md.error_code));
    }
    std::cout << boost::format(
        "Received packet: %u samples, %u full secs, %f frac secs"
    ) % num_rx_samps % md.time_spec.get_full_secs() % md.time_spec.get_frac_secs() << std::endl;
    std::cout << boost::format(
        "Stream time was: %u full secs, %f frac secs"
    ) % stream_time.get_full_secs() % stream_time.get_frac_secs() << std::endl;
    std::cout << boost::format(
        "Difference between stream time and first packet: %f us"
    ) % ((md.time_spec-stream_time).get_real_secs()/100*1e6) << std::endl;

    //finished
    std::cout << std::endl << "Done!" << std::endl << std::endl;

    return EXIT_SUCCESS;
}
int UHD_SAFE_MAIN(int argc, char *argv[]){
    uhd::set_thread_priority_safe();

    //variables to be set by po
    std::string args, file, ant, subdev, ref;
    size_t total_num_samps;
    double rate, freq, gain, bw;
    std::string addr, port;

    //setup the program options
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help", "help message")
        ("args", po::value<std::string>(&args)->default_value(""), "multi uhd device address args")
        ("nsamps", po::value<size_t>(&total_num_samps)->default_value(1000), "total number of samples to receive")
        ("rate", po::value<double>(&rate)->default_value(100e6/16), "rate of incoming samples")
        ("freq", po::value<double>(&freq)->default_value(0), "rf center frequency in Hz")
        ("gain", po::value<double>(&gain)->default_value(0), "gain for the RF chain")
        ("ant", po::value<std::string>(&ant), "daughterboard antenna selection")
        ("subdev", po::value<std::string>(&subdev), "daughterboard subdevice specification")
        ("bw", po::value<double>(&bw), "daughterboard IF filter bandwidth in Hz")
        ("port", po::value<std::string>(&port)->default_value("7124"), "server udp port")
        ("addr", po::value<std::string>(&addr)->default_value("192.168.1.10"), "resolvable server address")
        ("ref", po::value<std::string>(&ref)->default_value("internal"), "waveform type (internal, external, mimo)")
    ;
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    //print the help message
    if (vm.count("help")){
        std::cout << boost::format("UHD RX to UDP %s") % desc << std::endl;
        return ~0;
    }

    //create a usrp device
    std::cout << std::endl;
    std::cout << boost::format("Creating the usrp device with: %s...") % args << std::endl;
    uhd::usrp::multi_usrp::sptr usrp = uhd::usrp::multi_usrp::make(args);
    std::cout << boost::format("Using Device: %s") % usrp->get_pp_string() << std::endl;

    //Lock mboard clocks
    usrp->set_clock_source(ref);

    //set the rx sample rate
    std::cout << boost::format("Setting RX Rate: %f Msps...") % (rate/1e6) << std::endl;
    usrp->set_rx_rate(rate);
    std::cout << boost::format("Actual RX Rate: %f Msps...") % (usrp->get_rx_rate()/1e6) << std::endl << std::endl;

    //set the rx center frequency
    std::cout << boost::format("Setting RX Freq: %f Mhz...") % (freq/1e6) << std::endl;
    usrp->set_rx_freq(freq);
    std::cout << boost::format("Actual RX Freq: %f Mhz...") % (usrp->get_rx_freq()/1e6) << std::endl << std::endl;

    //set the rx rf gain
    std::cout << boost::format("Setting RX Gain: %f dB...") % gain << std::endl;
    usrp->set_rx_gain(gain);
    std::cout << boost::format("Actual RX Gain: %f dB...") % usrp->get_rx_gain() << std::endl << std::endl;

    //set the IF filter bandwidth
    if (vm.count("bw")){
        std::cout << boost::format("Setting RX Bandwidth: %f MHz...") % bw << std::endl;
        usrp->set_rx_bandwidth(bw);
        std::cout << boost::format("Actual RX Bandwidth: %f MHz...") % usrp->get_rx_bandwidth() << std::endl << std::endl;
    }

    //set the antenna
    if (vm.count("ant")) usrp->set_rx_antenna(ant);

    boost::this_thread::sleep(boost::posix_time::seconds(1)); //allow for some setup time

    //Check Ref and LO Lock detect
    std::vector<std::string> sensor_names;
    sensor_names = usrp->get_rx_sensor_names(0);
    if (std::find(sensor_names.begin(), sensor_names.end(), "lo_locked") != sensor_names.end()) {
        uhd::sensor_value_t lo_locked = usrp->get_rx_sensor("lo_locked",0);
        std::cout << boost::format("Checking RX: %s ...") % lo_locked.to_pp_string() << std::endl;
        UHD_ASSERT_THROW(lo_locked.to_bool());
    }
    sensor_names = usrp->get_mboard_sensor_names(0);
    if ((ref == "mimo") and (std::find(sensor_names.begin(), sensor_names.end(), "mimo_locked") != sensor_names.end())) {
        uhd::sensor_value_t mimo_locked = usrp->get_mboard_sensor("mimo_locked",0);
        std::cout << boost::format("Checking RX: %s ...") % mimo_locked.to_pp_string() << std::endl;
        UHD_ASSERT_THROW(mimo_locked.to_bool());
    }
    if ((ref == "external") and (std::find(sensor_names.begin(), sensor_names.end(), "ref_locked") != sensor_names.end())) {
        uhd::sensor_value_t ref_locked = usrp->get_mboard_sensor("ref_locked",0);
        std::cout << boost::format("Checking RX: %s ...") % ref_locked.to_pp_string() << std::endl;
        UHD_ASSERT_THROW(ref_locked.to_bool());
    }

    //create a receive streamer
    uhd::stream_args_t stream_args("fc32"); //complex floats
    uhd::rx_streamer::sptr rx_stream = usrp->get_rx_stream(stream_args);

    //setup streaming
    uhd::stream_cmd_t stream_cmd(uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE);
    stream_cmd.num_samps = total_num_samps;
    stream_cmd.stream_now = true;
    usrp->issue_stream_cmd(stream_cmd);

    //loop until total number of samples reached
    size_t num_acc_samps = 0; //number of accumulated samples
    uhd::rx_metadata_t md;
    std::vector<std::complex<float> > buff(rx_stream->get_max_num_samps());
    uhd::transport::udp_simple::sptr udp_xport = uhd::transport::udp_simple::make_connected(addr, port);

    while(num_acc_samps < total_num_samps){
        size_t num_rx_samps = rx_stream->recv(
            &buff.front(), buff.size(), md
        );

        //handle the error codes
        switch(md.error_code){
        case uhd::rx_metadata_t::ERROR_CODE_NONE:
            break;

        case uhd::rx_metadata_t::ERROR_CODE_TIMEOUT:
            if (num_acc_samps == 0) continue;
            std::cout << boost::format(
                "Got timeout before all samples received, possible packet loss, exiting loop..."
            ) << std::endl;
            goto done_loop;

        default:
            std::cout << boost::format(
                "Got error code 0x%x, exiting loop..."
            ) % md.error_code << std::endl;
            goto done_loop;
        }

        //send complex single precision floating point samples over udp
        udp_xport->send(boost::asio::buffer(buff, num_rx_samps*sizeof(buff.front())));

        num_acc_samps += num_rx_samps;
    } done_loop:

    //finished
    std::cout << std::endl << "Done!" << std::endl << std::endl;

    return 0;
}
예제 #3
0
/***********************************************************************
 * recv_to_file function
 **********************************************************************/
template<typename samp_type> void recv_to_file(
    uhd::usrp::multi_usrp::sptr usrp,
    const std::string &cpu_format,
    const std::string &wire_format,
    const std::string &file,
    size_t samps_per_buff,
    int num_requested_samples,
    float settling_time,
    std::vector<size_t> rx_channel_nums
) {
    int num_total_samps = 0;
    //create a receive streamer
    uhd::stream_args_t stream_args(cpu_format,wire_format);
    stream_args.channels = rx_channel_nums;
    uhd::rx_streamer::sptr rx_stream = usrp->get_rx_stream(stream_args);

    uhd::rx_metadata_t md;
    std::vector<samp_type> buff(samps_per_buff);
    std::ofstream outfile(file.c_str(), std::ofstream::binary);
    bool overflow_message = true;
    float timeout = settling_time + 0.1; //expected settling time + padding for first recv

    //setup streaming
    uhd::stream_cmd_t stream_cmd((num_requested_samples == 0)?
                                 uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS:
                                 uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE
                                );
    stream_cmd.num_samps = num_requested_samples;
    stream_cmd.stream_now = false;
    stream_cmd.time_spec = uhd::time_spec_t(settling_time);
    rx_stream->issue_stream_cmd(stream_cmd);

    while(not stop_signal_called and (num_requested_samples != num_total_samps or num_requested_samples == 0)) {
        size_t num_rx_samps = rx_stream->recv(&buff.front(), buff.size(), md, timeout);
        timeout = 0.1; //small timeout for subsequent recv

        if (md.error_code == uhd::rx_metadata_t::ERROR_CODE_TIMEOUT) {
            std::cout << boost::format("Timeout while streaming") << std::endl;
            break;
        }
        if (md.error_code == uhd::rx_metadata_t::ERROR_CODE_OVERFLOW) {
            if (overflow_message) {
                overflow_message = false;
                std::cerr << boost::format(
                              "Got an overflow indication. Please consider the following:\n"
                              "  Your write medium must sustain a rate of %fMB/s.\n"
                              "  Dropped samples will not be written to the file.\n"
                              "  Please modify this example for your purposes.\n"
                              "  This message will not appear again.\n"
                          ) % (usrp->get_rx_rate()*sizeof(samp_type)/1e6);
            }
            continue;
        }
        if (md.error_code != uhd::rx_metadata_t::ERROR_CODE_NONE) {
            throw std::runtime_error(str(boost::format(
                                             "Receiver error %s"
                                         ) % md.strerror()));
        }

        num_total_samps += num_rx_samps;

        outfile.write((const char*)&buff.front(), num_rx_samps*sizeof(samp_type));
    }

    outfile.close();
}
예제 #4
0
int UHD_SAFE_MAIN(int argc, char *argv[]){
    uhd::set_thread_priority_safe();

    //variables to be set by po
    std::string args;
    std::string wire;
    double seconds_in_future;
    size_t total_num_samps;
    double rate;
    std::string channel_list;

    //setup the program options
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help", "help message")
        ("args", po::value<std::string>(&args)->default_value(""), "single uhd device address args")
        ("wire", po::value<std::string>(&wire)->default_value(""), "the over the wire type, sc16, sc8, etc")
        ("secs", po::value<double>(&seconds_in_future)->default_value(1.5), "number of seconds in the future to receive")
        ("nsamps", po::value<size_t>(&total_num_samps)->default_value(10000), "total number of samples to receive")
        ("rate", po::value<double>(&rate)->default_value(100e6/16), "rate of incoming samples")
        ("dilv", "specify to disable inner-loop verbose")
        ("channels", po::value<std::string>(&channel_list)->default_value("0"), "which channel(s) to use (specify \"0\", \"1\", \"0,1\", etc)")
    
    ;
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    //print the help message
    if (vm.count("help")){
        std::cout << boost::format("UHD RX Timed Samples %s") % desc << std::endl;
        return ~0;
    }

    bool verbose = vm.count("dilv") == 0;

    //create a usrp device
    std::cout << std::endl;
    std::cout << boost::format("Creating the usrp device with: %s...") % args << std::endl;
    uhd::usrp::multi_usrp::sptr usrp = uhd::usrp::multi_usrp::make(args);
    std::cout << boost::format("Using Device: %s") % usrp->get_pp_string() << std::endl;

   //detect which channels to use
    std::vector<std::string> channel_strings;
    std::vector<size_t> channel_nums;
    boost::split(channel_strings, channel_list, boost::is_any_of("\"',"));
    for(size_t ch = 0; ch < channel_strings.size(); ch++){
        size_t chan = boost::lexical_cast<int>(channel_strings[ch]);
        if(chan >= usrp->get_tx_num_channels() or chan >= usrp->get_rx_num_channels()){
            throw std::runtime_error("Invalid channel(s) specified.");
        }
        else channel_nums.push_back(boost::lexical_cast<int>(channel_strings[ch]));
    }

    //set the rx sample rate
    std::cout << boost::format("Setting RX Rate: %f Msps...") % (rate/1e6) << std::endl;
    usrp->set_rx_rate(rate);
    std::cout << boost::format("Actual RX Rate: %f Msps...") % (usrp->get_rx_rate()/1e6) << std::endl << std::endl;

    std::cout << boost::format("Setting device timestamp to 0...") << std::endl;
    usrp->set_time_now(uhd::time_spec_t(0.0));

    //create a receive streamer
    uhd::stream_args_t stream_args("fc32", wire); //complex floats
    stream_args.channels = channel_nums;
    uhd::rx_streamer::sptr rx_stream = usrp->get_rx_stream(stream_args);

    //setup streaming
    std::cout << std::endl;
    std::cout << boost::format(
        "Begin streaming %u samples, %f seconds in the future..."
    ) % total_num_samps % seconds_in_future << std::endl;
    uhd::stream_cmd_t stream_cmd(uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE);
    stream_cmd.num_samps = total_num_samps;
    stream_cmd.stream_now = false;
    stream_cmd.time_spec = uhd::time_spec_t(seconds_in_future);
    rx_stream->issue_stream_cmd(stream_cmd);

    //meta-data will be filled in by recv()
    uhd::rx_metadata_t md;

    //allocate buffer to receive with samples
    std::vector<std::complex<float> > buff(rx_stream->get_max_num_samps());
    std::vector<void *> buffs;
    for (size_t ch = 0; ch < rx_stream->get_num_channels(); ch++)
        buffs.push_back(&buff.front()); //same buffer for each channel

    //the first call to recv() will block this many seconds before receiving
    double timeout = seconds_in_future + 0.1; //timeout (delay before receive + padding)

    size_t num_acc_samps = 0; //number of accumulated samples
    while(num_acc_samps < total_num_samps){
        //receive a single packet
        size_t num_rx_samps = rx_stream->recv(
            buffs, buff.size(), md, timeout, true
        );

        //use a small timeout for subsequent packets
        timeout = 0.1;

        //handle the error code
        if (md.error_code == uhd::rx_metadata_t::ERROR_CODE_TIMEOUT) break;
        if (md.error_code != uhd::rx_metadata_t::ERROR_CODE_NONE){
            throw std::runtime_error(str(boost::format(
                "Receiver error %s"
            ) % md.strerror()));
        }

        if(verbose) std::cout << boost::format(
            "Received packet: %u samples, %u full secs, %f frac secs"
        ) % num_rx_samps % md.time_spec.get_full_secs() % md.time_spec.get_frac_secs() << std::endl;

        num_acc_samps += num_rx_samps;
    }

    if (num_acc_samps < total_num_samps) std::cerr << "Receive timeout before all samples received..." << std::endl;

    //finished
    std::cout << std::endl << "Done!" << std::endl << std::endl;

    return EXIT_SUCCESS;
}
예제 #5
0
template<typename samp_type> void recv_to_file(
    uhd::usrp::multi_usrp::sptr usrp,
    const std::string &cpu_format,
    const std::string &wire_format,
    const std::string &file,
    size_t samps_per_buff,
    unsigned long long num_requested_samples,
    double time_requested = 0.0,
    bool bw_summary = false,
    bool stats = false,
    bool null = false,
    bool enable_size_map = false,
    bool continue_on_bad_packet = false
){
    unsigned long long num_total_samps = 0;
    //create a receive streamer
    uhd::stream_args_t stream_args(cpu_format,wire_format);
    uhd::rx_streamer::sptr rx_stream = usrp->get_rx_stream(stream_args);

    uhd::rx_metadata_t md;
    std::vector<samp_type> buff(samps_per_buff);
    std::ofstream outfile;
    if (not null)
        outfile.open(file.c_str(), std::ofstream::binary);
    bool overflow_message = true;

    //setup streaming
    uhd::stream_cmd_t stream_cmd((num_requested_samples == 0)?
        uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS:
        uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE
    );
    stream_cmd.num_samps = num_requested_samples;
    stream_cmd.stream_now = true;
    stream_cmd.time_spec = uhd::time_spec_t();
    rx_stream->issue_stream_cmd(stream_cmd);

    boost::system_time start = boost::get_system_time();
    unsigned long long ticks_requested = (long)(time_requested * (double)boost::posix_time::time_duration::ticks_per_second());
    boost::posix_time::time_duration ticks_diff;
    boost::system_time last_update = start;
    unsigned long long last_update_samps = 0;

    typedef std::map<size_t,size_t> SizeMap;
    SizeMap mapSizes;

    while(not stop_signal_called and (num_requested_samples != num_total_samps or num_requested_samples == 0)) {
        boost::system_time now = boost::get_system_time();

        size_t num_rx_samps = rx_stream->recv(&buff.front(), buff.size(), md, 3.0, enable_size_map);

        if (md.error_code == uhd::rx_metadata_t::ERROR_CODE_TIMEOUT) {
            std::cout << boost::format("Timeout while streaming") << std::endl;
            break;
        }
        if (md.error_code == uhd::rx_metadata_t::ERROR_CODE_OVERFLOW){
            if (overflow_message) {
                overflow_message = false;
                std::cerr << boost::format(
                    "Got an overflow indication. Please consider the following:\n"
                    "  Your write medium must sustain a rate of %fMB/s.\n"
                    "  Dropped samples will not be written to the file.\n"
                    "  Please modify this example for your purposes.\n"
                    "  This message will not appear again.\n"
                ) % (usrp->get_rx_rate()*sizeof(samp_type)/1e6);
            }
            continue;
        }
        if (md.error_code != uhd::rx_metadata_t::ERROR_CODE_NONE){
            std::string error = str(boost::format("Receiver error: %s") % md.strerror());
            if (continue_on_bad_packet){
                std::cerr << error << std::endl;
                continue;
            }
            else
                throw std::runtime_error(error);
        }

        if (enable_size_map) {
            SizeMap::iterator it = mapSizes.find(num_rx_samps);
            if (it == mapSizes.end())
                mapSizes[num_rx_samps] = 0;
            mapSizes[num_rx_samps] += 1;
        }

        num_total_samps += num_rx_samps;

        if (outfile.is_open())
            outfile.write((const char*)&buff.front(), num_rx_samps*sizeof(samp_type));

        if (bw_summary) {
            last_update_samps += num_rx_samps;
            boost::posix_time::time_duration update_diff = now - last_update;
            if (update_diff.ticks() > boost::posix_time::time_duration::ticks_per_second()) {
                double t = (double)update_diff.ticks() / (double)boost::posix_time::time_duration::ticks_per_second();
                double r = (double)last_update_samps / t;
                std::cout << boost::format("\t%f Msps") % (r/1e6) << std::endl;
                last_update_samps = 0;
                last_update = now;
            }
        }

        ticks_diff = now - start;
        if (ticks_requested > 0){
            if ((unsigned long long)ticks_diff.ticks() > ticks_requested)
                break;
        }
    }

    stream_cmd.stream_mode = uhd::stream_cmd_t::STREAM_MODE_STOP_CONTINUOUS;
    rx_stream->issue_stream_cmd(stream_cmd);

    if (outfile.is_open())
        outfile.close();

    if (stats) {
        std::cout << std::endl;

        double t = (double)ticks_diff.ticks() / (double)boost::posix_time::time_duration::ticks_per_second();
        std::cout << boost::format("Received %d samples in %f seconds") % num_total_samps % t << std::endl;
        double r = (double)num_total_samps / t;
        std::cout << boost::format("%f Msps") % (r/1e6) << std::endl;

        if (enable_size_map) {
            std::cout << std::endl;
            std::cout << "Packet size map (bytes: count)" << std::endl;
            for (SizeMap::iterator it = mapSizes.begin(); it != mapSizes.end(); it++)
                std::cout << it->first << ":\t" << it->second << std::endl;
        }
    }
}
예제 #6
0
int UHD_SAFE_MAIN(int argc, char *argv[]){
    
    uhd::set_thread_priority_safe();    

    std::string args, tx_file, rx_file, type, ref, wire_format, cpu_format;                
    size_t samples_per_buff;
    double rate, freq, tx_gain, rx_gain, rx_bw, delay, lo_off;

    rx_bw = RX_BW;
    rx_gain = RX_GAIN;
    wire_format = WIRE_FORMAT;
    cpu_format = CPU_FORMAT;
    rate = SAMP_RATE;
    args = ARGS;
    ref = REF_CLOCK;
    freq = CENT_FREQ;
    tx_gain = TX_GAIN;
    samples_per_buff = SAMPLES_PER_BUFFER;
    tx_file = TX_FILENAME;
    rx_file = RX_FILENAME;

    //------------------INIT TX------------------
                                        //Set the scheduling priority on the current thread. Same as set_thread_priority but does not throw on failure.
    std::cout << boost::format("Creating the usrp device with: %s...") % args << std::endl;
    uhd::usrp::multi_usrp::sptr usrp = uhd::usrp::multi_usrp::make(args);       //Make the usrp by calling the constructor with param the args

    usrp->set_clock_source(ref);                                          //Set the clock source for the usrp device. This sets the source for a 10 MHz reference clock. Typical options for source: internal, external, MIMO.
    std::cout << boost::format("Setting TX Rate: %f Msps...") % (rate/1e6) << std::endl;                           
    usrp->set_tx_rate(rate);                                                                                        //Set the sample rate
    std::cout << boost::format("Actual TX Rate: %f Msps...") % (usrp->get_tx_rate()/1e6) << std::endl << std::endl;

    std::cout << boost::format("Setting TX Freq: %f MHz...") % (freq/1e6) << std::endl;                              //Set up tuning frequency
    uhd::tune_request_t tune_request;                                                                               
    tune_request = uhd::tune_request_t(freq);                                                                        //Generate the tune request
    usrp->set_tx_freq(tune_request);                                                                                //Tune to CENT_FREQ
    std::cout << boost::format("Actual TX Freq: %f MHz...") % (usrp->get_tx_freq()/1e6) << std::endl << std::endl;  //PRINT Actual CENT_FREQ

    std::cout << boost::format("Setting TX Gain: %f dB...") % tx_gain << std::endl;                                    
    usrp->set_tx_gain(tx_gain);                                                                                     //Set the tx_gain
    std::cout << boost::format("Actual TX Gain: %f dB...") % usrp->get_tx_gain() << std::endl << std::endl;
    
    //------------------CHECK STUFF------------------
    //Check Ref and LO Lock detect
    std::vector<std::string> sensor_names;
    sensor_names = usrp->get_tx_sensor_names(0);
    if (std::find(sensor_names.begin(), sensor_names.end(), "lo_locked") != sensor_names.end()) {
        uhd::sensor_value_t lo_locked = usrp->get_tx_sensor("lo_locked",0);
        std::cout << boost::format("Checking TX: %s ...") % lo_locked.to_pp_string() << std::endl;
        UHD_ASSERT_THROW(lo_locked.to_bool());
    }        


    //------------------INIT TX STREAM------------------
    //create a transmit streamer    
    uhd::stream_args_t stream_args(cpu_format, wire_format);              //Call the constructor of the class stream_args_t and generate the stream_args object with inputs the cpu_format and wire_format (this is the format per sample)
    uhd::tx_streamer::sptr tx_stream = usrp->get_tx_stream(stream_args);    //Generate a tx_streamer object named tx_stream using the usrp->get_tx_stream(stream_args). Remember, usrp is already initialized

    //Setup tx_metadata
    uhd::tx_metadata_t tx_md;                                                  //TX metadata structure for describing received IF data. Includes time specification, and start and stop burst flags. The send routines will convert the metadata to IF data headers.        
    tx_md.start_of_burst = false;                                              //Set start of burst to true for the first packet in the chain. ?
    tx_md.end_of_burst = false;        

    //------------------LOAD DATA AND TX------------------
    std::vector<std::complex<float> > tx_buff(samples_per_buff);
    std::ifstream infile(tx_file.c_str(), std::ifstream::binary);

    if(!infile.good()){
        std::cout << "IN File error\n";
        return 0;
    }

    //loop until the entire file has been read
    int i = 0;

    for (int i = 0; i < samples_per_buff; ++i){
        infile.read((char*)&tx_buff.at(i), tx_buff.size()*sizeof(std::complex<float>));    
        // std::cout << tx_buff.at(i) << ' ';
    }
    
    tx_stream->send(&tx_buff.front(), samples_per_buff, tx_md);

    infile.close();                                                        //Close the file pointer

    //------------------INIT RX------------------

    //IS THIS NECESSARY?
    //always select the subdevice first, the channel mapping affects the other settings
    //usrp->set_rx_subdev_spec(subdev);

    std::cout << boost::format("Setting RX Rate: %f Msps...") % (rate/1e6) << std::endl;
    usrp->set_rx_rate(rate);
    std::cout << boost::format("Actual RX Rate: %f Msps...") % (usrp->get_rx_rate()/1e6) << std::endl << std::endl;

    //set the center frequency
    
    std::cout << boost::format("Setting RX Freq: %f MHz...") % (freq/1e6) << std::endl;
    usrp->set_rx_freq(tune_request);
    std::cout << boost::format("Actual RX Freq: %f MHz...") % (usrp->get_rx_freq()/1e6) << std::endl << std::endl;
    
    
    std::cout << boost::format("Setting RX Gain: %f dB...") % rx_gain << std::endl;
    usrp->set_rx_gain(rx_gain);
    std::cout << boost::format("Actual RX Gain: %f dB...") % usrp->get_rx_gain() << std::endl << std::endl;    

    boost::this_thread::sleep(boost::posix_time::seconds(1)); //allow 1sec  setup time
    //------------------CHECK STUFF------------------
    
    //Always check for locked sensor
    check_locked_sensor(usrp->get_rx_sensor_names(0), "lo_locked", boost::bind(&uhd::usrp::multi_usrp::get_rx_sensor, usrp, _1, 0), 1);

    //------------------INIT RX STREAM---------------
    
    //create a receive streamer with the same args as TX
    uhd::rx_streamer::sptr rx_stream = usrp->get_rx_stream(stream_args);

    

    uhd::rx_metadata_t rx_md;
    std::vector<std::complex<float> > rx_buff(samples_per_buff);
    
    std::ofstream outfile;    
    outfile.open(rx_file.c_str(), std::ofstream::binary);
    if(!outfile.good()){
        std::cout << "OUT File error\n";
        return 0;
    }

    //If RX_CONT == 1 enable continuoys sampling else just sent some packets and done
    uhd::stream_cmd_t stream_cmd((RX_CONT == 1)?
        uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS:
        uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE
    );


    stream_cmd.num_samps = samples_per_buff;                        //You might have a problem here...
    stream_cmd.stream_now = true;                                   //Start streaming ASAP
    stream_cmd.time_spec = uhd::time_spec_t();                      //Setup the time to the USRP time (Why??)
    
    rx_stream->issue_stream_cmd(stream_cmd);                        //Issue a stream command to the usrp device. This tells the usrp to send samples into the host. See the documentation for stream_cmd_t for more info.

    size_t num_rx_samps = rx_stream->recv(&rx_buff.front(), rx_buff.size(), rx_md, 10.0, false);  // Receive buffers containing samples described by the metadata.    
    std::cout << "Samples received in a single shot: " << num_rx_samps << std::endl;
    if (outfile.is_open()){
        outfile.write((const char*)&rx_buff.front(), num_rx_samps*sizeof(std::complex<float>)-1);          
    }
    
    return EXIT_SUCCESS;
}
예제 #7
0
파일: rx.cpp 프로젝트: tony2909/green
int UHD_SAFE_MAIN(int argc, char *argv[]){

  // Set priority of the main thread
  int which = PRIO_PROCESS;
  id_t pid;
  int priority = -20;
  int ret;

  pid = getpid();
  ret = setpriority(which, pid, priority);
  if(ret!=0){  std::cout << "Main priority went wrong: " << ret << std::endl ;}

    
  //Seting priority in the processor to run faster -> run with sudo
  if (!(uhd::set_thread_priority_safe(1,true))) {
    std::cout << "Problem setting thread priority" << std::endl;
    return 1;
  };
  //variables to be set by po -> Set when initializing the rx program
 
  size_t total_num_samps;
  double rx_rate, freq, LOoffset;
  bool use_external_10MHz;
  double scaling_8bits;
  std::string filename;
  float gain;
  bool realTime;
  uhd::device_addr_t dev_addr;
  uhd::usrp::multi_usrp::sptr dev;
  uhd::tune_result_t tr;
  uhd::stream_args_t stream_args;
  uhd::rx_streamer::sptr rx_stream;


  //setup the program options-> Passing it from terminal with boost library 
  po::options_description desc("Allowed options");
  desc.add_options()
    ("help", "help message")
    ("nsamps", po::value<size_t>(&total_num_samps)->default_value(27840), "total number of samples to receive")
    ("rxrate", po::value<double>(&rx_rate)->default_value(100e6/4), "rate of incoming samples")
    ("freq", po::value<double>(&freq)->default_value(5.5e9), "rf center frequency in Hz")
    ("LOoffset", po::value<double>(&LOoffset)->default_value(10e6), "Offset between main LO and center frequency")
    ("10MHz",po::value<bool>(&use_external_10MHz)->default_value(false), "external 10MHz on 'REF CLOCK' connector (true=1=yes)")
    ("filename",po::value<std::string>(&filename)->default_value("data_from_usrp.dat"), "output filename") 
    ("gain",po::value<float>(&gain)->default_value(15), "set the receiver gain") 
    ("8bits_scaling",po::value<double>(&scaling_8bits)->default_value(0.0), 
     "input scaling (invers) when 8bits is used, set to zero to get 16bits")
    ("realTime",po::value<bool>(&realTime)->default_value(true), "receives in loop and compares with synch sequence")
    ;
   
  //Variables stored in boost objects
  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc), vm);
  po::notify(vm);

  //print the help message
  if (vm.count("help")){
    std::cout << boost::format("rx %s") % desc << std::endl;
    return ~0;
  }

  ///////////Set device variables to read data////////////////
    
  dev_addr["addr0"]="192.168.10.2";
  dev = uhd::usrp::multi_usrp::make(dev_addr);//Create the device

  //receiving format
  stream_args.cpu_format="sc16";
  if (scaling_8bits==0.0) {
    stream_args.otw_format="sc16";     
  } else {
    stream_args.otw_format="sc8";
    std::stringstream temp_ss;
    temp_ss << scaling_8bits;
    stream_args.args["peak"]=temp_ss.str();
  };

  rx_stream=dev->get_rx_stream(stream_args); //set/get the streamer values to the device

  uhd::clock_config_t my_clock_config; 

  if (use_external_10MHz) { 
    my_clock_config.ref_source=uhd::clock_config_t::REF_SMA; 
  };  

  /////////////////Create an USRP device////////////////////////
  std::cout << std::endl;
 
  dev->set_rx_rate(rx_rate);

  bool is_xcvr2450=false;
  uhd::dict<std::string, std::string> rx_info;    
  rx_info=dev->get_usrp_rx_info(0);

  if (rx_info.has_key("rx_subdev_name")) {
    std::string str=rx_info.get("rx_subdev_name");
    uint temp=str.find("XCVR2450");
    if (temp<str.length()) {
      is_xcvr2450=true;
    };
  };

  if (is_xcvr2450) {
    dev->set_tx_antenna("J2");
    dev->set_rx_antenna("J1");      

    if (LOoffset>=9e6) {
      dev->set_rx_bandwidth(3.96e+07);
    };      
  };

  std::cout << "rx_rate=" << rx_rate << std::endl;
  std::cout << "freq=" << freq << std::endl;
  std::cout << "gain=" << gain << std::endl;
  std::cout << "LOoffset="<<LOoffset <<std::endl;

  uhd::tune_request_t trq(freq,LOoffset); 

  tr=dev->set_rx_freq(trq);
  dev->set_rx_gain(gain);

  std::cout << "tr=" << tr.actual_rf_freq << std::endl;


  if (use_external_10MHz) {
    dev->set_clock_config(my_clock_config); // PZ
    usleep(1e6); // Wait for the 10MHz to lock
  }; 

  size_t buffer_size=1000; // Select buffer USRP and detection size. <25.000

  int nStorage=2*total_num_samps; // Size of the buffer for the processing part

  dev->set_time_now(uhd::time_spec_t(0.0));

  std::cout << boost::format("Setting device timestamp to 0...") << std::endl;

   

  // Initialisation  

    
  uhd::stream_cmd_t stream_cmd(uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE);

  //USRP parameters
  stream_cmd.num_samps = buffer_size;
  stream_cmd.stream_now = true;
  stream_cmd.stream_mode=uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS;
  dev->issue_stream_cmd(stream_cmd);


  //////////////////////////////////Read data to buff_short and do processing////////////

  //Launch threads
  sem_init(&usrpReady, 0,0); 
  sem_init(&detectionReady, 0,0);
  std::thread usrpT(usrpGetData, rx_stream, dev, buffer_size);
  std::thread detectionT(detection, buffer_size, nStorage);
  std::thread processT(processing, nStorage);

  // Set highest priiority for usrpT
    sched_param sch;
    int policy; 
    pthread_getschedparam(usrpT.native_handle(), &policy, &sch);
    sch.sched_priority = 99;
    if(pthread_setschedparam(usrpT.native_handle(), SCHED_FIFO, &sch)) {
        std::cout << "Failed to setschedparam: " << std::strerror(errno) << '\n';
    }

    std::cout << "Priority set"<< std::endl;

  usrpT.join();
  detectionT.join();
  processT.join();

  //finished
  std::cout << std::endl << "Done receiving!" << std::endl << std::endl; 

  return 0;
}
예제 #8
0
파일: rx.cpp 프로젝트: tony2909/green
int UHD_SAFE_MAIN(int argc, char *argv[]){
    
     //Seting priority in the processor to run faster -> run with sudo
    if (!(uhd::set_thread_priority_safe(1,true))) {
      std::cout << "Problem setting thread priority" << std::endl;
      return 1;
    };


    //variables to be set by po -> Set when initializing the rx program
    //double seconds_in_future=0.01;
    size_t total_num_samps;
    double rx_rate, freq, LOoffset;
    bool use_external_10MHz;
    double scaling_8bits;
    std::string filename;
    float gain;
    bool realTime;
    uhd::device_addr_t dev_addr;
    uhd::usrp::multi_usrp::sptr dev;
    uhd::tune_result_t tr;
    uhd::stream_args_t stream_args;
    uhd::rx_streamer::sptr rx_stream;


    //setup the program options-> Passing it from terminal with boost library 
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help", "help message")
        ("nsamps", po::value<size_t>(&total_num_samps)->default_value(1000), "total number of samples to receive")
        ("rxrate", po::value<double>(&rx_rate)->default_value(100e6/4), "rate of incoming samples")
        ("freq", po::value<double>(&freq)->default_value(0), "rf center frequency in Hz")
        ("LOoffset", po::value<double>(&LOoffset)->default_value(0), "Offset between main LO and center frequency")
        ("10MHz",po::value<bool>(&use_external_10MHz)->default_value(false), "external 10MHz on 'REF CLOCK' connector (true=1=yes)")
      //  ("PPS",po::value<bool>(&trigger_with_pps)->default_value(false), "trigger reception with 'PPS IN' connector (true=1=yes)")
        ("filename",po::value<std::string>(&filename)->default_value("data_from_usrp.dat"), "output filename") 
        ("gain",po::value<float>(&gain)->default_value(0), "set the receiver gain") 
        ("8bits_scaling",po::value<double>(&scaling_8bits)->default_value(0.0), 
    "input scaling (invers) when 8bits is used, set to zero to get 16bits")
      
      /////////////////////////////
      ("realTime",po::value<bool>(&realTime)->default_value(false), "receives in loop and compares with synch sequence")
    ;
   
    //Variables stored in boost objects
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

     //print the help message
    if (vm.count("help")){
        std::cout << boost::format("rx %s") % desc << std::endl;
        return ~0;
    }

    ///////////Set device variables to read data////////////////
    
    dev_addr["addr0"]="192.168.10.2";
    dev = uhd::usrp::multi_usrp::make(dev_addr);//Create the device

    //receiving format
    stream_args.cpu_format="sc16";
    if (scaling_8bits==0.0) {
      stream_args.otw_format="sc16";     
    } else {
      stream_args.otw_format="sc8";
      std::stringstream temp_ss;
      temp_ss << scaling_8bits;
      stream_args.args["peak"]=temp_ss.str();
    };

    rx_stream=dev->get_rx_stream(stream_args); //set/get the streamer values to the device

    uhd::clock_config_t my_clock_config; 

    /*
    if (trigger_with_pps) {
      my_clock_config.pps_source=uhd::clock_config_t::PPS_SMA; 
    };
    */

    if (use_external_10MHz) { 
      my_clock_config.ref_source=uhd::clock_config_t::REF_SMA; 
    }; 

    

   /////////////////Create an USRP device////////////////////////
    std::cout << std::endl;
    //uhd::device::sptr udev = dev->get_device();
    dev->set_rx_rate(rx_rate);

    bool is_xcvr2450=false;
    uhd::dict<std::string, std::string> rx_info;    
    rx_info=dev->get_usrp_rx_info(0);

    if (rx_info.has_key("rx_subdev_name")) {
      std::string str=rx_info.get("rx_subdev_name");
      uint temp=str.find("XCVR2450");
      if (temp<str.length()) {
	is_xcvr2450=true;
      };
    };

    if (is_xcvr2450) {
      dev->set_tx_antenna("J2");
      dev->set_rx_antenna("J1");      
      //uhd::meta_range_t range=dev->get_tx_bandwidth_range();

      if (LOoffset>=9e6) {
	dev->set_rx_bandwidth(3.96e+07);
      };      
    };



    std::cout << "rx_rate=" << rx_rate << std::endl;
    std::cout << "freq=" << freq << std::endl;
    std::cout << "gain=" << gain << std::endl;
    uhd::tune_request_t trq(freq,LOoffset); 


    //dev->set_rx_bandwidth(36e6);

    tr=dev->set_rx_freq(trq);
    dev->set_rx_gain(gain);

    std::cout << "tr=" << tr.actual_rf_freq << std::endl;

    /*
        double target_rf_freq;
        double actual_rf_freq;
        double target_dsp_freq;
        double actual_dsp_freq;
    */

    // 
    //dev->set_tx_antenna("J2");
    //dev->set_rx_antenna("J1");
    

    if (use_external_10MHz) {
      dev->set_clock_config(my_clock_config); // PZ
      usleep(1e6); // Wait for the 10MHz to lock
    }; 

    size_t buffer_size=1000; // Select buffer size
    short *buff_short, *storage_short; //Always read short buffers
   
    storage_short=new short[2*total_num_samps]; // Create storage for the entire received signal to be saved on disk (2* for handling complex).
    
    buff_short=new short[2*buffer_size]; // Create storage for a single buffer


    /*if (trigger_with_pps) {
      dev->set_time_next_pps(uhd::time_spec_t(0.0));
      usleep(1e6); 
      } */
    //else {
      dev->set_time_now(uhd::time_spec_t(0.0));
      //};
    std::cout << boost::format("Setting device timestamp to 0...") << std::endl;

    //setup streaming
    //std::cout << std::endl;
    //std::cout << boost::format("Begin streaming %u samples, %d seconds in the future...")
    //    % total_num_samps % seconds_in_future << std::endl;
    

    //////////////////////////////////Read data to buff_short and do processing////////////

    uhd::stream_cmd_t stream_cmd(uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE);

    if (realTime == false){

      
    //Reads just one time the USRP rx dev and process data

    stream_cmd.num_samps = buffer_size;
    stream_cmd.stream_now = true;

    
    stream_cmd.stream_mode=uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS;

    //stream_cmd.time_spec = uhd::time_spec_t(seconds_in_future);
    

    dev->issue_stream_cmd(stream_cmd);

    size_t num_rx_samps=0;
    size_t num_rx_samps_latest_call;

    uhd::rx_metadata_t md;
    
    //keep reading until everything is read


    while (num_rx_samps<total_num_samps) {
      
     
      num_rx_samps_latest_call=0;   

       
      while (num_rx_samps_latest_call==0) {
	 num_rx_samps_latest_call= 
	   rx_stream->recv(&buff_short[0],buffer_size, md, 3.0);
       };
      
       if (num_rx_samps_latest_call!=buffer_size) {
	 std::cerr << "I expect the buffer size to be always the same!\n";
	 std::cout<<"Read only:"<<num_rx_samps_latest_call<<"\n";
	 std::cout<<"Buffer:"<<buffer_size<<"\n";
         exit(1); 
	 //May be changed->don't want program to crash when data is not available
       };

       /* Process the just received buffer -> Put all toghether in one buffer*/
       int i1=2*num_rx_samps;
       int i2=0;
      
       while ((i1<(int) (2*total_num_samps)) && (i2<2*((int) buffer_size))) 
       {	  
	  storage_short[i1]=buff_short[i2];
	  i1++; i2++;
       };
	 
       num_rx_samps=num_rx_samps+num_rx_samps_latest_call;
       std::cout << "num_rx_samps=" << num_rx_samps  << std::endl;
    };


    // Save output to disc

    //Computes total power:
    double P=powerTotArray( storage_short, 2*total_num_samps);

    std::cout << "\nTotal power=" << P <<"\n";

    //Computes power in the output of 25 filters:
    int num_filt=25;
       
    double shiftindex = 0.04;//how big the shift between the filters is (equidistantial)

    double *power_band;
    power_band=new double[num_filt];

     double *buff_double;
     buff_double=new double[2*buffer_size];
    

    for(int ii=0;ii<(int)(2*buffer_size);ii++){
      	 buff_double[ii]=(double)buff_short[ii];

    };

         
    powerOfFreqBands(buff_double, 2*buffer_size, shiftindex, power_band,num_filt);
	     

     for(int ii=0; ii< num_filt; ii++){
       DispVal(power_band[ii]);
     };

    std::ofstream s1(filename.c_str(), std::ios::binary);   


    s1.write((char *) storage_short,4*total_num_samps); 
    s1.flush(); //PZ
    s1.close(); //PZ
    

    //Process the received data with MATLAB from written file

    //finished reading 
    std::cout << std::endl << "Done reading->Data to MATLAB!" << std::endl << std::endl;

    }else{

      //////////REAL TIME IMPLEMENTATION////////////////////////////////////////////////////////////////////
      //Reads in loop untill it finds someone is trying to transmit -> Power detection and training sequence match///////////////////////////////////////////////////////////////////////////////////////////
    
  
	  
    std::cout << "Stop the transmitter by pressing ctrl-c\n";
	  
     
       size_t num_rx_samps_latest_call;
       size_t num_rx_samps;
          
      
       uhd::rx_metadata_t md;
      
       
       int num_filt=25;
       
       double shiftindex = 0.04;//how big the shift between the filters is (equidistantial)
       

       double *power_band;
       power_band=new double[num_filt];
     
       double *total_bandPower;
       total_bandPower=new double[num_filt];

       
       //Cycle to read continuously data

	 num_rx_samps=0;
	    
	 // std::cout<<"buffer:"<<buffer_size<<"\n";

	 for(int ii=0;ii<num_filt;ii++){
	   total_bandPower[ii]=0.0;
	 }
	  
	 int loop_count=0;

	 int size_all=100;
	 
	 total_num_samps= 4000;

	 double * all[total_num_samps];
	 
	 for(int ii=0;ii<size_all;ii++){
	   all[ii]= new double[2*(int)(total_num_samps)];
	 }


	  while(loop_count<size_all){

	    //DispVal(loop_count);

	     stream_cmd.num_samps = buffer_size;
	     stream_cmd.stream_now = true;

	     stream_cmd.stream_mode=uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS;

	     //stream_cmd.time_spec = uhd::time_spec_t(seconds_in_future);

	     dev->issue_stream_cmd(stream_cmd);

	    while (num_rx_samps<total_num_samps) {

	     
	     num_rx_samps_latest_call=0;   
	     	
       
	     while (num_rx_samps_latest_call==0) {
	       num_rx_samps_latest_call= 
		 rx_stream->recv(&buff_short[0],buffer_size, md, 3.0);
	      };

	    

	     
	     if (num_rx_samps_latest_call!=buffer_size) {
	       std::cerr << "I expect the buffer size to be always the same!\n";
	       std::cout<<"Read only:"<<num_rx_samps_latest_call<<"\n";
	       std::cout<<"Buffer:"<<buffer_size<<"\n";
	       exit(1); 
	       //May be changed->don't want program to crash when data is not available
	     };

	     /* Process the just received buffer -> Put all toghether in one buffer*/
	     int i1=2*num_rx_samps;
	     int i2=0;
      
	     while ((i1<(int) (2*total_num_samps)) && (i2<2*((int) buffer_size))) 
	       {	  
		all[loop_count][i1]=(double)buff_short[i2];
		 i1++; i2++;
	       };
	 
	     num_rx_samps=num_rx_samps+num_rx_samps_latest_call;
	     //std::cout << "num_rx_samps=" << num_rx_samps  << std::endl;
  
	   };

	   
	    stream_cmd.stream_now = false;
    
	    stream_cmd.stream_mode=uhd::stream_cmd_t::STREAM_MODE_STOP_CONTINUOUS;

	    //stream_cmd.time_spec = uhd::time_spec_t(seconds_in_future);
	    
	    dev->issue_stream_cmd(stream_cmd);

	     powerOfFreqBands( all[loop_count], total_num_samps,  shiftindex, power_band, num_filt);

	     for(int ii=0;ii<num_filt+1;ii++){
	       total_bandPower[ii]=total_bandPower[ii]+power_band[ii]/size_all;
	     }
	     if(loop_count==99){
	       loop_count=0;
	       for(int ii=0;ii<num_filt+1;ii++){
	       double shift=shiftindex*ii;
	       std::cout << "power: " << power_band[ii] << " at w0: " << shift << std::endl;
	     }
	       std::cout<<"-------------------------------------\n";
	     }else{
	       loop_count++;
	     }
	    num_rx_samps=0;

	 }
	  
    };

    //finished
    std::cout << std::endl << "Done receiving!" << std::endl << std::endl; 

    return 0;
}
예제 #9
0
/*******************************************************************************
 * Main function
 ******************************************************************************/
int UHD_SAFE_MAIN(int argc, char *argv[]){
    uhd::set_thread_priority_safe();

    /** Constant Decalartions *************************************************/
    const INT32U time = DURATION*(SAMPRATE/SPB);

    /** Variable Declarations *************************************************/

    // (circular) receive buffers
    std::vector< CINT16 >   ch0_rxbuff(time*SPB);   // Ch 0 is RX2-A
    std::vector< CINT16 >   ch1_rxbuff(time*SPB);   // Ch 1 is RX2-B

    // Vector of pointers to sectons of rx_buff
    std::vector< std::vector< CINT16 *> >   rxbuffs(time*2, std::vector< CINT16 *>(2));

        // Holds the number of received samples returned by rx_stream->recv()
    INT16U num_rx_samps;

        // Counters
    INT16U i = 0,j = 0,k = 0;               // Generic counters
    INT32U write_ctr = 0;                      // Counts loops through main while()

    /** Variable Initializations **********************************************/
        // Initialise rxbuffs (Vector of pointers)
    for(i = 0; i < time; i++){
        rxbuffs[i][0] = &ch0_rxbuff.front() + SPB * i;
        rxbuffs[i][1] = &ch1_rxbuff.front() + SPB * i;
    }

    /** Main code *************************************************************/

        // set USRP Rx params
    uhd::usrp::multi_usrp::sptr usrp_rx = uhd::usrp::multi_usrp::make(std::string("")); // create a usrp device
    uhd::tune_request_t tune_request(CARRIERFREQ);                                      // validate tune request
    usrp_rx->set_master_clock_rate(CLOCKRATE);                                          // set clock rate
    usrp_rx->set_clock_source(std::string("internal"));                                 // lock mboard clocks
    // usrp_rx->set_time_source("external");                                                   // Use external reference clock

    usrp_rx->set_rx_subdev_spec(std::string("A:A A:B"));                                // select the subdevice
    usrp_rx->set_rx_rate(SAMPRATE,0);                                                   // set the sample rate (Ch 0)
    usrp_rx->set_rx_rate(SAMPRATE,1);                                                   // set the sample rate (Ch 1)
    usrp_rx->set_rx_freq(tune_request,0);                                               // set the center frequency (Ch 0)
    usrp_rx->set_rx_freq(tune_request,1);                                               // set the center frequency (Ch 1)
    usrp_rx->set_rx_gain(RXGAIN,0);                                                     // set the rf gain (Ch 0)
    usrp_rx->set_rx_gain(RXGAIN,1);                                                     // set the rf gain (Ch 1)
    usrp_rx->set_rx_antenna(std::string("TX/RX"),0);                                    // set the antenna (Ch 0)
    usrp_rx->set_rx_antenna(std::string("TX/RX"),1);                                    // set the antenna (Ch 1)
    boost::this_thread::sleep(boost::posix_time::seconds(1.0));                         // allow for some setup time

        // check Ref and LO Lock detect for Rx
    check_locked_sensor(usrp_rx->get_rx_sensor_names(0), "lo_locked", boost::bind(&uhd::usrp::multi_usrp::get_rx_sensor, usrp_rx, _1, 0), 1.0);

        // create a receive streamer
    uhd::stream_args_t stream_args_rx("sc16", "sc16");
     stream_args_rx.channels = boost::assign::list_of(0)(1);
    uhd::rx_streamer::sptr rx_stream = usrp_rx->get_rx_stream(stream_args_rx);
    uhd::rx_metadata_t md_rx;

        // report stuff to user (things which may differ from what was requested)
    std::cout << boost::format("Actual RX Rate: %f Msps...") % (usrp_rx->get_rx_rate()/1e6) << std::endl;

        // set sigint so user can terminate via Ctrl-C
    std::signal(SIGINT, &sig_int_handler);
    std::cout << boost::format("Recording RX CH 0 and CH 1 for %i seconds") % DURATION << std::endl << std::endl;
    std::cout << "Press Enter to start recording..." << std::endl << std::endl;

        // Wait for "ENTER" key to be pressed
    while(std::cin.get() != '\n'){}

    std::cout << "Press Ctrl + C to stop recording..." << std::endl;

        // setup receive streaming
    uhd::stream_cmd_t stream_cmd(uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS);
    stream_cmd.stream_now = false;
    stream_cmd.time_spec = uhd::time_spec_t(0.25)+usrp_rx->get_time_now();  // tell USRP to start streaming 0.25 seconds in the future
    rx_stream->issue_stream_cmd(stream_cmd);

        // grab initial block of received samples from USRP with nice long timeout (gets discarded)
    num_rx_samps = rx_stream->recv(rxbuffs[0], SPB, md_rx, 3.0);

    while(not stop_signal_called){
            // grab block of received samples from USRP
        num_rx_samps = rx_stream->recv(rxbuffs[write_ctr], SPB, md_rx);

            // Increment counter
        write_ctr++;

            // Check if full time has passed
        if(write_ctr == time){
            break;
        }else{}

            // Report progress to terminal
        std::cout << boost::format("\r\t%2i Percent Complete      ") % (write_ctr*100/time) << std::flush;

    }   /** while(not stop_signal_called) *************************************/

            // Report progress to terminal
        std::cout << "\r\tdone!               " << std::endl << std::endl;

        if(stop_signal_called){
            std::cout << std::endl << "Writing partial buffers to file (this may take awhile)..." << std::endl;
        }else{
                // Write buffers to file
            std::cout << "Writing buffers to file (this may take awhile)..." << std::endl;
        }

        std::cout << "    Channel 0 (RX2-A)..." << std::flush;
        writebuff("./RX2-A.dat", &ch0_rxbuff.front(), write_ctr*SPB);
        std::cout << "done!" << std::endl;

        std::cout << "    Channel 1 (RX2-B)..." << std::flush;
        writebuff("./RX2-B.dat", &ch1_rxbuff.front(), write_ctr*SPB);
        std::cout << "done!" << std::endl;

    return EXIT_SUCCESS;
}   /** main() ****************************************************************/
int UHD_SAFE_MAIN(int argc, char *argv[]){



    if (uhd::set_thread_priority_safe(1,true)) {
       std::cout << "set priority went well " << std::endl;
    };


    #if 0
    int portno=30000;
    //int s=socket(AF_INET,SOCK_STREAM,0);
    struct sockaddr_in  server;
    struct hostent *hp;
    struct in_addr ipv4addr;
    

    inet_pton(AF_INET, "127.0.0.1", &ipv4addr);

    bzero((char *)&server, sizeof (server));
    hp = gethostbyaddr(&ipv4addr,sizeof(ipv4addr), AF_INET);
    bcopy(hp->h_addr, (char *)&server.sin_addr,
          hp->h_length);  
    server.sin_family = hp->h_addrtype;
    server.sin_port = htons(portno);
    int s = socket(hp->h_addrtype, SOCK_STREAM, 0);
    if (s < 0) 
      std::cerr << "ERROR opening socket";

    connect(s, (struct sockaddr *)&server, sizeof(server));
    usleep(1003);

    char buffer[6];
    usleep(1e6);
    buffer[0]=65;
    buffer[1]=66;
    buffer[2]=67;
    buffer[3]=68;
    buffer[4]=10;
    buffer[5]=0;

    short nb[5];
    nb[0]=htons(23); nb[1]=htons(-24); nb[2]=htons(77); 
    nb[3]=htons(-18);  nb[4]=htons(-33); 

    std::cout << "strlen=" << strlen(buffer) << "\n";

    
    for (int i1=0;i1<10;i1++) {
      std::cout << "buffer[" << i1 << "]=" << (unsigned int)buffer[i1] << "\n";
    };
    

    //int n = write(s,buffer,strlen(buffer));
    int n = write(s,nb,sizeof(nb));

    std::cout << "n=" << n << "\n";
    if (n < 0) 
      std::cerr << "ERROR writing to socket";

    close(s);
    usleep(100e6);
    #endif


    //variables to be set by po
    std::string args;
    double seconds_in_future;
    size_t total_num_samps, total_num_repeats;
    int send_to_listener;
    
    double rate, freq_tx, freq_rx;
    float gain;
    std::string filename_rx, filename_tx;
    uhd::tx_streamer::sptr tx_stream;
    uhd::rx_streamer::sptr rx_stream;
    uhd::device_addr_t dev_addr;
    uhd::usrp::multi_usrp::sptr dev;
    uhd::stream_args_t stream_args;

    //setup the program options
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help", "help message")
        ("args", po::value<std::string>(&args)->default_value(""), "simple uhd device address args")
        ("secs", po::value<double>(&seconds_in_future)->default_value(0.5), "number of seconds in the future to transmit")
        ("nsamps", po::value<size_t>(&total_num_samps)->default_value(1000), "Total number of samples to transmit and receive")
        ("nrep", po::value<size_t>(&total_num_repeats)->default_value(1), "Total number of repeats")
        ("rate", po::value<double>(&rate)->default_value(100e6/8), "rate of outgoing and ingoing samples")
        ("freq_rx", po::value<double>(&freq_rx)->default_value(20e6), "receive center frequency in Hz")
        ("freq_tx", po::value<double>(&freq_tx)->default_value(20e6), "transmit center frequency in Hz")
        ("filename_tx",po::value<std::string>(&filename_tx)->default_value("data_to_usrp.dat"), "tx filename")
        ("filename_rx",po::value<std::string>(&filename_rx)->default_value("data_from_usrp.dat"), "rx filename")        
        ("gain",po::value<float>(&gain)->default_value(0), "gain of transmitter")        
        ("n",po::value<int>(&send_to_listener)->default_value(0), "Every n:th received buffer is sent to a client listening on port 3000. ")        

    ;

    

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    if (vm.count("help")){
        std::cout << boost::format("rxtx_bidirectional %s") % desc << std::endl;
        return ~0;
    }





    int s; 

    if (send_to_listener>0) {

      struct sockaddr_in  server;
      struct hostent *hp;
      struct in_addr ipv4addr;
      int portno=30000;    

      inet_pton(AF_INET, "127.0.0.1", &ipv4addr);

      bzero((char *)&server, sizeof (server));
      hp = gethostbyaddr(&ipv4addr,sizeof(ipv4addr), AF_INET);
      bcopy(hp->h_addr, (char *)&server.sin_addr,
          hp->h_length);  
      server.sin_family = hp->h_addrtype;
      server.sin_port = htons(portno);
      s = socket(hp->h_addrtype, SOCK_STREAM, 0);
      if (s < 0) 
	std::cerr << "ERROR opening socket";

      connect(s, (struct sockaddr *)&server, sizeof(server));
    } ;



    int process_buffer_size=9000; // Buffer size in processing
    int tx_ahead_buffers=3; // Number of buffers transmitted before starting
                            // to receive.

    signal_processing sp(total_num_samps,total_num_repeats,send_to_listener,s,
	       process_buffer_size,filename_rx,filename_tx);


    std::complex<int16_t> *process_buffer_tx;
    process_buffer_tx = new std::complex<int16_t>[process_buffer_size];

    std::complex<int16_t> *process_buffer_rx;
    process_buffer_rx = new std::complex<int16_t>[process_buffer_size];

    
    /* Create buffer storage for trailing zeros */
    std::complex<int16_t> *buffer_zeros;
    buffer_zeros = new std::complex<int16_t>[process_buffer_size]();
    

    //create a usrp device and streamer
    dev_addr["addr0"]="192.168.10.2";
    dev = uhd::usrp::multi_usrp::make(dev_addr);    

    dev->set_clock_source("internal");
    dev->set_time_now(uhd::time_spec_t(0.0), 0);

    // Internal variables 
    uhd::clock_config_t my_clock_config; 



    uhd::tune_result_t tr;
    uhd::tune_request_t trq_rx(freq_rx,0); //std::min(tx_rate,10e6));
    tr=dev->set_rx_freq(trq_rx,0);

    uhd::tune_request_t trq_tx(freq_tx,0); //std::min(tx_rate,10e6));
    tr=dev->set_tx_freq(trq_tx,0);

    

    uhd::dict<std::string, std::string> tx_info;    
    tx_info=dev->get_usrp_tx_info(0);


    dev->set_tx_gain(gain);
    std::cout << tr.to_pp_string() << "\n";
 

    stream_args.cpu_format="sc16";
    tx_stream=dev->get_tx_stream(stream_args);
    rx_stream=dev->get_rx_stream(stream_args);



    //set properties on the device
    dev->set_tx_rate(rate);
    dev->set_rx_rate(rate);
    std::cout << boost::format("Actual TX Rate: %f Msps...") % (dev->get_tx_rate()/1e6) << std::endl;
    std::cout << boost::format("Actual RX Rate: %f Msps...") % (dev->get_rx_rate()/1e6) << std::endl;
    std::cout << boost::format("Setting device timestamp to 0...") << std::endl;
    uhd::tx_metadata_t md;
  


    dev->set_time_now(uhd::time_spec_t(0.0));



    uhd::rx_metadata_t md_rx;
    //uhd::stream_cmd_t 
    //  stream_cmd(uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE);

    uhd::stream_cmd_t 
      stream_cmd(uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS);


    stream_cmd.num_samps = total_num_samps;
    stream_cmd.stream_now = false;
    stream_cmd.time_spec = uhd::time_spec_t(seconds_in_future);
    rx_stream->issue_stream_cmd(stream_cmd);


    md.start_of_burst = true;
    md.end_of_burst = false;
    md.has_time_spec = true;
    md.time_spec = uhd::time_spec_t(seconds_in_future);

    for (int i1=tx_ahead_buffers;i1>0;i1--) {
      tx_stream->send(buffer_zeros, 
		    process_buffer_size , md);
      md.start_of_burst = false;
      md.has_time_spec = false;
    };
 
    md.start_of_burst = false;
    int return_value=1;

    while (return_value!=0) {

       rx_stream->recv(process_buffer_rx,
	    process_buffer_size, md_rx, seconds_in_future+1);
       return_value=sp.process_buffers(process_buffer_rx, process_buffer_tx);
       tx_stream->send(process_buffer_tx, 
		    process_buffer_size , md); 

      
    };

    md.end_of_burst = true;
    tx_stream->send(buffer_zeros, process_buffer_size , md);


    //finished
    std::cout << std::endl << "Done!" << std::endl << std::endl;



    return 0;
}
예제 #11
0
int UHD_SAFE_MAIN(int argc, char *argv[]){
    uhd::set_thread_priority_safe();

    //variables to be set by po
    std::string args, file, type, ant, subdev;
    size_t total_num_samps, spb;
    double rate, freq, gain, bw;

    //setup the program options
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help", "help message")
        ("args", po::value<std::string>(&args)->default_value("addr0=192.168.10.2"), "multi uhd device address args")
        ("file", po::value<std::string>(&file)->default_value("usrp_samples.dat"), "name of the file to write binary samples to")
        ("type", po::value<std::string>(&type)->default_value("float"), "sample type: double, float, or short")
        ("nsamps", po::value<size_t>(&total_num_samps)->default_value(0), "total number of samples to receive")
        ("spb", po::value<size_t>(&spb)->default_value(10000), "samples per buffer")
		("rate", po::value<double>(&rate)->default_value(1e4), "rate of incoming samples")
		("freq", po::value<double>(&freq)->default_value(920e6), "RF center frequency in Hz")
		("gain", po::value<double>(&gain)->default_value(0), "gain for the RF chain")
		("ant", po::value<std::string>(&ant)->default_value("TX/RX"), "daughterboard antenna selection")
        ("subdev", po::value<std::string>(&subdev), "daughterboard subdevice specification")
        ("bw", po::value<double>(&bw), "daughterboard IF filter bandwidth in Hz")
    ;
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    //print the help message
    if (vm.count("help")){
        std::cout << boost::format("UHD RX samples to file %s") % desc << std::endl;
        return ~0;
    }

	printf("George's modified Demo version of RX_Samples_to_file.\n\rNote that this version sets up the device but doesn't write to disk.\n\r\n\r");
    //create a usrp device
    std::cout << std::endl;
    std::cout << boost::format("Creating the usrp device with: %s...") % args << std::endl;
    uhd::usrp::multi_usrp::sptr usrp = uhd::usrp::multi_usrp::make(args);

    //always select the subdevice first, the channel mapping affects the other settings
    if (vm.count("subdev")) usrp->set_rx_subdev_spec(subdev);

    std::cout << boost::format("Using Device: %s") % usrp->get_pp_string() << std::endl;

    //set the sample rate
    if (not vm.count("rate")){
        std::cerr << "Please specify the sample rate with --rate" << std::endl;
        return ~0;
    }
    std::cout << boost::format("Setting RX Rate: %f Msps...") % (rate/1e6) << std::endl;
    usrp->set_rx_rate(rate);
    std::cout << boost::format("Actual RX Rate: %f Msps...") % (usrp->get_rx_rate()/1e6) << std::endl << std::endl;

    //set the center frequency
    if (not vm.count("freq")){
        std::cerr << "Please specify the center frequency with --freq" << std::endl;
        return ~0;
    }
    std::cout << boost::format("Setting RX Freq: %f MHz...") % (freq/1e6) << std::endl;
    usrp->set_rx_freq(freq);
    std::cout << boost::format("Actual RX Freq: %f MHz...") % (usrp->get_rx_freq()/1e6) << std::endl << std::endl;

    //set the rf gain
    if (vm.count("gain")){
        std::cout << boost::format("Setting RX Gain: %f dB...") % gain << std::endl;
        usrp->set_rx_gain(gain);
        std::cout << boost::format("Actual RX Gain: %f dB...") % usrp->get_rx_gain() << std::endl << std::endl;
    }

    //set the IF filter bandwidth
    if (vm.count("bw")){
        std::cout << boost::format("Setting RX Bandwidth: %f MHz...") % bw << std::endl;
        usrp->set_rx_bandwidth(bw);
        std::cout << boost::format("Actual RX Bandwidth: %f MHz...") % usrp->get_rx_bandwidth() << std::endl << std::endl;
    }

    //set the antenna
    if (vm.count("ant")) usrp->set_rx_antenna(ant);

    boost::this_thread::sleep(boost::posix_time::seconds(1)); //allow for some setup time

    //setup streaming
    uhd::stream_cmd_t stream_cmd((total_num_samps == 0)?
        uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS:
        uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE
    );
    stream_cmd.num_samps = total_num_samps;
    stream_cmd.stream_now = true;
    usrp->issue_stream_cmd(stream_cmd);
    if (total_num_samps == 0){
        std::signal(SIGINT, &sig_int_handler);
        std::cout << "Press Ctrl + C to stop streaming..." << std::endl;
    }

    //recv to file
    if (type == "double") recv_to_file<std::complex<double> >(usrp, uhd::io_type_t::COMPLEX_FLOAT64, file, spb);
    else if (type == "float") recv_to_file<std::complex<float> >(usrp, uhd::io_type_t::COMPLEX_FLOAT32, file, spb);
    else if (type == "short") recv_to_file<std::complex<short> >(usrp, uhd::io_type_t::COMPLEX_INT16, file, spb);
    //else throw std::runtime_error("Unknown type " + type);
	
	boost::this_thread::sleep(boost::posix_time::seconds(1)); //allow for some setup time

	printf("turning off streaming...\n\r");
	//turn off streaming
	stream_cmd.stream_now = false;
	stream_cmd.stream_mode = uhd::stream_cmd_t::STREAM_MODE_STOP_CONTINUOUS;
	usrp->issue_stream_cmd(stream_cmd);

    //finished
    std::cout << std::endl << "Done!" << std::endl << std::endl;

    return 0;
}
예제 #12
0
파일: rx_3.cpp 프로젝트: tony2909/green
void storeDataX(uhd::rx_streamer::sptr rx_stream, uhd::usrp::multi_usrp::sptr dev, size_t buffer_size, uint nDetect){



  // Create storage for a single buffer from USRP
  short *buff_short;
  buff_short=new short[2*buffer_size]; 
 
  short *storage_short;
  storage_short=new short [2*nDetect];

  uhd::stream_cmd_t stream_cmd(uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE);
	  
    std::cout << "Stop the transmitter by pressing ctrl-c \n";
	  
      stream_cmd.num_samps = buffer_size;
      stream_cmd.stream_now = true;
    
       stream_cmd.stream_mode=uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS;

       dev->issue_stream_cmd(stream_cmd);


  uhd::rx_metadata_t md;
  size_t n_rx_samps=0;

  int n_rx_last;

  while (1){
    n_rx_samps=0;
    // Fill the storage buffer loop
    while (n_rx_samps<nDetect){
      n_rx_last=0;
      // Fill buff_short
      while (n_rx_last==0) {
	n_rx_last=rx_stream->recv(&buff_short[0], buffer_size, md, 3.0);
	//std::this_thread::yield();
      };

      sec_count++;
      // Check if no overflow
      if (n_rx_last!=(int)buffer_size) {
	std::cerr << "I expect the buffer size to be always the same!\n";
	std::cout<<"Read only:"<<n_rx_last<<"\n";
	std::cout<<"Buffer:"<<buffer_size<<"\n";
	exit(1); 
      };
      
      // Fill storage
      int i1=2*n_rx_samps;
      int i2=0;   
      while ((i1<(int) (2*nDetect)) && (i2<2*((int) buffer_size))){	  
	storage_short[i1]=buff_short[i2];
	i1++; i2++;
      };
      
      //storage_short=buff_short;
      n_rx_samps=n_rx_samps+n_rx_last;
      //std::cout << "n_rx_samps=" << n_rx_samps  << std::endl;	 
    }//storage_short now full


    mtxQ.lock();
    bufferQ.push(buff_short);
    mtxQ.unlock();
    //delete buff_short;
    buff_short=new short [2*buffer_size]; // Change memory cell used

    //usleep(1000000/4);
    sem_post( &isReady); // Gives the start to detection part

  }//end while 1
}
예제 #13
0
//set program_options
int UHD_SAFE_MAIN (int argc, char *argv[])
{ 
   uhd::set_thread_priority_safe();
   std::string args;
   size_t total_samples,number_bins,num_acc_samps;
   double bw,rate, freq, gain;
   po::options_description desc("allowed options");

   desc.add_options()
	("args",po::value<std::string>(&args)->default_value(""),"multi uhd device address args")
   ("help","help message")
  ("nsamps",po::value<size_t> (&total_samples)->default_value(0),"Total number of samples to receive, zero for continous mode")
     ("rate", po::value<double>(&rate)->default_value(2e6), "rate of incoming samples")
   ("freq",po::value<double>(&freq)->default_value(400e6),"rf center frequency in Hz")
   ("gain",po::value<double>(&gain)->default_value(0),"gain for the RF chain")
   ("number_bins",po::value<size_t>(&number_bins)->default_value(1024),"number of FFT points")
     ("bw", po::value<double>(&bw), "daughterboard IF filter bandwidth in Hz")

   ;
 po::variables_map vm;
 po::store(po::parse_command_line(argc,argv,desc),vm);
 po::notify(vm);


 if (vm.count("help"))
 	{//if
 		std::cout<< boost::format("UHD RX timed Samples %s") % desc <<std::endl;
		return ~0; 
	}//if

//create usrp device
	std::cout<<std::endl;
	std::cout<<boost::format("setting RX Rate: %f Msps...") % args <<std::endl;
	uhd::usrp::multi_usrp::sptr usrp =uhd::usrp::multi_usrp::make(args);
	std::cout<<boost::format("Using Device: %s ") % usrp->get_pp_string()<<std::endl;
	//set bandwidth
	if (vm.count("bw")){
	  std::cout << boost::format("Setting RX Bandwidth: %f MHz...") % bw << std::endl;
	  usrp->set_rx_bandwidth(bw);
	  std::cout << boost::format("Actual RX Bandwidth: %f MHz...") % usrp->get_rx_bandwidth() << std::endl << std::endl;
	}
//set the sample rate

	std::cout << boost::format("setting RX Rate: %f Msps...") % (rate/1e6) <<std::endl<<std::endl;
	usrp->set_rx_rate(rate);
	std::cout<<boost::format("actual RX rate: %f Msps...") % (usrp->get_rx_rate()/1e6) <<std::endl<<std::endl;

//set the rx center frequency
    std::cout << boost::format("Setting RX Freq: %f Mhz...") % (freq/1e6) << std::endl;
    usrp->set_rx_freq(freq);
    std::cout << boost::format("Actual RX Freq: %f Mhz...") % (usrp->get_rx_freq()/1e6) << std::endl << std::endl;


//create a receiver streamer
    uhd::stream_args_t stream_args("fc32");
    uhd::rx_streamer::sptr rx_streamer =usrp-> get_rx_stream(stream_args);

//rm// set up streaming ...0 means continues
    uhd::stream_cmd_t stream_cmd((total_samples==0)?
    uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS:
    uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE);



stream_cmd.num_samps =total_samples;
stream_cmd.stream_now = true;
stream_cmd.time_spec =uhd::time_spec_t();
usrp->issue_stream_cmd(stream_cmd);

size_t num_rx_samps =0; //initialize number of received samples

uhd::rx_metadata_t md;

std::vector<std::complex<float> > buff(number_bins);
std::vector<std::complex<float> > out_buff(number_bins);

//initialize fft plan

fftwf_complex *in = (fftwf_complex*)&buff.front(); //allocate  array in
fftwf_complex *out = (fftwf_complex*)&out_buff.front(); //allocate array out
fftwf_plan f;  
f =fftwf_plan_dft_1d(number_bins,in, out, FFTW_FORWARD,FFTW_ESTIMATE);

 while(not stop_signal_called and (num_acc_samps < total_samples or total_samples == 0))
   {
     size_t num_rx_samps = rx_streamer->recv( &buff.front(), buff.size(), md, 3.0);
     std::cout <<" current buffer size: "<< buff.size()<<std::endl<<std::endl;   
     //handle the error codes
     switch(md.error_code){
     case uhd::rx_metadata_t::ERROR_CODE_NONE:
       break;

     case uhd::rx_metadata_t::ERROR_CODE_TIMEOUT:
       if (num_acc_samps == 0) continue;
       std::cout << boost::format(
                "Got timeout before all samples received, possible packet loss, exiting loop..."
				  ) << std::endl;
       goto done_loop;

     default:
       std::cout << boost::format(
                "Got error code 0x%x, exiting loop..."
				  ) % md.error_code << std::endl;
       goto done_loop;
     }

     std::cout<<"performing fft to samples at frequency"<<usrp->get_rx_freq()<<std::endl;
     fftwf_execute(f);
     num_acc_samps = num_rx_samps +1;

     std::cout<<"number of accumulated samples"<<num_acc_samps<<std::endl<<std::endl;
     std::cout <<"nubmer of rx samples: "<<num_rx_samps <<std::endl<<std::endl;
     float energy = find_energy(out_buff);
     std::cout<<"the energy for incoming samples: " <<energy;

     //     print_data(out_buff);  
     
   }


done_loop:

fftwf_destroy_plan(f);

std::cout<<std::endl<<"done";
return 0;

 }
예제 #14
0
파일: rx.cpp 프로젝트: tony2909/green
int UHD_SAFE_MAIN(int argc, char *argv[]){
    
    
    if (!(uhd::set_thread_priority_safe(1,true))) {
      std::cout << "Problem setting thread priority" << std::endl;
      return 1;
    };


    //variables to be set by po
    //double seconds_in_future=0.01;
    size_t total_num_samps;
    double rx_rate, freq, LOoffset;
    bool use_external_10MHz;
    double scaling_8bits;
    std::string filename;
    float gain;
    uhd::device_addr_t dev_addr;
    uhd::usrp::multi_usrp::sptr dev;
    uhd::tune_result_t tr;
    uhd::stream_args_t stream_args;
    uhd::rx_streamer::sptr rx_stream;


    //setup the program options
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help", "help message")
        ("nsamps", po::value<size_t>(&total_num_samps)->default_value(1000), "total number of samples to receive")
        ("rxrate", po::value<double>(&rx_rate)->default_value(100e6/4), "rate of incoming samples")
        ("freq", po::value<double>(&freq)->default_value(0), "rf center frequency in Hz")
        ("LOoffset", po::value<double>(&LOoffset)->default_value(0), "Offset between main LO and center frequency")
        ("10MHz",po::value<bool>(&use_external_10MHz)->default_value(false), "external 10MHz on 'REF CLOCK' connector (true=1=yes)")
      //  ("PPS",po::value<bool>(&trigger_with_pps)->default_value(false), "trigger reception with 'PPS IN' connector (true=1=yes)")
        ("filename",po::value<std::string>(&filename)->default_value("data_from_usrp.dat"), "output filename") 
        ("gain",po::value<float>(&gain)->default_value(0), "set the receiver gain") 
        ("8bits_scaling",po::value<double>(&scaling_8bits)->default_value(0.0), 
    "input scaling (invers) when 8bits is used, set to zero to get 16bits")
    ;
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);


    dev_addr["addr0"]="192.168.10.2";
    //dev_addr["addr0"]="192.168.10.2";
    dev = uhd::usrp::multi_usrp::make(dev_addr);

    stream_args.cpu_format="sc16";
    if (scaling_8bits==0.0) {
      stream_args.otw_format="sc16";     
    } else {
      stream_args.otw_format="sc8";
      std::stringstream temp_ss;
      temp_ss << scaling_8bits;
      stream_args.args["peak"]=temp_ss.str();
    };

    rx_stream=dev->get_rx_stream(stream_args);

    uhd::clock_config_t my_clock_config; 

    #if 0
    if (trigger_with_pps) {
      my_clock_config.pps_source=uhd::clock_config_t::PPS_SMA; 
    };
    #endif

    if (use_external_10MHz) { 
      my_clock_config.ref_source=uhd::clock_config_t::REF_SMA; 
    }; 

    //print the help message
    if (vm.count("help")){
        std::cout << boost::format("UHD RX Timed Samples %s") % desc << std::endl;
        return ~0;
    }

    //create a usrp device
    std::cout << std::endl;
    uhd::device::sptr udev = dev->get_device();
    dev->set_rx_rate(rx_rate);

    bool is_xcvr2450=false;
    uhd::dict<std::string, std::string> rx_info;    
    rx_info=dev->get_usrp_rx_info(0);

    if (rx_info.has_key("rx_subdev_name")) {
      std::string str=rx_info.get("rx_subdev_name");
      uint temp=str.find("XCVR2450");
      if (temp<str.length()) {
	is_xcvr2450=true;
      };
    };

    if (is_xcvr2450) {
      dev->set_tx_antenna("J2");
      dev->set_rx_antenna("J1");      
      //uhd::meta_range_t range=dev->get_tx_bandwidth_range();

      if (LOoffset>=9e6) {
	dev->set_rx_bandwidth(3.96e+07);
      };      
    };



    std::cout << "rx_rate=" << rx_rate << std::endl;
    std::cout << "freq=" << freq << std::endl;
    std::cout << "gain=" << gain << std::endl;
    uhd::tune_request_t trq(freq,LOoffset); 


    //dev->set_rx_bandwidth(36e6);

    tr=dev->set_rx_freq(trq);
    dev->set_rx_gain(gain);

    std::cout << "tr=" << tr.actual_rf_freq << std::endl;

    /*
        double target_rf_freq;
        double actual_rf_freq;
        double target_dsp_freq;
        double actual_dsp_freq;
    */

    // 
    //dev->set_tx_antenna("J2");
    //dev->set_rx_antenna("J1");
    

    if (use_external_10MHz) {
      dev->set_clock_config(my_clock_config); // PZ
      usleep(1e6); // Wait for the 10MHz to lock
    }; 

    size_t buffer_size=1000; // Select buffer size
    short *buff_short, *storage_short;
    storage_short=new short[2*total_num_samps]; // Create storage for the 
    // entire received signal to be saved on disk.
    buff_short=new short[2*buffer_size]; // Create storage for a single 
                                                // buffer




    /*if (trigger_with_pps) {
      dev->set_time_next_pps(uhd::time_spec_t(0.0));
      usleep(1e6); 
      } */
    //else {
      dev->set_time_now(uhd::time_spec_t(0.0));
      //};
    std::cout << boost::format("Setting device timestamp to 0...") << std::endl;

    //setup streaming
    //std::cout << std::endl;
    //std::cout << boost::format("Begin streaming %u samples, %d seconds in the future...")
    //    % total_num_samps % seconds_in_future << std::endl;
    uhd::stream_cmd_t stream_cmd(uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE);
    
    

    stream_cmd.num_samps = buffer_size;
    stream_cmd.stream_now = true;
    
    stream_cmd.stream_mode=uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS;

    //stream_cmd.time_spec = uhd::time_spec_t(seconds_in_future);
    dev->issue_stream_cmd(stream_cmd);


    size_t num_rx_samps=0;
    size_t num_rx_samps_latest_call;

    uhd::rx_metadata_t md;
    while (num_rx_samps<total_num_samps) {
 

       num_rx_samps_latest_call=0;             
       while (num_rx_samps_latest_call==0) {
	 num_rx_samps_latest_call= 
	   rx_stream->recv(&buff_short[0],buffer_size, md, 3.0);
       };
       if (num_rx_samps_latest_call!=buffer_size)  {
	 std::cerr << "I expect the buffer size to be always the same!";
         exit(1); 
       };

       /* Process the just received buffer */
       int i1=2*num_rx_samps;
       int i2=0;
       while ((i1<(int) (2*total_num_samps)) && (i2<2*((int) buffer_size))) 
       {	  
	  storage_short[i1]=buff_short[i2];
	  i1++; i2++;
       };
	 
       num_rx_samps=num_rx_samps+num_rx_samps_latest_call;
       std::cout << "num_rx_samps=" << num_rx_samps  << std::endl;
    };




    //finished
    std::cout << std::endl << "Done!" << std::endl << std::endl; 

    // Save output to disc

    //std::ofstream s1(filename.c_str(), std::ios::binary);   


    //s1.write((char *) storage_short,4*total_num_samps); 
    //s1.flush(); //PZ
    //s1.close(); //PZ

    //Process the received data


    short tp =  powerTotArray( storage_short, 2*total_num_samps);

    std::cout << "Total power" << tp << "\nDone!\n";


    std::complex<short> * comp_rec=(std::complex<short> *) storage_short;

   


    return 0;
}
예제 #15
0
int UHD_SAFE_MAIN(int argc, char *argv[]) {
    uhd::set_thread_priority_safe();

    //variables to be set by po
    std::string args;
    size_t nsamps;
    double rate;
    double rtt;
    size_t nruns;

    //setup the program options
    po::options_description desc("Allowed options");
    desc.add_options()
    ("help", "help message")
    ("args",   po::value<std::string>(&args)->default_value(""), "single uhd device address args")
    ("nsamps", po::value<size_t>(&nsamps)->default_value(100),   "number of samples per run")
    ("nruns",  po::value<size_t>(&nruns)->default_value(1000),   "number of tests to perform")
    ("rtt",    po::value<double>(&rtt)->default_value(0.001),    "delay between receive and transmit (seconds)")
    ("rate",   po::value<double>(&rate)->default_value(100e6/4), "sample rate for receive and transmit (sps)")
    ("verbose", "specify to enable inner-loop verbose")
    ;
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    //print the help message
    if (vm.count("help")) {
        std::cout << boost::format("UHD - Latency Test %s") % desc << std::endl;
        std::cout <<
                  "    Latency test receives a packet at time t,\n"
                  "    and tries to send a packet at time t + rtt,\n"
                  "    where rtt is the round trip time sample time\n"
                  "    from device to host and back to the device.\n"
                  << std::endl;
        return ~0;
    }

    bool verbose = vm.count("verbose") != 0;

    //create a usrp device
    std::cout << std::endl;
    //std::cout << boost::format("Creating the usrp device with: %s...") % args << std::endl;
    uhd::usrp::multi_usrp::sptr usrp = uhd::usrp::multi_usrp::make(args);
    //std::cout << boost::format("Using Device: %s") % usrp->get_pp_string() << std::endl;

    usrp->set_time_now(uhd::time_spec_t(0.0));

    //set the tx sample rate
    usrp->set_tx_rate(rate);
    std::cout << boost::format("Actual TX Rate: %f Msps...") % (usrp->get_tx_rate()/1e6) << std::endl;

    //set the rx sample rate
    usrp->set_rx_rate(rate);
    std::cout << boost::format("Actual RX Rate: %f Msps...") % (usrp->get_rx_rate()/1e6) << std::endl;

    //allocate a buffer to use
    std::vector<std::complex<float> > buffer(nsamps);

    //create RX and TX streamers
    uhd::stream_args_t stream_args("fc32"); //complex floats
    uhd::rx_streamer::sptr rx_stream = usrp->get_rx_stream(stream_args);
    uhd::tx_streamer::sptr tx_stream = usrp->get_tx_stream(stream_args);

    //initialize result counts
    int time_error = 0;
    int ack = 0;
    int underflow = 0;
    int other = 0;

    for(size_t nrun = 0; nrun < nruns; nrun++) {

        /***************************************************************
         * Issue a stream command some time in the near future
         **************************************************************/
        uhd::stream_cmd_t stream_cmd(uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE);
        stream_cmd.num_samps = buffer.size();
        stream_cmd.stream_now = false;
        stream_cmd.time_spec = usrp->get_time_now() + uhd::time_spec_t(0.01);
        usrp->issue_stream_cmd(stream_cmd);

        /***************************************************************
         * Receive the requested packet
         **************************************************************/
        uhd::rx_metadata_t rx_md;
        size_t num_rx_samps = rx_stream->recv(
                                  &buffer.front(), buffer.size(), rx_md
                              );

        if(verbose) std::cout << boost::format("Got packet: %u samples, %u full secs, %f frac secs")
                                  % num_rx_samps % rx_md.time_spec.get_full_secs() % rx_md.time_spec.get_frac_secs() << std::endl;

        /***************************************************************
         * Transmit a packet with delta time after received packet
         **************************************************************/
        uhd::tx_metadata_t tx_md;
        tx_md.start_of_burst = true;
        tx_md.end_of_burst = true;
        tx_md.has_time_spec = true;
        tx_md.time_spec = rx_md.time_spec + uhd::time_spec_t(rtt);
        size_t num_tx_samps = tx_stream->send(
                                  &buffer.front(), buffer.size(), tx_md
                              );
        if(verbose) std::cout << boost::format("Sent %d samples") % num_tx_samps << std::endl;

        /***************************************************************
         * Check the async messages for result
         **************************************************************/
        uhd::async_metadata_t async_md;
        if (not usrp->get_device()->recv_async_msg(async_md)) {
            std::cout << boost::format("failed:\n    Async message recv timed out.\n") << std::endl;
            continue;
        }
        switch(async_md.event_code) {
        case uhd::async_metadata_t::EVENT_CODE_TIME_ERROR:
            time_error++;
            break;

        case uhd::async_metadata_t::EVENT_CODE_BURST_ACK:
            ack++;
            break;

        case uhd::async_metadata_t::EVENT_CODE_UNDERFLOW:
            underflow++;
            break;

        default:
            std::cerr << boost::format(
                          "failed:\n    Got unexpected event code 0x%x.\n"
                      ) % async_md.event_code << std::endl;
            other++;
            break;
        }
    }

    /***************************************************************
     * Print the summary
     **************************************************************/
    std::cout << boost::format("\nACK %d, UNDERFLOW %d, TIME_ERR %d, other %d")
              % ack % underflow % time_error % other << std::endl;
    return 0;
}
예제 #16
0
//This is the main sample receiving thread (private)
void *usrp_receiver_thread (void *param)
{            
    uhd::rx_metadata_t md;	    
    std::vector<std::complex<float> > buff(MAX_USRP_RX_BUFFER);       
    int old_state, old_type;
    QUEUE_BUFFER_ENTRY *item;

    pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,&old_state);
    pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,&old_type);       
    
    //Setup the samples streaming
    uhd::stream_cmd_t stream_cmd(uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS);    
    stream_cmd.num_samps = 0;
    stream_cmd.stream_now = true;
    usrp.sdev->issue_stream_cmd(stream_cmd);
    
    std::cerr << "Starting the USRP receiver thread cycle" << std::endl;
        
    //TIME BENCHMARKING 
    struct timeval *tod, *tod1;
    tod = (timeval *) malloc(sizeof(*tod));
    tod1 = (timeval *) malloc(sizeof(*tod1));
    int elapsed_usec = 0, diff_usec = 0; 
    long int recv_samps = 0;    
    gettimeofday(tod, NULL);
    
    while (1){	
        
        size_t num_rx_samps = usrp.dev->recv(
                                            &buff.front(), buff.size(), md,
                                            uhd::io_type_t::COMPLEX_FLOAT32,
                                            uhd::device::RECV_MODE_ONE_PACKET
                                           );                                            
        
        recv_samps += num_rx_samps;
        //std::cerr << boost::format("%s: received from USRP %d samples\n") % __FUNCTION__, num_rx_samps << std::endl;
                
        //TIME BECHMARKING
        gettimeofday(tod1, NULL);
        //std::cerr << boost::format("After recv: %d (SAMPS: %d)|\n") % (tod1->tv_usec - tod->tv_usec) % num_rx_samps;
        
        //handle the error codes
        switch(md.error_code){
        case uhd::rx_metadata_t::ERROR_CODE_NONE:
             break;

        case uhd::rx_metadata_t::ERROR_CODE_TIMEOUT:            
            std::cerr << boost::format(
                "Got timeout before all samples received, possible packet loss, exiting loop..."
            ) << std::endl;
            goto done_loop;
                        
        case uhd::rx_metadata_t::ERROR_CODE_OVERFLOW:              
            /*
             * Let the progranm continue.
             * In current version, overflows will be detected by "OOO's" at stderr
             * More elegant management will come in official version.
             * 
            std::cerr << boost::format(
                "Internal USRP receiver buffer overflow, exiting loop..."
            ) << std::endl;  
            goto done_loop;
             */
            break; 

        default:
            std::cerr << boost::format(
                "Got error code 0x%x, exiting loop..."
            ) % md.error_code << std::endl;
            goto done_loop;
        }
        
        //ENQUEUE The buffer
        
        pthread_mutex_lock(&RECEIVER_CYCLE_lock); 
        bool do_add_queue = RECEIVER_CYCLE;
        pthread_mutex_unlock(&RECEIVER_CYCLE_lock);
        
        if (! do_add_queue) continue;
        
        //Copy of the buffer in a NEW allocated buffer
        std::vector<std::complex<float> > *buff2 = new std::vector<std::complex<float> >(buff);

        //If there is space in queue
        if (rx_queue_length < MAX_QUEUE) {    
            //Add container to queue
            item = (QUEUE_BUFFER_ENTRY *) malloc(sizeof(*item));
            item->data = buff2;    
            //std::cerr << boost::format("Add to queue: len %d") % rx_queue_length << std::endl;        
            pthread_mutex_lock(&rx_queue_lock);
            TAILQ_INSERT_TAIL(&rx_samples_iq_stream, item, entries);
            rx_queue_length++;
            pthread_mutex_unlock(&rx_queue_lock);    
        } else {
            //else discard the rx buffer...
            std::cerr << boost::format("RX queue is full: rx buffer not forwarded!") << std::endl;
        }
                        
        //TIME BENCHMARKING 
        /*
        long int prev_usec=tod->tv_usec;
        gettimeofday(tod, NULL);
        elapsed_usec += ((diff_usec = tod->tv_usec - prev_usec) > 0 ? diff_usec : diff_usec + 1000000);        
        std::cerr << boost::format("Actual receiving rate (MSPS): %f") % (recv_samps * 1.0 / elapsed_usec) << std::endl;         
         */
        
    } done_loop:
	std::cerr << "Exiting USRP receiver thread" << std::endl;

    return 0;
}
예제 #17
0
void recv_to_file(uhd::rx_streamer::sptr rx_stream,
    const std::string& file,
    const size_t samps_per_buff,
    const double rx_rate,
    const unsigned long long num_requested_samples,
    double time_requested       = 0.0,
    bool bw_summary             = false,
    bool stats                  = false,
    bool enable_size_map        = false,
    bool continue_on_bad_packet = false)
{
    unsigned long long num_total_samps = 0;

    uhd::rx_metadata_t md;
    std::vector<samp_type> buff(samps_per_buff);
    std::ofstream outfile;
    if (not file.empty()) {
        outfile.open(file.c_str(), std::ofstream::binary);
    }
    bool overflow_message = true;

    // setup streaming
    uhd::stream_cmd_t stream_cmd((num_requested_samples == 0)
                                     ? uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS
                                     : uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE);
    stream_cmd.num_samps  = size_t(num_requested_samples);
    stream_cmd.stream_now = true;
    stream_cmd.time_spec  = uhd::time_spec_t();
    std::cout << "Issuing stream cmd" << std::endl;
    rx_stream->issue_stream_cmd(stream_cmd);

    const auto start_time = std::chrono::steady_clock::now();
    const auto stop_time =
        start_time + std::chrono::milliseconds(int64_t(1000 * time_requested));
    // Track time and samps between updating the BW summary
    auto last_update                     = start_time;
    unsigned long long last_update_samps = 0;

    typedef std::map<size_t, size_t> SizeMap;
    SizeMap mapSizes;

    // Run this loop until either time expired (if a duration was given), until
    // the requested number of samples were collected (if such a number was
    // given), or until Ctrl-C was pressed.
    while (not stop_signal_called
           and (num_requested_samples != num_total_samps or num_requested_samples == 0)
           and (time_requested == 0.0 or std::chrono::steady_clock::now() <= stop_time)) {
        const auto now = std::chrono::steady_clock::now();

        size_t num_rx_samps =
            rx_stream->recv(&buff.front(), buff.size(), md, 3.0, enable_size_map);

        if (md.error_code == uhd::rx_metadata_t::ERROR_CODE_TIMEOUT) {
            std::cout << boost::format("Timeout while streaming") << std::endl;
            break;
        }
        if (md.error_code == uhd::rx_metadata_t::ERROR_CODE_OVERFLOW) {
            if (overflow_message) {
                overflow_message = false;
                std::cerr
                    << boost::format(
                           "Got an overflow indication. Please consider the following:\n"
                           "  Your write medium must sustain a rate of %fMB/s.\n"
                           "  Dropped samples will not be written to the file.\n"
                           "  Please modify this example for your purposes.\n"
                           "  This message will not appear again.\n")
                           % (rx_rate * sizeof(samp_type) / 1e6);
            }
            continue;
        }
        if (md.error_code != uhd::rx_metadata_t::ERROR_CODE_NONE) {
            std::string error = str(boost::format("Receiver error: %s") % md.strerror());
            if (continue_on_bad_packet) {
                std::cerr << error << std::endl;
                continue;
            } else
                throw std::runtime_error(error);
        }

        if (enable_size_map) {
            SizeMap::iterator it = mapSizes.find(num_rx_samps);
            if (it == mapSizes.end())
                mapSizes[num_rx_samps] = 0;
            mapSizes[num_rx_samps] += 1;
        }

        num_total_samps += num_rx_samps;

        if (outfile.is_open()) {
            outfile.write((const char*)&buff.front(), num_rx_samps * sizeof(samp_type));
        }

        if (bw_summary) {
            last_update_samps += num_rx_samps;
            const auto time_since_last_update = now - last_update;
            if (time_since_last_update > std::chrono::seconds(UPDATE_INTERVAL)) {
                const double time_since_last_update_s =
                    std::chrono::duration<double>(time_since_last_update).count();
                const double rate = double(last_update_samps) / time_since_last_update_s;
                std::cout << "\t" << (rate / 1e6) << " MSps" << std::endl;
                last_update_samps = 0;
                last_update       = now;
            }
        }
    }
    const auto actual_stop_time = std::chrono::steady_clock::now();

    stream_cmd.stream_mode = uhd::stream_cmd_t::STREAM_MODE_STOP_CONTINUOUS;
    std::cout << "Issuing stop stream cmd" << std::endl;
    rx_stream->issue_stream_cmd(stream_cmd);

    // Run recv until nothing is left
    int num_post_samps = 0;
    do {
        num_post_samps = rx_stream->recv(&buff.front(), buff.size(), md, 3.0);
    } while (num_post_samps and md.error_code == uhd::rx_metadata_t::ERROR_CODE_NONE);

    if (outfile.is_open())
        outfile.close();

    if (stats) {
        std::cout << std::endl;

        const double actual_duration_seconds =
            std::chrono::duration<float>(actual_stop_time - start_time).count();

        std::cout << boost::format("Received %d samples in %f seconds") % num_total_samps
                         % actual_duration_seconds
                  << std::endl;
        const double rate = (double)num_total_samps / actual_duration_seconds;
        std::cout << (rate / 1e6) << " MSps" << std::endl;

        if (enable_size_map) {
            std::cout << std::endl;
            std::cout << "Packet size map (bytes: count)" << std::endl;
            for (SizeMap::iterator it = mapSizes.begin(); it != mapSizes.end(); it++)
                std::cout << it->first << ":\t" << it->second << std::endl;
        }
    }
}
예제 #18
0
파일: rx_60GHz.cpp 프로젝트: tony2909/green
int UHD_SAFE_MAIN(int argc, char *argv[]) {


    // Set priority of the main thread
    int which = PRIO_PROCESS;
    id_t pid;
    int priority = -19;
    int ret;

    pid = getpid();
    ret = setpriority(which, pid, priority);
    if(ret!=0) {
        std::cout << "Main priority went wrong: " << ret << std::endl ;
    }


    //Seting priority in the processor to run faster -> run with sudo
    if (!(uhd::set_thread_priority_safe(1,true))) {
        std::cout << "Problem setting thread priority" << std::endl;
        return 1;
    };


    if (!(uhd::set_thread_priority_safe(1,true))) {
        std::cout << "Problem setting thread priority" << std::endl;
        return 1;
    };


    //variables to be set by po
    //double seconds_in_future=0.01;
    size_t total_num_samps;
    double rx_rate, freq, LOoffset;
    bool use_external_10MHz;
    bool realTime;
    double scaling_8bits;
    std::string filename;
    float gain;
    uhd::device_addr_t dev_addr;
    uhd::usrp::multi_usrp::sptr dev;
    uhd::tune_result_t tr;
    uhd::stream_args_t stream_args;
    uhd::rx_streamer::sptr rx_stream;


    //setup the program options
    po::options_description desc("Allowed options");
    desc.add_options()
    ("help", "help message")
    ("nsamps", po::value<size_t>(&total_num_samps)->default_value(150000), "total number of samples to receive")
    ("rxrate", po::value<double>(&rx_rate)->default_value(100e6/4), "rate of incoming samples")
    ("freq", po::value<double>(&freq)->default_value(70e6), "rf center frequency in Hz")
    ("LOoffset", po::value<double>(&LOoffset)->default_value(0), "Offset between main LO and center frequency")
    ("10MHz",po::value<bool>(&use_external_10MHz)->default_value(false), "external 10MHz on 'REF CLOCK' connector (true=1=yes)")
    //  ("PPS",po::value<bool>(&trigger_with_pps)->default_value(false), "trigger reception with 'PPS IN' connector (true=1=yes)")
    ("filename",po::value<std::string>(&filename)->default_value("data_from_usrp.dat"), "output filename")
    ("gain",po::value<float>(&gain)->default_value(5), "set the receiver gain (0-15)")
    ("8bits_scaling",po::value<double>(&scaling_8bits)->default_value(0.0),
     "input scaling (invers) when 8bits is used, set to zero to get 16bits")
    ("realTime",po::value<bool>(&realTime)->default_value(true), "receives in loop and compares with synch sequence")
    ;

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    //print the help message
    if (vm.count("help")) {
        std::cout << boost::format("rx %s") % desc << std::endl;
        return ~0;
    }


    dev_addr["addr0"]="192.168.10.2";
    //dev_addr["addr0"]="192.168.10.2";
    dev = uhd::usrp::multi_usrp::make(dev_addr);

    //dev->set_rx_subdev_spec(uhd::usrp::subdev_spec_t("A:A"), 0); // 60GHz

    stream_args.cpu_format="sc16";
    if (scaling_8bits==0.0) {
        stream_args.otw_format="sc16";
    } else {
        stream_args.otw_format="sc8";
        std::stringstream temp_ss;
        temp_ss << scaling_8bits;
        stream_args.args["peak"]=temp_ss.str();
    };

    rx_stream=dev->get_rx_stream(stream_args);

    uhd::clock_config_t my_clock_config;


    if (use_external_10MHz) {
        my_clock_config.ref_source=uhd::clock_config_t::REF_SMA;
    };

    //print the help message
    if (vm.count("help")) {
        std::cout << boost::format("UHD RX Timed Samples %s") % desc << std::endl;
        return ~0;
    }

    //create a usrp device
    std::cout << std::endl;
    uhd::device::sptr udev = dev->get_device();
    dev->set_rx_rate(rx_rate);
    uhd::tune_request_t trq(freq,LOoffset);
    tr=dev->set_rx_freq(trq);


    uhd::usrp::dboard_iface::sptr db_iface;
    db_iface=dev->get_tx_dboard_iface(0);

    board_60GHz_RX my_60GHz_RX(db_iface);    // 60GHz
    my_60GHz_RX.set_gain(gain);    // 60GHz


    if (use_external_10MHz) {
        dev->set_clock_config(my_clock_config);
        usleep(1e6); // Wait for the 10MHz to lock
    };

    size_t buffer_size=1000; // Select buffer size
    int nStorage=2*total_num_samps;

    dev->set_time_now(uhd::time_spec_t(0.0));

    std::cout << boost::format("Setting device timestamp to 0...") << std::endl;


    //    % total_num_samps % seconds_in_future << std::endl;
    uhd::stream_cmd_t stream_cmd(uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE);



    stream_cmd.num_samps = buffer_size;
    stream_cmd.stream_now = true;

    stream_cmd.stream_mode=uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS;


    dev->issue_stream_cmd(stream_cmd);






    //////////////////////////////////Read data to buff_short and do processing////////////

    //Launch threads
    sem_init(&usrpReady, 0,0);
    sem_init(&detectionReady, 0,0);
    std::thread usrpT(usrpGetData, rx_stream, dev, buffer_size, &my_60GHz_RX);
    std::thread detectionT(detection, buffer_size, nStorage);

    // Set highest priority for usrpT
    sched_param sch;
    int policy;
    pthread_getschedparam(usrpT.native_handle(), &policy, &sch);
    sch.sched_priority = 99;
    if(pthread_setschedparam(usrpT.native_handle(), SCHED_FIFO, &sch)) {
        std::cout << "Failed to setschedparam: " << std::strerror(errno) << '\n';
    }
    // pthread_getschedparam(detectionT.native_handle(), &policy, &sch);
    // sch.sched_priority = 99;
    // if(pthread_setschedparam(detectionT.native_handle(), SCHED_FIFO, &sch)) {
    //     std::cout << "Failed to setschedparam: " << std::strerror(errno) << '\n';
    // }

    std::cout << "Priority set"<< std::endl;

    usrpT.join();
    detectionT.join();

    //finished
    std::cout << std::endl << "Done!" << std::endl << std::endl;

    return 0;
}
예제 #19
0
void BlindOFDM_UHDDevice::run(){

    if(is_sending){
        int num_tx_samps=0;

        while(is_sending){

            //cout << "Send PACKET at time " << tx_timestamp << endl;
            tx_md.start_of_burst = true;
            tx_md.end_of_burst = true;
            tx_md.has_time_spec = true;
            tx_md.time_spec = uhd::time_spec_t(tx_timestamp);
            if(time()>tx_timestamp){
                cout << "WRONG TX TIMESTAMP!!!!!!!!!!!!!!!!" << endl;
                //break;
                while(time()>tx_timestamp)
                        tx_timestamp=tx_timestamp+time_gap;
            }
            num_tx_samps=tx_stream->send(&tx_buff(0), tx_buff.size(), tx_md, tx_timestamp+tx_buff.size()/tx_rate);
            if(tx_buff2!=tx_buff){
                tx_buff=tx_buff2;
            }
            tx_timestamp=tx_timestamp+time_gap;
            tx_md.start_of_burst = false;
            tx_md.end_of_burst = true;
            tx_md.has_time_spec = false;
            tx_stream->send("", 0, tx_md);
            has_sent=true;
        }
        has_sent=false;


    }
    if(is_receiving){

        //uhd::rx_metadata_t rx_md;
        uhd::stream_args_t stream_args("fc64");
        uhd::rx_streamer::sptr rx_stream = usrp->get_rx_stream(stream_args);
        cvec rx_buff2;
        int num_rx_samps=0;
        int lost_samples=500;
        //Receiving mode
        uhd::stream_cmd_t stream_cmd(uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE);
        //allocate buffer with data to receive


         while(is_receiving){
             if(rx_buff_size!=rx_buff.size()){
                 rx_buff_size=rx_buff.size();
                 rx_buff2.set_size(lost_samples+rx_buff_size);
                 rx_buff2.zeros();
                 stream_cmd.num_samps = rx_buff2.size();
                 stream_cmd.stream_now = false;
             }
             //cout << "Receive PACKET at time " << timestamp << endl;
             timestamp=timestamp+time_gap;
             if((previous_correction!=correction)&&(abs(previous_correction-correction)*rx_rate>1)){
                  timestamp=timestamp+correction;
                  previous_correction=correction;

             }
            if(time()>timestamp){
                cout << "WRONG RX TIMESTAMP!!!!!!!!!!!!!!!!" << endl;
                //break;
                while(time()>timestamp)
                        timestamp=timestamp+time_gap;

            }
            stream_cmd.time_spec = uhd::time_spec_t(timestamp-lost_samples/rx_rate);
            usrp->issue_stream_cmd(stream_cmd);
            num_rx_samps=rx_stream->recv(&rx_buff2(0), rx_buff2.size(), rx_md, timestamp-lost_samples/rx_rate,false);
            rx_buff=rx_buff2.get(lost_samples,lost_samples+rx_buff_size-1);

         }

    }


}
예제 #20
0
int UHD_SAFE_MAIN(int argc, char *argv[]){
    uhd::set_thread_priority_safe();

    //variables to be set by po
    std::string args, file;
    size_t total_num_samps;
    double rate, freq, gain;

    //setup the program options
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help", "help message")
        ("args", po::value<std::string>(&args)->default_value(""), "multi uhd device address args")
        ("file", po::value<std::string>(&file)->default_value("out.16sc.dat"), "name of the file to write binary samples to")
        ("nsamps", po::value<size_t>(&total_num_samps)->default_value(1000), "total number of samples to receive")
        ("rate", po::value<double>(&rate)->default_value(100e6/16), "rate of incoming samples")
        ("freq", po::value<double>(&freq)->default_value(0), "rf center frequency in Hz")
        ("gain", po::value<double>(&gain)->default_value(0), "gain for the RF chain")
    ;
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    //print the help message
    if (vm.count("help")){
        std::cout << boost::format("UHD RX samples to file %s") % desc << std::endl;
        return ~0;
    }

    //create a usrp device
    std::cout << std::endl;
    std::cout << boost::format("Creating the usrp device with: %s...") % args << std::endl;
    uhd::usrp::multi_usrp::sptr usrp = uhd::usrp::multi_usrp::make(args);
    std::cout << boost::format("Using Device: %s") % usrp->get_pp_string() << std::endl;

    //set the rx sample rate
    std::cout << boost::format("Setting RX Rate: %f Msps...") % (rate/1e6) << std::endl;
    usrp->set_rx_rate(rate);
    std::cout << boost::format("Actual RX Rate: %f Msps...") % (usrp->get_rx_rate()/1e6) << std::endl << std::endl;

    //set the rx center frequency
    std::cout << boost::format("Setting RX Freq: %f Mhz...") % (freq/1e6) << std::endl;
    usrp->set_rx_freq(freq);
    std::cout << boost::format("Actual RX Freq: %f Mhz...") % (usrp->get_rx_freq()/1e6) << std::endl << std::endl;

    //set the rx rf gain
    std::cout << boost::format("Setting RX Gain: %f dB...") % gain << std::endl;
    usrp->set_rx_gain(gain);
    std::cout << boost::format("Actual RX Gain: %f dB...") % usrp->get_rx_gain() << std::endl << std::endl;

    boost::this_thread::sleep(boost::posix_time::seconds(1)); //allow for some setup time
    std::cout << "LO Locked = " << usrp->get_rx_lo_locked() << std::endl;

    //setup streaming
    uhd::stream_cmd_t stream_cmd(uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE);
    stream_cmd.num_samps = total_num_samps;
    stream_cmd.stream_now = true;
    usrp->issue_stream_cmd(stream_cmd);

    //loop until total number of samples reached
    size_t num_acc_samps = 0; //number of accumulated samples
    uhd::rx_metadata_t md;
    std::vector<std::complex<short> > buff(usrp->get_device()->get_max_recv_samps_per_packet());
    std::ofstream outfile(file.c_str(), std::ofstream::binary);

    while(num_acc_samps < total_num_samps){
        size_t num_rx_samps = usrp->get_device()->recv(
            &buff.front(), buff.size(), md,
            uhd::io_type_t::COMPLEX_INT16,
            uhd::device::RECV_MODE_ONE_PACKET
        );

        //handle the error codes
        switch(md.error_code){
        case uhd::rx_metadata_t::ERROR_CODE_NONE:
            break;

        case uhd::rx_metadata_t::ERROR_CODE_TIMEOUT:
            if (num_acc_samps == 0) continue;
            std::cout << boost::format(
                "Got timeout before all samples received, possible packet loss, exiting loop..."
            ) << std::endl;
            goto done_loop;

        default:
            std::cout << boost::format(
                "Got error code 0x%x, exiting loop..."
            ) % md.error_code << std::endl;
            goto done_loop;
        }

        //write complex short integer samples to the binary file
        outfile.write((const char*)&buff[0], num_rx_samps * sizeof(std::complex<short>));

        num_acc_samps += num_rx_samps;
    } done_loop:

    outfile.close();

    //finished
    std::cout << std::endl << "Done!" << std::endl << std::endl;

    return 0;
}
예제 #21
0
int UHD_SAFE_MAIN(int argc, char *argv[]){
    
    
    if (!(uhd::set_thread_priority_safe(1,true))) {
      std::cout << "Problem setting thread priority" << std::endl;
      return 1;
    };


    //variables to be set by po
    //double seconds_in_future=0.01;
    size_t total_num_samps;
    double rx_rate, freq, LOoffset, rf_freq, clock_freq;
    bool use_external_10MHz;
    double scaling_8bits;
    std::string filename;
    float gain;
    std::string dev_addr_str;
    uhd::device_addr_t dev_addr;
    uhd::usrp::multi_usrp::sptr dev;
    uhd::tune_result_t tr;
    uhd::stream_args_t stream_args;
    uhd::rx_streamer::sptr rx_stream;


    //setup the program options
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help", "help message")
        ("nsamps", po::value<size_t>(&total_num_samps)->default_value(1000), "total number of samples to receive")
        ("rxrate", po::value<double>(&rx_rate)->default_value(100e6/4), "rate of incoming samples")
        ("rf_freq", po::value<double>(&rf_freq)->default_value(60e9), "rf center frequency in Hz of 60GHz RX board")
        ("freq", po::value<double>(&freq)->default_value(60e9), "center frequency at input of basic daughterboard")
        ("LOoffset", po::value<double>(&LOoffset)->default_value(0), "Offset between main LO and center frequency")
        ("10MHz",po::value<bool>(&use_external_10MHz)->default_value(false), "external 10MHz on 'REF CLOCK' connector (true=1=yes)")
      //  ("PPS",po::value<bool>(&trigger_with_pps)->default_value(false), "trigger reception with 'PPS IN' connector (true=1=yes)")
        ("filename",po::value<std::string>(&filename)->default_value("data_from_usrp.dat"), "output filename") 
        ("gain",po::value<float>(&gain)->default_value(0), "set the receiver gain (0-15)") 
        ("8bits_scaling",po::value<double>(&scaling_8bits)->default_value(0.0), 
    "input scaling (invers) when 8bits is used, set to zero to get 16bits")
       ("dev_addr",po::value<std::string>(&dev_addr_str)->default_value("192.168.10.2"), 
    "IP address of USRP")
("clock_freq", po::value<double>(&clock_freq)->default_value(285.714), "Clock frequency of CLK board")

    ;
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    dev_addr["addr0"]=dev_addr_str;
    dev = uhd::usrp::multi_usrp::make(dev_addr);


    //create a usrp device
    std::cout << std::endl;
    uhd::device::sptr udev = dev->get_device();
    dev->set_rx_rate(rx_rate);
    uhd::tune_request_t trq(freq,LOoffset); 
    tr=dev->set_rx_freq(trq);

    uhd::usrp::dboard_iface::sptr db_iface;
    db_iface=dev->get_tx_dboard_iface(0);
       
    board_60GHz_RX my_60GHz_RX(db_iface,clock_freq);    // 60GHz
    my_60GHz_RX.set_gain(gain);    // 60GHz
    if (rf_freq!=64e9) {
      my_60GHz_RX.set_freq(rf_freq);    // 60GHz
    };


    uhd::clock_config_t my_clock_config; 

    if (use_external_10MHz) {
      dev->set_clock_config(my_clock_config); 
      usleep(1e6); // Wait for the 10MHz to lock
    }; 


    if (scaling_8bits<0) {


      stream_args.cpu_format="sc16";
      stream_args.otw_format="sc16";     
      rx_stream=dev->get_rx_stream(stream_args);
      std::complex<int16_t> *d_buffer_rx;


    uhd::stream_cmd_t stream_cmd(uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE);    

      uint32_t buffer_size=rx_stream->get_max_num_samps();
      stream_cmd.num_samps = buffer_size;
      stream_cmd.stream_now = true;    
      stream_cmd.stream_mode=uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS;

      std::cout << "buffer_size=" << buffer_size << "\n";


      d_buffer_rx = new std::complex<int16_t>[buffer_size];   
      rx_stream->issue_stream_cmd(stream_cmd);


       uhd::rx_metadata_t md;
       size_t num_rx_samps_latest_call=0;             
       while (num_rx_samps_latest_call==0) {
	  num_rx_samps_latest_call= 
	   rx_stream->recv(&d_buffer_rx[0],buffer_size, md, 3.0);
       };


      

       double max_value=0.0;
       double new_value;
       for (uint32_t i2=10;i2<num_rx_samps_latest_call;i2++){ 
	  new_value=abs(d_buffer_rx[i2]);
	  if (new_value>max_value) {
	      max_value=new_value;
	  };
       };
       
       std::cout << "max_value=" << max_value << "\n";
       scaling_8bits=max_value*3.0518e-05*abs(scaling_8bits);
       if (scaling_8bits<0.0039062)
	 scaling_8bits=0.0039062;
       std::cout << "scaling_8bits=" << scaling_8bits << "\n";

    };






    stream_args.cpu_format="sc16";
    if (scaling_8bits==0.0) {
      stream_args.otw_format="sc16";     
    } else {
      stream_args.otw_format="sc8";
      std::stringstream temp_ss;
      temp_ss << scaling_8bits;
      stream_args.args["peak"]=temp_ss.str();
    };

    rx_stream=dev->get_rx_stream(stream_args);


    if (use_external_10MHz) { 
      my_clock_config.ref_source=uhd::clock_config_t::REF_SMA; 
    }; 

    //print the help message
    if (vm.count("help")){
        std::cout << boost::format("rx_60GHz %s") % desc << std::endl;
        return ~0;
    }


    size_t buffer_size=1000; // Select buffer size
    short *buff_short, *storage_short;
    storage_short=new short[2*total_num_samps]; // Create storage for the 
    // entire received signal to be saved on disk.
    buff_short=new short[2*buffer_size]; // Create storage for a single 
                                                // buffer


    //    dev->set_time_now(uhd::time_spec_t(0.0));
    //std::cout << boost::format("Setting device timestamp to 0...") << std::endl;

    uhd::stream_cmd_t stream_cmd(uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE);    
    
    stream_cmd.num_samps = total_num_samps; //buffer_size;
    stream_cmd.stream_now = true;
    dev->issue_stream_cmd(stream_cmd);


    size_t num_rx_samps=0;
    size_t num_rx_samps_latest_call;

    uhd::rx_metadata_t md;
    while (num_rx_samps<total_num_samps) {
 

       num_rx_samps_latest_call=0;             
       while (num_rx_samps_latest_call==0) {
	 num_rx_samps_latest_call= 
	   rx_stream->recv(&buff_short[0],buffer_size, md, 3.0);
       };

       stream_cmd.stream_mode=uhd::stream_cmd_t::STREAM_MODE_STOP_CONTINUOUS;
       dev->issue_stream_cmd(stream_cmd);


       /* Process the just received buffer */
       int i1=2*num_rx_samps;
       int i2=0;
       while ((i1<(int) (2*total_num_samps)) && (i2<2*((int) num_rx_samps_latest_call ))) 
       {	  
	  storage_short[i1]=buff_short[i2];
	  i1++; i2++;
       };
	 

       num_rx_samps=num_rx_samps+num_rx_samps_latest_call;
    };




    //finished
    std::cout << std::endl << "Done!" << std::endl << std::endl; 

    // Save output to disc
    std::ofstream s1(filename.c_str(), std::ios::binary);   


    s1.write((char *) storage_short,4*total_num_samps); 
    s1.flush(); //PZ
    s1.close(); //PZ



    return 0;
}