summaryrefslogtreecommitdiff
path: root/gr-uhd
diff options
context:
space:
mode:
Diffstat (limited to 'gr-uhd')
-rw-r--r--gr-uhd/doc/uhd.dox5
-rw-r--r--gr-uhd/examples/c++/tag_source_demo.h46
-rw-r--r--gr-uhd/examples/c++/tags_demo.cc8
-rwxr-xr-xgr-uhd/examples/python/freq_hopping.py216
-rw-r--r--gr-uhd/grc/gen_uhd_usrp_blocks.py29
-rw-r--r--gr-uhd/include/gnuradio/uhd/usrp_sink.h79
-rw-r--r--gr-uhd/lib/usrp_sink_impl.cc321
-rw-r--r--gr-uhd/lib/usrp_sink_impl.h30
-rw-r--r--gr-uhd/python/uhd/qa_uhd.py8
-rw-r--r--gr-uhd/swig/uhd_swig.i15
10 files changed, 668 insertions, 89 deletions
diff --git a/gr-uhd/doc/uhd.dox b/gr-uhd/doc/uhd.dox
index 4cd30a86b6..538c98c438 100644
--- a/gr-uhd/doc/uhd.dox
+++ b/gr-uhd/doc/uhd.dox
@@ -1,3 +1,4 @@
+// vim: set ft=doxygen:
/*! \page page_uhd UHD Interface
\section Introduction
@@ -27,12 +28,12 @@ Ettus Research keeps the comprehensive documentation to the underlying UHD drive
http://files.ettus.com/uhd_docs/manual/html/
-The UHD Doxygen page is located:
+The UHD Doxygen page is located at:
http://files.ettus.com/uhd_docs/doxygen/html/index.html
-\section Typical Setup
+\section Configuring a UHD object
A typical option parser setup for a UHD device looks like
diff --git a/gr-uhd/examples/c++/tag_source_demo.h b/gr-uhd/examples/c++/tag_source_demo.h
index 71fb94482a..8508c32680 100644
--- a/gr-uhd/examples/c++/tag_source_demo.h
+++ b/gr-uhd/examples/c++/tag_source_demo.h
@@ -35,7 +35,8 @@ public:
const double start_fracs,
const double samp_rate,
const double idle_duration,
- const double burst_duration
+ const double burst_duration,
+ const std::string &length_tag_name = ""
):
sync_block(
"uhd tag source demo",
@@ -48,7 +49,9 @@ public:
_samps_per_burst(samp_rate*burst_duration),
_cycle_duration(idle_duration + burst_duration),
_samps_left_in_burst(1), //immediate EOB
- _do_new_burst(false)
+ _do_new_burst(false),
+ _firstrun(not length_tag_name.empty()),
+ _length_tag_key(length_tag_name.empty() ? pmt::PMT_NIL : pmt::string_to_symbol(length_tag_name))
{
//NOP
}
@@ -80,6 +83,19 @@ public:
this->add_item_tag(0/*chan0*/, tag_count, key, value, srcid);
}
+ void make_length_tag(const uint64_t tag_count, const uint64_t burst_len)
+ {
+ if (pmt::is_null(_length_tag_key)) {
+ //no length_tag was specified at initialization; make a tx_sob tag instead
+ this->make_sob_tag(tag_count);
+ return;
+ }
+ const pmt::pmt_t key = _length_tag_key;
+ const pmt::pmt_t value = pmt::from_long((long)burst_len);
+ const pmt::pmt_t srcid = pmt::string_to_symbol(this->name());
+ this->add_item_tag(0/*chan0*/, tag_count, key, value, srcid);
+ }
+
int work(
int noutput_items,
gr_vector_const_void_star &input_items,
@@ -87,18 +103,29 @@ public:
{
//load the output with a constant
std::complex<float> *output = reinterpret_cast<std::complex<float> *>(output_items[0]);
- for (size_t i = 0; i < size_t(noutput_items); i++){
+ for (size_t i = 0; i < size_t(noutput_items); i++) {
output[i] = std::complex<float>(0.7, 0.7);
}
//Handle the start of burst condition.
//Tag a start of burst and timestamp.
//Increment the time for the next burst.
- if (_do_new_burst){
+ if (_do_new_burst) {
_do_new_burst = false;
_samps_left_in_burst = _samps_per_burst;
- this->make_sob_tag(this->nitems_written(0));
+ if (pmt::is_null(_length_tag_key))
+ this->make_sob_tag(this->nitems_written(0));
+ else
+#if 1
+ this->make_length_tag(this->nitems_written(0), _samps_left_in_burst);
+#else
+ //Test usrp_sink's ability to cancel remainder of burst if new length_tag is found early
+ //sets burst time to 10% greater than the cycle duration to guarantee early length_tag
+ //In a real implementation the user should guard against this so that the number of
+ //samples promised by the length_tag are actually processed by the usrp_sink.
+ this->make_length_tag(this->nitems_written(0), uint64_t(1.1 * _samp_rate * _cycle_duration));
+#endif
this->make_time_tag(this->nitems_written(0));
_time_fracs += _cycle_duration;
@@ -111,7 +138,12 @@ public:
//Tag an end of burst and return early.
//the next work call will be a start of burst.
if (_samps_left_in_burst < size_t(noutput_items)){
- this->make_eob_tag(this->nitems_written(0) + _samps_left_in_burst - 1);
+ if (pmt::is_null(_length_tag_key))
+ this->make_eob_tag(this->nitems_written(0) + _samps_left_in_burst - 1);
+ else if (_firstrun){
+ _firstrun = false;
+ this->make_length_tag(this->nitems_written(0), 1);
+ }
_do_new_burst = true;
noutput_items = _samps_left_in_burst;
}
@@ -128,5 +160,7 @@ private:
const double _cycle_duration;
uint64_t _samps_left_in_burst;
bool _do_new_burst;
+ bool _firstrun;
+ const pmt::pmt_t _length_tag_key;
};
diff --git a/gr-uhd/examples/c++/tags_demo.cc b/gr-uhd/examples/c++/tags_demo.cc
index 0f87109109..787e3d2e4b 100644
--- a/gr-uhd/examples/c++/tags_demo.cc
+++ b/gr-uhd/examples/c++/tags_demo.cc
@@ -43,7 +43,7 @@ void sig_int_handler(int){stop_signal_called = true;}
**********************************************************************/
int main(int argc, char *argv[]){
- std::string device_addr;
+ std::string device_addr, length_tag;
double center_freq, samp_rate, burst_dur, idle_dur;
//setup the program options
@@ -55,6 +55,7 @@ int main(int argc, char *argv[]){
("freq", po::value<double>(&center_freq)->default_value(10e6), "the center frequency in Hz")
("burst", po::value<double>(&burst_dur)->default_value(0.1), "the duration of each burst in seconds")
("idle", po::value<double>(&idle_dur)->default_value(0.05), "idle time between bursts in seconds")
+ ("length_tag", po::value<std::string>(&length_tag)->default_value(""), "the length tag key name")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
@@ -95,14 +96,15 @@ int main(int argc, char *argv[]){
//-- make the usrp sink test blocks
//------------------------------------------------------------------
gr::uhd::usrp_sink::sptr usrp_sink = gr::uhd::usrp_sink::make
- (device_addr, uhd::stream_args_t("fc32"));
+ (device_addr, uhd::stream_args_t("fc32"), length_tag);
usrp_sink->set_samp_rate(samp_rate);
usrp_sink->set_center_freq(center_freq);
const uhd::time_spec_t time_now = usrp_sink->get_time_now();
+ const double actual_samp_rate = usrp_sink->get_samp_rate();
boost::shared_ptr<tag_source_demo> tag_source = boost::make_shared<tag_source_demo>(
time_now.get_full_secs() + 1, time_now.get_frac_secs(), //time now + 1 second
- samp_rate, idle_dur, burst_dur
+ actual_samp_rate, idle_dur, burst_dur, length_tag
);
//------------------------------------------------------------------
diff --git a/gr-uhd/examples/python/freq_hopping.py b/gr-uhd/examples/python/freq_hopping.py
new file mode 100755
index 0000000000..3b4c426976
--- /dev/null
+++ b/gr-uhd/examples/python/freq_hopping.py
@@ -0,0 +1,216 @@
+#!/usr/bin/env python
+#
+# Copyright 2014 Free Software Foundation, Inc.
+#
+# This file is part of GNU Radio
+#
+# GNU Radio is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3, or (at your option)
+# any later version.
+#
+# GNU Radio is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with GNU Radio; see the file COPYING. If not, write to
+# the Free Software Foundation, Inc., 51 Franklin Street,
+# Boston, MA 02110-1301, USA.
+#
+
+"""
+TXs a waveform (either from a file, or a sinusoid) in a frequency-hopping manner.
+"""
+
+import time
+import numpy
+import argparse
+import pmt
+from gnuradio import gr
+from gnuradio import blocks
+from gnuradio import uhd
+
+def setup_parser():
+ """ Setup the parser for the frequency hopper. """
+ parser = argparse.ArgumentParser(
+ description="Transmit a signal in a frequency-hopping manner, using tx_freq tags."
+ )
+ parser.add_argument('-i', '--input-file', type=file, default=None,
+ help="File with samples to transmit. If left out, will transmit a sinusoid.")
+ parser.add_argument("-a", "--args", default="",
+ help="UHD device address args.")
+ parser.add_argument("--spec", default="",
+ help="UHD subdev spec.")
+ parser.add_argument("--antenna", default="",
+ help="UHD antenna settings.")
+ parser.add_argument("--gain", default=None, type=float,
+ help="USRP gain (defaults to mid-point in dB).")
+ parser.add_argument("-r", "--rate", type=float, default=1e6,
+ help="Sampling rate")
+ parser.add_argument("-N", "--samp-per-burst", type=int, default=10000,
+ help="Samples per burst")
+ parser.add_argument("-t", "--hop-time", type=float, default=1000,
+ help="Time between hops in milliseconds. This must be larger than or equal to the burst duration as set by --samp-per-burst")
+ parser.add_argument("-f", "--freq", type=float, default=2.45e9,
+ help="Base frequency. This is the lowest frequency at which the USRP will Tx.")
+ parser.add_argument("-d", "--freq-delta", type=float, default=1e6,
+ help="Channel spacing.")
+ parser.add_argument("-c", "--num-channels", type=int, default=5,
+ help="Number of channels.")
+ parser.add_argument("-B", "--num-bursts", type=int, default=30,
+ help="Number of bursts to transmit before terminating.")
+ parser.add_argument("-p", "--post-tuning", action='count',
+ help="Tune after transmitting. Default is to tune immediately before transmitting.")
+ parser.add_argument("-v", "--verbose", action='count',
+ help="Print more information.")
+ return parser
+
+
+class FrequencyHopperSrc(gr.hier_block2):
+ """ Provides tags for frequency hopping """
+ def __init__(
+ self,
+ n_bursts, n_channels,
+ freq_delta, base_freq,
+ burst_length, base_time, hop_time,
+ post_tuning=False,
+ tx_gain=0,
+ verbose=False
+ ):
+ gr.hier_block2.__init__(self,
+ "FrequencyHopperSrc",
+ gr.io_signature(1, 1, gr.sizeof_gr_complex),
+ gr.io_signature(1, 1, gr.sizeof_gr_complex),
+ )
+ n_samples_total = n_bursts * burst_length
+ self.hop_sequence = numpy.arange(base_freq, base_freq + n_channels * freq_delta, freq_delta)
+ numpy.random.shuffle(self.hop_sequence)
+ self.hop_sequence = [self.hop_sequence[x % n_channels] for x in xrange(n_bursts)]
+ if verbose:
+ print "Hop Frequencies | Hop Pattern"
+ print "=================|================================"
+ for f in self.hop_sequence:
+ print "{:6.3f} MHz | ".format(f/1e6),
+ if n_channels < 50:
+ print " " * int((f - base_freq) / freq_delta) + "#"
+ else:
+ print "\n"
+ print "=================|================================"
+ # There's no real point in setting the gain via tag for this application,
+ # but this is an example to show you how to do it.
+ gain_tag = gr.tag_t()
+ gain_tag.offset = 0
+ gain_tag.key = pmt.string_to_symbol('tx_command')
+ gain_tag.value = pmt.cons(
+ pmt.intern("gain"),
+ pmt.to_pmt((0, tx_gain))
+ )
+ tag_list = [gain_tag,]
+ for i in xrange(n_bursts):
+ tune_tag = gr.tag_t()
+ tune_tag.offset = i * burst_length
+ if i > 0 and post_tuning:
+ tune_tag.offset -= 1 # Move it to last sample of previous burst
+ tune_tag.key = pmt.string_to_symbol('tx_freq')
+ tune_tag.value = pmt.to_pmt((0, self.hop_sequence[i]))
+ tag_list.append(tune_tag)
+ length_tag = gr.tag_t()
+ length_tag.offset = i * burst_length
+ length_tag.key = pmt.string_to_symbol('packet_len')
+ length_tag.value = pmt.from_long(burst_length)
+ tag_list.append(length_tag)
+ time_tag = gr.tag_t()
+ time_tag.offset = i * burst_length
+ time_tag.key = pmt.string_to_symbol('tx_time')
+ time_tag.value = pmt.make_tuple(
+ pmt.from_uint64(int(base_time + i * hop_time)),
+ pmt.from_double((base_time + i * hop_time) % 1),
+ )
+ tag_list.append(time_tag)
+ tag_source = blocks.vector_source_c((1.0,) * n_samples_total, repeat=False, tags=tag_list)
+ mult = blocks.multiply_cc()
+ self.connect(self, mult, self)
+ self.connect(tag_source, (mult, 1))
+
+
+class FlowGraph(gr.top_block):
+ """ Flow graph that does the frequency hopping. """
+ def __init__(self, options):
+ gr.top_block.__init__(self)
+
+ if options.input_file is not None:
+ src = blocks.file_source(gr.sizeof_gr_complex, options.filename, repeat=True)
+ else:
+ src = blocks.vector_source_c((.5,) * int(1e6) * 2, repeat=True)
+ # Setup USRP
+ self.u = uhd.usrp_sink(options.args, uhd.stream_args('fc32'), "packet_len")
+ if(options.spec):
+ self.u.set_subdev_spec(options.spec, 0)
+ if(options.antenna):
+ self.u.set_antenna(options.antenna, 0)
+ self.u.set_samp_rate(options.rate)
+ # Gain is set in the hopper block
+ if options.gain is None:
+ g = self.u.get_gain_range()
+ options.gain = float(g.start()+g.stop())/2.0
+ print "-- Setting gain to {} dB".format(options.gain)
+ r = self.u.set_center_freq(options.freq)
+ if not r:
+ print '[ERROR] Failed to set base frequency.'
+ raise SystemExit, 1
+ hopper_block = FrequencyHopperSrc(
+ options.num_bursts, options.num_channels,
+ options.freq_delta, options.freq,
+ options.samp_per_burst, 1.0, options.hop_time / 1000.,
+ options.post_tuning,
+ options.gain,
+ options.verbose,
+ )
+ self.connect(src, hopper_block, self.u)
+
+def print_hopper_stats(args):
+ """ Nothing to do with Grace Hopper """
+ print """
+Parameter | Value
+===================+=========================
+Hop Interval | {hop_time} ms
+Burst duration | {hop_duration} ms
+Lowest Frequency | {lowest_freq:6.3f} MHz
+Highest Frequency | {highest_freq:6.3f} MHz
+Frequency spacing | {freq_delta:6.4f} MHz
+Number of channels | {num_channels}
+Sampling rate | {rate} Msps
+Transmit Gain | {gain} dB
+===================+=========================
+ """.format(
+ hop_time=args.hop_time,
+ hop_duration=1000.0/args.rate*args.samp_per_burst,
+ gain=args.gain,
+ lowest_freq=args.freq/1e6,
+ highest_freq=(args.freq + (args.num_channels-1) * args.freq_delta)/1e6,
+ freq_delta=args.freq_delta/1e6,
+ num_channels=args.num_channels,
+ rate=args.rate/1e6,
+ )
+
+def main():
+ """ Go, go, go! """
+ args = setup_parser().parse_args()
+ if (1.0 * args.samp_per_burst / args.rate) > args.hop_time * 1e-3:
+ print "Burst duration must be smaller than hop time."
+ raise SystemExit, 1
+ if args.verbose:
+ print_hopper_stats(args)
+ top_block = FlowGraph(args)
+ print "Starting to hop, skip and jump... press Ctrl+C to exit."
+ top_block.u.set_time_now(uhd.time_spec(0.0))
+ top_block.run()
+
+if __name__ == '__main__':
+ try:
+ main()
+ except KeyboardInterrupt:
+ pass
+
diff --git a/gr-uhd/grc/gen_uhd_usrp_blocks.py b/gr-uhd/grc/gen_uhd_usrp_blocks.py
index f80a7ee26e..5981bb4c89 100644
--- a/gr-uhd/grc/gen_uhd_usrp_blocks.py
+++ b/gr-uhd/grc/gen_uhd_usrp_blocks.py
@@ -27,8 +27,8 @@ MAIN_TMPL = """\
<import>from gnuradio import uhd</import>
<import>import time</import>
<make>uhd.usrp_$(sourk)(
- device_addr=\$dev_addr,
- stream_args=uhd.stream_args(
+ \$dev_addr,
+ uhd.stream_args(
cpu_format="\$type",
\#if \$otw()
otw_format=\$otw,
@@ -41,7 +41,7 @@ MAIN_TMPL = """\
\#else
channels=range(\$nchan),
\#end if
- ),
+ ),$lentag_arg
)
\#if \$clock_rate()
self.\$(id).set_clock_rate(\$clock_rate, uhd.ALL_MBOARDS)
@@ -165,7 +165,7 @@ self.\$(id).set_bandwidth(\$bw$(n), $n)
<param>
<name>Device Addr</name>
<key>dev_addr</key>
- <value></value>
+ <value>""</value>
<type>string</type>
<hide>
\#if \$dev_addr()
@@ -373,6 +373,10 @@ To use the default bandwidth filter setting, this should be zero. \\
Only certain subdevices have configurable bandwidth filters. \\
See the daughterboard application notes for possible configurations.
+Length tag key (Sink only):
+When a nonempty string is given, the USRP sink will look for length tags \\
+to determine transmit burst lengths.
+
See the UHD manual for more detailed documentation:
http://code.ettus.com/redmine/ettus/projects/uhd/wiki
</doc>
@@ -426,6 +430,18 @@ PARAMS_TMPL = """
</param>
"""
+LENTAG_PARAM = """ <param>
+ <name>Length tag name</name>
+ <key>len_tag_name</key>
+ <value></value>
+ <type>string</type>
+ </param>"""
+
+LENTAG_ARG = """
+ #if $len_tag_name()
+ $len_tag_name,
+ #end if"""
+
def parse_tmpl(_tmpl, **kwargs):
from Cheetah import Template
return str(Template.Template(_tmpl, kwargs))
@@ -445,7 +461,12 @@ if __name__ == '__main__':
else: raise Exception, 'is %s a source or sink?'%file
params = ''.join([parse_tmpl(PARAMS_TMPL, n=n) for n in range(max_num_channels)])
+ if sourk == 'sink':
+ params += LENTAG_PARAM
+ lentag_arg = LENTAG_ARG
+ else: lentag_arg = ''
open(file, 'w').write(parse_tmpl(MAIN_TMPL,
+ lentag_arg=lentag_arg,
max_nchan=max_num_channels,
max_mboards=max_num_mboards,
params=params,
diff --git a/gr-uhd/include/gnuradio/uhd/usrp_sink.h b/gr-uhd/include/gnuradio/uhd/usrp_sink.h
index 18640fe902..35bb2e4384 100644
--- a/gr-uhd/include/gnuradio/uhd/usrp_sink.h
+++ b/gr-uhd/include/gnuradio/uhd/usrp_sink.h
@@ -27,6 +27,7 @@
#include <gnuradio/sync_block.h>
#include <uhd/usrp/multi_usrp.hpp>
+// TODO In 3.8, UHD 3.4 will be required and we can remove all these ifdefs
#ifndef INCLUDED_UHD_STREAM_HPP
namespace uhd {
struct GR_UHD_API stream_args_t
@@ -60,36 +61,16 @@ namespace gr {
typedef boost::shared_ptr<usrp_sink> sptr;
/*!
- * \brief Make a new USRP sink block.
- * \ingroup uhd_blk
- *
- * The USRP sink block reads a stream and transmits the samples.
- * The sink block also provides API calls for transmitter settings.
- *
- * TX Stream tagging:
- *
- * The following tag keys will be consumed by the work function:
- * - pmt::string_to_symbol("tx_sob")
- * - pmt::string_to_symbol("tx_eob")
- * - pmt::string_to_symbol("tx_time")
- *
- * The sob and eob (start and end of burst) tag values are pmt booleans.
- * When present, burst tags should be set to true (pmt::PMT_T).
- *
- * The timstamp tag value is a pmt tuple of the following:
- * (uint64 seconds, and double fractional seconds).
+ * \brief DEPRECATED Make a new USRP sink block using the deprecated io_type_t.
*
- * See the UHD manual for more detailed documentation:
- * http://code.ettus.com/redmine/ettus/projects/uhd/wiki
+ * This function will be removed in the future. Please use the other make function,
+ * gr::uhd::make(const ::uhd::device_addr_t, const ::uhd::stream_args_t, const std::string).
*
- * \param device_addr the address to identify the hardware
- * \param io_type the desired input data type
- * \param num_channels number of stream from the device
- * \return a new USRP sink block object
+ * \ingroup uhd_blk
*/
static sptr make(const ::uhd::device_addr_t &device_addr,
- const ::uhd::io_type_t &io_type,
- size_t num_channels);
+ const ::uhd::io_type_t &io_type,
+ size_t num_channels);
/*!
* \brief Make a new USRP sink block.
@@ -97,28 +78,68 @@ namespace gr {
* The USRP sink block reads a stream and transmits the samples.
* The sink block also provides API calls for transmitter settings.
*
- * TX Stream tagging:
+ * \section uhd_tx_tagging TX Stream tagging
*
* The following tag keys will be consumed by the work function:
* - pmt::string_to_symbol("tx_sob")
* - pmt::string_to_symbol("tx_eob")
* - pmt::string_to_symbol("tx_time")
+ * - pmt::string_to_symbol("tx_freq")
+ * - pmt::string_to_symbol("tx_command")
+ * - pmt::string_to_symbol(length_tag_name)
+ *
+ * Any other tag will be ignored.
*
* The sob and eob (start and end of burst) tag values are pmt booleans.
* When present, burst tags should be set to true (pmt::PMT_T).
*
- * The timstamp tag value is a pmt tuple of the following:
+ * If length_tag_name is not an empty string, all "tx_sob" and "tx_eob"
+ * tags will be ignored, and the input is assumed to a tagged stream,
+ * as described in \ref page_tagged_stream_blocks.
+ * The length tag value should be a PMT long specifying the number
+ * of samples contained in the corresponding tagged stream.
+ *
+ * If sob/eob tags or length tags are used, this block understands that
+ * the data is bursty, and will configure the USRP to make sure there's
+ * no underruns etc.
+ *
+ * The timestamp tag value is a PMT tuple of the following:
* (uint64 seconds, and double fractional seconds).
*
+ * The tx_freq tag has to be a double, and will issue a tune command to the USRP
+ * to the given frequency, if possible. Note that oscillators need some time
+ * to stabilize after this! Don't expect clean data to be sent immediately after this command.
+ *
+ * The command tag can carry a PMT command. See the following section.
+ *
+ * \section uhd_commands Command interface
+ *
+ * There are two ways of passing commands to this block:
+ * 1) tx_command tag. The command is attached to a sample, and will executed
+ * before the sample is transmitted, and after the previous sample.
+ * 2) The 'command' message port. The command is executed asynchronously,
+ * as soon as possible.
+ *
+ * In both cases, the payload of the command is a PMT pair, with the first
+ * item ('car') being the command name, and second ('cdr') the command value.
+ *
+ * Command name | Command value
+ * -------------|--------------------------------------------------------------------------
+ * `freq` | Tuple: (chan, new_freq). Requests a tune to `new_freq` on channel `chan`.
+ * `lo_offset` | Tuple: (chan, lo_offset). Adds a LO offset on channel `chan`.
+ * `gain` | Tuple: (chan, gain). Requests a gain change to `gain` on channel `chan`.
+ *
* See the UHD manual for more detailed documentation:
* http://code.ettus.com/redmine/ettus/projects/uhd/wiki
*
* \param device_addr the address to identify the hardware
* \param stream_args the IO format and channel specification
+ * \param length_tag_name the name of the tag identifying tagged stream length
* \return a new USRP sink block object
*/
static sptr make(const ::uhd::device_addr_t &device_addr,
- const ::uhd::stream_args_t &stream_args);
+ const ::uhd::stream_args_t &stream_args,
+ const std::string &length_tag_name = "");
/*!
* Set the start time for outgoing samples.
diff --git a/gr-uhd/lib/usrp_sink_impl.cc b/gr-uhd/lib/usrp_sink_impl.cc
index 828537fab3..b6a98391be 100644
--- a/gr-uhd/lib/usrp_sink_impl.cc
+++ b/gr-uhd/lib/usrp_sink_impl.cc
@@ -20,19 +20,20 @@
* Boston, MA 02110-1301, USA.
*/
+#include <climits>
+#include <stdexcept>
#include "usrp_sink_impl.h"
#include "gr_uhd_common.h"
#include <gnuradio/io_signature.h>
#include <boost/make_shared.hpp>
-#include <stdexcept>
namespace gr {
namespace uhd {
usrp_sink::sptr
usrp_sink::make(const ::uhd::device_addr_t &device_addr,
- const ::uhd::io_type_t &io_type,
- size_t num_channels)
+ const ::uhd::io_type_t &io_type,
+ size_t num_channels)
{
//fill in the streamer args
::uhd::stream_args_t stream_args;
@@ -44,35 +45,55 @@ namespace gr {
stream_args.otw_format = "sc16"; //only sc16 known to work
for(size_t chan = 0; chan < num_channels; chan++)
- stream_args.channels.push_back(chan); //linear mapping
+ stream_args.channels.push_back(chan); //linear mapping
- return usrp_sink::make(device_addr, stream_args);
+ return usrp_sink::make(device_addr, stream_args, "");
}
usrp_sink::sptr
usrp_sink::make(const ::uhd::device_addr_t &device_addr,
- const ::uhd::stream_args_t &stream_args)
+ const ::uhd::stream_args_t &stream_args,
+ const std::string &length_tag_name)
{
check_abi();
return usrp_sink::sptr
- (new usrp_sink_impl(device_addr, stream_args_ensure(stream_args)));
+ (new usrp_sink_impl(device_addr, stream_args_ensure(stream_args), length_tag_name));
}
usrp_sink_impl::usrp_sink_impl(const ::uhd::device_addr_t &device_addr,
- const ::uhd::stream_args_t &stream_args)
+ const ::uhd::stream_args_t &stream_args,
+ const std::string &length_tag_name)
: sync_block("gr uhd usrp sink",
args_to_io_sig(stream_args),
io_signature::make(0, 0, 0)),
_stream_args(stream_args),
_nchan(stream_args.channels.size()),
- _stream_now(_nchan == 1),
- _start_time_set(false)
+ _stream_now(_nchan == 1 and length_tag_name.empty()),
+ _start_time_set(false),
+ _length_tag_key(length_tag_name.empty() ? pmt::PMT_NIL : pmt::string_to_symbol(length_tag_name)),
+ _nitems_to_send(0),
+ _curr_freq(stream_args.channels.size(), 0.0),
+ _curr_lo_offset(stream_args.channels.size(), 0.0),
+ _curr_gain(stream_args.channels.size(), 0.0),
+ _chans_to_tune(stream_args.channels.size(), false),
+ _call_tune(false)
{
if(stream_args.cpu_format == "fc32")
_type = boost::make_shared< ::uhd::io_type_t >(::uhd::io_type_t::COMPLEX_FLOAT32);
if(stream_args.cpu_format == "sc16")
_type = boost::make_shared< ::uhd::io_type_t >(::uhd::io_type_t::COMPLEX_INT16);
_dev = ::uhd::usrp::multi_usrp::make(device_addr);
+
+ message_port_register_in(pmt::mp("command"));
+ set_msg_handler(
+ pmt::mp("command"),
+ boost::bind(&usrp_sink_impl::msg_handler_command, this, _1)
+ );
+ //message_port_register_in(pmt::mp("query"));
+ //set_msg_handler(
+ //pmt::mp("query"),
+ //boost::bind(&usrp_sink_impl::msg_handler_query, this, _1)
+ //);
}
usrp_sink_impl::~usrp_sink_impl()
@@ -133,10 +154,40 @@ namespace gr {
usrp_sink_impl::set_center_freq(const ::uhd::tune_request_t tune_request,
size_t chan)
{
+ _curr_freq[chan] = tune_request.target_freq;
+ if (tune_request.rf_freq_policy == ::uhd::tune_request_t::POLICY_MANUAL) {
+ _curr_lo_offset[chan] = tune_request.rf_freq - tune_request.target_freq;
+ } else {
+ _curr_lo_offset[chan] = 0.0;
+ }
chan = _stream_args.channels[chan];
return _dev->set_tx_freq(tune_request, chan);
}
+ ::uhd::tune_result_t
+ usrp_sink_impl::_set_center_freq_from_internals(size_t chan)
+ {
+ _chans_to_tune[chan] = false;
+ if (_curr_lo_offset[chan] == 0.0) {
+ return _dev->set_tx_freq(_curr_freq[chan], _stream_args.channels[chan]);
+ } else {
+ return _dev->set_tx_freq(
+ ::uhd::tune_request_t(_curr_freq[chan], _curr_lo_offset[chan]),
+ _stream_args.channels[chan]
+ );
+ }
+ }
+
+ void
+ usrp_sink_impl::_set_center_freq_from_internals_allchans()
+ {
+ for (size_t chan = 0; chan < _nchan; chan++) {
+ if (_chans_to_tune[chan]) {
+ _set_center_freq_from_internals(chan);
+ }
+ }
+ }
+
double
usrp_sink_impl::get_center_freq(size_t chan)
{
@@ -154,6 +205,7 @@ namespace gr {
void
usrp_sink_impl::set_gain(double gain, size_t chan)
{
+ _curr_gain[chan] = gain;
chan = _stream_args.channels[chan];
return _dev->set_tx_gain(gain, chan);
}
@@ -163,6 +215,7 @@ namespace gr {
const std::string &name,
size_t chan)
{
+ _curr_gain[chan] = gain;
chan = _stream_args.channels[chan];
return _dev->set_tx_gain(gain, name, chan);
}
@@ -464,9 +517,9 @@ namespace gr {
gr_vector_const_void_star &input_items,
gr_vector_void_star &output_items)
{
- int ninput_items = noutput_items; //cuz its a sync block
+ int ninput_items = noutput_items; //cuz it's a sync block
- //send a mid-burst packet with time spec
+ // default to send a mid-burst packet
_metadata.start_of_burst = false;
_metadata.end_of_burst = false;
@@ -476,6 +529,27 @@ namespace gr {
if(not _tags.empty())
this->tag_work(ninput_items);
+ if(not pmt::is_null(_length_tag_key)) {
+ //check if there is data left to send from a burst tagged with length_tag
+ //If a burst is started during this call to work(), tag_work() should have
+ //been called and we should have _nitems_to_send > 0.
+ if (_nitems_to_send > 0) {
+ ninput_items = std::min<long>(_nitems_to_send, ninput_items);
+ //if we run out of items to send, it's the end of the burst
+ if(_nitems_to_send - long(ninput_items) == 0)
+ _metadata.end_of_burst = true;
+ }
+ else {
+ //There is a tag gap since no length_tag was found immediately following
+ //the last sample of the previous burst. Drop samples until the next
+ //length_tag is found. Notify the user of the tag gap.
+ std::cerr << "tG" << std::flush;
+ //increment the timespec by the number of samples dropped
+ _metadata.time_spec += ::uhd::time_spec_t(0, ninput_items, _sample_rate);
+ return ninput_items;
+ }
+ }
+
#ifdef GR_UHD_USE_STREAM_API
//send all ninput_items with metadata
const size_t num_sent = _tx_stream->send
@@ -486,8 +560,20 @@ namespace gr {
*_type, ::uhd::device::SEND_MODE_FULL_BUFF, 1.0);
#endif
+ //if using length_tags, decrement items left to send by the number of samples sent
+ if(not pmt::is_null(_length_tag_key) and _nitems_to_send > 0) {
+ _nitems_to_send -= long(num_sent);
+ }
+
//increment the timespec by the number of samples sent
_metadata.time_spec += ::uhd::time_spec_t(0, num_sent, _sample_rate);
+
+ // Some post-processing tasks if we actually transmitted the entire burst
+ if (_call_tune and num_sent == size_t(ninput_items)) {
+ _set_center_freq_from_internals_allchans();
+ _call_tune = false;
+ }
+
return num_sent;
}
@@ -501,54 +587,156 @@ namespace gr {
std::sort(_tags.begin(), _tags.end(), tag_t::offset_compare);
//extract absolute sample counts
- const tag_t &tag0 = _tags.front();
- const uint64_t tag0_count = tag0.offset;
const uint64_t samp0_count = this->nitems_read(0);
-
- //only transmit nsamples from 0 to the first tag
- //this ensures that the next work starts on a tag
- if(samp0_count != tag0_count) {
- ninput_items = tag0_count - samp0_count;
- return;
- }
-
- //time will not be set unless a time tag is found
- _metadata.has_time_spec = false;
-
- //process all of the tags found with the same count as tag0
+ uint64_t max_count = samp0_count + ninput_items;
+
+ // Go through tag list until something indicates the end of a burst.
+ bool found_time_tag = false;
+ bool found_eob = false;
+ bool found_freq_tag_in_burst = false;
+ uint64_t freq_cmd_offset = 0;
+ double freq_cmd_freq;
+ int freq_cmd_chan;
BOOST_FOREACH(const tag_t &my_tag, _tags) {
const uint64_t my_tag_count = my_tag.offset;
const pmt::pmt_t &key = my_tag.key;
const pmt::pmt_t &value = my_tag.value;
- //determine how many samples to send...
- //from zero until the next tag or end of work
- if(my_tag_count != tag0_count) {
- ninput_items = my_tag_count - samp0_count;
+ if (my_tag_count >= max_count) {
break;
}
-
- //handle end of burst with a mini end of burst packet
- else if(pmt::equal(key, EOB_KEY)) {
- _metadata.end_of_burst = pmt::to_bool(value);
- ninput_items = 1;
- return;
- }
-
- //set the start of burst flag in the metadata
- else if(pmt::equal(key, SOB_KEY)) {
- _metadata.start_of_burst = pmt::to_bool(value);
+ else if (not pmt::is_null(_length_tag_key) and my_tag_count > samp0_count + _nitems_to_send) {
+ break;
+ }
+
+ /* I. Bursts that can only be on the first sample of burst
+ *
+ * This includes:
+ * - tx_time
+ * - tx_command
+ * - tx_sob
+ * - length tags
+ *
+ * With these tags, we check if they're on the first item, otherwise,
+ * we stop before that tag so they are on the first item the next time round.
+ */
+ else if (pmt::equal(key, COMMAND_KEY)) {
+ if (my_tag_count != samp0_count) {
+ max_count = my_tag_count;
+ break;
+ }
+ msg_handler_command(value);
}
//set the time specification in the metadata
else if(pmt::equal(key, TIME_KEY)) {
+ if (my_tag_count != samp0_count) {
+ max_count = my_tag_count;
+ break;
+ }
+ found_time_tag = true;
_metadata.has_time_spec = true;
_metadata.time_spec = ::uhd::time_spec_t
(pmt::to_uint64(pmt::tuple_ref(value, 0)),
pmt::to_double(pmt::tuple_ref(value, 1)));
}
+
+ //set the start of burst flag in the metadata; ignore if length_tag_key is not null
+ else if(pmt::is_null(_length_tag_key) and pmt::equal(key, SOB_KEY)) {
+ if (my_tag.offset != samp0_count) {
+ max_count = my_tag_count;
+ break;
+ }
+ // Bursty tx will not use time specs, unless a tx_time tag is also given.
+ _metadata.has_time_spec = false;
+ _metadata.start_of_burst = pmt::to_bool(value);
+ }
+
+ //length_tag found; set the start of burst flag in the metadata
+ else if(not pmt::is_null(_length_tag_key) and pmt::equal(key, _length_tag_key)) {
+ if (my_tag_count != samp0_count) {
+ max_count = my_tag_count;
+ break;
+ }
+ //If there are still items left to send, the current burst has been preempted.
+ //Set the items remaining counter to the new burst length. Notify the user of
+ //the tag preemption.
+ else if(_nitems_to_send > 0) {
+ std::cerr << "tP" << std::flush;
+ }
+ _nitems_to_send = pmt::to_long(value);
+ _metadata.start_of_burst = true;
+ }
+
+ /* II. Bursts that can be on the first OR last sample of a burst
+ *
+ * This includes:
+ * - tx_freq (tags that don't actually change the frequency are ignored)
+ *
+ * With these tags, we check if they're at the start of a burst, and do
+ * the appropriate action. Otherwise, make sure the corresponding sample
+ * is the last one.
+ */
+ else if (pmt::equal(key, FREQ_KEY) and my_tag_count == samp0_count) {
+ int chan = pmt::to_long(pmt::tuple_ref(value, 0));
+ double new_freq = pmt::to_double(pmt::tuple_ref(value, 1));
+ if (new_freq != _curr_freq[chan]) {
+ _curr_freq[chan] = new_freq;
+ _set_center_freq_from_internals(chan);
+ }
+ }
+
+ else if(pmt::equal(key, FREQ_KEY) and not found_freq_tag_in_burst) {
+ int chan = pmt::to_long(pmt::tuple_ref(value, 0));
+ double new_freq = pmt::to_double(pmt::tuple_ref(value, 1));
+ if (new_freq != _curr_freq[chan]) {
+ freq_cmd_freq = new_freq;
+ freq_cmd_chan = chan;
+ freq_cmd_offset = my_tag_count;
+ max_count = my_tag_count + 1;
+ found_freq_tag_in_burst = true;
+ }
+ }
+
+ /* III. Bursts that can only be on the last sample of a burst
+ *
+ * This includes:
+ * - tx_eob
+ *
+ * Make sure that no more samples are allowed through.
+ */
+ else if(pmt::is_null(_length_tag_key) and pmt::equal(key, EOB_KEY)) {
+ found_eob = true;
+ max_count = my_tag_count + 1;
+ _metadata.end_of_burst = pmt::to_bool(value);
+ }
+ } // end foreach
+
+ if(not pmt::is_null(_length_tag_key) and long(max_count - samp0_count) == _nitems_to_send) {
+ found_eob = true;
}
- }
+
+ if (found_freq_tag_in_burst) {
+ if (not found_eob) {
+ // If it's in the middle of a burst, only send() until before the tag
+ max_count = freq_cmd_offset;
+ } else if (freq_cmd_offset < max_count) {
+ // Otherwise, tune after work()
+ _curr_freq[freq_cmd_chan] = freq_cmd_freq;
+ _chans_to_tune[freq_cmd_chan] = true;
+ _call_tune = true;
+ }
+ }
+
+ if (found_time_tag) {
+ _metadata.has_time_spec = true;
+ }
+
+ // Only transmit up to and including end of burst,
+ // or everything if no burst boundaries are found.
+ ninput_items = int(max_count - samp0_count);
+
+ } // end tag_work()
void
usrp_sink_impl::set_start_time(const ::uhd::time_spec_t &time)
@@ -569,7 +757,9 @@ namespace gr {
_metadata.start_of_burst = true;
_metadata.end_of_burst = false;
- _metadata.has_time_spec = not _stream_now;
+ // Bursty tx will need to send a tx_time to activate time spec
+ _metadata.has_time_spec = not _stream_now and pmt::is_null(_length_tag_key);
+ _nitems_to_send = 0;
if(_start_time_set) {
_start_time_set = false; //cleared for next run
_metadata.time_spec = _start_time;
@@ -597,6 +787,7 @@ namespace gr {
_metadata.start_of_burst = false;
_metadata.end_of_burst = true;
_metadata.has_time_spec = false;
+ _nitems_to_send = 0;
#ifdef GR_UHD_USE_STREAM_API
_tx_stream->send(gr_vector_const_void_star(_nchan), 0, _metadata, 1.0);
@@ -608,6 +799,50 @@ namespace gr {
return true;
}
+
+ /************** External interfaces (RPC + Message passing) ********************/
+ // Helper function for msg_handler_command: Extracts chan and command value from
+ // the 2-tuple in cmd_val, updates the value in vector_to_update[chan] and returns
+ // true if it was different from the old value.
+ bool _unpack_chan_command(pmt::pmt_t &cmd_val, int &chan, std::vector<double> &vector_to_update)
+ {
+ chan = pmt::to_long(pmt::tuple_ref(cmd_val, 0));
+ double new_value = pmt::to_double(pmt::tuple_ref(cmd_val, 1));
+ if (new_value == vector_to_update[chan]) {
+ return false;
+ } else {
+ vector_to_update[chan] = new_value;
+ return true;
+ }
+ }
+
+ void usrp_sink_impl::msg_handler_command(pmt::pmt_t msg)
+ {
+ const std::string command(pmt::symbol_to_string(pmt::car(msg)));
+ pmt::pmt_t value(pmt::cdr(msg));
+ int chan = 0;
+ if (command == "freq") {
+ if (_unpack_chan_command(value, chan, _curr_freq)) {
+ _set_center_freq_from_internals(chan);
+ }
+ } else if (command == "lo_offset") {
+ if (_unpack_chan_command(value, chan, _curr_lo_offset)) {
+ _set_center_freq_from_internals(chan);
+ }
+ } else if (command == "gain") {
+ if (_unpack_chan_command(value, chan, _curr_gain)) {
+ set_gain(_curr_gain[chan], chan);
+ }
+ } else {
+ GR_LOG_ALERT(d_logger, boost::format("Received unknown command: %s") % command);
+ }
+ }
+
+ void usrp_sink_impl::msg_handler_query(pmt::pmt_t msg)
+ {
+ //tbi
+ }
+
void
usrp_sink_impl::setup_rpc()
{
diff --git a/gr-uhd/lib/usrp_sink_impl.h b/gr-uhd/lib/usrp_sink_impl.h
index c714eb53eb..12a25658e3 100644
--- a/gr-uhd/lib/usrp_sink_impl.h
+++ b/gr-uhd/lib/usrp_sink_impl.h
@@ -1,6 +1,6 @@
/* -*- c++ -*- */
/*
- * Copyright 2010-2013 Free Software Foundation, Inc.
+ * Copyright 2010-2014 Free Software Foundation, Inc.
*
* This file is part of GNU Radio
*
@@ -26,6 +26,8 @@
static const pmt::pmt_t SOB_KEY = pmt::string_to_symbol("tx_sob");
static const pmt::pmt_t EOB_KEY = pmt::string_to_symbol("tx_eob");
static const pmt::pmt_t TIME_KEY = pmt::string_to_symbol("tx_time");
+static const pmt::pmt_t FREQ_KEY = pmt::string_to_symbol("tx_freq");
+static const pmt::pmt_t COMMAND_KEY = pmt::string_to_symbol("tx_command");
namespace gr {
namespace uhd {
@@ -53,7 +55,8 @@ namespace gr {
{
public:
usrp_sink_impl(const ::uhd::device_addr_t &device_addr,
- const ::uhd::stream_args_t &stream_args);
+ const ::uhd::stream_args_t &stream_args,
+ const std::string &length_tag_name);
~usrp_sink_impl();
void setup_rpc();
@@ -119,6 +122,15 @@ namespace gr {
inline void tag_work(int &ninput_items);
private:
+ //! Like set_center_freq(), but uses _curr_freq and _curr_lo_offset
+ ::uhd::tune_result_t _set_center_freq_from_internals(size_t chan);
+ //! Calls _set_center_freq_from_internals() on all channels
+ void _set_center_freq_from_internals_allchans();
+ //! Receives commands and handles them
+ void msg_handler_command(pmt::pmt_t msg);
+ //! Receives queries and posts a response
+ void msg_handler_query(pmt::pmt_t msg);
+
::uhd::usrp::multi_usrp::sptr _dev;
const ::uhd::stream_args_t _stream_args;
boost::shared_ptr< ::uhd::io_type_t > _type;
@@ -135,6 +147,20 @@ namespace gr {
//stream tags related stuff
std::vector<tag_t> _tags;
+ const pmt::pmt_t _length_tag_key;
+ long _nitems_to_send;
+
+ //! Stores the last value we told the USRP to tune to for every channel
+ // (this is not necessarily the true value the USRP is currently tuned to!).
+ // We could theoretically ask the device, but during streaming, we want to minimize
+ // communication with the USRP.
+ std::vector<double> _curr_freq;
+ //! Stores the last value we told the USRP to have the LO offset for every channel.
+ std::vector<double> _curr_lo_offset;
+ //! Stores the last gain value we told the USRP to have for every channel.
+ std::vector<double> _curr_gain;
+ std::vector<bool> _chans_to_tune;
+ bool _call_tune;
};
} /* namespace uhd */
diff --git a/gr-uhd/python/uhd/qa_uhd.py b/gr-uhd/python/uhd/qa_uhd.py
index 511c098753..4df0d4273e 100644
--- a/gr-uhd/python/uhd/qa_uhd.py
+++ b/gr-uhd/python/uhd/qa_uhd.py
@@ -35,6 +35,14 @@ class test_uhd(gr_unittest.TestCase):
They may not have a UHD device connected, etc. Don't try to run anything"""
pass
+ def test_time_spec_t (self):
+ seconds = 42.0
+ time = uhd.time_spec_t(seconds)
+ twice_time = time + time;
+ zero_time = time - time;
+ self.assertEqual(time.get_real_secs() * 2, seconds * 2 )
+ self.assertEqual(time.get_real_secs() - time.get_real_secs() , 0.0)
+
def test_stream_args_channel_foo(self):
"""
Try to manipulate the stream args channels for proper swig'ing checks.
diff --git a/gr-uhd/swig/uhd_swig.i b/gr-uhd/swig/uhd_swig.i
index c98416f307..4eaef9112d 100644
--- a/gr-uhd/swig/uhd_swig.i
+++ b/gr-uhd/swig/uhd_swig.i
@@ -84,6 +84,21 @@
%include <uhd/types/time_spec.hpp>
+%extend uhd::time_spec_t{
+ uhd::time_spec_t __add__(const uhd::time_spec_t &what)
+ {
+ uhd::time_spec_t temp = *self;
+ temp += what;
+ return temp;
+ }
+ uhd::time_spec_t __sub__(const uhd::time_spec_t &what)
+ {
+ uhd::time_spec_t temp = *self;
+ temp -= what;
+ return temp;
+ }
+};
+
%include <uhd/types/stream_cmd.hpp>
%include <uhd/types/clock_config.hpp>