forked from govtmirror/gr-analyzer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gr_analyzer.py
executable file
·282 lines (219 loc) · 9.5 KB
/
gr_analyzer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
#!/usr/bin/env python
from __future__ import print_function
import os
import sys
import math
import time
import threading
import logging
from copy import copy
from gnuradio import gr
from gnuradio import blocks
from gnuradio import fft
from analyzer import (usrp_controller_cc,
bin_statistics_ff,
stitch_fft_segments_ff,
plotter_f)
from cli_parser import init_parser
from configuration import configuration
import gui
from usrp import usrp
class top_block(gr.top_block):
def __init__(self, cfg):
gr.top_block.__init__(self)
self.logger = logging.getLogger("gr-analyzer.top_block")
# Use 2 copies of the configuration:
# cgf - settings that matches the current state of the flowgraph
# pending_cfg - requested config changes that will be applied during
# the next run of configure
self.cfg = cfg
self.pending_cfg = copy(self.cfg)
if cfg.realtime:
# Attempt to enable realtime scheduling
r = gr.enable_realtime_scheduling()
if r != gr.RT_OK:
self.logger.warning("failed to enable realtime scheduling")
try:
self.usrp = usrp(cfg)
except RuntimeError as err:
print("Error initializing USRP." + str(err), file=sys.stderr)
sys.exit(0)
# The main loop blocks at the end of the loop until either continuous
# or single run mode is set.
self.continuous_run = threading.Event()
self.single_run = threading.Event()
self.plot_iface = gui.plot_interface(self)
self.rebuild_flowgraph = False
self.configure(initial=True)
def set_single_run(self):
self.clear_continuous_run()
if self.cfg.continuous_run:
self.rebuild_flowgraph = True
self.cfg.continuous_run = False
self.pending_cfg.continuous_run = False
self.single_run.set()
def clear_single_run(self):
self.single_run.clear()
def set_continuous_run(self):
self.clear_single_run()
if not self.cfg.continuous_run:
self.clear_exit_after_complete()
self.rebuild_flowgraph = True
self.pending_cfg.continuous_run = True
self.continuous_run.set()
def clear_continuous_run(self):
self.set_exit_after_complete()
self.continuous_run.clear()
def set_exit_after_complete(self):
self.ctrl.set_exit_after_complete()
def clear_exit_after_complete(self):
self.ctrl.clear_exit_after_complete()
def reconfigure(self, redraw_plot=False):
msg = "tb.reconfigure called - redraw_plot: {}"
self.logger.debug(msg.format(redraw_plot))
self.rebuild_flowgraph = True
self.set_exit_after_complete() # exit flowgraph to apply new config
if redraw_plot:
self.plot_iface.redraw_plot.set()
def configure(self, initial=False):
"""Configure or reconfigure the flowgraph"""
self.lock()
if self.usrp.apply_cfg(self.pending_cfg):
self.pending_cfg = copy(self.usrp.get_cfg())
# Apply any pending configuration changes
cfg = self.cfg = copy(self.pending_cfg)
if not initial:
self.disconnect_all()
self.msg_disconnect(self.plot, "gui_busy_notifier",
self.copy_if_gui_idle, "en")
self.ctrl = usrp_controller_cc(self.usrp.uhd,
cfg.center_freqs,
cfg.lo_offset,
cfg.skip_initial,
cfg.tune_delay,
cfg.fft_size * cfg.nframes)
if cfg.continuous_run:
self.set_continuous_run()
else:
self.set_single_run()
self.scaleV = blocks.multiply_const_cc(cfg.scale)
timedata_vlen = 1
self.timedata_sink = blocks.vector_sink_c(timedata_vlen)
stream_to_fft_vec = blocks.stream_to_vector(gr.sizeof_gr_complex,
cfg.fft_size)
forward = True
shift = True
self.fft = fft.fft_vcc(cfg.fft_size,
forward,
cfg.window_coefficients,
shift)
freqdata_vlen = cfg.fft_size
self.freqdata_sink = blocks.vector_sink_c(freqdata_vlen)
c2mag_sq = blocks.complex_to_mag_squared(cfg.fft_size)
stats = bin_statistics_ff(cfg.fft_size, cfg.nframes, cfg.detector)
power = sum(tap * tap for tap in cfg.window_coefficients)
# Divide magnitude-square by a constant to obtain power
# in Watts. Assumes unit of USRP source is volts.
impedance = 50.0 # ohms
Vsq2W_dB = -10.0 * math.log10(cfg.fft_size * power * impedance)
# Convert from Watts to dBm.
W2dBm = blocks.nlog10_ff(10.0, cfg.fft_size, 30 + Vsq2W_dB)
stitch = stitch_fft_segments_ff(cfg.fft_size,
cfg.n_segments,
cfg.overlap)
fft_vec_to_stream = blocks.vector_to_stream(gr.sizeof_float,
cfg.fft_size)
n_valid_bins = cfg.fft_size - (cfg.fft_size * (cfg.overlap / 2) * 2)
# FIXME: think about whether to cast to int vs round vs...
stitch_vec_len = int(cfg.n_segments * cfg.fft_size)
stream_to_stitch_vec = blocks.stream_to_vector(gr.sizeof_float,
stitch_vec_len)
plot_vec_len = int(cfg.n_segments * n_valid_bins)
# Only copy sample to plot if enabled to avoid overwhelming gui thread
self.copy_if_gui_idle = blocks.copy(gr.sizeof_float * plot_vec_len)
self.plot = plotter_f(self, plot_vec_len)
# Create the flowgraph:
#
# USRP - hardware source output stream of 32bit complex floats
# ctrl - copy N samples then call retune callback and loop
# scaleV - scale voltage by scalar to get calibrated output
# fft - compute forward FFT, complex in complex out
# mag^2 - convert vectors from complex to real by taking mag squared
# stats - linear average or peak detect vectors if nframes > 1
# W2dBm - convert volt to dBm
# stitch - overlap FFT segments by a certain number of bins
# copy - copy if gui thread is idle, else drop
# plot - plot data
#
# USRP > ctrl > fft > mag^2 > stats > W2dBm > stitch > copy > plot
self.connect(self.usrp.uhd, self.ctrl, self.scaleV)
if self.single_run.is_set():
self.logger.debug("Connected timedata_sink")
self.connect((self.scaleV, 0), self.timedata_sink)
else:
self.logger.debug("Disconnected timedata_sink")
self.connect((self.scaleV, 0), stream_to_fft_vec, self.fft)
if self.single_run.is_set():
self.logger.debug("Connected freqdata_sink")
self.connect((self.fft, 0), self.freqdata_sink)
else:
self.logger.debug("Disconnected freqdata_sink")
self.connect((self.fft, 0), c2mag_sq, stats, W2dBm, fft_vec_to_stream)
self.connect(fft_vec_to_stream, stream_to_stitch_vec, stitch)
self.connect(stitch, self.copy_if_gui_idle, self.plot)
self.msg_connect(self.plot, "gui_busy_notifier",
self.copy_if_gui_idle, "en")
self.unlock()
def set_sample_rate(self, rate):
new_rate = self.usrp.set_sample_rate(rate)
# Pass the actual samp rate back to cfgs so they have it before
# calling cfg.update()
requested_rate = self.cfg.sample_rate
self.pending_cfg.sample_rate = self.cfg.sample_rate = new_rate
# If the rate was adjusted, recalculate freqs and reconfigure flowgraph
if requested_rate != self.sample_rate:
self.pending_cfg.update()
self.reconfigure(redraw_plot=True)
def save_time_data_to_file(self, data):
print("NOOP")
def save_freq_data_to_file(self, data):
print("NOOP")
def main(tb):
"""Run the main loop of the program"""
logger = logging.getLogger('gr-analyzer.main')
gui_alive = True
while True:
# Execute flow graph and wait for it to stop
tb.run()
tb.clear_single_run()
if tb.continuous_run.is_set() and not tb.plot_iface.is_alive():
# GUI was destroyed while in continuous mode
return
while not (tb.single_run.is_set() or tb.continuous_run.is_set()):
# keep certain gui elements alive
gui_alive = tb.plot_iface.keep_alive()
if not gui_alive:
# GUI was destroyed while in single mode
return
# check run mode again in 1/4 second
time.sleep(.25)
tb.timedata_sink.reset()
tb.freqdata_sink.reset()
if tb.rebuild_flowgraph:
logger.info("rebuild flowgraph")
tb.configure()
tb.rebuild_flowgraph = False
if __name__ == '__main__':
parser = init_parser()
args = parser.parse_args()
cfg = configuration(args)
if cfg.debug:
print("pid = {}".format(os.getpid()))
raw_input("Press Enter to continue...")
tb = top_block(cfg)
try:
main(tb)
logging.getLogger('gr-analyzer').info("Exiting.")
except KeyboardInterrupt:
tb.stop()
tb.wait()