Example #1
0
def configure_sdr(frequency, offset, sample_rate):
    sdr = RtlSdr()
    center_frequency = frequency - offset 
    sdr.sample_rate = sample_rate
    sdr.center_freq = center_frequency
    sdr.gain = 'auto'
    return sdr
Example #2
0
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()
Example #3
0
async def streaming():
    size = 256
    x_vec = np.linspace(0, 5, size + 1)[0:-1]
    y_vec = np.random.randn(len(x_vec))
    line1 = []
    sdr = RtlSdr()
    sdr.sample_rate = 2.048e6  # Hz
    sdr.center_freq = 101e6  # Hz
    sdr.freq_correction = 60  # PPM
    sdr.gain = 4
    i = 0

    async for samples in sdr.stream(256):
        i = i + 1
        print("{i} sample")
        print(samples)
        for sample in samples:
            rand_val = sample * 10000
            y_vec[-1] = rand_val
            line1 = live_plotter(x_vec, y_vec, line1)
            y_vec = np.append(y_vec[1:], 0.0)
            print(rand_val)

    # to stop streaming:
    await sdr.stop()

    # done
    sdr.close()
Example #4
0
async def streaming():
    sdr = RtlSdr()
    # configure device
    Fs = 2.4e6  # Hz
    sdr.sample_rate = Fs  # Hz
    sdr.center_freq = 98e6  # Hz
    sdr.freq_correction = 60  # PPM
    sdr.gain = 'auto'
    # Sampling for 1 sec
    t_sampling = 1
    N_samples = round(Fs * t_sampling)
    samples = sdr.read_samples(N_samples)

    fig = plt.figure(1)
    plt.xlabel('Frequency (MHz)')
    plt.ylabel('Relative power (dB)')
    fig.show()

    async for samples in sdr.stream():

        plt.psd(samples,
                NFFT=1024,
                Fs=sdr.sample_rate / 1e6,
                Fc=sdr.center_freq / 1e6)
        plt.title("Dynamic Plot")
        plt.draw()
        plt.pause(0.1)
        fig.clear()

    # to stop streaming:
    await sdr.stop()

    # done
    sdr.close()
Example #5
0
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()
Example #6
0
def get_muestras(n_samples):
	sdr = RtlSdr()
	sdr.sample_rate = Fs
	sdr.center_freq = Fo
	sdr.freq_correction = 60
	sdr.gain = 'auto'
	return sdr.read_samples(n_samples)
Example #7
0
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()
def __main__(sdr=None, read_event=None, collect_event=None):
	global Radio_Data

	# Initialize SDR Component
	if sdr == None:
		sdr = RtlSdr()
		sdr.set_bandwidth(.2e6) # Hz
		sdr.sample_rate = 2.4e6
		sdr.freq_correction = 60   # PPM
		sdr.gain = 0.0

	# Load initial data for all stations
	start = time.time()
	Collect_Data(sdr, read_event)
	end = time.time()
	print('All stations initialized in', end - start, 'seconds')

	# Eliminate Dead Stations
	# TODO: Re-enable call once it actually works
	# Determine_Available_Stations()

	# Clear event prior to its availability
	if collect_event != None:
		collect_event.clear()

	# Infinite Runtime Loop
	while True:
		# TODO: Add interface for messages (remove station from search, terminate, ect)
		if collect_event != None and collect_event.is_set():
			Collect_Data(sdr, read_event)
			collect_event.clear()
Example #9
0
def get_muestras(n_samples, sample_rate, center_freq):
    sdr = RtlSdr()
    sdr.sample_rate = sample_rate
    sdr.center_freq = center_freq
    sdr.freq_correction = 60
    sdr.gain = 20
    return sdr.read_samples(n_samples)
Example #10
0
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()
Example #11
0
def main():

    ### setting up sdr streaming
    srate = 2400000 #sampling rate
    samplesperbit = 1000000 / 38400 / (1000000 / srate)
    sdr = RtlSdr()
    # Just like in URH
    sdr.freq_correction = 1
    sdr.sample_rate = srate
    sdr.center_freq = 100.000e6
    sdr.gain = 'auto'
    # Run check_samples in another thread to make sure we don't miss any samples
    
    ### setting up TCP server
    # Create a TCP/IP socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # Bind the socket to the port
    server_address = (ipAddress, portNum)

    print('starting up on {} port {}'.format(*server_address))

    sock.bind(server_address)
    
    # Listen for incoming connections
    sock.listen(1)

    t1 = threading.Thread(target=server_run, args=(sock,q2))
    t1.start()

    # This is the main loop
    loop = asyncio.get_event_loop()
    loop.run_until_complete(get_samples(sdr, q1, q2))
def collectSignal(freq, freq_file_path, mag_file_path):
    # Define function for writing signal data into file
    def write_data(data_points, magnitudeData, frequencyData, mag_file,
                   freq_file):
        i = 0
        mag_file.write('[')
        freq_file.write('[')
        while i < data_points - 1:
            mag_file.write("%s, " % magnitudeData[i])
            freq_file.write("%s, " % frequencyData[i])
            i += 1
        mag_file.write('%s]\n' % magnitudeData[i])
        freq_file.write('%s]\n' % frequencyData[i])

    sdr = RtlSdr()

    # Configure SDR
    sdr.sample_rate = 2.4e6  # Hz
    sdr.center_freq = freq  # Hz
    sdr.freq_correction = 60  # PPM
    sdr.gain = 4  # 'auto'

    # Initialize
    data_points = 1024
    samples = sdr.read_samples(256 * data_points)
    mag_file_path = mag_file_path + "magdata.txt"
    freq_file_path = freq_file_path + "freqdata.txt"

    ### *** IMPORTANT *** (for later, when optimizing)
    ### I'm not sure if we should leave this outside of the function
    ### and move it to the end of the main code, after the flight path
    ### ends. Idk the impact of leaving the SDR open/on for an extended
    ### period of time. If we move sdr.close() outside, we have to
    ### remember to also move the above code outside as well.
    ### Leaving this line within this function should be fine for now.
    sdr.close()

    # PSD plot data
    psddata = psd(samples,
                  NFFT=data_points,
                  Fs=sdr.sample_rate / 1e6,
                  Fc=sdr.center_freq / 1e6)

    # Extracting pertinent information from the PSD plot calculation
    magnitudeData = psddata[0]
    frequencyData = psddata[1]

    # Check for .txt file and write data
    # Magnitude has not been converted to dB yet. To convert, 10*log(magnitude). This comment is for Ron.
    if Path(mag_file_path).is_file() and Path(freq_file_path).is_file():
        with open(mag_file_path, 'a') as mag_file, open(freq_file_path,
                                                        'a') as freq_file:
            write_data(data_points, magnitudeData, frequencyData, mag_file,
                       freq_file)
    else:
        with open(mag_file_path, 'w') as mag_file, open(freq_file_path,
                                                        'w') as freq_file:
            write_data(data_points, magnitudeData, frequencyData, mag_file,
                       freq_file)
 def capture_samples(self):
     sdr = RtlSdr()
     sdr.sample_rate = self.sample_rate
     sdr.center_freq = self.freq - self.dc_offset
     sdr.gain = 'auto'
     self.samples = sdr.read_samples(self.sample_count)
     self.samples_to_np()
     sdr.close()
Example #14
0
def sdr_init(index, freq, gain, sample_rate=2.4e6):
    sdr = RtlSdr(device_index=index)
    sdr.sample_rate = 2.4e6
    sdr.center_freq = freq * 1e6
    sdr.gain = gain
    sdr.set_agc_mode(0)
    sdr_get_power(sdr)  #First read doesn't work
    return sdr
Example #15
0
def main():
    sdr = RtlSdr()

    # some defaults
    sdr.rs = 2.4e6
    sdr.fc = 146e6
    sdr.gain = 50

    noiseWindowLength = 20
    noiseWindow = []

    rampWindowLength = 5
    rampWindow = []
    rampPercent = 1.2

    backgroundNoise = False
    pulseFound = False

    results = []

    # Loop enough times to collect 3 seconds of data
    sampleLoops = int(sdr.rs * 3 / 1024)

    for i in range(0, sampleLoops):
        samples = sdr.read_samples(1024)
        curMag, freqs = magnitude_spectrum(samples, Fs=sdr.rs)
        maxSignal = max(curMag)

        noiseWindow.append(maxSignal)
        if len(noiseWindow) > noiseWindowLength:
            noiseWindow.pop(0)
            backgroundNoise = sum(noiseWindow) / noiseWindowLength
            rampWindow.append(backgroundNoise)

            if len(rampWindow) > rampWindowLength:
                rampWindow.pop(0)

                if rampWindow[rampWindowLength -
                              1] > rampWindow[0] * rampPercent:
                    pulseFound = True
                else:
                    pulseFound = False

        results.append([maxSignal, backgroundNoise, pulseFound])

    sdr.close()

    f = open("data.csv", "w")
    for result in results:
        f.write(str(result[0]))
        f.write(",")
        f.write(str(result[1]))
        f.write(",")
        f.write(str(result[2]))
        f.write("\n")
    f.close()
Example #16
0
def main():
    sdr = RtlSdr()

    # some defaults
    sdr.rs = 2.4e6
    sdr.fc = 146e6
    sdr.gain = 50

    noiseWindowLength = 20
    noiseWindow = []

    rampWindowLength = 5
    rampWindow = []
    rampPercent = 1.2

    backgroundNoise = False
    pulseFound = False

    sampleCount = int(sdr.rs * 3 / 1024)

    f = open("data.csv", "w")

    for i in range(0, sampleCount):
        samples = sdr.read_samples(1024)
        curMag, freqs = magnitude_spectrum(samples, Fs=sdr.rs)
        maxSignal = max(curMag)

        noiseWindow.append(maxSignal)
        if len(noiseWindow) > noiseWindowLength:
            noiseWindow.pop(0)
            backgroundNoise = sum(noiseWindow) / noiseWindowLength
            rampWindow.append(backgroundNoise)

            if len(rampWindow) > rampWindowLength:
                rampWindow.pop(0)

                if rampWindow[rampWindowLength -
                              1] > rampWindow[0] * rampPercent:
                    pulseFound = True
                else:
                    pulseFound = False

        f.write(str(maxSignal))
        f.write(",")
        f.write(str(backgroundNoise))
        f.write(",")
        f.write(str(pulseFound))
        f.write("\n")

    f.close()

    # cleanup
    sdr.close()
Example #17
0
 def run(self):
   
   # Read 128ms of data at a time (must be a multiple of a power of two)
   blkSize = SAMPLE_RATE_KHZ()*128;
   blockLoc = np.zeros(1,dtype=np.uint64);
   
   sdr = RtlSdr();
   # configure device
   sdr.sample_rate = SAMPLE_RATE_KHZ()*1e3  # Hz
   sdr.center_freq = 1575420000     # Hz
   sdr.gain = 29;
   sdrQueue.put((sdr,blockLoc,blkSize/SAMPLE_RATE_KHZ(),1));
   sdr.read_samples_async(sdrCallback, blkSize, context=sdrQueue);
Example #18
0
    def run(self):

        # Read 128ms of data at a time (must be a multiple of a power of two)
        blkSize = SAMPLE_RATE_KHZ() * 128
        blockLoc = np.zeros(1, dtype=np.uint64)

        sdr = RtlSdr()
        # configure device
        sdr.sample_rate = SAMPLE_RATE_KHZ() * 1e3  # Hz
        sdr.center_freq = 1575420000  # Hz
        sdr.gain = 29
        sdrQueue.put((sdr, blockLoc, blkSize / SAMPLE_RATE_KHZ(), 1))
        sdr.read_samples_async(sdrCallback, blkSize, context=sdrQueue)
Example #19
0
def main():
    sdr = RtlSdr()
    wf = Waterfall(sdr)

    # some defaults
    sdr.rs = 2.4e6
    sdr.fc = 100e6
    sdr.gain = 10

    wf.start()

    # cleanup
    sdr.close()
Example #20
0
def main():
    sdr = RtlSdr()
    wf = Waterfall(sdr)

    # some defaults
    sdr.rs = 2.4e6
    sdr.fc = 100e6
    sdr.gain = 10

    wf.start()

    # cleanup
    sdr.close()
Example #21
0
def get_sdr():
	sdr = RtlSdr()

	#configure device
	#sdr.sample_rate = 2.048e6 	#Hz
	#sdr.center_freq = 70e6		#Hz
	#sdr.freq_correction = 60	# PPM
	#sdr.gain = 'auto'
	sdr.sample_rate = 200000
	sdr.center_freq = 907 * 1000 * 1000
	sdr.freq_correction = 60	# PPM
	sdr.gain = 'auto'

	return sdr
Example #22
0
def get_sdr():
    sdr = RtlSdr()

    #configure device
    #sdr.sample_rate = 2.048e6 	#Hz
    #sdr.center_freq = 70e6		#Hz
    #sdr.freq_correction = 60	# PPM
    #sdr.gain = 'auto'
    sdr.sample_rate = 200000
    sdr.center_freq = 907 * 1000 * 1000
    sdr.freq_correction = 60  # PPM
    sdr.gain = 'auto'

    return sdr
Example #23
0
def main():
    from rtlsdr import RtlSdr

    sdr = RtlSdr()

    print 'Configuring SDR...'
    sdr.rs = 1e6
    sdr.fc = 70e6
    sdr.gain = 5
    print '   sample rate: %0.6f MHz' % (sdr.rs/1e6)
    print '   center ferquency %0.6f MHz' % (sdr.fc/1e6)
    print '   gain: %d dB' % sdr.gain

    print 'Testing callback...'
    sdr.read_samples_async(test_callback)
Example #24
0
def main():
    from rtlsdr import RtlSdr

    sdr = RtlSdr()

    print 'Configuring SDR...'
    sdr.rs = 1e6
    sdr.fc = 70e6
    sdr.gain = 5
    print '   sample rate: %0.6f MHz' % (sdr.rs / 1e6)
    print '   center ferquency %0.6f MHz' % (sdr.fc / 1e6)
    print '   gain: %d dB' % sdr.gain

    print 'Testing callback...'
    sdr.read_samples_async(test_callback)
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()
Example #26
0
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()
Example #27
0
def main():
    sdr = RtlSdr()
    sdr.sample_rate = 2.048e6
    sdr.center_freq = 103900000  #70e6
    sdr.freq_correction = 60
    sdr.gain = 'auto'
    samples = sdr.read_samples(sdr.sample_rate * 2)
    # print(samples, type(samples))
    demod_list = []
    for ind in range(len(samples) - 1):
        demod_list.append(np.angle(np.conj(samples[ind]) * samples[ind + 1]))

    # print(demod_list)

    demod_list = demod_list[::4]

    writer.write('sample.wav', 44100, np.array(demod_list))
Example #28
0
def main():
    sdr = RtlSdr()
    wf = Waterfall(sdr)

    # some defaults
    sdr.rs = 2.4e6
    sdr.fc = 100e6
    #sdr.gain = 10
    sdr.gain = 'auto'

    ### setting up TCP server
    t1 = threading.Thread(target=server_run, args=(q2,))
    t1.start()
    wf.start()

    # cleanup
    sdr.close()
Example #29
0
def main():

    now = datetime.datetime.now()

    current_time = now.strftime("%H:%M:%S.%f")
    print("Current Time =", current_time)
    #aquire location

    #start calibration process (needed?)

    #start syc process

    sdr = RtlSdr()  # rtl-sdr instance
    # configure device
    timeToSample = 1  # in sec
    sampleRate = 2.4e6  # in Mhz
    sdr.sample_rate = sampleRate
    sdr.center_freq = 433e6  # in Mhz
    sdr.gain = 30  # in dB
    print("gain set to:", sdr.get_gain())
    print(now)

    numberOfSamples = sampleRate * timeToSample
    fig = figure()
    ax = fig.add_subplot(111, projection='3d')  # used for 3d IQ/time plot
    samples = sdr.read_samples(numberOfSamples)  # aquire samples
    sdr.close()
    # I/Q seperation
    real = samples.real
    imag = samples.imag
    samp = np.arange(0, numberOfSamples, 1)  # used as an axis
    #ax.scatter(samp[0:-1:100],real[0:-1:100],imag[0:-1:100],marker='^',s=2)#used for pumba slack

    simulateRecivers(real, sampleRate)  # used to simulation
    #plt.subplot(3, 1, 2)
    # xlabel('Real axis')#used for pumba slack
    # ylabel('img axis')#used for pumba slack
    '''
    pxx,farr=psd(samples, NFFT=1024, Fs=sampleRate / 1e6, Fc=sdr.center_freq / 1e6)
    plt.subplot(2, 1, 1)
    plt.plot(samp, imag)
    plt.subplot(2, 1, 2)
    plt.plot(farr,pxx)
    '''
    show()
def main():

    sdr = RtlSdr()

    # configure device
    sdr.sample_rate = 1.024e6  # Hz
    sdr.center_freq = 433.9e6  # Hz
    sdr.freq_correction = 20  # PPM
    sdr.gain = 'auto'

    tones = AudioTones()
    tones.init()

    for i in range(0, 10):
        rssi = MeasureRSSI(sdr)

    # Measure minimum RSSI over a few readings, auto-adjust for dongle gain
    min_rssi = 1000
    avg_rssi = 0
    for i in range(0, 10):
        rssi = MeasureRSSI(sdr)
        min_rssi = min(min_rssi, rssi)
        avg_rssi += rssi
    avg_rssi /= 10
    ampl_offset = avg_rssi
    max_rssi = MeasureRSSI(sdr) - ampl_offset
    avg_rssi = max_rssi + 20
    counter = 0
    #   redirect_stderr()

    while (True):
        wdt = Timer(3.0, watchdog_timeout)
        wdt.start()
        rssi = MeasureRSSI(sdr) - ampl_offset
        wdt.cancel()
        avg_rssi = ((15 * avg_rssi) + rssi) / 16

        max_rssi = max(max_rssi, rssi)
        counter += 1
        if counter & 0x1F == 0:
            tone_idx = int(max_rssi)
            tone_idx = max(0, tone_idx)
            tone_idx = min(45, tone_idx)
            tones.play(tone_idx)
            max_rssi = rssi
def read_n_plot():
    sdr = RtlSdr()
    # configure device
    sdr.sample_rate = 2.4e6
    sdr.center_freq = 90e6
    sdr.gain = 4
    samples = sdr.read_samples(12000 * 1024)
    sdr.close()
    demod_result = demodulate(samples)

    write_to_txt(demod_result)
    write_to_audio(demod_result, "recmusic.wav")
    plot_t(demod_result)

    # use matplotlib to estimate and plot the PSD
    psd(samples, NFFT=1024, Fs=sdr.sample_rate / 1e6, Fc=sdr.center_freq / 1e6)
    xlabel('Frequency (MHz)')
    ylabel('Relative power (dB)')
    show()
Example #32
0
def get_data(freq):
    sdr = RtlSdr()

    sdr.sample_rate = 2.048e6
    sdr.center_freq = int(decimal.Decimal(str(freq) + 'e6'))
    sdr.freq_correction = 60
    sdr.gain = 'auto'

    data = sdr.read_samples(512)

    if not data.any():
        app.abort(404, 'No data!')

    d = []
    for item in data:
        d.append(str(item))

    js = json.dumps(d)
    return js
Example #33
0
def main():
    sdr = RtlSdr()

    print 'Configuring SDR...'
    sdr.rs = 2.4e6
    sdr.fc = 70e6
    sdr.gain = 4
    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(1024)
    print '  signal mean:', sum(samples) / len(samples)

    print 'Testing callback...'
    sdr.read_samples_async(test_callback)

    sdr.close()
Example #34
0
def main():
    sdr = RtlSdr()

    print 'Configuring SDR...'
    sdr.rs = 2.4e6
    sdr.fc = 70e6
    sdr.gain = 4
    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(1024)
    print '  signal mean:', sum(samples)/len(samples)

    print 'Testing callback...'
    sdr.read_samples_async(test_callback)

    sdr.close()
Example #35
0
def capture(freq, label, range_freq, range_gain):
    for freq_var in range_freq:
        for gain_var in range_gain:
            # Configure device (freq in herz, freq_correction is PPM)
            sdr = RtlSdr()
            sdr.sample_rate = 250000
            sdr.center_freq = freq + freq_var
            sdr.freq_correction = 60
            sdr.gain = gain_var
            # Read 10 seconds of 250k sampled data
            samples = sdr.read_samples(10 * 256 * 1024)
            sdr.close()

            # Use matplotlib to estimate and plot the PSD
            psd(samples[:65536],
                NFFT=1024,
                Fs=sdr.sample_rate / 1e6,
                Fc=sdr.center_freq / 1e6)
            #print(psd)
            xlabel('Frequency (MHz)')
            ylabel('Relative power (dB)')
            # Show and save a pic
            #show()
            file_name = 'data-' + label + '-' + str(
                double(freq + freq_var)) + '-g-' + str(gain_var)
            print("Saving " + file_name)
            savefig(file_name + '.png')

            # Save samples to file
            fh = open(file_name + '.iq', "wb")
            x = samples
            x = x[:5000000]

            for sample in x:
                ba = bytearray(struct.pack("f", numpy.float32(sample.real)))
                for b in ba:
                    fh.write(bytearray([b]))

                ba = bytearray(struct.pack("f", numpy.float32(sample.imag)))
                for b in ba:
                    fh.write(bytearray([b]))
            fh.close()
            clf()
Example #36
0
def get_data(freq):
    sdr = RtlSdr()

    sdr.sample_rate = 2.048e6
    sdr.center_freq = int(decimal.Decimal(str(freq) + 'e6'))
    sdr.freq_correction = 60
    sdr.gain = 'auto'

    data = sdr.read_samples(512)

    if not data.any():
        app.abort(404, 'No data!')

    d = []
    for item in data:
        d.append(str(item))

    js = json.dumps(d)
    return js
def main():

    sdr = RtlSdr(1)

    wf = Waterfall(sdr)

    # some defaults

    sdr.rs = 1.024e6

    sdr.fc = 89.3e6

    sdr.gain = 'auto'

    wf.start()

    # cleanup

    sdr.close()
Example #38
0
def find_powerfull_FM():
    sdr = RtlSdr()
    # configure device
    Fs = 2e6  # Hz
    sdr.sample_rate = Fs  # Hz
    sdr.freq_correction = 60  # PPM
    sdr.gain = 'auto'

    FM_band_min = 87.5
    FM_band_max = 109

    powe = np.ndarray(0)
    freq = np.ndarray(0)

    t_sampling = 0.1  # Sampling for 100 ms
    N_samples = round(Fs * t_sampling)

    for i in np.arange(FM_band_min, FM_band_max, Fs / 1e6):
        sdr.center_freq = i * 1e6  # Hz
        counter = 0
        prev_int = 0
        while 1:
            counter = counter + 1
            samples = sdr.read_samples(N_samples)
            ###################################################################################
            power, psd_freq = plt.psd(samples,
                                      NFFT=1024,
                                      Fs=sdr.sample_rate / 1e6,
                                      Fc=sdr.center_freq / 1e6)
            #####################################################################################
            ind_pow = np.argmax(power)
            freq_ind = round(psd_freq[ind_pow], 1)
            if freq_ind == prev_int and counter >= 3:
                powe = np.append(powe, ind_pow)
                freq = np.append(freq, freq_ind)
                break
            prev_int = freq_ind
    # done
    sdr.close()
    max_fm_station_power = np.argmax(powe)
    max_fm_station_freq = freq[max_fm_station_power]
    return max_fm_station_freq
Example #39
0
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()
Example #40
0
def main():

    @limit_time(0.01)
    @limit_calls(20)
    def read_callback(buffer, rtlsdr_obj):
        print('In callback')
        print('   signal mean:', sum(buffer)/len(buffer))

    from rtlsdr import RtlSdr

    sdr = RtlSdr()

    print('Configuring SDR...')
    sdr.rs = 1e6
    sdr.fc = 70e6
    sdr.gain = 5
    print('   sample rate: %0.6f MHz' % (sdr.rs/1e6))
    print('   center ferquency %0.6f MHz' % (sdr.fc/1e6))
    print('   gain: %d dB' % sdr.gain)

    print('Testing callback...')
    sdr.read_samples_async(read_callback)
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
Example #42
0
pa = pyaudio.PyAudio()
stream = pa.open( format = pyaudio.paFloat32,
         channels = 1,
         rate = 48000,
         output = True)

def play(samples):
   
    stream.write( samples.astype(np.float32).tostring() )
   


sdr = RtlSdr()
sdr.center_freq = 99.7e6
sdr.sample_rate = 2.4e5
sdr.gain = 22.9


sample_buffer = Queue.Queue(maxsize=10)

def sampler_callback(samples,context):
    sample_buffer.put(samples)

class MakeDaemon(threading.Thread):

    def __init__(self, function, args=None):
        threading.Thread.__init__(self)
        self.runnable = function
        self.args = args
        self.daemon = True
     hopCount = options.required_bw/options.samp_rate

     if hopCount == 0:
	hopCount = 1

     sampleCount = options.dwell_time*options.samp_rate
	
     p = int(math.log(sampleCount,2) + 1)
	
     sampleCount = pow(2,p)
	
     print "SampleCount ", sampleCount
   
     sdr = RtlSdr()
     sdr.sample_rate = options.samp_rate
     sdr.gain = 4
     sdr.freq_correction = 60

     while True:
         for i in range(0,int(hopCount) - 1):
	     sdr.center_freq = startHz + i*options.samp_rate + offset
	     samples = sdr.read_samples(sampleCount)
	     energy = numpy.linalg.norm(samples)/sampleCount
	     print "Center Freq ", (startHz + i*options.samp_rate + offset)/1e6 , " Mhz", " Energy ", energy


     
    
     

def main():
    print("you are using", platform.system(), platform.release(), os.name)

    # creating the central shared dgsn-node-data for all programs on the nodes
    #######################################
    pathname = os.path.abspath(os.path.dirname(sys.argv[0]))
    pathname_all = ""
    for i in range(len(pathname.split(path_separator))-2): # creating the folders two folder levels above
        pathname_all = pathname_all + pathname.split(path_separator)[i] + path_separator
    pathname_save = pathname_all + "dgsn-node-data"
    pathname_config = pathname_all + "dgsn-hub-ops"

    # creating the dump folder for files and the needed data folders
    #######################################
    if not os.path.exists(pathname_save):
        os.makedirs(pathname_save)

    folder = pathname_save + path_separator + "rec"
    subfolders = ["iq", "sdr", "gapped", "coded", "monitor"]
    if not os.path.exists(folder):
        os.makedirs(folder)

    if os.path.exists(folder):
        for i in range(len(subfolders)):
            if not os.path.exists(folder + path_separator + subfolders[i]):
                os.makedirs(folder + path_separator + subfolders[i])

    if not os.path.exists(pathname_config):
        os.makedirs(pathname_config)

    pathname_config = pathname_config + path_separator + "io-radio"

    if not os.path.exists(pathname_config):
        os.makedirs(pathname_config)

    # setting the rtlsdr before the gain finding
    #####################################

    # getting one file to each node very simple via github, or via a local file copy
    data = loading_config_file(pathname_config)

    # getting the specific settings for the node itself. perhaps it cannot be as fast as others
    with open(pathname + path_separator +'node-config.json') as data_file:
        data_node = json.load(data_file)

    device_number = data["device_number"]
    center_frequency = data["center_frequency"]
    samplerate = data["samplerate"]

    # this will be necessary in case a full fledged pc is a node or in case a micro pc is used with less RAM
    secondsofrecording = min(data["secondsofrecording"], data_node["secondsofrecording_maximum"])
    print("record seconds commanded", data["secondsofrecording"], "record seconds maximum",
          data_node["secondsofrecording_maximum"], "and it is", secondsofrecording)

    nsamples = secondsofrecording * samplerate
    freq_correction = data["freq_correction"]
    user_hash = get_groundstationid()

    dt = datetime.datetime(data["recording_start"]["year"], data["recording_start"]["month"], data["recording_start"]["day"],
                           data["recording_start"]["hour"], data["recording_start"]["minute"], data["recording_start"]["second"])
    recording_start = time.mktime(dt.timetuple())

    dt = datetime.datetime(data["recording_end"]["year"], data["recording_end"]["month"], data["recording_end"]["day"],
                           data["recording_end"]["hour"], data["recording_end"]["minute"], data["recording_end"]["second"])
    recording_stop = time.mktime(dt.timetuple())

    # getting the data for calibration
    calibration_start = data["calibration_start"]
    gain_start = data["gain_start"]
    gain_end = data["gain_end"]
    gain_step = data["gain_step"]
    signal_threshold = data["signal_threshold"]
    print("gg", gain_start, gain_end)

    ##################################
    print("starting the fun...")

    if platform.system() == "Windows":
        print("detecting a windows")
        ##############
        device_count = librtlsdr.rtlsdr_get_device_count()
        print("number of rtl-sdr devices:", device_count)

        if device_count > 0:
            lock = Lock()
            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")

        # getNumber_of_rtlsdrs_with_linux()

        gain = 0
        calibration_finished = 0

        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:
                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 = 0
                    else:
                        gain = gain_start

                else:
                    print("calibrated gain")
                    gain = calibrating_gain_with_linux(device_number, center_frequency, samplerate, gain_step,
                                                       gain_start, gain_end, signal_threshold)
                print("used gain", gain)
                calibration_finished = 1

        utctime = time.mktime(time.gmtime())
        if utctime >= recording_start and utctime <= recording_stop:
            print("recording starts now...")

            rtl_sdr_exe = "rtl_sdr"
            sdr = Popen([rtl_sdr_exe, "-d", str(device_number), "-f", str(center_frequency), "-s", str(samplerate),
                         "-g", str(gain), "-p", str(freq_correction), "-"],
                        stdout=PIPE, stderr=None)

            while time.mktime(time.gmtime()) <= recording_stop:
                stream_data = sdr.stdout.read(nsamples*2)
                storing_stream_with_linux(stream_data, device_number, folder, subfolders, center_frequency, samplerate,
                                          gain, nsamples, freq_correction, user_hash)

            sdr.kill()
    print("it's done. thank you, please come back again!")
Example #45
0
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from rtlsdr import RtlSdr

sdr = RtlSdr()
# Sampling rate
sdr.rs = 256000. #1024e3
# Pins 4 and 5
sdr.set_direct_sampling(2)

# Center frequency
sdr.fc = 0
# I don't think this is used?
sdr.gain = 1

fig = plt.figure()
ax = fig.add_subplot(211, autoscale_on=False, xlim=(-1, 513), ylim=(-1.1,1.1))
ax.grid()
rline, = ax.plot([], [], 'r-', lw=2)
iline, = ax.plot([], [], 'g-', lw=2)
ax = fig.add_subplot(212, autoscale_on=False, xlim=(-1, 513), ylim=(-1.3,1.3))
ax.grid()
mline, = ax.plot([], [], 'b-', lw=2)

def animate(i):
    samples = sdr.read_samples(1024)
    try:
      zc = np.where(np.diff(np.sign(samples))>0)[0][0]
    except:
def acquireSamplesAsync(fs, fc, t_total, chunk_size=1024, num_SDRs=3, gain=36):
    """
    Asynchronously acquire samples and save them.
    """

    assert type(t_total) == int, "Time must be an integer."
    N_samples = 1024000*t_total #1024000 256000 3.2e6
    SDRs = []

    # Initialize the SDRs
    for i in xrange(num_SDRs):
        sdr_i = RtlSdr(device_index=i)
        sdr_i.sample_rate = fs
        sdr_i.center_freq = fc
        sdr_i.gain = gain
        SDRs.append(sdr_i)

    # Setup the output queues
    output_queues = [Queue() for _ in xrange(num_SDRs)]

    rec_thrds = []

    # Create the thread objects for acquisition
    for i, sdr_i in enumerate(SDRs):
        y = output_queues[i]
        sdr_rec = threading.Thread(target=recordSamples, \
                          args=(sdr_i, i, N_samples, y, N_samples))
        rec_thrds.append(sdr_rec)

    # Start the threads
    for rec_thread in rec_thrds:
        rec_thread.start()


    # Wait until threads are done
    while any([thrd.is_alive() for thrd in rec_thrds]):
        time.sleep(1)
        """
        for i, size in enumerate(last_size):
            curr_size = output_queues[i].qsize()
            if not done_arr[i] and size == curr_size:
                #rec_thrds[i].terminate()
                done_arr[i] = True
            else:
                last_size[i] = curr_size
        """

    # For DEBUG
    samples = []
    for i, q in enumerate(output_queues):
        print "Printing Queue %d" % i
        print "\t- Queue size: %d" % q.qsize()
        samples.append([])
        while not q.empty():
            print q.qsize()
            samples[i] += list(q.get())

        print "Done"

    np.save('demo.npy',samples)
    for i in range(num_SDRs-1):
        assert len(samples[i]) == len(samples[i+1])

    return samples
Example #47
0
                        bitstr += "0"
                    else:
                        bitstr += "1"
                        if bitCount < 6:
                            scancode += 1 << bitCount
                    bitCount += 1
                    bitValue = 0
                    if bitCount > 10:
                        bitCount = 0
                        state = 0  # fin demod
        except:
            exit(0)


if __name__ == "__main__":
    q = Queue()
    p = Process(target=AsyncWelchProcess, args=(q,))
    p.start()

    def on_sample(buf, queue):
        queue.put(list(buf))

    from rtlsdr import RtlSdr

    sdr = RtlSdr()
    # configure device
    sdr.sample_rate = SAMPLE_RATE  # sample rate
    sdr.center_freq = FREQ
    sdr.gain = "auto"
    sdr.read_samples_async(on_sample, 2048, context=q)
Example #48
0
	elif (arg == "-c"):
		config.center_freq = int(sys.argv[i+1])
	elif (arg == "-r"):
		config.sample_rate = int(sys.argv[i+1])

#init RTLSDR and if no then go out
try:
	sdr = RtlSdr()
except IOError:
	print "Probably RTLSDR device not attached"
	sys.exit(0)

# configure device
sdr.sample_rate = config.sample_rate  # Hz
sdr.center_freq = config.center_freq     # Hz
sdr.freq_correction = 60   # PPM
sdr.gain = 'auto'


samples = sdr.read_samples( config.sample_num )
if config.matlab_flag == False:
	print( samples )
else:
	print "samples = [",
	for s in samples:
		if s.imag < 0.0:
			print "%s%si "%(str(s.real), str(s.imag)),
		else:
			print "%s+%s "%(str(s.real), str(s.imag)),
	print "];"
i_curve = data_plot.plot(pen='r', name = "In-Phase Signal")
q_curve = data_plot.plot(pen='y', name = "Quadrature Signal")

win.nextRow()
# initialize plot
fft_plot = win.addPlot(title="Power Vs. Frequency")
fft_plot.showGrid(True, True, alpha = 1)
fft_plot.addLegend()
# initialize a curve for the plot 
curve = fft_plot.plot(pen='g', name = "Power Spectrum")
max_curve = fft_plot.plot(pen='r', name = "Max Hold")
sdr = RtlSdr()
# some defaults
sdr.rs = 2e6
sdr.fc = 106.9e6
sdr.gain = 30
max_data = []
def update():
    global dut, curve, max_data
    samples = sdr.read_samples(SAMPLE_SIZE)
    samples = samples * np.hanning(len(samples))
    pow = 20 * np.log10(np.abs(np.fft.fftshift(np.fft.fft(samples))))
    i_curve.setData(samples.real)
    q_curve.setData(samples.imag)
    if len(max_data) == 0:
        max_data = pow
    else:
        max_data = np.maximum(max_data, pow)
    curve.setData(pow)
    max_curve.setData(max_data)
    data_plot.enableAutoRange('xy', False)