#!/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, gru
from mrts import blks
from gnuradio import usrp
from gnuradio import eng_notation
from gnuradio.eng_option import eng_option
from optparse import OptionParser

import random
import struct

# from current dir


#import os
#print os.getpid()
#raw_input('Attach and press enter')

# /////////////////////////////////////////////////////////////////////////////
#                              receive path
# /////////////////////////////////////////////////////////////////////////////

class receive_path(gr.hier_block):
	def __init__(self, fg, sub_spec, decim, rx_callback, log_p):

		threshold = -1     # use system default
        
		self.u = usrp.source_c(decim_rate=decim)
		adc_rate = self.u.adc_rate()
		actual_decim = self.u.decim_rate()

		if sub_spec is None:
			sub_spec = usrp.pick_rx_subdevice(self.u)
		self.subdev = usrp.selected_subdev(self.u, sub_spec)
		print "Using RX d'board %s" % (self.subdev.side_and_name(),)

		self.u.set_mux(usrp.determine_rx_mux_value(self.u, sub_spec))

		# receiver
		self.packet_receiver = blks.ask_demod_pkts(fg, callback=rx_callback,
													threshold=threshold)

		fg.connect(self.u, self.packet_receiver)
		gr.hier_block.__init__(self, fg, None, None)

		if log_p:
			self._add_logging(fg)

	def _add_logging(self, fg):
		self.u.before = gr.file_sink (gr.sizeof_float, "before2.dat")
		fg.connect(self.u.gmsk_demod.adj, self.u.before)
		self.u.after = gr.file_sink (gr.sizeof_float, "after2.dat")
		fg.connect(self.u.gmsk_demod.clock_recovery, self.u.after)

class my_graph(gr.flow_graph):

    def __init__(self, rx_subdev_spec, decim_rate, rx_callback, log):
        gr.flow_graph.__init__(self)
        self.rxpath = receive_path(self, rx_subdev_spec, decim_rate,
                                   rx_callback, log)

# /////////////////////////////////////////////////////////////////////////////
#                                   main
# /////////////////////////////////////////////////////////////////////////////

global n_rcvd, n_right

def main():
    global n_rcvd, n_right

    n_rcvd = 0
    n_right = 0
    
    def rx_callback(ok, payload):
        global n_rcvd, n_right
        (pktno,) = struct.unpack('!H', payload[0:2])
        n_rcvd += 1
        if ok:
            n_right += 1

        print "ok = %r  pktno = %4d  n_rcvd = %4d  n_right = %4d" % (
            ok, pktno, n_rcvd, n_right)

    parser = OptionParser (option_class=eng_option)
    parser.add_option("-R", "--rx-subdev-spec", type="subdev", default=(0, 0),
                      help="select USRP Rx side A or B")
    parser.add_option("-F", "--fcar", type="eng_float", default=3600.0,
                          help="set carrier frequency to FREQ", metavar="FREQ")
    parser.add_option("-d", "--decim", type="int", default=250,
                      help="set fpga decim rate to DECIM [default=%default]")
    parser.add_option("","--log", action="store_true", default=False,
                      help="enable diagnostic logging")
    (options, args) = parser.parse_args ()

    if len(args) != 0:
        parser.print_help()
        sys.exit(1)

    # build the graph
    fg = my_graph(options.rx_subdev_spec, options.decim, rx_callback, options.log)

    fg.start()        # start flow graph
    fg.wait()         # wait for it to finish

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        pass
