#!/usr/bin/env python
#
# Copyright 2006 Martin Dudok van Heel (nldudok1_olifantasia_com).
#(for my emailadres look at http://www.olifantasia.com/gnuradio/ under Contact.
#You can also try at nldudok1_olifantasia_com but I don't check this email regularly because it is bombarded with spam)
# 
# 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., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
# 
from gnuradio import gr, gru, eng_notation, optfir
from gnuradio import audio
from gnuradio import usrp
from gnuradio import blks

import drm_rcv
"""
drm_rcv.py is expected in this directory
"""
from gnuradio.eng_option import eng_option
from gnuradio.wxgui import slider, powermate
from gnuradio.wxgui import stdgui, fftsink, form
from optparse import OptionParser
import usrp_dbid
import sys
import math
import wx
import os
import signal

def pick_subdevice(u):
    """
    The user didn't specify a subdevice on the command line.
    Try for one of these, in order: TV_RX, BASIC_RX, whatever is on side A.

    @return a subdev_spec
    """
    return usrp.pick_subdev(u, (usrp_dbid.TV_RX,
                                usrp_dbid.TV_RX_REV_2,
                                usrp_dbid.BASIC_RX))

class dream_wrapper:
    def __init__(self,dream_executable_name,fifo_filename): 
        print "start dream_wrapper"
        fifo_filename='/tmp/fifo'
        self.dream_executable_name='dream'
        os.spawnlp(os.P_WAIT, 'rm', 'rm',fifo_filename)
        os.spawnlp(os.P_WAIT, 'mkfifo', 'mkfifo',fifo_filename)
        self.dream_pid= os.spawnlp(os.P_NOWAIT, self.dream_executable_name, self.dream_executable_name,"-f",fifo_filename)  
        print "dream pid is",self.dream_pid
    def __del__(self):
        print "killing ",self.dream_executable_name," with pid ",self.dream_pid, "using SIGTERM (",signal.SIGTERM,")"
        os.kill(self.dream_pid,signal.SIGTERM)
        #print "killing all dream instances"
        #os.spawnlp(os.P_WAIT, 'killall', 'killall',self.dream_executable_name)

class drm_rx_graph (stdgui.gui_flow_graph):
    def __init__(self,frame,panel,vbox,argv):
        stdgui.gui_flow_graph.__init__ (self,frame,panel,vbox,argv)

        parser=OptionParser(option_class=eng_option)
        parser.add_option("-R", "--rx-subdev-spec", type="subdev", default=None,
                          help="select USRP Rx side A or B (default=A)")
        parser.add_option("-f", "--freq", type="eng_float", default=1440.0e3,
                          help="set frequency to FREQ", metavar="FREQ")
        parser.add_option("-c", "--chan", type="int", default=8,
                          help="set channel to CHAN", metavar="CHAN")
        parser.add_option("-d", "--dream", default="dream",
                          help="set dream executable name (default is dream). If that doesn't exist, try drm.")
        parser.add_option( "--fifo", default="/tmp/fifo",
                          help="set fifo filename for streaming to dream (default is /tmp/fifo)")
        parser.add_option("-g", "--gain", type="eng_float", default=20,
                          help="set gain in dB (default is midpoint)")

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

        self.dream=dream_wrapper(options.dream,options.fifo)

        #frequencies extracted from  DRMSchedule.ini
        self.freq_list=[177, 594, 693, 729, 855, 1008, 1296, 1386, 1440, 1485, 1530, 1575,
          1593, 1611, 3995, 5875, 5905, 5970, 5990, 6015, 6060, 6065, 6080, 6095,
          6105, 6130, 6175, 7145, 7240, 7275, 7295, 7300, 7320, 7340, 7370, 7465,
          9470, 9655, 9750, 9760, 9790, 9800, 9815, 9850, 9880, 9890, 11615, 11635,
          11675, 13590, 13620, 13770, 13810, 15425, 15440, 15605, 15720, 15725,
          15896, 17675, 17860, 25695, 25775, 25795, 26000, 26012, 26045]
        self.frame = frame
        self.panel = panel
        self.if_offset=9.0e3
        self.state = "FREQ"
        self.freq = 0
        self.chan = 0
        # build graph
        usrp_decim = 250        
        self.u = usrp.source_c(decim_rate=usrp_decim)                    # usrp is data source
        adc_rate = self.u.adc_rate()                # 64 MS/s

        self.u.set_decim_rate(usrp_decim)
        usrp_rate = adc_rate / usrp_decim           # 320 kS/s

        if options.rx_subdev_spec is None:
            options.rx_subdev_spec = pick_subdevice(self.u)

        self.u.set_mux(usrp.determine_rx_mux_value(self.u, options.rx_subdev_spec))
        self.subdev = usrp.selected_subdev(self.u, options.rx_subdev_spec)
        print "Using RX d'board %s" % (self.subdev.side_and_name(),)

        self.guts = drm_rcv.drm_rcv (self, usrp_rate,options.dream,self.if_offset,options.fifo)
 
        # now wire it all together
        self.connect (self.u, self.guts)
        self._build_gui(vbox, usrp_rate, self.guts.if_rate, self.guts.out_rate)

        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

        if abs(options.freq) < 1e3:
            options.freq *= 1e3

        # set initial values

        self.set_gain(options.gain)
        #if not(self.set_freq(options.freq)):
        #    self._set_status_msg("Failed to set initial frequency")
        self.set_channel(options.chan)
        self.myform['chan_slider'].set_value(options.chan)  # update displayed value

    
    def _set_status_msg(self, msg, which=0):
        self.frame.GetStatusBar().SetStatusText(msg, which)

    def _build_gui(self, vbox, usrp_rate, demod_rate, audio_rate):

        def _form_set_freq(kv):
            return self.set_freq(kv['freq'])

        self.src_fft=None
        if 0:
            self.src_fft = fftsink.fft_sink_c (self, self.panel, title="Data from USRP",
                                               fft_size=512, sample_rate=usrp_rate,average=True)
            self.connect (self.u, self.src_fft)
            vbox.Add (self.src_fft.win, 4, wx.EXPAND)

        self.zero_if_fft=None
        if 0:
            self.zero_if_fft = fftsink.fft_sink_c (self, self.panel, title="IF 1", 
                                                fft_size=512, sample_rate=demod_rate,
                                                y_per_div=20, ref_level=40,average=True)
            self.connect (self.guts.resampler, self.zero_if_fft)
            vbox.Add (self.zero_if_fft.win, 4, wx.EXPAND)

        if 0:
            if_12kHz_fft = fftsink.fft_sink_f (self, self.panel, title="IF 2  12 kHz sent to dream",
                                                  fft_size=512, sample_rate=audio_rate,
                                                  y_per_div=20, ref_level=80,average=True)
            self.connect (self.guts.c2f, if_12kHz_fft)
            vbox.Add (if_12kHz_fft.win, 4, wx.EXPAND)

        
        # control area form at bottom
        self.myform = myform = form.form()

        hbox = wx.BoxSizer(wx.HORIZONTAL)
        hbox.Add((5,0), 0)
        myform['freq'] = form.float_field(
            parent=self.panel, sizer=hbox, label="Freq", weight=1,
            callback=myform.check_input_and_call(_form_set_freq, self._set_status_msg))

        hbox.Add((5,0), 0)
        myform['chan_slider'] = \
            form.quantized_slider_field(parent=self.panel,label="Chan", sizer=hbox, weight=3,
                                        range=(0, len(self.freq_list), 1),
                                        callback=self.set_channel)
        hbox.Add((5,0), 0)
        vbox.Add(hbox, 0, wx.EXPAND)

        hbox = wx.BoxSizer(wx.HORIZONTAL)
        hbox.Add((5,0), 0)

        myform['gain'] = \
            form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Gain",
                                        weight=3, range=self.subdev.gain_range(),
                                        callback=self.set_gain)
        hbox.Add((5,0), 0)
        vbox.Add(hbox, 0, wx.EXPAND)

        try:
            self.knob = powermate.powermate(self.frame)
            self.rot = 0
            powermate.EVT_POWERMATE_ROTATE (self.frame, self.on_rotate)
            powermate.EVT_POWERMATE_BUTTON (self.frame, self.on_button)
        except:
            print "FYI: No Powermate or Contour Knob found"


    def on_rotate (self, event):
        self.rot += event.delta
        if self.rot >= 3:
            self.set_freq(self.freq + .1e6)
            self.rot -= 3
        elif self.rot <=-3:
            self.set_freq(self.freq - .1e6)
            self.rot += 3
            
    def on_button (self, event):
        if event.value == 0:        # button up
            return
        self.rot = 0
        self.update_status_bar ()

    def set_channel(self, target_chan):
        self.chan=target_chan
        self.set_freq(self.freq_list[int(target_chan)]*1.0e3)
        #self.myform['chan_slider'].set_value(target_chan)  # update displayed value
                                        
    def set_freq(self, target_freq):
        """
        Set the center frequency we're interested in.

        @param target_freq: frequency in Hz
        @rypte: bool

        Tuning is a two step process.  First we ask the front-end to
        tune as close to the desired frequency as it can.  Then we use
        the result of that operation and our target_frequency to
        determine the value for the digital down converter.
        """
        r = usrp.tune(self.u, 0, self.subdev, target_freq+self.if_offset)
        
        if r:
            self.freq = target_freq
            self.myform['freq'].set_value(target_freq)         # update displayed value
            #self.myform['chan_slider'].set_value(target_freq)  # update displayed value
            self.update_status_bar()
            self._set_status_msg("OK", 0)
            return True

        self._set_status_msg("Failed", 0)
        return False

    def set_gain(self, gain):
        self.gain=gain
        self.myform['gain'].set_value(gain)     # update displayed value
        self.subdev.set_gain(gain)
        self.update_status_bar()

    def update_status_bar (self):
        msg = "Chan: %i Freq: %f Gain: %f" % (self.chan,self.freq,self.gain)
        self._set_status_msg(msg, 1)
        if self.src_fft:
          self.src_fft.set_baseband_freq(self.freq+self.if_offset)
        if self.zero_if_fft:
          self.zero_if_fft.set_baseband_freq(self.freq+self.if_offset)
        

if __name__ == '__main__':

    app = stdgui.stdapp (drm_rx_graph, "USRP DRM RX")
    app.MainLoop ()

