/
rtanimexample.py
266 lines (185 loc) · 7.83 KB
/
rtanimexample.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
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
from rtlsdr import RtlSdr
import pyaudio
import sys
import threading
import Queue
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtGui import QWidget
#from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
#from matplotlib.figure import Figure
#from matplotlib import ticker #used to get rid of axes labels
#from matplotlib import animation
import cv2
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
class MainWindow(QMainWindow):
def __init__(self):
# set up py audio
self.pa = pyaudio.PyAudio()
self.stream = self.pa.open(format = pyaudio.paFloat32,
channels = 1,
rate = 48000,
output = True)
# set up rtlsdr
self.sdr = RtlSdrSampler()
self.sdr.num_samples = 32768
self.sdr.center_freq = 94.9e6
self.sdr.sample_rate = 1.2e6
self.sdr.gain = 22.9
# create the Qt ui
QMainWindow.__init__(self)
self.setupUi()
#self.spec = np.zeros((820,600))
print 'finished setting up'
# create a sampler object.
# Note that sdr.read_samples_async creates its own background thread
self.sdr.beginSampling()
# create a processor daemon (background process)
self.process_d = MakeDaemon(self.process_th)
self.process_d.start()
print 'finished init'
# set up the main canvas for plotting stuff
# doing this last because p.spec needs to be set up before drawing it
#self.initCanvas()
self.main_frame = cv2.namedWindow('Spectrum')
def play(self,samples):
self.stream.write( samples.astype(np.float32).tostring() )
def draw_image(self,idk):
self.axes.clear()
self.axes.imshow(self.p.spec, cmap='spectral')
self.axes.xaxis.set_major_locator(ticker.NullLocator())
self.axes.yaxis.set_major_locator(ticker.NullLocator())
self.axes.set_aspect('auto',adjustable='box',anchor='NW')
self.canvas.draw()
def process_th(self):
self.p = Processor()
while(1):
try:
samples = self.sdr.sample_buffer.get()
except:
break # used to end process when program terminates
processed = self.p.process(samples)
self.sdr.sample_buffer.task_done()
self.play(processed)
# self.spec = np.roll(self.spec,1,axis = 1)
#self.spec[:,0] = processed[0]
#self.draw_image(spec)
def initCanvas(self):
self.main_frame = QWidget()
self.dpi = 100
self.fig = Figure((7.29,4.20), dpi=self.dpi)
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self.main_frame)
self.setCentralWidget(self.main_frame)
self.axes = self.fig.add_subplot(111) #, aspect=200/431)
self.axes.xaxis.set_major_locator(ticker.NullLocator())
self.axes.yaxis.set_major_locator(ticker.NullLocator())
#self.axes.invert_yaxis
self.anim = animation.FuncAnimation(self.fig,self.draw_image,interval=100,blit=False)
def gen_spec(self,x,m):
itsreal = np.isreal(x[0])
lx = x.size
nt = (lx +m -1) // m
xb = np.append(x,np.zeros(-lx+nt*m))
xc = np.append(np.roll(x,int(m/2)),np.zeros(nt*m - lx))
xr = np.reshape(xb, (m,nt), order='F') * np.outer(np.hanning(m),np.ones(nt))
xs = np.reshape(xc, (m,nt), order='F') * np.outer(np.hanning(m),np.ones(nt))
xm = np.zeros((m,2*nt),dtype='complex')
xm[:,::2] = xr
xm[:,1::2] = xs
#xm=xr
if itsreal:
spec = np.fft.fft(xm,m,axis=0)[int(m/2):]
else:
spec = np.fft.fftshift(np.fft.fft(xm,m,axis=0))
mx = np.max(spec)
pwr = 64*(20* np.log(np.abs(spec)/mx + 1e-6) + 60 )/60
return np.real(pwr)
def setupUi(self):
self.setWindowTitle('Demo: Real Time with RtlSdr')
self.setObjectName(_fromUtf8("MainWindow"))
self.resize(729, 451)
#self.centralwidget = QtGui.QWidget(self)
#self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
#self.setCentralWidget(self.centralwidget)
#self.plotFrame = QWidget(self.centralwidget)
#self.plotFrame.setGeometry(QtCore.QRect(40, 40, 689, 411))
#self.plotFrame.setObjectName(_fromUtf8("plotFrame"))
def __del__(self):
# Program will continue running in the background unless the RTL is told to stop sampling
self.sdr.cancel_read_async()
print "sdr closed"
self.sdr.close()
print "pyaudio terminated"
self.pa.terminate()
# sys.exit()
class RtlSdrSampler(RtlSdr):
num_samples = 32768 # default
def __init__(self):
RtlSdr.__init__(self)
# create a Queue for read_samples_async
self.sample_buffer = Queue.Queue(maxsize=10)
def sampler_callback(self,samples,context):
self.sample_buffer.put(samples)
def beginSampling(self):
self.sample_t = threading.Thread(target=self.read_samples_async,args=(self.sampler_callback,self.num_samples))
self.sample_t.start()
print 'started sampling async'
class Processor:
prevB = 0
prevConv1 = np.zeros(256)
prevConv2 = np.zeros(256)
prevConv3 = np.zeros(128)
spec = np.zeros((820,600))
def process(self,samples):
h = signal.firwin(256,80000,nyq=1.2e6/2)
output = signal.fftconvolve(samples,h)
output[:h.size/2] += self.prevConv1[h.size/2:] #add the latter half of tail end of the previous convolution
outputa = np.append(self.prevConv1[:h.size/2], output) # also delayed by half size of h so append the first half
self.prevConv1 = output[output.size-h.size:] # set the tail for next iteration
lp_samples = outputa[:output.size-h.size:5] # chop off the tail and decimate
#lp_samples = output[::5]
dmod = np.zeros(lp_samples.size)
A = lp_samples[1:]
B = lp_samples[:lp_samples.size-1]
dmod[1:] = np.real(np.angle(A * np.conj(B))) / (np.pi)
dmod[0] = np.real(np.angle(lp_samples[0] * np.conj(self.prevB))) / (np.pi)
self.prevB = lp_samples[lp_samples.size-1]
h = signal.firwin(256,1.6e4,nyq=1.2e5)
output = signal.fftconvolve(dmod,h)
output[:h.size/2] += self.prevConv2[h.size/2:] #add the latter half of tail end of the previous convolution
outputa = np.append(self.prevConv2[:h.size/2], output) # also delayed by half size of h so append the first half
self.prevConv2 = output[output.size-h.size:] # set the tail for next iteration
audible = outputa[:output.size-h.size:5] # chop off the tail and decimate
spectrum = np.log(np.abs( np.fft.fftshift(np.fft.fft(dmod))))[::8] #smaller spectrum to handle when drawing
self.spec = np.roll(self.spec,1,axis = 1)
self.spec[:,0] = spectrum
spectsc = cv2.convertScaleAbs(self.spec,alpha=255/np.max(self.spec))
spect = cv2.applyColorMap(spectsc,cv2.COLORMAP_JET)
cv2.imshow('Spectrum',spect)
cv2.waitKey(1)
return np.real(.5*audible)
class MakeDaemon(threading.Thread):
def __init__(self, function, args=None):
threading.Thread.__init__(self)
self.runnable = function
self.args = args
self.daemon = True
def run(self):
self.runnable()
def main():
app = QtGui.QApplication(sys.argv)
frame = MainWindow()
frame.show()
app.exec_()
cv2.destroyAllWindows()
frame.__del__()
main()