#!/usr/bin/env python

"""
Read samples file formatted as binary and output to the USRP
single-precision complex values.

"""

from gnuradio import gr, eng_notation
from gnuradio import audio
from gnuradio import usrp
from gnuradio.eng_option import eng_option
from optparse import OptionParser

class my_graph(gr.flow_graph):

    def __init__(self):
        gr.flow_graph.__init__(self)

        usage="%prog: [options] input_filename"
        parser = OptionParser(option_class=eng_option, usage=usage)
        parser.add_option("-R", "--tx-subdev-spec", type="subdev", default=(0, 0),
                          help="select USRP Rx side A or B (default=A)")
        parser.add_option ("-i", "--interp", type="int", default=64,
                       help="set fgpa interpolation rate to INTERP")
        parser.add_option("-f", "--freq", type="eng_float", default=None,
                          help="set frequency to FREQ", metavar="FREQ")
        parser.add_option("-g", "--gain", type="eng_float", default=None,
                          help="set gain in dB (default is midpoint)")
        parser.add_option("-N", "--nsamples", type="eng_float", default=None,
                          help="number of samples to send [default=+inf]")
        (options, args) = parser.parse_args ()
        if len(args) != 1:
            parser.print_help()
            raise SystemExit, 1
        filename = args[0]

        if options.freq is None:
            parser.print_help()
            sys.stderr.write('You must specify the frequency with -f FREQ\n');
            raise SystemExit, 1

        # build the graph
        self.src = gr.file_source(gr.sizeof_gr_complex, filename, True)

        self.u = usrp.sink_c (0, options.interp)


        # choose the daughterboard subdevice
        if options.tx_subdev_spec is None:
            options.tx_subdev_spec = usrp.pick_tx_subdevice(self.u)

        # determine the daughterboard subdevice we're using
        self.subdev = usrp.selected_subdev(self.u, options.tx_subdev_spec)
        print "Using TX d'board %s" % (self.subdev.side_and_name(),)
        output_rate = (self.u.dac_freq()) / self.u.interp_rate()
        print "USB sample rate %s" % (eng_notation.num_to_str(output_rate))

        #self.waveform_type = gr.GR_CONST_WAVE
        #self.waveform_ampl = 16000 #options.amplitude
        #self.waveform_freq = 100.1234e3 #15625 #100.12345e3
        #self.waveform_offset = 0

        #self.src = gr.sig_source_c (output_rate,
        #                               gr.GR_SIN_WAVE,
        #                               self.waveform_freq,
        #                               self.waveform_ampl,
        #                               self.waveform_offset)
        if options.nsamples is None:
            self.connect(self.src, self.u)
        else:
            self.head = gr.head(gr.sizeof_gr_complex, int(options.nsamples))
            self.connect(self.src, self.head, self.u)
        if options.gain is None:
            # if no gain was specified, use the mid-point in dB
            g = self.subdev.gain_range()
            options.gain = float(g[0]+g[1])/2
            print g
        self.subdev.set_gain(options.gain)
        self.subdev.set_enable(True)
        r = self.u.tune(0, self.subdev, options.freq)
        if not r:
            sys.stderr.write('Failed to set frequency\n')
            raise SystemExit, 1

        
if __name__ == '__main__':
    try:
        my_graph().run()
    except KeyboardInterrupt:
        pass

