On Mar 15, 2007, at 5:15 PM, [EMAIL PROTECTED] wrote:
I've got an application with 3 plot windows and a control area in the bottom. Depending on the screen resolution, the control area on the bottom is "covered" by the lowest of the 3 plot windows. The applicatoin works fine at 1600x1200 but less well at 1440x900, and certainly at lower resolutions the control boxes are getting covered.

What can I do so that even at lower resolutions I can see the entire application? I've tried adjusting the middle numeric field (vbox.add(self.scope.win, 4, wx.EXPAND)) in the vbox.add entry from 4 to 0, which helps for 1440x900 but this doesn't work for all resolutions and I don't know what this value represents anyway. Is there a recommendation for making my application resolution- independent? I've attached the python-code. Any advice is appreciated!

I've been studying GUI design recently, and I can tell you that it's not simple learning WX or wxPython as documentation really isn't very good (IMHO). Does folks have particular references (online tutorial, book, PDF) that they really like? I could use some pointers ... I've seen those provided by the WX and wxPython projects, and Google'd various others, but none really do justice to all the methods and variables for even such "simple" things as a BoxSizer.

I think this is correct: The "0" or "4" you're referring to is a "weight" of the particular added object. The "weight" is taking into account when the BoxSizer [0] determines how big an object should be; "0" weight (I think) means to not consider this object in the sizing but rather instead to just allocate its actual size (in pixels). Tweaking this value helps only so much, as objects can get only so small and screens only so large. Each object has a property, something like "minimum size"; some of these are straight forward to set while others seem to be less so if not impossible.

In the case of the "fftsink" GUI, the default frame size is (X,Y) = (640, 240), as found in gr-wxgui/src/python/fftsink.py , and you can change this in the call to "fftsink.fft_sink_c" with "size=(50,50)" or whatever you want. Ditto for fftsink2.py. Then you'll want to change the "weight" in the "vbox.Add" call to 1 for each of these.

That for "scopesink" is also (640, 240) [gr-wxgui/src/python/ scopesink.py], except that this value doesn't actually get used for anything (oops, bug alert). The "scopesink" also has some extra GUI stuff below it that doesn't seem to be set to EXPAND; nor is "size" passed around to any of the classes that actually create the GUI objects. Thus some work needs to be done on the scopesink classes stuff in order to get "size" to work.

Once the scopesink is corrected (as appended [1]), then you'll probably want (in your am_rcv_plasma.py) to vbox.Add them with a weight of 1, and everything else with a weight of 0. At least for me, this looks OK at down to around (X,Y) = (750,525) ... nothing special that small, but it does work.

[0] The BoxSizer 'vbox' to which you refer is a means for placing objects into a GUI with minimal user defined parameters; this particular one is a "vertical box" only, which means that items are added from the top of a window towards the bottom, in rows. Each row can have a different number of columns, each of which is generally a BoxSizer in its own right (a "horizontal" one).

[1] I've appended updated files, with corrections for these issues. Place them in the same directory before trying to execute your "am_.." script since it now depends on the fftsink_mod script being in that same directory. I'll think about what should really be done to scopesink to get it working properly, since this is just a quick fix for an obvious problem but it's not "ideal" I don't believe.

#!/usr/bin/env python

from gnuradio import gr, gru, eng_notation, optfir
from gnuradio import audio
from gnuradio import usrp
from gnuradio import blks
from gnuradio.eng_option import eng_option
from gnuradio.wxgui import slider, powermate
from gnuradio.wxgui import stdgui, form, fftsink
from optparse import OptionParser
import usrp_dbid
import sys
import math
import wx
import wx.lib.evtmgr as em
import scopesink_mod as scopesink

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))


plot1 = 1
plot2 = 1
plot3 = 1

class am_plasma_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=3e6,
                          help="set frequency to FREQ", metavar="FREQ")
        parser.add_option("-g", "--gain", type="int", default=10,
                          help="set gain in dB (default is midpoint)")
        parser.add_option("-O", "--audio-output", type="string", default="",
                          help="pcm device name.  E.g., hw:0,0 or surround51 or /dev/dsp")

        (options, args) = parser.parse_args()
        if len(args) != 0:
            parser.print_help()
            sys.exit(1)
        
        self.frame = frame
        self.panel = panel
        
        self.vol = 0
        self.state = "FREQ"
        self.freq = 0

        # build graph
        
        self.u = usrp.source_c()                    # usrp is data source

        adc_rate = self.u.adc_rate()                # 64 MS/s
        usrp_decim = 250
        self.u.set_decim_rate(usrp_decim)
        usrp_rate = adc_rate / usrp_decim           # 256 kS/s
        chanfilt_decim = 16
        #chanfilt_decim = 512
        demod_rate = usrp_rate / chanfilt_decim     # 16 kHz
        audio_decimation = 1
        audio_rate = demod_rate / audio_decimation  # 16 kHz


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

        # Select USRP channel (0)
        self.u.set_mux(usrp.determine_rx_mux_value(self.u, options.rx_subdev_spec))
        # Tune to the desired IF frequency
        self.subdev = usrp.selected_subdev(self.u, options.rx_subdev_spec)

        # Channelize the signal of interest.
        chan_filt_coeffs = gr.firdes.low_pass (1,           # gain
                                            usrp_rate,   # sampling rate
					    #1000,
                                            6000,        # passband cutoff
                                            500,       # stopband cutoff
                                            gr.firdes.WIN_HANN)
        self.lpfilter =  gr.fir_filter_ccf (chanfilt_decim,chan_filt_coeffs)

        # Demodulate with classic sqrt (I*I + Q*Q)
        self.magblock = gr.complex_to_mag()
        self.volume_control = gr.multiply_const_ff(self.vol)

        # Deemphasis.  Is this necessary on AM?
        #TAU  = 75e-6  # 75us in US, 50us in EUR
        #fftaps = [ 1 - math.exp(-1/TAU/usrp_rate), 0]
        #fbtaps= [ 0 , math.exp(-1/TAU/usrp_rate) ]
        
        #self.deemph = gr.iir_filter_ffd(fftaps,fbtaps)

        # sound card as final sink
        audio_sink = audio.sink (int (audio_rate),
                                 options.audio_output,
                                 False)   # ok_to_block
        
        # now wire it all together
        self.connect (self.u, self.lpfilter)
	self.connect (self.lpfilter, self.magblock)
        self.connect (self.magblock, self.volume_control)
        self.connect (self.volume_control, (audio_sink, 0))

        #self.connect (self.volume_control, audio_filter)
        #self.connect (audio_filter, (audio_sink, 0))
        #self.connect (self.volume_control,self.deemph)
	#self.connect (self.deemph,audio_filter)
        #self.connect (audio_filter, (audio_sink, 0))

        self._build_gui(vbox, usrp_rate, demod_rate, audio_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) < 1e6:
            options.freq *= 1e6

        # set initial values

        self.set_gain(options.gain)
        if not(self.set_freq(options.freq)):
            self._set_status_msg("Failed to set initial frequency")


    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'])


        if plot1:
            self.src_fft = fftsink.fft_sink_c (self, self.panel, title="Data from Sensor",
                                               fft_size=1024, sample_rate=usrp_rate, size=(50,100))
            self.connect (self.u, self.src_fft)
            vbox.Add (self.src_fft.win, 1, wx.EXPAND)

        if plot2:
            self.post_filt = fftsink.fft_sink_f (self, self.panel, title="AM Demodulated FFT", fft_size=1024, sample_rate=demod_rate, size=(50,100))
            self.connect (self.magblock,self.post_filt)
            vbox.Add (self.post_filt.win, 1, wx.EXPAND)

        if plot3:
            self.scope = scopesink.scope_sink_f(self, self.panel, title="AM Demodulated Time Series", sample_rate=demod_rate, size=(50,100), vbox=vbox)
            self.connect(self.magblock, self.scope)
            vbox.Add (self.scope.win, 1, 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="Carrier Freq", weight=1,
            callback=myform.check_input_and_call(_form_set_freq, self._set_status_msg))

        hbox.Add((5,0), 0)
        myform['freq_slider'] = \
            form.quantized_slider_field(parent=self.panel, sizer=hbox, weight=3,
                                        range=(.5e6, 3.5e6, 0.001e6),
                                        callback=self.set_freq)
        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.state == "FREQ"):
            if self.rot >= 3:
                self.set_freq(self.freq + .001e6)
                self.rot -= 3
            elif self.rot <=-3:
                self.set_freq(self.freq - .001e6)
                self.rot += 3
        else:
            step = self.subdev.gain_range()[2]
            if self.rot >= 3:
                self.set_gain(self.gain + step)
                self.rot -= 3
            elif self.rot <=-3:
                self.set_gain(self.gain - step)
                self.rot += 3
	    self.update_status_bar ()
            
    def on_button (self, event):
        if event.value == 0:        # button up
            return
        self.rot = 0
        if self.state == "FREQ":
            self.state = "GAIN"
        else:
            self.state = "FREQ"
        self.update_status_bar ()
        
                                        
    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)
        
        if r:
            self.freq = target_freq
            self.myform['freq'].set_value(target_freq)         # update displayed value
            self.myform['freq_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 = "Gain:%r  Setting:%s" % (self.gain, self.state)
        self._set_status_msg(msg, 1)
        if plot1: 
	  self.src_fft.set_baseband_freq(self.freq)

    def gain_range(self):
        return (0, 20, 1)


if __name__ == '__main__':
    app = stdgui.stdapp (am_plasma_rx_graph, "USRP PLASMA AM RX")
    app.MainLoop ()

#!/usr/bin/env python
#
# Copyright 2003,2004,2006 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., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
# 

from gnuradio import gr, gru, eng_notation
from gnuradio.wxgui import stdgui
import wx
import gnuradio.wxgui.plot as plot
import Numeric
import threading
import struct

default_scopesink_size = (200, 100)
default_v_scale = 1000
default_frame_decim = gr.prefs().get_long('wxgui', 'frame_decim', 1)

class scope_sink_f(gr.hier_block):
    def __init__(self, fg, parent, title='', sample_rate=1,
                 size=default_scopesink_size, frame_decim=default_frame_decim,
                 v_scale=default_v_scale, t_scale=None, vbox=None):
        msgq = gr.msg_queue(2)         # message queue that holds at most 2 messages
        self.guts = gr.oscope_sink_f(sample_rate, msgq)
        gr.hier_block.__init__(self, fg, self.guts, self.guts)
        self.win = scope_window(win_info (msgq, sample_rate, frame_decim,
                                          v_scale, t_scale, self.guts, title), parent, size=size)

    def set_sample_rate(self, sample_rate):
        self.guts.set_sample_rate(sample_rate)
        self.win.info.set_sample_rate(sample_rate)

class scope_sink_c(gr.hier_block):
    def __init__(self, fg, parent, title='', sample_rate=1,
                 size=default_scopesink_size, frame_decim=default_frame_decim,
                 v_scale=default_v_scale, t_scale=None, vbox=None):
        msgq = gr.msg_queue(2)         # message queue that holds at most 2 messages
        c2f = gr.complex_to_float()
        self.guts = gr.oscope_sink_f(sample_rate, msgq)
        fg.connect((c2f, 0), (self.guts, 0))
        fg.connect((c2f, 1), (self.guts, 1))
        gr.hier_block.__init__(self, fg, c2f, self.guts)
        self.win = scope_window(win_info(msgq, sample_rate, frame_decim,
                                         v_scale, t_scale, self.guts, title), parent, size=size)
        
    def set_sample_rate(self, sample_rate):
        self.guts.set_sample_rate(sample_rate)
        self.win.info.set_sample_rate(sample_rate)

# ========================================================================
# This is the deprecated interface, retained for compatibility...
#
# returns (block, win).
#   block requires a N input stream of float
#   win is a subclass of wxWindow

def make_scope_sink_f (fg, parent, label, input_rate):
    block = scope_sink_f(fg, parent, title=label, sample_rate=input_rate)
    return (block, block.win)

# ========================================================================


time_base_list = [                      # time / division
    1.0e-7,   # 100ns / div
    2.5e-7,
    5.0e-7,
    1.0e-6,   #   1us / div
    2.5e-6,
    5.0e-6,
    1.0e-5,   #  10us / div
    2.5e-5,
    5.0e-5,
    1.0e-4,   # 100us / div
    2.5e-4,
    5.0e-4,
    1.0e-3,   #   1ms / div
    2.5e-3,
    5.0e-3,
    1.0e-2,   #  10ms / div
    2.5e-2,
    5.0e-2
    ]

v_scale_list = [ # counts / div, LARGER gains are SMALLER /div, appear EARLIER
    2.0e-3,   # 2m / div, don't call it V/div it's actually counts/div
    5.0e-3,
    1.0e-2,
    2.0e-2,
    5.0e-2,
    1.0e-1,
    2.0e-1,
    5.0e-1,
    1.0e+0,
    2.0e+0,
    5.0e+0,
    1.0e+1,
    2.0e+1,
    5.0e+1,
    1.0e+2,
    2.0e+2,
    5.0e+2,
    1.0e+3,
    2.0e+3,
    5.0e+3,
    1.0e+4 # 10000 /div, USRP full scale is -/+ 32767
    ]

    
wxDATA_EVENT = wx.NewEventType()

def EVT_DATA_EVENT(win, func):
    win.Connect(-1, -1, wxDATA_EVENT, func)

class DataEvent(wx.PyEvent):
    def __init__(self, data):
        wx.PyEvent.__init__(self)
        self.SetEventType (wxDATA_EVENT)
        self.data = data

    def Clone (self): 
        self.__class__ (self.GetId())


class win_info (object):
    __slots__ = ['msgq', 'sample_rate', 'frame_decim', 'v_scale', 
                 'scopesink', 'title',
                 'time_scale_cursor', 'v_scale_cursor', 'marker', 'xy',
                 'autorange', 'running']

    def __init__ (self, msgq, sample_rate, frame_decim, v_scale, t_scale,
                  scopesink, title = "Oscilloscope"):
        self.msgq = msgq
        self.sample_rate = sample_rate
        self.frame_decim = frame_decim
        self.scopesink = scopesink
        self.title = title;

        self.time_scale_cursor = gru.seq_with_cursor(time_base_list, initial_value = t_scale)
        self.v_scale_cursor = gru.seq_with_cursor(v_scale_list, initial_value = v_scale)

        self.marker = 'line'
        self.xy = False
        if v_scale == None:        # 0 and None are both False, but 0 != None
            self.autorange = True
        else:
            self.autorange = False # 0 is a valid v_scale            
        self.running = True

    def get_time_per_div (self):
        return self.time_scale_cursor.current ()

    def get_volts_per_div (self):
        return self.v_scale_cursor.current ()

    def set_sample_rate(self, sample_rate):
        self.sample_rate = sample_rate
        
    def get_sample_rate (self):
        return self.sample_rate

    def get_decimation_rate (self):
        return 1.0

    def set_marker (self, s):
        self.marker = s

    def get_marker (self):
        return self.marker


class input_watcher (threading.Thread):
    def __init__ (self, msgq, event_receiver, frame_decim, **kwds):
        threading.Thread.__init__ (self, **kwds)
        self.setDaemon (1)
        self.msgq = msgq
        self.event_receiver = event_receiver
        self.frame_decim = frame_decim
        self.iscan = 0
        self.keep_running = True
        self.start ()

    def run (self):
        # print "input_watcher: pid = ", os.getpid ()
        while (self.keep_running):
            msg = self.msgq.delete_head()   # blocking read of message queue
            if self.iscan == 0:            # only display at frame_decim
                self.iscan = self.frame_decim
                                
                nchan = int(msg.arg1())    # number of channels of data in msg
                nsamples = int(msg.arg2()) # number of samples in each channel

                s = msg.to_string()      # get the body of the msg as a string

                bytes_per_chan = nsamples * gr.sizeof_float

                records = []
                for ch in range (nchan):

                    start = ch * bytes_per_chan
                    chan_data = s[start:start+bytes_per_chan]
                    rec = Numeric.fromstring (chan_data, Numeric.Float32)
                    records.append (rec)

                # print "nrecords = %d, reclen = %d" % (len (records),nsamples)

                de = DataEvent (records)
                wx.PostEvent (self.event_receiver, de)
                records = []
                del de

            # end if iscan == 0
            self.iscan -= 1
    

class scope_window(wx.Panel):
    def __init__ (self, info, parent, id = -1,
                  pos = wx.DefaultPosition, size = wx.DefaultSize,
		  name = ""):
        wx.Panel.__init__ (self, parent, -1, size=size)
        self.info = info

	vbox = wx.BoxSizer (wx.VERTICAL)

        self.graph = graph_window (info, self, -1, size=size)

        vbox.Add (self.graph, 1, wx.EXPAND)
        vbox.Add (self.make_control_box(), 0, wx.EXPAND)
        vbox.Add (self.make_control2_box(), 0, wx.EXPAND)

        self.sizer = vbox
	self.SetSizer (self.sizer)
	self.SetAutoLayout (True)
	self.sizer.Fit (self)
	self.set_autorange(self.info.autorange)

    # second row of control buttons etc. appears BELOW control_box
    def make_control2_box (self):
        ctrlbox = wx.BoxSizer (wx.HORIZONTAL)

        self.inc_v_button = wx.Button (self, 1101, " < ", style=wx.BU_EXACTFIT)
        self.inc_v_button.SetToolTipString ("Increase vertical range")
        wx.EVT_BUTTON (self, 1101, self.incr_v_scale) # ID matches button ID above

        self.dec_v_button  = wx.Button (self, 1100, " > ", style=wx.BU_EXACTFIT)
        self.dec_v_button.SetToolTipString ("Decrease vertical range")
        wx.EVT_BUTTON (self, 1100, self.decr_v_scale)

        self.v_scale_label = wx.StaticText (self, 1002, "None") # vertical /div
        self.update_v_scale_label ()

        self.autorange_checkbox = wx.CheckBox (self, 1102, "Autorange")
        self.autorange_checkbox.SetToolTipString ("Select autorange on/off")
        wx.EVT_CHECKBOX(self, 1102, self.autorange_checkbox_event)

        ctrlbox.Add ((5,0) ,0) # left margin space
        ctrlbox.Add (self.inc_v_button, 0, wx.EXPAND)
        ctrlbox.Add (self.dec_v_button, 0, wx.EXPAND)
        ctrlbox.Add (self.v_scale_label, 0, wx.ALIGN_CENTER | wx.EXPAND)
        ctrlbox.Add ((20,0) ,0) # spacer
        ctrlbox.Add (self.autorange_checkbox, 0, wx.ALIGN_CENTER | wx.EXPAND)

        return ctrlbox

    def make_control_box (self):
        ctrlbox = wx.BoxSizer (wx.HORIZONTAL)

        tb_left = wx.Button (self, 1001, " < ", style=wx.BU_EXACTFIT)
        tb_left.SetToolTipString ("Increase time base")
        wx.EVT_BUTTON (self, 1001, self.incr_timebase)


        tb_right  = wx.Button (self, 1000, " > ", style=wx.BU_EXACTFIT)
        tb_right.SetToolTipString ("Decrease time base")
        wx.EVT_BUTTON (self, 1000, self.decr_timebase)

        self.time_base_label = wx.StaticText (self, 1002, "")
        self.update_timebase_label ()

        ctrlbox.Add ((5,0) ,0)
        # ctrlbox.Add (wx.StaticText (self, -1, "Horiz Scale: "), 0, wx.ALIGN_CENTER | wx.EXPAND)
        ctrlbox.Add (tb_left, 0, wx.EXPAND)
        ctrlbox.Add (tb_right, 0, wx.EXPAND)
        ctrlbox.Add (self.time_base_label, 0, wx.ALIGN_CENTER | wx.EXPAND)

        ctrlbox.Add ((10,0) ,1)            # stretchy space

        ctrlbox.Add (wx.StaticText (self, -1, "Trig: "), 0, wx.ALIGN_CENTER)
        self.trig_chan_choice = wx.Choice (self, 1004,
                                           choices = ['Ch1', 'Ch2', 'Ch3', 'Ch4'])
        self.trig_chan_choice.SetToolTipString ("Select channel for trigger")
        wx.EVT_CHOICE (self, 1004, self.trig_chan_choice_event)
        ctrlbox.Add (self.trig_chan_choice, 0, wx.ALIGN_CENTER | wx.EXPAND)

        self.trig_mode_choice = wx.Choice (self, 1005,
                                           choices = ['Auto', 'Pos', 'Neg'])
        self.trig_mode_choice.SetToolTipString ("Select trigger slope or Auto (untriggered roll)")
        wx.EVT_CHOICE (self, 1005, self.trig_mode_choice_event)
        ctrlbox.Add (self.trig_mode_choice, 0, wx.ALIGN_CENTER | wx.EXPAND)

        trig_level50 = wx.Button (self, 1006, "50%")
        trig_level50.SetToolTipString ("Set trigger level to 50%")
        wx.EVT_BUTTON (self, 1006, self.set_trig_level50)
        ctrlbox.Add (trig_level50, 0, wx.EXPAND)

        run_stop = wx.Button (self, 1007, "Run/Stop")
        run_stop.SetToolTipString ("Toggle Run/Stop mode")
        wx.EVT_BUTTON (self, 1007, self.run_stop)
        ctrlbox.Add (run_stop, 0, wx.EXPAND)

        ctrlbox.Add ((10, 0), 1)            # stretchy space

        ctrlbox.Add (wx.StaticText (self, -1, "Fmt: "), 0, wx.ALIGN_CENTER | wx.EXPAND)
        self.marker_choice = wx.Choice (self, 1002, choices = self._marker_choices)
        self.marker_choice.SetToolTipString ("Select plotting with lines, pluses or dots")
        wx.EVT_CHOICE (self, 1002, self.marker_choice_event)
        ctrlbox.Add (self.marker_choice, 0, wx.ALIGN_CENTER | wx.EXPAND)

        self.xy_choice = wx.Choice (self, 1003, choices = ['X:t', 'X:Y'])
        self.xy_choice.SetToolTipString ("Select X vs time or X vs Y display")
        wx.EVT_CHOICE (self, 1003, self.xy_choice_event)
        ctrlbox.Add (self.xy_choice, 0, wx.ALIGN_CENTER | wx.EXPAND)

        return ctrlbox
    
    _marker_choices = ['line', 'plus', 'dot']

    def update_timebase_label (self):
        time_per_div = self.info.get_time_per_div ()
        s = ' ' + eng_notation.num_to_str (time_per_div) + 's/div'
        self.time_base_label.SetLabel (s)
        
    def decr_timebase (self, evt):
        self.info.time_scale_cursor.prev ()
        self.update_timebase_label ()

    def incr_timebase (self, evt):
        self.info.time_scale_cursor.next ()
        self.update_timebase_label ()

    def update_v_scale_label (self):
        volts_per_div = self.info.get_volts_per_div ()
        s = ' ' + eng_notation.num_to_str (volts_per_div) + '/div' # Not V/div
        self.v_scale_label.SetLabel (s)
        
    def decr_v_scale (self, evt):
        self.info.v_scale_cursor.prev ()
        self.update_v_scale_label ()

    def incr_v_scale (self, evt):
        self.info.v_scale_cursor.next ()
        self.update_v_scale_label ()
        
    def marker_choice_event (self, evt):
        s = evt.GetString ()
        self.set_marker (s)

    def set_autorange(self, on):
        if on:
            self.v_scale_label.SetLabel(" (auto)")
            self.info.autorange = True
            self.autorange_checkbox.SetValue(True)
            self.inc_v_button.Enable(False)
            self.dec_v_button.Enable(False)
        else:
            if self.graph.y_range:
                (l,u) = self.graph.y_range # found by autorange
                self.info.v_scale_cursor.set_index_by_value((u-l)/8.0)
            self.update_v_scale_label()
            self.info.autorange = False
            self.autorange_checkbox.SetValue(False)
            self.inc_v_button.Enable(True)
            self.dec_v_button.Enable(True)
            
    def autorange_checkbox_event(self, evt):
        if evt.Checked():
            self.set_autorange(True)
        else:
            self.set_autorange(False)
            
    def set_marker (self, s):
        self.info.set_marker (s)        # set info for drawing routines
        i = self.marker_choice.FindString (s)
        assert i >= 0, "Hmmm, set_marker problem"
        self.marker_choice.SetSelection (i)

    def set_format_line (self):
        self.set_marker ('line')

    def set_format_dot (self):
        self.set_marker ('dot')

    def set_format_plus (self):
        self.set_marker ('plus')
        
    def xy_choice_event (self, evt):
        s = evt.GetString ()
        self.info.xy = s == 'X:Y'

    def trig_chan_choice_event (self, evt):
        s = evt.GetString ()
        ch = int (s[-1]) - 1
        self.info.scopesink.set_trigger_channel (ch)

    def trig_mode_choice_event (self, evt):
        sink = self.info.scopesink
        s = evt.GetString ()
        if s == 'Pos':
            sink.set_trigger_mode (gr.gr_TRIG_POS_SLOPE)
        elif s == 'Neg':
            sink.set_trigger_mode (gr.gr_TRIG_NEG_SLOPE)
        elif s == 'Auto':
            sink.set_trigger_mode (gr.gr_TRIG_AUTO)
        else:
            assert 0, "Bad trig_mode_choice string"
    
    def set_trig_level50 (self, evt):
        self.info.scopesink.set_trigger_level_auto ()

    def run_stop (self, evt):
        self.info.running = not self.info.running
        

class graph_window (plot.PlotCanvas):

    channel_colors = ['BLUE', 'RED',
                      'CYAN', 'MAGENTA', 'GREEN', 'YELLOW']
    
    def __init__ (self, info, parent, id = -1,
                  pos = wx.DefaultPosition, size = (640, 240),
                  style = wx.DEFAULT_FRAME_STYLE, name = ""):
        plot.PlotCanvas.__init__ (self, parent, id, pos, size, style, name)

        self.SetXUseScopeTicks (True)
        self.SetEnableGrid (True)
        self.SetEnableZoom (True)
        self.SetEnableLegend(True)
        # self.SetBackgroundColour ('black')
        
        self.info = info;
        self.y_range = None
        self.x_range = None
        self.avg_y_min = None
        self.avg_y_max = None
        self.avg_x_min = None
        self.avg_x_max = None

        EVT_DATA_EVENT (self, self.format_data)

        self.input_watcher = input_watcher (info.msgq, self, info.frame_decim)

    def channel_color (self, ch):
        return self.channel_colors[ch % len(self.channel_colors)]
       
    def format_data (self, evt):
        if not self.info.running:
            return
        
        if self.info.xy:
            self.format_xy_data (evt)
            return

        info = self.info
        records = evt.data
        nchannels = len (records)
        npoints = len (records[0])

        objects = []

        Ts = 1.0 / (info.get_sample_rate () / info.get_decimation_rate ())
        x_vals = Ts * Numeric.arrayrange (-npoints/2, npoints/2)

        # preliminary clipping based on time axis here, instead of in graphics code
        time_per_window = self.info.get_time_per_div () * 10
        n = int (time_per_window / Ts + 0.5)
        n = n & ~0x1                    # make even
        n = max (2, min (n, npoints))

        self.SetXUseScopeTicks (True)   # use 10 divisions, no labels

        for ch in range(nchannels):
            r = records[ch]

            # plot middle n points of record

            lb = npoints/2 - n/2
            ub = npoints/2 + n/2
            # points = zip (x_vals[lb:ub], r[lb:ub])
            points = Numeric.zeros ((ub-lb, 2), Numeric.Float64)
            points[:,0] = x_vals[lb:ub]
            points[:,1] = r[lb:ub]

            m = info.get_marker ()
            if m == 'line':
                objects.append (plot.PolyLine (points,
                                               colour=self.channel_color (ch),
                                               legend=('Ch%d' % (ch+1,))))
            else:
                objects.append (plot.PolyMarker (points,
                                                 marker=m,
                                                 colour=self.channel_color (ch),
                                                 legend=('Ch%d' % (ch+1,))))

        graphics = plot.PlotGraphics (objects,
                                      title=self.info.title,
                                      xLabel = '', yLabel = '')

        time_per_div = info.get_time_per_div ()
        x_range = (-5.0 * time_per_div, 5.0 * time_per_div) # ranges are tuples!
        volts_per_div = info.get_volts_per_div ()
        if not self.info.autorange:
            self.y_range = (-4.0 * volts_per_div, 4.0 * volts_per_div)
        self.Draw (graphics, xAxis=x_range, yAxis=self.y_range)
        self.update_y_range () # autorange to self.y_range


    def format_xy_data (self, evt):
        info = self.info
        records = evt.data
        nchannels = len (records)
        npoints = len (records[0])

        if nchannels < 2:
            return

        objects = []
        # points = zip (records[0], records[1])
        points = Numeric.zeros ((len(records[0]), 2), Numeric.Float32)
        points[:,0] = records[0]
        points[:,1] = records[1]
        
        self.SetXUseScopeTicks (False)

        m = info.get_marker ()
        if m == 'line':
            objects.append (plot.PolyLine (points,
                                           colour=self.channel_color (0)))
        else:
            objects.append (plot.PolyMarker (points,
                                             marker=m,
                                             colour=self.channel_color (0)))

        graphics = plot.PlotGraphics (objects,
                                      title=self.info.title,
                                      xLabel = 'I', yLabel = 'Q')

        self.Draw (graphics, xAxis=self.x_range, yAxis=self.y_range)
        self.update_y_range ()
        self.update_x_range ()


    def update_y_range (self):
        alpha = 1.0/25
        graphics = self.last_draw[0]
        p1, p2 = graphics.boundingBox ()     # min, max points of graphics

        if self.avg_y_min: # prevent vertical scale from jumping abruptly --?
            self.avg_y_min = p1[1] * alpha + self.avg_y_min * (1 - alpha)
            self.avg_y_max = p2[1] * alpha + self.avg_y_max * (1 - alpha)
        else: # initial guess
            self.avg_y_min = p1[1] # -500.0 workaround, sometimes p1 is ~ 10^35
            self.avg_y_max = p2[1] # 500.0

        self.y_range = self._axisInterval ('auto', self.avg_y_min, self.avg_y_max)
        # print "p1 %s  p2 %s  y_min %s  y_max %s  y_range %s" \
        #        % (p1, p2, self.avg_y_min, self.avg_y_max, self.y_range)


    def update_x_range (self):
        alpha = 1.0/25
        graphics = self.last_draw[0]
        p1, p2 = graphics.boundingBox ()     # min, max points of graphics

        if self.avg_x_min:
            self.avg_x_min = p1[0] * alpha + self.avg_x_min * (1 - alpha)
            self.avg_x_max = p2[0] * alpha + self.avg_x_max * (1 - alpha)
        else:
            self.avg_x_min = p1[0]
            self.avg_x_max = p2[0]

        self.x_range = self._axisInterval ('auto', self.avg_x_min, self.avg_x_max)


# ----------------------------------------------------------------
# Stand-alone test application
# ----------------------------------------------------------------

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

        if len(argv) > 1:
            frame_decim = int(argv[1]) 
        else:
            frame_decim = 1

        if len(argv) > 2:
            v_scale = float(argv[2])  # start up at this v_scale value
        else:
            v_scale = None  # start up in autorange mode, default

        if len(argv) > 3:
            t_scale = float(argv[3])  # start up at this t_scale value
        else:
            t_scale = None  # old behavior

        print "frame decim %s  v_scale %s  t_scale %s" % (frame_decim,v_scale,t_scale)
            
        input_rate = 1e6

        # Generate a complex sinusoid
        src0 = gr.sig_source_c (input_rate, gr.GR_SIN_WAVE, 25.1e3, 1e3)

        # We add this throttle block so that this demo doesn't suck down
        # all the CPU available.  You normally wouldn't use it...
        throttle = gr.throttle(gr.sizeof_gr_complex, input_rate)

        scope = scope_sink_c (self, panel,"Secret Data",sample_rate=input_rate,
                              frame_decim=frame_decim,
                              v_scale=v_scale, t_scale=t_scale)
        vbox.Add (scope.win, 1, wx.EXPAND)

        # wire the blocks together
        self.connect (src0, throttle, scope)

def main ():
    app = stdgui.stdapp (test_app_flow_graph, "O'Scope Test App")
    app.MainLoop ()

if __name__ == '__main__':
    main ()

# ----------------------------------------------------------------
_______________________________________________
Discuss-gnuradio mailing list
Discuss-gnuradio@gnu.org
http://lists.gnu.org/mailman/listinfo/discuss-gnuradio

Reply via email to