#!/usr/bin/env python

from gnuradio import gr
from gnuradio import usrp
from gnuradio.eng_option import eng_option
from optparse import OptionParser

from wxPython.wx import *
import time

#### Dont bother explicitly assigning these, just get a new one for each ID_ #########
ID_ABOUT = wxNewId()
ID_EXIT  = wxNewId()
ID_TIMER = wxNewId()
ID_AMPL  = wxNewId()
ID_FREQ  = wxNewId()
ID_LED1  = wxNewId()
ID_LED2  = wxNewId()
ID_START  = wxNewId()
ID_STOP   = wxNewId()


class MyFrame(wxFrame):


 
    def __init__(self, parent, id, title):
        # First, call the base class' __init__ method to create the frame
        
	
	wxFrame.__init__(self, parent, id, title)

	
	
	
	

	
	
	
	
	
	
		
	
	
	
#### Make a 500ms timer tick for repetitively reading the registers in the USRP ######        
	self.t = None
        tid = wxNewId()
        self.tim = wxTimer(self, tid)
        self.tim.Start(10000, False)
        EVT_TIMER(self, tid, self.OnTimer)
#### End of creating the 500ms timer tick ############################################scp
	
#### Add a panel and some controls to display the size and position ##########
        panel = wxPanel(self, -1)
        AmplLabel = wxStaticText(panel, -1, "Amplitude (mv)",(wxPoint)(10, 15))
        FreqLabel = wxStaticText(panel, -1, "Frequency (kHz)", (wxPoint)(75, 180))
	
        self.AmplCtrl = wxTextCtrl(panel, ID_AMPL, "",(wxPoint)(10, 40),
	 (wxSize)(40,20), wxTE_PROCESS_ENTER)
        self.FreqCtrl = wxTextCtrl(panel, ID_FREQ, "",(wxPoint)(175, 175),
	 (wxSize)(50,20), wxTE_PROCESS_ENTER)
        self.panel = panel

#### Add the slider for amplitude and frequency next #########################        
 	AmplSlider = wxSlider(panel, -1, 0, 0, 1000, (70, 10), (100,
	115), wxSL_VERTICAL | wxSL_TOP | wxSL_AUTOTICKS | wxSL_LABELS |
	wxTRANSPARENT_WINDOW)

 	FreqSlider = wxSlider(panel, -1, 1000, 0, 10000, (25, 142), (350,
	-1), wxSL_HORIZONTAL | wxSL_TOP | wxSL_AUTOTICKS | wxSL_LABELS |
	wxTRANSPARENT_WINDOW)
	
#### Add the button group for controlling bits on the USRP ###################	
	led1 = wxButton(panel, ID_LED1, "LED1", (250, 10), (50, 25))
	led2 = wxButton(panel, ID_LED2, "LED2", (250, 40), (50, 25))
	spr1 = wxButton(panel, ID_START, "Start", (250, 70), (50, 25))
	spr2 = wxButton(panel, ID_STOP, "Stop", (250, 100), (50, 25))
	
	SinButn  = wxRadioButton(panel, -1, "Sine",     (155, 10), (70,25))
	SqrButn  = wxRadioButton(panel, -1, "Square",   (155, 30), (70,25))
	TriButn  = wxRadioButton(panel, -1, "Triangle", (155, 50), (70,25))
	
	panel.SetBackgroundColour("sky blue")	
        
        self.CreateStatusBar()
        self.SetStatusText("statusbar")
        menu = wxMenu()
        menu.Append(ID_ABOUT, "&About",
                    "More information about this program")
        menu.AppendSeparator()
        menu.Append(ID_EXIT, "E&xit", "Terminate the program")
        menuBar = wxMenuBar()
        menuBar.Append(menu, "&File");
        self.SetMenuBar(menuBar)

        EVT_MENU(self, ID_ABOUT, self.OnAbout)
        EVT_MENU(self, ID_EXIT,  self.TimeToQuit)
	EVT_BUTTON(self, ID_LED1, self.OnLed1)
	EVT_BUTTON(self, ID_LED2, self.OnLed2)
	EVT_BUTTON(self, ID_START, self.OnStart)
	EVT_BUTTON(self, ID_STOP, self.OnStop)
	
	EVT_TEXT_ENTER(self.AmplCtrl, ID_AMPL, self.OnAmpl)	
	EVT_TEXT_ENTER(self.FreqCtrl, ID_FREQ, self.OnFreq)	
	
    def OnAbout(self, event):
        dlg = wxMessageDialog(self, "This test program configures a\n"
                              "prototype SDR as a modest signal\n"
                              "generator to test DAC functionality",
                              "About Me", wxOK | wxICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()
	
    def TimeToQuit(self, event):
        self.Close(true)

#not finished yet as of 2-9-05 #####################################    
    def OnTimer(self, event):
        self.Skip()
	
    def OnAmpl(self, event):
#    	self.AmplSlider.SetValue(500)
        self.waveform_ampl = self.AmplCtrl.GetValue()
	print self.waveform_ampl
	
    def OnFreq(self, event):
        self.waveform_freq = self.FreqCtrl.GetValue()
        print self.waveform_freq
	
    def OnTimer(self, evt):
#	self.Skip()
            print self.waveform_ampl, self.waveform_freq

    def OnLed1(self, evt):
	usrp.usrp_set_led(1)
        print self.waveform_ampl, self.waveform_freq

	    
    def OnLed2(self, evt):
#	self.Skip()
            print self.waveform_ampl, self.waveform_freq

    def OnStart(self, evt):
	sg.start()
	
    def OnStop(self, evt):
	sg.stop()

	    
	    






































class siggen (object):
    __slots__ = ['interp', 'waveform_type', 'waveform_ampl',
                 'waveform_freq', 'waveform_offset', 'fg', 'usrp',
                 'siggen', 'noisegen', 'src', 'file_sink' ]

    def __init__ (self):
        # controllable values
        self.interp = 64
        self.waveform_type = gr.GR_SIN_WAVE
        self.waveform_ampl = 16000
        self.waveform_freq = 100.12345e3
        self.waveform_offset = 0
        self._instantiate_blocks ()
        self.set_waveform_type (self.waveform_type)

    def start (self):
        self.fg.start ()

    def stop (self):
        self.fg.stop ()
        
    def usb_freq (self):
        return self.usrp.dac_freq() / self.interp

    def usb_throughput (self):
        return self.usb_freq () * 4
        
    def set_waveform_type (self, type):
        '''
        valid waveform types are: gr.GR_SIN_WAVE, gr.GR_CONST_WAVE,
        gr.GR_UNIFORM and gr.GR_GAUSSIAN
        '''
        self._configure_graph (type)
        self.waveform_type = type

    def set_waveform_ampl (self, ampl):
        self.waveform_ampl = ampl
        self.siggen.set_amplitude (ampl)
        self.noisegen.set_amplitude (ampl)

    def set_waveform_freq (self, freq):
        self.waveform_freq = freq
        self.siggen.set_frequency (freq)
        
    def set_waveform_offset (self, offset):
        self.waveform_offset = offset
        self.siggen.set_offset (offset)

    def set_interpolator (self, interp):
        self.interp = interp
        self.siggen.set_sampling_freq (self.usb_freq ())
        self.usrp.set_interp_rate (interp)

    def set_duc_freq (self, freq):
        self.usrp.set_tx_freq (0, freq)
        
    def _instantiate_blocks (self):
        self.fg = gr.flow_graph ()
        self.src = None
        self.usrp = usrp.sink_c (0, self.interp)
        
        self.siggen = gr.sig_source_c (self.usb_freq (),
                                       gr.GR_SIN_WAVE,
                                       self.waveform_freq,
                                       self.waveform_ampl,
                                       self.waveform_offset)

        self.noisegen = gr.noise_source_c (gr.GR_UNIFORM,
                                           self.waveform_ampl)

        # self.file_sink = gr.file_sink (gr.sizeof_gr_complex, "siggen.dat")

    def _configure_graph (self, type):
        was_running = self.fg.is_running ()
        if was_running:
            self.fg.stop ()
        self.fg.disconnect_all ()
        if type == gr.GR_SIN_WAVE or type == gr.GR_CONST_WAVE:
            self.fg.connect (self.siggen, self.usrp)
            # self.fg.connect (self.siggen, self.file_sink)
            self.siggen.set_waveform (type)
            self.src = self.siggen
        elif type == gr.GR_UNIFORM or type == gr.GR_GAUSSIAN:
            self.fg.connect (self.noisegen, self.usrp)
            self.noisegen.set_type (type)
            self.src = self.noisegen
        else:
            raise ValueError, type
        if was_running:
            self.fg.start ()

# Every wxWidgets application must have a class derived from wx.App
class MyApp(wxApp):

# wxWindows calls this method to initialize the application
    def OnInit(self):

# Create an instance of our customized Frame class
        frame = MyFrame(None, -1, "USRP Signal Generator")
        frame.Show(True)

# Tell wxWindows that this is our main window
        self.SetTopWindow(frame)

# Return a success flag
        return True

	    
	    
	    
	    
def main ():


    sg = siggen ()

    app = MyApp(0)
    app.MainLoop()
    
    
    
    sg.start ()
    raw_input ('Press Enter again to quit: ')
    sg.stop ()

if __name__ == '__main__':
    main ()
