當前位置: 首頁>>代碼示例>>Python>>正文


Python RtlSdr.close方法代碼示例

本文整理匯總了Python中rtlsdr.RtlSdr.close方法的典型用法代碼示例。如果您正苦於以下問題:Python RtlSdr.close方法的具體用法?Python RtlSdr.close怎麽用?Python RtlSdr.close使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在rtlsdr.RtlSdr的用法示例。


在下文中一共展示了RtlSdr.close方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: main

# 需要導入模塊: from rtlsdr import RtlSdr [as 別名]
# 或者: from rtlsdr.RtlSdr import close [as 別名]
def main():
    sdr = RtlSdr()

    print 'Configuring SDR...'
    sdr.rs = 2.4e6
    sdr.fc = 100e6
    sdr.gain = 10
    print '  sample rate: %0.6f MHz' % (sdr.rs/1e6)
    print '  center frequency %0.6f MHz' % (sdr.fc/1e6)
    print '  gain: %d dB' % sdr.gain

    print 'Reading samples...'
    samples = sdr.read_samples(256*1024)
    print '  signal mean:', sum(samples)/len(samples)

    print 'Testing callback...'
    sdr.read_samples_async(test_callback, 256*1024)

    try:
        import pylab as mpl

        print 'Testing spectrum plotting...'
        mpl.figure()
        mpl.psd(samples, NFFT=1024, Fc=sdr.fc/1e6, Fs=sdr.rs/1e6)

        mpl.show()
    except:
        # matplotlib not installed/working
        pass

    print 'Done\n'
    sdr.close()
開發者ID:Mondego,項目名稱:pyreco,代碼行數:34,代碼來源:allPythonContent.py

示例2: main

# 需要導入模塊: from rtlsdr import RtlSdr [as 別名]
# 或者: from rtlsdr.RtlSdr import close [as 別名]
async def main():
    import math

    sdr = RtlSdr()

    print('Configuring SDR...')
    sdr.rs = 2.4e6
    sdr.fc = 100e6
    sdr.gain = 10
    print('  sample rate: %0.6f MHz' % (sdr.rs/1e6))
    print('  center frequency %0.6f MHz' % (sdr.fc/1e6))
    print('  gain: %d dB' % sdr.gain)

    print('Streaming samples...')

    i = 0
    async for samples in sdr.stream():
        power = sum(abs(s)**2 for s in samples) / len(samples)
        print('Relative power:', 10*math.log10(power), 'dB')

        i += 1

        if i > 100:
            sdr.stop()
            break

    print('Done')

    sdr.close()
開發者ID:Erae11,項目名稱:pyrtlsdr,代碼行數:31,代碼來源:rtlsdraio.py

示例3: Rtl_threading

# 需要導入模塊: from rtlsdr import RtlSdr [as 別名]
# 或者: from rtlsdr.RtlSdr import close [as 別名]
class Rtl_threading(threading.Thread):
	def __init__(self, addr, fc, fs, size, corr):
		'''Add one more augument, corr'''
		threading.Thread.__init__(self)
		self.sdr = RtlSdr(addr)
		# configure device
		self.sdr.sample_rate = fs;  # Hz
		self.sdr.center_freq = fc;     # Hz
		# self.freq_correction = corr;   # PPM
		if addr==1:
			self.sdr.gain = 32.8
		else: #0
			self.sdr.gain = 32.8
		# init param
		self.addr = addr;
		self.size = size
		self.counter = 0;

#0.0 0.9 1.4 2.7 3.7 7.7 8.7 12.5 14.4 15.7 16.6 19.7 20.7 22.9 25.4 28.0 29.7 32.8 33.8 36.4 37.2 38.6 40.2 42.1 43.4 43.9 44.5 48.0 49.6

	def run(self):
		# start lock to avoid reading the same data
		global event, output; #init the synchronization
		if event.isSet():
			event.clear()
			event.wait()
		else:
			event.set()
		output[self.addr] = self.sdr.read_samples(self.size);
	def close(self):
		self.sdr.close();
開發者ID:TuringTW,項目名稱:SoftwareRadar,代碼行數:33,代碼來源:go_rt.py

示例4: __init__

# 需要導入模塊: from rtlsdr import RtlSdr [as 別名]
# 或者: from rtlsdr.RtlSdr import close [as 別名]
class SDR:
    def __init__(self,freq):
        self.sample_rate = 1e6

        self.center_freq = freq
        self.gain = 36

        self.sdr =  RtlSdr()
        self.sdr.direct_sampling = 1
        self.sdr.sample_rate = self.sample_rate
        self.sdr.center_freq = self.center_freq
        self.sdr.gain = self.gain
    def __del__(self):
        self.sdr.close()
開發者ID:peragwin,項目名稱:fmradio-qt,代碼行數:16,代碼來源:radio_minimal.py

示例5: main

# 需要導入模塊: from rtlsdr import RtlSdr [as 別名]
# 或者: from rtlsdr.RtlSdr import close [as 別名]
def main():
    sdr = RtlSdr()
    wf = Waterfall(sdr)

    # some defaults
    # Sample rate
    sdr.rs = 1e6
    sdr.set_direct_sampling('q')

    sdr.fc = 0
    sdr.gain = 10

    wf.start()

    # cleanup
    sdr.close()
開發者ID:tarquasso,項目名稱:softroboticfish4,代碼行數:18,代碼來源:demo_waterfall.py

示例6: transmit_and_capture

# 需要導入模塊: from rtlsdr import RtlSdr [as 別名]
# 或者: from rtlsdr.RtlSdr import close [as 別名]
def transmit_and_capture(data, outfile, length, title='Captured Data', verbose=False, fs_audio=48000, fs_sdr=240000, fc0=443.650e6,  plot=False):
    """Transmit and receive a signal.
    length seconds
    """
    sdr = RtlSdr()          # Create an RtlSdr object
    p = pyaudio.PyAudio()   # Create a PyAudio object
    Nsamples=256000*length
    fc = fc0*(1.0-85e-6)

    # Get device numbers
    din, dout, dusb = audio_dev_numbers(p, in_name='USB', out_name='default', debug=verbose)

    # Create SDR capture thread as daemon
    capture = threading.Thread(target=sdr_record, args=(sdr, outfile, Nsamples, fc, fs_sdr))
    capture.daemon = True

    # Create play thread as daemon
    play = threading.Thread(target=play_audio, args=(data, p, fs_audio, dusb))
    play.daemon = True

    # Start both threads
    capture.start()
    play.start()

    time.sleep(length+2)

    try:
        if plot:
            print 'Loading data...'
            y = np.load(outfile)
            print 'Generating plot...'
            tt,ff,xmf = myspectrogram_hann_ovlp(y, 256, fs_sdr, fc)
            plt.title(title)
            plt.show()
        else:
            print 'Captured data saved to ' + outfile
    except IOError:
        type, value, traceback = sys.exc_info()
        print('Error loading %s: %s' % (value.filename, value.strerror))
    except Exception as e:
        print 'Error: '+str(e)
    finally:
        print 'Cleaning up...'
        sdr.close()
        p.terminate()
        print 'Closed SDR and PyAudio'
開發者ID:viyer,項目名稱:ham_qam,代碼行數:48,代碼來源:lab3_1.py

示例7: main

# 需要導入模塊: from rtlsdr import RtlSdr [as 別名]
# 或者: from rtlsdr.RtlSdr import close [as 別名]
def main():

    gin=sys.argv[1]
    ppm=sys.argv[2]
    chn=sys.argv[3]
    if ppm=='0': ppm='1'
    if chn=='a': frc=161.975e6
    if chn=='b': frc=162.025e6

    sdr = RtlSdr()
    wf = Waterfall(sdr)

    # some defaults
    sdr.rs = 1e6
    sdr.fc = frc
    sdr.gain = float(gin)
    sdr.freq_correction = int(float(ppm))

    wf.start()

    # cleanup
    sdr.close()
開發者ID:OskarRaftegard,項目名稱:openplotter,代碼行數:24,代碼來源:waterfall.py

示例8: storing_stream_with_windows

# 需要導入模塊: from rtlsdr import RtlSdr [as 別名]
# 或者: from rtlsdr.RtlSdr import close [as 別名]
def storing_stream_with_windows(l, device_number, folder, subfolders, center_frequency, samplerate, gain, nsamples, freq_correction,
                   user_hash):
    l.acquire()
    print(device_number, center_frequency, samplerate, gain, nsamples, freq_correction)
    # configure device
    sdr = RtlSdr(device_index=device_number)
    sdr.center_freq = center_frequency
    sdr.sample_rate = samplerate
    if freq_correction:
        sdr.freq_correction = freq_correction   # PPM
    sdr.gain = gain
    print('hello world')
    timestamp = time.mktime(time.gmtime())
    samples = sdr.read_bytes(nsamples*2)
    sdr.close()
    l.release()

    print("save")
    basename = "{hash}_{freq}_{time:0.0f}".format(hash=user_hash, freq=center_frequency, time=timestamp)
    filename = path.join(folder, subfolders[0], "tmp_" + basename)
    # np.savez_compressed(filename, samples) # storing by numpy and copressing it
    '''np.save(filename, samples)
    os.rename(filename + ".npy",
              path.join(folder, subfolders[0], basename + ".npy"))'''

    f = open(filename, 'wb')
    f.write(samples)
    f.close()
    os.rename(filename,
              path.join(folder, subfolders[0], basename + ".dat"))

    del samples

    filename = path.join(folder, subfolders[1], basename + ".npy")
    sdrmeta(filename, device_number, folder, subfolders, center_frequency,
            samplerate, gain, nsamples, freq_correction, user_hash)

    return filename
開發者ID:aerospaceresearch,項目名稱:dgsn-node-io-radio,代碼行數:40,代碼來源:record-radio.py

示例9: FMRadio

# 需要導入模塊: from rtlsdr import RtlSdr [as 別名]
# 或者: from rtlsdr.RtlSdr import close [as 別名]

#.........這裏部分代碼省略.........

    def setFreq(self,freq):
        if freq % 2 == 0:
            freq += 1
        freq /= 10.0
        text = "%.1f MHz" % freq
        self.ui.curFreq.setText(text)
        self.center_freq = freq*1e6 #+ 250e3
        setf_t = threading.Thread(target=self.setF_th, args=[self.center_freq,])
        setf_t.start()
        setf_t.join()



    # This function is what is used to adjust the tuner on the RTL
    # Currently, it causes the program to crash if used after an unspecified period of inactivity
    #     commented lines are attempts that didn't work
    def setF_th(self,f):
        while(self.is_sampling == True):
            pass
        #self.sdr.cancel_read_async()
        time.sleep(.1)
        self.sdr.center_freq = f
        #self.getSamplesAsync()

    def setUseStereo(self,u):
        self.useStereo = u
    def setStereoWidth(self,w):
        self.stereoWidth = w/5

    def setDemodMain(self,s):
        self.demodMain = s
        self.demodSub1 = not s
        self.demodSub2 = not s
        #self.useStereo = True
    def setDemodSub1(self,s):
        self.demodMain = not s
        self.demodSub1 = s
        self.demodSub2 = not s
        #self.useStereo = False
    def setDemodSub2(self,s):
        self.demodMain = not s
        self.demodSub1 = not s
        self.demodSub2 = s
        #self.useStereo = False

    def setSpectrumOverall(self,s):
        #self.initplot()
        #self.cur_spectrogram = self.spectrogram
        self.plotOverall = s
        self.plotChannel = not s
        self.plotPlaying = not s
        self.plotWaveform = not s
    def setSpectrumChannel(self,s):
        #self.initplot()
        self.plotChannel = s
        self.plotOverall = not s
        self.plotPlaying = not s
        self.plotWaveform = not s
    def setSpectrumPlaying(self,s):
        #self.initplot()
        self.plotPlaying = s
        self.plotChannel = not s
        self.plotOverall= not s
        self.plotWaveform = not s
    def setSpectrumWaveform(self,s):
        self.plotWaveform = s
        self.plotPlaying = not s
        self.plotChannel = not s
        self.plotOverall= not s

    def setDemodFiltMedian(self,s):
        self.useMedianFilt = s
        self.useLPFilt = not s
    def setDemodFiltLP(self,s):
        self.useLPFilt = s
        self.useMedianFilt = not s
    def setDemodFiltSize(self,s):
        #if(s % 2 == 0):
        #    s+=1
        self.demodFiltSize = s

    def setAudioFiltUse(self,s):
        self.useAudioFilter = s
    def setAudioFiltSize(self,s):
        self.audioFilterSize = s

    def terminate(self):
        self.__del__()

    # Destructor - also used to exit the program when user clicks "Quit"
    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()
        cv2.destroyAllWindows()
開發者ID:peragwin,項目名稱:fmradio-qt,代碼行數:104,代碼來源:qtradio.py

示例10: WSHandler

# 需要導入模塊: from rtlsdr import RtlSdr [as 別名]
# 或者: from rtlsdr.RtlSdr import close [as 別名]
class WSHandler(tornado.websocket.WebSocketHandler):    
    def check_origin(self, origin):
        return True

    def open(self):        
        self.siggen = SigGen()
        self.sdr = RtlSdr()    
        self.scan = Scan(self.sdr)
        self.rotor = Rotor()
        self.callback = PeriodicCallback(self.send_values, timeInterval)
        

    def send_values(self):
        print "::WS: Begin scanning...."
        scan_vals = self.scan.scan()
        
        print "::WS: Detecting Signal Peaks...."
        peaks = detect_peaks(scan_vals)
        
        print "::WS: Sending peak vals to WS...."
        self.write_message("++")
        self.write_message(json_encode(peaks))

    def on_message(self, message):

        print ":: Recvd message: %s" % message
        
        if (message.startswith("==Frequency:")):
                
                str = message.split("|");
                freq = str[0].split(" ")[1]
                rxgain = str[1].split(" ")[1]
                
                print "::WS: Setting Tx Freq:" + freq
                self.siggen.setTxFreq(freq)
                
                print "::WS: Setting Rx Freq:" + freq + "| RxGain: " + rxgain
                self.scan.setFreqGain(freq, rxgain)
                
                print "::WS: Initializing Callback function..."
                self.callback.start()			
                
        elif (message.startswith("==TxOff")):
                print "::WS: Resetting Callback"
                self.callback.stop()
                
                print "::WS: Setting Tx Off"			
                self.siggen.setTxOff()
                
                print "::WS: Closing SDR instance"
                #self.sdr.close()
				
        elif (message.startswith("==Rotor:")):   # ==Rotor: R|2000
			
                str = message.split("|");
                dir = str[0].split(" ")[1]
                deg = str[1]
                self.rotor.setRotor(dir,deg)
        
                        

    def on_close(self):
        print "::WS: Resetting Callback"
        self.callback.stop()
                
        print "::WS: Setting Tx Off"			
        self.siggen.setTxOff()
        
        print "::WS: Closing SDR instance"
        self.sdr.close()
        self.rotor.close();
        self.siggen.close();
開發者ID:r4d10n,項目名稱:openlab,代碼行數:74,代碼來源:wvl-websocketserver.py

示例11: __init__

# 需要導入模塊: from rtlsdr import RtlSdr [as 別名]
# 或者: from rtlsdr.RtlSdr import close [as 別名]
class FMRadio:

    sample_buffer = Queue.Queue(maxsize=100)
    base_spectrum = np.ones(5780)

    def __init__(self,freq,N_samples):

        self.sample_rate = 1e6
        self.decim_r1 = 1e6/2e5 # for wideband fm
        self.decim_r2 = 2e5/44100 # for baseband recovery
        self.center_freq = freq+250e3
        self.gain = 36

        self.N_samples = N_samples
        self.is_sampling = False

        self.sdr =  RtlSdr()
        self.sdr.direct_sampling = 1
        self.sdr.sample_rate = self.sample_rate
        self.sdr.center_freq = self.center_freq
        self.sdr.gain = self.gain

        self.pa = pyaudio.PyAudio()
        self.stream = self.pa.open( format = pyaudio.paFloat32,
                                    channels = 1,
                                    rate = 44100,
                                    output = True)

        adj = 0
        hamming = 10*signal.hamming(self.N_samples*.10 + adj)
        lpf = np.append( np.zeros(self.N_samples*.45),hamming)
        self.lpf = np.roll(np.fft.fftshift(np.append(lpf,np.zeros(self.N_samples*.45))),int(-.25*self.N_samples))

    def __del__(self):
        print "sdr closed"
        self.sdr.close()
        print "pyaudio terminated"
        self.pa.terminate()

    def getSamples(self):
        #N_samples = self.N_samples # 1/24.4 seconds   ~46336 #approximately a 2048/44100 amount's time
        return self.sdr.read_samples(self.N_samples)

    def getSamplesAsync(self):
        #Asynchronous call. Meant to be put in a loop w/ a calback fn
        #print 'gonna sample'
        self.is_sampling = True
        samples = self.sdr.read_samples_async(self.sampleCallback,self.N_samples,context=self)

    def sampleCallback(self,samples,sself):

        self.is_sampling = False
        self.sample_buffer.put(samples)
        #print 'put some samples in the jar'

        # recursive loop
        #sself.getSamplesAsync()

    def demodulate_th(self):
        while(1):

            try:
                samples = self.sample_buffer.get()
                #samples2 = self.sample_buffer.get()
              #  print 'gottum'
            except:
                print "wtf idk no samples?"
                break

            out1 = self.demodulate(samples)
            self.sample_buffer.task_done()
            #out2 = self.demodulate(samples2)
            #self.sample_buffer.task_done()

            audio_out = out1 #np.append(out1,out2)

            self.play(audio_out)

        print 'gonna try to finish off the to-do list'
        sample_buffer.join()


    def demodulate(self,samples):
        # DEMODULATION CODE
        #samples = #self.sample_buffer.get()
        # LIMITER goes here

        # low pass & down sampling via fft


        spectrum = np.fft.fft(samples)*self.lpf

        toplot = False
        if(toplot):
            fig = plt.figure()
            plt.plot(np.abs(spectrum))
            plt.show()

# Decimate in two rounds. One to 200k, another to 44.1k
        # DECIMATE HERE. Note that we're looking at 1MHz bandwidth.
#.........這裏部分代碼省略.........
開發者ID:peragwin,項目名稱:fmradio-qt,代碼行數:103,代碼來源:radio-final.py

示例12: __init__

# 需要導入模塊: from rtlsdr import RtlSdr [as 別名]
# 或者: from rtlsdr.RtlSdr import close [as 別名]

#.........這裏部分代碼省略.........
    codes = np.argmax(np.array(corrs), 0)
    return maxes, codes

  def debounce(self, i, l, rxstr):
    try:
      if i != self.debounce_i or abs(l - self.debounce_l) > 1:
        self.rxcallback(rxstr)
    except AttributeError:
      self.rxcallback(rxstr)
    self.debounce_i = i
    self.debounce_l = l

  def extract(self, nc):
    for codeoffset in range(self.codelen):
      pkts = []
      codestr = "".join(map(repr, map(int, nc[codeoffset::self.codelen])))

      for p in self.tocheck[codeoffset]['pkts']:
        pkt = p + codestr[0:self.pktlen-len(p)]
        if len(pkt) < self.pktlen:
          pkts.append(pkt)
        elif len(self.footer) == 0 or pkt[-len(self.footer):] == self.footer:
          str = ""
          for j in range(0,len(pkt)-1,8):
            str += chr(int(pkt[j:j+8][::-1], 2))
          self.debounce(self.index, -len(p), str)
          sys.stdout.flush()

      codestr = self.tocheck[codeoffset]['last'] + codestr
      for ind in find_all(codestr, self.header):
        pkt = codestr[ind+len(self.header):ind+len(self.header)+self.pktlen]
        if len(pkt) < self.pktlen:
          pkts.append(pkt)
        elif len(self.footer) == 0 or pkt[-len(self.footer):] == self.footer:
          str = ""
          for j in range(0,len(pkt)-1,8):
            str += chr(int(pkt[j:j+8][::-1], 2))
          self.debounce(self.index, ind, str)
          sys.stdout.flush()
      self.tocheck[codeoffset]['pkts'] = [] + pkts
      self.tocheck[codeoffset]['last'] = "" + codestr[-len(self.header)+1:]

  def ddc(self, samp, sdr):
    s = np.asarray(samp)
    i, q = s[::2], s[1::2]
    i = np.mean(i.reshape(-1,self.decim), 1) # poor man's decimation
    q = np.mean(q.reshape(-1,self.decim), 1) # poor man's decimation
    iq = np.empty(len(i), 'complex')
    iq.real, iq.imag = i, q
    iq /= (255/2)
    iq -= (1 + 1j)

    baseband = np.concatenate((self.last, iq))
    self.last = iq
    mag, phase, dp  = self.bb2c(baseband)
    if self.mod == Mods.MAGNITUDE:
      sig = mag
    elif self.mod == Mods.PHASE:
      sig = phase
    elif self.mod == Mods.DPHASE:
      sig = dp
    else:
      sig = baseband
    corrs, codes = self.decode(sig)

    nc = codes[self.codelen:self.codelen+self.sampchips]
    self.extract(nc)

    self.index += 1

  def end(self):
    self.sdr.close()

  def plot(self):
    plt.ion()
    fig = plt.figure()
    ax1 = fig.add_subplot(311)
    ax1.plot(self.chips)
    ax2 = fig.add_subplot(312, sharex=ax1)
    ax2.plot(self.corrs)
    ax3 = fig.add_subplot(313, sharex=ax1)
    ax3.plot(self.demod)
    plt.show()

  def checkdemod(self, index, demod=None, packetlen=5):
    if demod is None:
      demod = self.demod
    l = packetlen*8+6+7
    b = self.demod[index:index+l*self.codelen:self.codelen]
    return chipsToString(np.concatenate(([1,0], b, [0])))

  def findstring(self, demod = None, packetlen=5):
    if demod is None:
      demod = self.demod
    find = []
    for i in range(len(demod)):
      s, c = self.checkdemod(i, demod, packetlen)
      if len(s) and s[0] == 'a' and s[-1] == 'x':
        find.append((i, s[1:-1]))
    return find
開發者ID:tarquasso,項目名稱:softroboticfish4,代碼行數:104,代碼來源:rx.py

示例13: FMRadio

# 需要導入模塊: from rtlsdr import RtlSdr [as 別名]
# 或者: from rtlsdr.RtlSdr import close [as 別名]

#.........這裏部分代碼省略.........
        self.plotChannel = not s
        self.plotOverall= not s
        self.plotWaveform = not s
    def setSpectrumWaveform(self,s):
        self.plotWaveform = s
        self.plotPlaying = not s
        self.plotChannel = not s
        self.plotOverall= not s

    def setDemodFiltMedian(self,s):
        self.useMedianFilt = s
        self.useLPFilt = not s
    def setDemodFiltLP(self,s):
        self.useLPFilt = s
        self.useMedianFilt = not s
    def setDemodFiltSize(self,s):
        if(s % 2 == 0):
            s+=1
        self.demodFiltSize = s

    def setAudioFiltUse(self,s):
        self.useAudioFilter = s
    def setAudioFiltSize(self,s):
        self.audioFilterSize = s

    def terminate(self):
        self.__del__()

    def __del__(self):
        #QtGui.QMainWindow.__del__()
        #Ui_MainWindow.__del__()
        #self.streamer.stop()
        #self.sampler_t.stop()
        print "sdr closed"
        self.sdr.close()
        print "pyaudio terminated"
        self.pa.terminate()
        sys.exit()

    def getSamples(self):
        #N_samples = self.N_samples # 1/24.4 seconds   ~46336 #approximately a 2048/44100 amount's time
        return self.sdr.read_samples(self.N_samples)

    def getSamplesAsync(self):
        #Asynchronous call. Meant to be put in a loop w/ a calback fn
        #print 'gonna sample'
        self.is_sampling = True
        samples = self.sdr.read_samples_async(self.sampleCallback,self.N_samples,context=self)

    def sampleCallback(self,samples,sself):

        self.is_sampling = False
        self.sample_buffer.put(samples)
        #print 'put some samples in the jar'

        # recursive loop
        #sself.getSamplesAsync()

    def demodulate_th(self):
        while(1):

            try:
                samples = self.sample_buffer.get()
                #samples2 = self.sample_buffer.get()
              #  print 'gottum'
            except:
開發者ID:peragwin,項目名稱:fmradio-qt,代碼行數:70,代碼來源:radio-multithread.py

示例14: Sampler

# 需要導入模塊: from rtlsdr import RtlSdr [as 別名]
# 或者: from rtlsdr.RtlSdr import close [as 別名]
class Sampler(QtCore.QObject):
    samplerError = QtCore.pyqtSignal(object)
    dataAcquired = QtCore.pyqtSignal(object)

    def __init__(self, gain, sampRate, freqs, numSamples, parent=None):
        super(Sampler, self).__init__(parent)
        self.gain = gain
        self.sampRate = sampRate
        self.freqs = freqs
        self.numSamples = numSamples
        self.offset = 0
        self.sdr = None
        self.errorMsg = None

        self.WORKING = True
        self.BREAK = False
        self.MEASURE = False

        try:
            self.sdr = RtlSdr()
            self.sdr.set_manual_gain_enabled(1)
            self.sdr.gain = self.gain
            self.sdr.sample_rate = self.sampRate
        except IOError:
            self.WORKING = False
            print "Failed to initiate device. Please reconnect."
            self.errorMsg = "Failed to initiate device. Please reconnect."
            self.samplerError.emit(self.errorMsg)

    def sampling(self):
        print 'Starting sampler...'
        while self.WORKING:
            prev = 0
            counter = 0
            gain = self.gain
            numSamples = self.numSamples
            self.BREAK = False
            self.sdr.gain = gain
            start = time.time()
            #print self.sdr.get_gain()
            for i in range(len(self.freqs)):
                if self.BREAK:
                    break
                else:
                    centerFreq = self.freqs[i]
                    #print "frequency: " + str(center_freq/1e6) + "MHz"
                    if centerFreq != prev:
                        try:
                            self.sdr.set_center_freq(centerFreq)
                        except:
                            self.WORKING = False
                            print "Device failure while setting center frequency"
                            self.errorMsg = "Device failure while setting center frequency"
                            self.samplerError.emit(self.errorMsg)
                            break
                        prev = centerFreq
                    else:
                        pass

                    #time.sleep(0.01)
                    try:
                        x = self.sdr.read_samples(2048)
                        data = self.sdr.read_samples(numSamples)

                    except:
                        self.WORKING = False
                        print "Device failure while getting samples"
                        self.errorMsg = "Device failure while getting samples"
                        self.samplerError.emit(self.errorMsg)
                        break

                    if self.MEASURE:
                        self.offset = np.mean(data)

                    counter += 1
                    self.dataAcquired.emit([i, centerFreq, data])

        if self.errorMsg is not None:
            self.samplerError.emit(self.errorMsg)
        if self.sdr is not None:
            self.sdr.close()
開發者ID:tapczan666,項目名稱:potworniak,代碼行數:83,代碼來源:sampler.py

示例15: main

# 需要導入模塊: from rtlsdr import RtlSdr [as 別名]
# 或者: from rtlsdr.RtlSdr import close [as 別名]

#.........這裏部分代碼省略.........
            jobs = []
            gain = 0
            calibration_finished = 0 # 1 means calibration is done

            while time.mktime(time.gmtime()) <= recording_start or calibration_finished == 0:
                # waiting for the time to be right :)
                time.sleep(10)
                print("still to wait", recording_start - time.mktime(time.gmtime()), "to record and",
                  recording_start - time.mktime(time.gmtime())- calibration_start, "to calibration")

                if time.mktime(time.gmtime()) > recording_start - calibration_start and calibration_finished == 0:
                    sdr = RtlSdr(device_index=device_number)
                    sdr.center_freq = center_frequency
                    sdr.sample_rate = samplerate
                    # sdr.freq_correction = 1   # PPM

                    # calibrating the dongle
                    if gain_start >= gain_end or gain_start >= 49.0:
                        print("fixed gain")
                        if gain_start==0 or gain_start > 49.0:
                            print("autogain")
                            gain = 'auto'
                        else:
                            gain = gain_start

                    else:
                        print("calibrated gain")
                        gain = calibrating_gain_with_windows(sdr, samplerate, gain_step, gain_start,
                                                             gain_end, signal_threshold)

                    print("used gain", gain)
                    sdr.gain = gain

                    sdr.close()
                    calibration_finished = 1

            utctime = time.mktime(time.gmtime())
            if utctime >= recording_start and utctime <= recording_stop:
                print("recording starts now...")
                for recs in range(2):
                    p = Process(target=storing_stream_with_windows, args=(lock, device_number, folder, subfolders,
                                                                          center_frequency, samplerate, gain, nsamples,
                                                                          freq_correction, user_hash))
                    jobs.append(p)
                    p.start()
                print("end")

                while time.mktime(time.gmtime()) <= recording_stop:
                    time.sleep(2)
                    for n, p in enumerate(jobs):
                        if not p.is_alive() and time.mktime(time.gmtime()) <= recording_stop:
                            jobs.pop(n)
                            recs += 1
                            p = Process(target=storing_stream_with_windows, args=(lock, device_number, folder,
                                                                                  subfolders, center_frequency,
                                                                                  samplerate, gain, nsamples,
                                                                                  freq_correction, user_hash))
                            jobs.append(p)
                            p.start()
                            print("rec number", recs, 'added')

            for job in jobs:
                job.join()

    elif platform.system() == "Linux" or platform.system() == "Linux2":
        print("detecting a linux")
開發者ID:aerospaceresearch,項目名稱:dgsn-node-io-radio,代碼行數:70,代碼來源:record-radio.py


注:本文中的rtlsdr.RtlSdr.close方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。