#!/usr/bin/env python
#
# Copyright 2005 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 2, 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., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
#

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

from gr_socket import *

#
# return a gr.flow_graph
#
def build_graph (IF_freq, address, port):
    adc_rate = 64e6
    decim = 250
    quad_rate = adc_rate / decim               # 256 kHz
    audio_decimation = 8
    audio_rate = quad_rate / audio_decimation  # 32 kHz

    fg = gr.flow_graph ()
    
    # usrp is data source
    src = usrp.source_c (0, decim)
    src.set_rx_freq (0, -IF_freq)

    # create socket client
    (sink, fd) = make_socket_sink(address,
                                  port,
                                  gr.sizeof_gr_complex)
    
    fg.connect (src, sink)

    # very important to keep fd in scope of run thread
    return (fg,fd)

def main ():
    usage = "usage: %prog [options]"
    parser = OptionParser(option_class=eng_option, usage=usage)
    parser.add_option("-i", "--address", type="string",
                      help="spectify the ip address to connect to",default="localhost")
    parser.add_option("-p", "--port", type="int",
                      help="spectify the port to connect to",default=8881)
    parser.add_option("-f", "--freq1", type="eng_float",
                      help="Set usrp freq",default=88.1e6)
    (options, args) = parser.parse_args()

    # connect to RF front end
    rf_front_end = gr.microtune_4937_eval_board ()
    if not rf_front_end.board_present_p ():
        raise IOError, 'RF front end not found'

    # set front end gain
    rf_front_end.set_AGC (300)
    IF_freq = rf_front_end.get_output_freq ()
    IF_freq = 5.75e6

    rf_front_end.set_RF_freq (freq1)
    (fg,fd) = build_graph (IF_freq, options.address, options.port)

    fg.start ()        # fork thread(s) and return
    raw_input ('Press Enter to quit: ')
    fg.stop ()

if __name__ == '__main__':
    main ()
