3 # Copyright 2003,2004,2006,2007 Free Software Foundation, Inc.
5 # This file is part of GNU Radio
7 # GNU Radio is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 2, or (at your option)
12 # GNU Radio is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with GNU Radio; see the file COPYING. If not, write to
19 # the Free Software Foundation, Inc., 51 Franklin Street,
20 # Boston, MA 02110-1301, USA.
23 from gnuradio import gr, gru, eng_notation
24 from gnuradio.wxgui import stdgui2
26 import gnuradio.wxgui.plot as plot
31 default_scopesink_size = (640, 240)
32 default_v_scale = 1000
33 default_frame_decim = gr.prefs().get_long('wxgui', 'frame_decim', 1)
35 class scope_sink_f(gr.hier_block2):
36 def __init__(self, parent, title='', sample_rate=1,
37 size=default_scopesink_size, frame_decim=default_frame_decim,
38 v_scale=default_v_scale, t_scale=None):
40 gr.hier_block2.__init__(self, "scope_sink_f",
41 gr.io_signature(1, 1, gr.sizeof_float),
42 gr.io_signature(0,0,0))
44 msgq = gr.msg_queue(2) # message queue that holds at most 2 messages
45 self.guts = gr.oscope_sink_f(sample_rate, msgq)
46 self.connect(self, self.guts)
48 self.win = scope_window(win_info (msgq, sample_rate, frame_decim,
49 v_scale, t_scale, self.guts, title), parent)
51 def set_sample_rate(self, sample_rate):
52 self.guts.set_sample_rate(sample_rate)
53 self.win.info.set_sample_rate(sample_rate)
55 class scope_sink_c(gr.hier_block2):
56 def __init__(self, parent, title='', sample_rate=1,
57 size=default_scopesink_size, frame_decim=default_frame_decim,
58 v_scale=default_v_scale, t_scale=None):
60 gr.hier_block2.__init__(self, "scope_sink_c",
61 gr.io_signature(1, 1, gr.sizeof_gr_complex),
62 gr.io_signature(0,0,0))
64 msgq = gr.msg_queue(2) # message queue that holds at most 2 messages
65 self.c2f = gr.complex_to_float()
66 self.guts = gr.oscope_sink_f(sample_rate, msgq)
67 self.connect(self, self.c2f)
68 self.connect((self.c2f, 0), (self.guts, 0))
69 self.connect((self.c2f, 1), (self.guts, 1))
71 self.win = scope_window(win_info(msgq, sample_rate, frame_decim,
72 v_scale, t_scale, self.guts, title), parent)
74 def set_sample_rate(self, sample_rate):
75 self.guts.set_sample_rate(sample_rate)
76 self.win.info.set_sample_rate(sample_rate)
78 # ========================================================================
81 time_base_list = [ # time / division
102 v_scale_list = [ # counts / div, LARGER gains are SMALLER /div, appear EARLIER
103 2.0e-3, # 2m / div, don't call it V/div it's actually counts/div
123 1.0e+4 # 10000 /div, USRP full scale is -/+ 32767
127 wxDATA_EVENT = wx.NewEventType()
129 def EVT_DATA_EVENT(win, func):
130 win.Connect(-1, -1, wxDATA_EVENT, func)
132 class DataEvent(wx.PyEvent):
133 def __init__(self, data):
134 wx.PyEvent.__init__(self)
135 self.SetEventType (wxDATA_EVENT)
139 self.__class__ (self.GetId())
142 class win_info (object):
143 __slots__ = ['msgq', 'sample_rate', 'frame_decim', 'v_scale',
144 'scopesink', 'title',
145 'time_scale_cursor', 'v_scale_cursor', 'marker', 'xy',
146 'autorange', 'running']
148 def __init__ (self, msgq, sample_rate, frame_decim, v_scale, t_scale,
149 scopesink, title = "Oscilloscope"):
151 self.sample_rate = sample_rate
152 self.frame_decim = frame_decim
153 self.scopesink = scopesink
156 self.time_scale_cursor = gru.seq_with_cursor(time_base_list, initial_value = t_scale)
157 self.v_scale_cursor = gru.seq_with_cursor(v_scale_list, initial_value = v_scale)
161 if v_scale == None: # 0 and None are both False, but 0 != None
162 self.autorange = True
164 self.autorange = False # 0 is a valid v_scale
167 def get_time_per_div (self):
168 return self.time_scale_cursor.current ()
170 def get_volts_per_div (self):
171 return self.v_scale_cursor.current ()
173 def set_sample_rate(self, sample_rate):
174 self.sample_rate = sample_rate
176 def get_sample_rate (self):
177 return self.sample_rate
179 def get_decimation_rate (self):
182 def set_marker (self, s):
185 def get_marker (self):
189 class input_watcher (threading.Thread):
190 def __init__ (self, msgq, event_receiver, frame_decim, **kwds):
191 threading.Thread.__init__ (self, **kwds)
194 self.event_receiver = event_receiver
195 self.frame_decim = frame_decim
197 self.keep_running = True
201 # print "input_watcher: pid = ", os.getpid ()
202 while (self.keep_running):
203 msg = self.msgq.delete_head() # blocking read of message queue
204 if self.iscan == 0: # only display at frame_decim
205 self.iscan = self.frame_decim
207 nchan = int(msg.arg1()) # number of channels of data in msg
208 nsamples = int(msg.arg2()) # number of samples in each channel
210 s = msg.to_string() # get the body of the msg as a string
212 bytes_per_chan = nsamples * gr.sizeof_float
215 for ch in range (nchan):
217 start = ch * bytes_per_chan
218 chan_data = s[start:start+bytes_per_chan]
219 rec = numpy.fromstring (chan_data, numpy.float32)
222 # print "nrecords = %d, reclen = %d" % (len (records),nsamples)
224 de = DataEvent (records)
225 wx.PostEvent (self.event_receiver, de)
233 class scope_window (wx.Panel):
235 def __init__ (self, info, parent, id = -1,
236 pos = wx.DefaultPosition, size = wx.DefaultSize, name = ""):
237 wx.Panel.__init__ (self, parent, -1)
240 vbox = wx.BoxSizer (wx.VERTICAL)
242 self.graph = graph_window (info, self, -1)
244 vbox.Add (self.graph, 1, wx.EXPAND)
245 vbox.Add (self.make_control_box(), 0, wx.EXPAND)
246 vbox.Add (self.make_control2_box(), 0, wx.EXPAND)
249 self.SetSizer (self.sizer)
250 self.SetAutoLayout (True)
251 self.sizer.Fit (self)
252 self.set_autorange(self.info.autorange)
255 # second row of control buttons etc. appears BELOW control_box
256 def make_control2_box (self):
257 ctrlbox = wx.BoxSizer (wx.HORIZONTAL)
259 self.inc_v_button = wx.Button (self, 1101, " < ", style=wx.BU_EXACTFIT)
260 self.inc_v_button.SetToolTipString ("Increase vertical range")
261 wx.EVT_BUTTON (self, 1101, self.incr_v_scale) # ID matches button ID above
263 self.dec_v_button = wx.Button (self, 1100, " > ", style=wx.BU_EXACTFIT)
264 self.dec_v_button.SetToolTipString ("Decrease vertical range")
265 wx.EVT_BUTTON (self, 1100, self.decr_v_scale)
267 self.v_scale_label = wx.StaticText (self, 1002, "None") # vertical /div
268 self.update_v_scale_label ()
270 self.autorange_checkbox = wx.CheckBox (self, 1102, "Autorange")
271 self.autorange_checkbox.SetToolTipString ("Select autorange on/off")
272 wx.EVT_CHECKBOX(self, 1102, self.autorange_checkbox_event)
274 ctrlbox.Add ((5,0) ,0) # left margin space
275 ctrlbox.Add (self.inc_v_button, 0, wx.EXPAND)
276 ctrlbox.Add (self.dec_v_button, 0, wx.EXPAND)
277 ctrlbox.Add (self.v_scale_label, 0, wx.ALIGN_CENTER)
278 ctrlbox.Add ((20,0) ,0) # spacer
279 ctrlbox.Add (self.autorange_checkbox, 0, wx.ALIGN_CENTER)
283 def make_control_box (self):
284 ctrlbox = wx.BoxSizer (wx.HORIZONTAL)
286 tb_left = wx.Button (self, 1001, " < ", style=wx.BU_EXACTFIT)
287 tb_left.SetToolTipString ("Increase time base")
288 wx.EVT_BUTTON (self, 1001, self.incr_timebase)
291 tb_right = wx.Button (self, 1000, " > ", style=wx.BU_EXACTFIT)
292 tb_right.SetToolTipString ("Decrease time base")
293 wx.EVT_BUTTON (self, 1000, self.decr_timebase)
295 self.time_base_label = wx.StaticText (self, 1002, "")
296 self.update_timebase_label ()
298 ctrlbox.Add ((5,0) ,0)
299 # ctrlbox.Add (wx.StaticText (self, -1, "Horiz Scale: "), 0, wx.ALIGN_CENTER)
300 ctrlbox.Add (tb_left, 0, wx.EXPAND)
301 ctrlbox.Add (tb_right, 0, wx.EXPAND)
302 ctrlbox.Add (self.time_base_label, 0, wx.ALIGN_CENTER)
304 ctrlbox.Add ((10,0) ,1) # stretchy space
306 ctrlbox.Add (wx.StaticText (self, -1, "Trig: "), 0, wx.ALIGN_CENTER)
307 self.trig_chan_choice = wx.Choice (self, 1004,
308 choices = ['Ch1', 'Ch2', 'Ch3', 'Ch4'])
309 self.trig_chan_choice.SetToolTipString ("Select channel for trigger")
310 wx.EVT_CHOICE (self, 1004, self.trig_chan_choice_event)
311 ctrlbox.Add (self.trig_chan_choice, 0, wx.ALIGN_CENTER)
313 self.trig_mode_choice = wx.Choice (self, 1005,
314 choices = ['Auto', 'Pos', 'Neg'])
315 self.trig_mode_choice.SetToolTipString ("Select trigger slope or Auto (untriggered roll)")
316 wx.EVT_CHOICE (self, 1005, self.trig_mode_choice_event)
317 ctrlbox.Add (self.trig_mode_choice, 0, wx.ALIGN_CENTER)
319 trig_level50 = wx.Button (self, 1006, "50%")
320 trig_level50.SetToolTipString ("Set trigger level to 50%")
321 wx.EVT_BUTTON (self, 1006, self.set_trig_level50)
322 ctrlbox.Add (trig_level50, 0, wx.EXPAND)
324 run_stop = wx.Button (self, 1007, "Run/Stop")
325 run_stop.SetToolTipString ("Toggle Run/Stop mode")
326 wx.EVT_BUTTON (self, 1007, self.run_stop)
327 ctrlbox.Add (run_stop, 0, wx.EXPAND)
329 ctrlbox.Add ((10, 0) ,1) # stretchy space
331 ctrlbox.Add (wx.StaticText (self, -1, "Fmt: "), 0, wx.ALIGN_CENTER)
332 self.marker_choice = wx.Choice (self, 1002, choices = self._marker_choices)
333 self.marker_choice.SetToolTipString ("Select plotting with lines, pluses or dots")
334 wx.EVT_CHOICE (self, 1002, self.marker_choice_event)
335 ctrlbox.Add (self.marker_choice, 0, wx.ALIGN_CENTER)
337 self.xy_choice = wx.Choice (self, 1003, choices = ['X:t', 'X:Y'])
338 self.xy_choice.SetToolTipString ("Select X vs time or X vs Y display")
339 wx.EVT_CHOICE (self, 1003, self.xy_choice_event)
340 ctrlbox.Add (self.xy_choice, 0, wx.ALIGN_CENTER)
344 _marker_choices = ['line', 'plus', 'dot']
346 def update_timebase_label (self):
347 time_per_div = self.info.get_time_per_div ()
348 s = ' ' + eng_notation.num_to_str (time_per_div) + 's/div'
349 self.time_base_label.SetLabel (s)
351 def decr_timebase (self, evt):
352 self.info.time_scale_cursor.prev ()
353 self.update_timebase_label ()
355 def incr_timebase (self, evt):
356 self.info.time_scale_cursor.next ()
357 self.update_timebase_label ()
359 def update_v_scale_label (self):
360 volts_per_div = self.info.get_volts_per_div ()
361 s = ' ' + eng_notation.num_to_str (volts_per_div) + '/div' # Not V/div
362 self.v_scale_label.SetLabel (s)
364 def decr_v_scale (self, evt):
365 self.info.v_scale_cursor.prev ()
366 self.update_v_scale_label ()
368 def incr_v_scale (self, evt):
369 self.info.v_scale_cursor.next ()
370 self.update_v_scale_label ()
372 def marker_choice_event (self, evt):
376 def set_autorange(self, on):
378 self.v_scale_label.SetLabel(" (auto)")
379 self.info.autorange = True
380 self.autorange_checkbox.SetValue(True)
381 self.inc_v_button.Enable(False)
382 self.dec_v_button.Enable(False)
384 if self.graph.y_range:
385 (l,u) = self.graph.y_range # found by autorange
386 self.info.v_scale_cursor.set_index_by_value((u-l)/8.0)
387 self.update_v_scale_label()
388 self.info.autorange = False
389 self.autorange_checkbox.SetValue(False)
390 self.inc_v_button.Enable(True)
391 self.dec_v_button.Enable(True)
393 def autorange_checkbox_event(self, evt):
395 self.set_autorange(True)
397 self.set_autorange(False)
399 def set_marker (self, s):
400 self.info.set_marker (s) # set info for drawing routines
401 i = self.marker_choice.FindString (s)
402 assert i >= 0, "Hmmm, set_marker problem"
403 self.marker_choice.SetSelection (i)
405 def set_format_line (self):
406 self.set_marker ('line')
408 def set_format_dot (self):
409 self.set_marker ('dot')
411 def set_format_plus (self):
412 self.set_marker ('plus')
414 def xy_choice_event (self, evt):
416 self.info.xy = s == 'X:Y'
418 def trig_chan_choice_event (self, evt):
421 self.info.scopesink.set_trigger_channel (ch)
423 def trig_mode_choice_event (self, evt):
424 sink = self.info.scopesink
427 sink.set_trigger_mode (gr.gr_TRIG_POS_SLOPE)
429 sink.set_trigger_mode (gr.gr_TRIG_NEG_SLOPE)
431 sink.set_trigger_mode (gr.gr_TRIG_AUTO)
433 assert 0, "Bad trig_mode_choice string"
435 def set_trig_level50 (self, evt):
436 self.info.scopesink.set_trigger_level_auto ()
438 def run_stop (self, evt):
439 self.info.running = not self.info.running
442 class graph_window (plot.PlotCanvas):
444 channel_colors = ['BLUE', 'RED',
445 'CYAN', 'MAGENTA', 'GREEN', 'YELLOW']
447 def __init__ (self, info, parent, id = -1,
448 pos = wx.DefaultPosition, size = (640, 240),
449 style = wx.DEFAULT_FRAME_STYLE, name = ""):
450 plot.PlotCanvas.__init__ (self, parent, id, pos, size, style, name)
452 self.SetXUseScopeTicks (True)
453 self.SetEnableGrid (True)
454 self.SetEnableZoom (True)
455 self.SetEnableLegend(True)
456 # self.SetBackgroundColour ('black')
461 self.avg_y_min = None
462 self.avg_y_max = None
463 self.avg_x_min = None
464 self.avg_x_max = None
466 EVT_DATA_EVENT (self, self.format_data)
468 self.input_watcher = input_watcher (info.msgq, self, info.frame_decim)
470 def channel_color (self, ch):
471 return self.channel_colors[ch % len(self.channel_colors)]
473 def format_data (self, evt):
474 if not self.info.running:
478 self.format_xy_data (evt)
483 nchannels = len (records)
484 npoints = len (records[0])
488 Ts = 1.0 / (info.get_sample_rate () / info.get_decimation_rate ())
489 x_vals = Ts * numpy.arange (-npoints/2, npoints/2)
491 # preliminary clipping based on time axis here, instead of in graphics code
492 time_per_window = self.info.get_time_per_div () * 10
493 n = int (time_per_window / Ts + 0.5)
494 n = n & ~0x1 # make even
495 n = max (2, min (n, npoints))
497 self.SetXUseScopeTicks (True) # use 10 divisions, no labels
499 for ch in range(nchannels):
502 # plot middle n points of record
506 # points = zip (x_vals[lb:ub], r[lb:ub])
507 points = numpy.zeros ((ub-lb, 2), numpy.float64)
508 points[:,0] = x_vals[lb:ub]
509 points[:,1] = r[lb:ub]
511 m = info.get_marker ()
513 objects.append (plot.PolyLine (points,
514 colour=self.channel_color (ch),
515 legend=('Ch%d' % (ch+1,))))
517 objects.append (plot.PolyMarker (points,
519 colour=self.channel_color (ch),
520 legend=('Ch%d' % (ch+1,))))
522 graphics = plot.PlotGraphics (objects,
523 title=self.info.title,
524 xLabel = '', yLabel = '')
526 time_per_div = info.get_time_per_div ()
527 x_range = (-5.0 * time_per_div, 5.0 * time_per_div) # ranges are tuples!
528 volts_per_div = info.get_volts_per_div ()
529 if not self.info.autorange:
530 self.y_range = (-4.0 * volts_per_div, 4.0 * volts_per_div)
531 self.Draw (graphics, xAxis=x_range, yAxis=self.y_range)
532 self.update_y_range () # autorange to self.y_range
535 def format_xy_data (self, evt):
538 nchannels = len (records)
539 npoints = len (records[0])
545 # points = zip (records[0], records[1])
546 points = numpy.zeros ((len(records[0]), 2), numpy.float32)
547 points[:,0] = records[0]
548 points[:,1] = records[1]
550 self.SetXUseScopeTicks (False)
552 m = info.get_marker ()
554 objects.append (plot.PolyLine (points,
555 colour=self.channel_color (0)))
557 objects.append (plot.PolyMarker (points,
559 colour=self.channel_color (0)))
561 graphics = plot.PlotGraphics (objects,
562 title=self.info.title,
563 xLabel = 'I', yLabel = 'Q')
565 self.Draw (graphics, xAxis=self.x_range, yAxis=self.y_range)
566 self.update_y_range ()
567 self.update_x_range ()
570 def update_y_range (self):
572 graphics = self.last_draw[0]
573 p1, p2 = graphics.boundingBox () # min, max points of graphics
575 if self.avg_y_min: # prevent vertical scale from jumping abruptly --?
576 self.avg_y_min = p1[1] * alpha + self.avg_y_min * (1 - alpha)
577 self.avg_y_max = p2[1] * alpha + self.avg_y_max * (1 - alpha)
578 else: # initial guess
579 self.avg_y_min = p1[1] # -500.0 workaround, sometimes p1 is ~ 10^35
580 self.avg_y_max = p2[1] # 500.0
582 self.y_range = self._axisInterval ('auto', self.avg_y_min, self.avg_y_max)
583 # print "p1 %s p2 %s y_min %s y_max %s y_range %s" \
584 # % (p1, p2, self.avg_y_min, self.avg_y_max, self.y_range)
587 def update_x_range (self):
589 graphics = self.last_draw[0]
590 p1, p2 = graphics.boundingBox () # min, max points of graphics
593 self.avg_x_min = p1[0] * alpha + self.avg_x_min * (1 - alpha)
594 self.avg_x_max = p2[0] * alpha + self.avg_x_max * (1 - alpha)
596 self.avg_x_min = p1[0]
597 self.avg_x_max = p2[0]
599 self.x_range = self._axisInterval ('auto', self.avg_x_min, self.avg_x_max)
602 # ----------------------------------------------------------------
603 # Stand-alone test application
604 # ----------------------------------------------------------------
606 class test_top_block (stdgui2.std_top_block):
607 def __init__(self, frame, panel, vbox, argv):
608 stdgui2.std_top_block.__init__ (self, frame, panel, vbox, argv)
611 frame_decim = int(argv[1])
616 v_scale = float(argv[2]) # start up at this v_scale value
618 v_scale = None # start up in autorange mode, default
621 t_scale = float(argv[3]) # start up at this t_scale value
623 t_scale = None # old behavior
625 print "frame decim %s v_scale %s t_scale %s" % (frame_decim,v_scale,t_scale)
629 # Generate a complex sinusoid
630 self.src0 = gr.sig_source_c (input_rate, gr.GR_SIN_WAVE, 25.1e3, 1e3)
632 # We add this throttle block so that this demo doesn't suck down
633 # all the CPU available. You normally wouldn't use it...
634 self.thr = gr.throttle(gr.sizeof_gr_complex, input_rate)
636 scope = scope_sink_c (panel,"Secret Data",sample_rate=input_rate,
637 frame_decim=frame_decim,
638 v_scale=v_scale, t_scale=t_scale)
639 vbox.Add (scope.win, 1, wx.EXPAND)
641 # Ultimately this will be
642 # self.connect("src0 throttle scope")
643 self.connect(self.src0, self.thr, scope)
646 app = stdgui2.stdapp (test_top_block, "O'Scope Test App")
649 if __name__ == '__main__':
652 # ----------------------------------------------------------------