def thread_task(self): """ """ self.data = self.Qin.get() if self.Qout: self.Qout.put(self.data) cmplx_data = unpack_to_complex(self.data) datalen = len(cmplx_data) self.logger.debug("thread_task: obtained %d complex samples from the queue", datalen) num_spectra = datalen/self.num_freqs self.logger.debug("thread_task: %d spectra will be processed",num_spectra) avg = zeros(self.num_freqs) for i in range(num_spectra-1): index = i*self.num_freqs self.logger.debug("thread_task: taking data from %d to %d", index,index+self.num_freqs) dataslice = cmplx_data[index:index+self.num_freqs] self.logger.debug("thread_task: spectrum has %d points", len(dataslice)) xform = fft(dataslice) spectrum = fftshift(xform) avg += abs(spectrum*conj(spectrum)) self.logger.debug("thread_task: plotting") self.specaxes.clear() self.specaxes.semilogy(avg) self.logger.debug("thread_task: plot done") grid()
def get_data_block(self, num_samples=None): """ """ rawdata = self.synch_read(num=num_samples) if rawdata.min() < -125 or rawdata.max() > 125: module_logger.warning("data min=%d, max=%d", rawdata.min(), rawdata.max()) data = unpack_to_complex(rawdata) return data
def grab_SDR_spectrum(self): """ Grab a set of samples and compute the power spectrum Example of timing ================= On server:: rtl_tcp -a 192.168.0.13 -f 89900000 -s 200000 Found 1 device(s). Found Rafael Micro R820T tuner Using Generic RTL2832U OEM Tuned to 89900000 Hz. listening... client accepted! set freq 89900000 set sample rate 200000 On client:: In [1]: from RealtekSDR.TCPclient import RtlTCP In [2]: from RealtekSDR.stations import FM_freq In [3]: sr = 200000 In [4]: freq = FM_freq["KCRW"] In [5]: sdr = RtlTCP(samplerate=sr, freq=int(freq*1e6)) In [6]: t0 = time(); spectrum = sdr.grab_SDR_spectrum(); t1 = time() In [7]: t1-t0 Out[7]: 0.0011088848114013672 It requires 5 us to take one complex sample. BUFFER_SIZE = 1024 means 512 complex samples which takes 2.56 ms so we can process faster than the spectrum refresh rate. """ not_read = True while not_read: try: buf = self.conn.recv(BUFFER_SIZE) except socket.error as (code, msg): if code != errno.EINTR: raise Exception(msg) if len(buf) == BUFFER_SIZE: rawdata = unpack(str(len(buf))+'b', buf) data = unpack_to_complex(array(rawdata)) self.logger.debug("grab_SDR_spectrum: got %d", len(data)) xform = fft(data) shifted = fftshift(xform) spectrum = abs(shifted*conj(shifted)) not_read = False elif len(buf) == 0: self.logger.warning("grab_SDR_spectrum: server died") self.conn.close() exit() else: self.logger.warning("grab_SDR_spectrum: short read")
def get_power_scan(self, start, end, step, gain=0): """ Performs a power scan between two frequencies with a given step size. Returns lists with frequencies, LSB powers, USB powers, total powers, LSB voltages, USB voltages. @param start : lower end of scan in MHz. @type start : float or int. @param end : upper end of scan in MHz. @type end : float or int @param step : step size and sampling rate in MHz @type step : float or int @return: tuple(freqs,pwrl,pwru,pwr,signll,signlu) """ freqs = [] signlu = [] signll = [] pwru = [] pwrl = [] pwr = [] for freq in arange(start,end,step): # MHz cf = self.set_freq(int(int(freq*1000000))) freqs.append(cf/1e6-0.25*step) freqs.append(cf/1e6+0.25*step) status = self.reset_buffer() sleep(0.01) rawdata = self.synch_read() if rawdata.min() < -120 or rawdata.max() > 120: module_logger.warning( "get_power_scan: saturating; %7.2f MHz, min=%d, max=%d", cf/1.e6, rawdata.min(), rawdata.max()) data = unpack_to_complex(rawdata) module_logger.debug("get_power_scan: %7.2f MHz, min=%s, max=%s", cf/1.e6, str(data.min()),str(data.max())) datalen = len(data) lsb,usb = sideband_separate(data) signll += list(lsb) signlu += list(usb) LSB = (lsb**2).sum()/datalen USB = (usb**2).sum()/datalen pwrl.append(LSB) pwru.append(USB) pwr.append(LSB) pwr.append(USB) return freqs,pwrl,pwru,pwr,signll,signlu
print args samplerate = float(args.samplerate) centerfreq = float(args.centerfreq) else: raise RuntimeError("Invalid selection") num_bins = 1024 num_spec = 2048 refreshinterval = 1/(samplerate/1024)*1e6 # usec bandwidth = samplerate freqs = array(arange(centerfreq-samplerate/2, centerfreq+samplerate/2, samplerate/num_bins))/1e6 # kHz fd = open(files[choice],"r") buf = fd.read() fd.close() rawdata = unpack(str(len(buf))+'b', buf) data = unpack_to_complex(array(rawdata)) image = make_spectrogram(data,num_spec,num_bins) extent=(freqs[0], freqs[-1], 0, num_spec*refreshinterval) show_image(image, extent) show() response = raw_input("Save image? ") if response[0] in "yY": savefig("Figures/spectrum.png")
waterfall_bottom_axes.set_ylabel(ylabel) # add a colorbar on the right colorbar_axes = fig.add_axes([0.85,0.05,.15,.9],aspect=20) fig.colorbar(waterfall_artist_bottom, cax=colorbar_axes) fig.canvas.draw() fig.show() run = True buf = s.recv(BUFFER_SIZE) print buf[:4] while run: try: buf = s.recv(BUFFER_SIZE) rawdata = unpack(str(len(buf))+'b', buf) cmplx_data = unpack_to_complex(array(rawdata)).reshape(nch,1) ydata = unpack_to_complex(array(rawdata)).reshape(nch,1) xform = fft(ydata) shifted = fftshift(xform) spectrum = (shifted*conj(shifted)).real water_spectrum_lines[0].set_ydata(spectrum) waterfall_top_axes.redraw_in_frame() waterfall_top_axes.draw_artist(water_spectrum_lines[0]) data = np.append(data,spectrum,1) im = data[oldest_displayed:oldest_displayed+nspec,:] if waterfall_on: waterfall_bottom_axes.cla() # Just update the image data waterfall_artist_bottom.set_data(im) waterfall_bottom_axes.draw_artist(waterfall_artist_bottom)
#cf = int(FM_freq['KCRW']*1e6) sr = 2000000 rtlsdr = init_sdr() freq, samp_rate, gain = rtlsdr.state() centerfreq, samplerate = rtlsdr.configure(cf,sr) # Let's get some data using the synchronous read method rawdata = rtlsdr.synch_read() print "raw data samples:",rawdata[:16] status = rtlsdr.close() print "Close status:",status if plot_it: # Now do something with the data data = unpack_to_complex(rawdata) datalen = len(data) num_bins = 512 num_spec = datalen/num_bins freqs = array(arange(centerfreq-samplerate/2, centerfreq+samplerate/2, samplerate/num_bins))/1e6 # MHz if normalize: coeffile = open("baseline_coefs.pkl","rb") coef_dict = load(coeffile) coeffile.close() coefs = coef_dict[float(sr/1e6)] print "Coefficients loaded" normalizer = 1./chebval(freqs-centerfreq/1.e6,coefs) image = make_spectrogram(data, num_spec, num_bins, log=True, normalizer=normalizer)