Ejemplo n.º 1
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()
Ejemplo n.º 2
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))
Ejemplo n.º 3
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()
Ejemplo n.º 4
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)
Ejemplo n.º 5
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)
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()
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)
Ejemplo n.º 8
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
Ejemplo n.º 9
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
Ejemplo n.º 10
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))
Ejemplo n.º 11
0
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
Ejemplo n.º 12
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
Ejemplo n.º 13
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
Ejemplo n.º 14
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()
Ejemplo n.º 15
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
Ejemplo n.º 16
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()
Ejemplo n.º 17
0
async def streaming(sample_processor: Callable[[SampleStream, RtlSdr], None],
                    center_freq=100300000,
                    sample_rate=2.048e6):
    """SDR streaming function
    :param sample_processor: Function that is used to process the samples, must
        take an array of floats as the first argument and an sdr object
        (for metadata) as the second
    :param sample_rate: The sample rate to obtain samples at in Hz
    :param center_freq int: The center frequency for capturing in Hz
    """
    sdr = RtlSdr()
    sdr.sample_rate=sample_rate
    sdr.center_freq = center_freq
    sdr.freq_correction = 60
    sdr.gain = 'auto'

    async for samples in sdr.stream():
        sample_processor(samples, sdr)

    await sdr.stop()

    sdr.close()
Ejemplo n.º 18
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()
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
Ejemplo n.º 20
0
def saveSignal(freq, 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 = file_path + "/magdata.txt"
    freq_file_path = 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
    # For Ron: Magnitude has not been converted to dB yet. To convert, 10*log(magnitude).
    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)

    print("Data saved successfully.")


# CHANGELOG

# Feb 9, 2018
# Cleared up a few comments/notes to self and cleaned up code in [measurements.py]

# Feb 10, 2018
# Verified exchangeable formatting for sdr.center_freq (95.1e6 vs 95100000 vs 95100000.0)
# Added ability to allow user to choose save location [in Flight_Control_v2.py]
# Made code more robust by preventing user from inputting invalid arugments [in Flight_Control_v2.py]

# Feb 11, 2018
# Renamed functions from collectBlah to saveBlah for clarity
# Added ability to configure center frequency of SDR
# Modified saveSignal to save data dynamically based off of user input
# Added data save confirmation for verification
# Modified saveGPS to save data dynamically based off of user input
Ejemplo n.º 21
0
async def streaming():
    sdr = RtlSdr()
    # configure device
    # Fs = 2.4e6   # Hz
    Fs = 1e6
    sdr.sample_rate = Fs  # Hz
    sdr.center_freq = 95.8e6  # Hz
    sdr.freq_correction = 60  # PPM
    sdr.gain = 'auto'
    # Sampling for 1 sec
    t_sampling = 0.1
    N_samples = round(Fs * t_sampling)
    samples = sdr.read_samples(N_samples)
    CFO_corr_en = 0

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

    LEFT = 15000
    BW = 8000
    F_center = LEFT + BW / 2

    async for samples in sdr.stream():

        # Convert samples to a numpy array
        x1 = np.array(samples).astype("complex64")

        if CFO_corr_en == 1:
            analog_signal_packets = CFO_pilot_tone(x1, Fs)
        else:
            analog_signal_packets = x1

        # To mix the data down, generate a digital complex exponential
        # (with the same length as x1) with phase -F_offset/Fs
        fc1 = np.exp(-1.0j * 2.0 * np.pi * F_center / Fs *
                     np.arange(len(analog_signal_packets)))
        # Now, just multiply x1 and the digital complex exponential
        x2 = analog_signal_packets * fc1

        # channelize the signal Method 1
        ########################################################################
        newrate = BW
        samples = round(x2.size * newrate / Fs)
        resampled_signal1 = sps.resample(x2, samples)
        ########################################################################
        # channelize the signal Method 2
        ########################################################################
        # Find a decimation rate to achieve audio sampling rate between 44-48 kHz
        audio_freq = 44100.0
        dec_audio = round(Fs / audio_freq)
        resampled_signal2 = sps.decimate(x2, dec_audio)
        Fs_audio = Fs / dec_audio
        ########################################################################

        plt.psd(resampled_signal2,
                NFFT=1024,
                Fs=Fs_audio,
                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()
Ejemplo n.º 22
0
def main(stdscr):

    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()

    curses.noecho()
    curses.cbreak()
    curses.curs_set(0)

    curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
    curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK)
    curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK)
    curses.init_pair(4, curses.COLOR_WHITE, curses.COLOR_BLACK)

    stdscr.clear()  # Clear screen

    bargraph_str = chr(0x2588) * 80 + ' ' * 80  # "block" character

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

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

    while (True):
        rssi = MeasureRSSI(sdr) - ampl_offset
        if rssi - avg_rssi > 10:
            stdscr.addch(3, 3, '*')
        else:
            stdscr.addch(3, 3, ' ')
        avg_rssi = ((15 * avg_rssi) + rssi) / 16
        stdscr.addstr(0, 0, "{0:4.0f} : {1:4.0f}".format(rssi, avg_rssi))
        stdscr.addstr(20, 0, "{0:4.1f}".format(rssi))

        # select the bargraph's colour:
        if rssi > 30:
            bargraph_color = 4
        elif rssi > 20:
            bargraph_color = 3
        elif rssi > 15:
            bargraph_color = 2
        else:
            bargraph_color = 1
# draw the bargraph:
        bargraph_idx = min(int(78 - rssi), 80)
        stdscr.addstr(7, 0, bargraph_str[bargraph_idx:bargraph_idx + 80],
                      curses.color_pair(bargraph_color))
        stdscr.addstr(8, 0, bargraph_str[bargraph_idx:bargraph_idx + 80],
                      curses.color_pair(bargraph_color))

        stdscr.refresh()

        max_rssi = max(max_rssi, rssi)
        counter += 1
        if counter & 0x1F == 0:
            tone_idx = max_rssi
            tone_idx = max(0, tone_idx)
            tone_idx = min(40, tone_idx)
            tones.play(tone_idx)
            max_rssi = rssi
            stdscr.addstr(21, 0, "{0:4.1f}".format(max_rssi))
Ejemplo n.º 23
0
def main():
    clear = lambda: os.system('clear')
    clear()
    print("\nFALCON-B Tracking and Monitoring Software v0.0.2.")
    print("Created by Ian Carney, Michael Krzystowczyk, William Lee, and Frank Palermo.")
    print("Louisiana Tech University")
    print("This program is for technical demonstration only and is not for use\nin any commercial, industrial, or operational environments.\n")

    sdrgain = 5
    bw = 32e3
    sampRate = 1.024e6
    correction = 50



    #global snr1, snr2, snr3, snr4
    if len(sys.argv)==2:
        centerfreq = sys.argv[1]
    else:
        centerfreq = 462562500

    #Configures SDR1
    sdr1 = RtlSdr(serial_number='0000101')
    sdr1.sample_rate = sampRate
    sdr1.bandwidth = bw
    sdr1.center_freq = centerfreq
    print(sdr1.center_freq)
    sdr1.gain=5
    sdr1.freq_correction = correction

    #Configures SDR2
    sdr2 = RtlSdr(serial_number='0000102')
    sdr2.sample_rate = sampRate
    sdr2.bandwidth = bw
    sdr2.center_freq = centerfreq
    sdr2.gain=5
    sdr2.freq_correction = correction

    #Configures SDR3
    sdr3 = RtlSdr(serial_number='0000103')
    sdr3.sample_rate = sampRate
    sdr3.bandwidth = bw
    sdr3.center_freq = centerfreq
    sdr3.gain=5
    sdr3.freq_correction = correction

    #Configures SDR4
    sdr4 = RtlSdr(serial_number='0000104')
    sdr4.sample_rate = sampRate
    sdr4.bandwidth = bw
    sdr4.center_freq = centerfreq
    sdr4.gain=4
    sdr4.freq_correction = correction
    _idx = 0
    while(1):
        print("Collecting data...")

        sdr1data = readValues(sdr1, sampRate) #Returns Power of SDR1
        sleep(0.1)
        sdr2data = readValues(sdr2, sampRate) #Returns Power of SDR2
        sleep(0.1)
        sdr3data = readValues(sdr3, sampRate) #Returns Power of SDR3
        sleep(0.1)
        sdr4data = readValues(sdr4, sampRate) #Returns Power of SDR4

        snr1 = np.float32(getSNR(sdr1data)) #Returns SNR of SDR1
        snr2 = np.float32(getSNR(sdr2data)) #Returns SNR of SDR2
        snr3 = np.float32(getSNR(sdr3data)) #Returns SNR of SDR3
        snr4 = np.float32(getSNR(sdr4data)) #Returns SNR of SDR4
        all_snr = [snr1, snr2, snr3, snr4] #Puts all SDR Data in an array
        #print("All SNR: ")
       # print(all_snr)
        all_snr.sort()
        #print("Sorted SNR: ")
        highSNR = all_snr[-1] #Gets highest SNR
        secondSNR = all_snr[-2] #Gets second highest SNR
	if(highSNR == snr1):
		snr3 = 0
	if(highSNR == snr2):
		snr4 = 0
	if(highSNR == snr3):
		snr1 = 0
	if(highSNR == snr4):
		snr2 = 0
	all_snr2 = [snr1, snr2, snr3, snr4]
	#print(all_snr2)
	all_snr2.sort()
	highSNR2 = all_snr2[-1]
	secondSNR2 = all_snr2[-2]
	#print(all_snr2)
        #print("High SNR: ", highSNR,"\n")
        #print("Second SNR: ", secondSNR, "\n")

        if((highSNR2 or secondSNR2) != 0 and (highSNR2 or secondSNR2) > 2):
            shortDist = getDist(highSNR2) #Uses highest SNR to find distance
            #longDist = getDist(secondSNR2) #Gets distance from second highest antenna SNR
         #   print(highSNR, secondSNR)
            #print(snr1, snr2, snr3, snr4)
            try:
                case, ceiling = findCase(highSNR2, secondSNR2, snr1, snr2, snr3, snr4)
                minDist, maxDist, colorZone = findZone(highSNR)
                locationMatrix = [case, colorZone]
                #print("The signal is between ", minDist, " feet away and ", maxDist, " feet away.")
                if(case==0):
                    raise TypeError
          #      print("\n")
          #      print("Case Number: ", case)
          #      print("Ceiling: ", ceiling, " degrees")

                #angle = dirFind(shortDist, longDist, ceiling)
                print("Signal Detected!")
                print "Distance: ", minDist, " to ", maxDist, " feet away."
                #print "Distance Zone: ", colorZone
                print "Direction Zone: ", case
                print "Ceiling: ", ceiling, " degrees to ", ceiling-45, " degrees"
                data_log = open("./webserver/data_log.txt","a+",0)
                data_log.write("Dist: {},Brng: {},Zone: {}.{},Idx: {},\n".format((minDist+maxDist)//2, ceiling, case, colorZone,_idx))
                data_log.close()
                _idx += 1
                #print("Signal Detected! There is a signal that is ", shortDist, " away at an angle of ", angle, " degrees.")
                for _ in range(2):
                    print('\n')
            except:
Ejemplo n.º 24
0
Fo = 101.723e6

if len(sys.argv)>1:
	print(sys.argv[1])
	Fo = float(sys.argv[1]+'e6')


fm = Demodulador(Fs,Fo)
output_Fs = fm.outputFs()

p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16,channels=1,rate=output_Fs,output=True)
sdr = RtlSdr()
sdr.sample_rate = Fs  # Hz
sdr.center_freq = Fo     # Hz
sdr.freq_correction = 60   # PPM
sdr.gain = 'auto'

loop = asyncio.get_event_loop()

async def streaming(queue):
	elapsed_time = time.time()
	async for samples in sdr.stream(num_samples_or_bytes=10240000):
		queue.put(samples)    
		print("Samples: {0}".format(time.time() - elapsed_time))
	# to stop streaming:
	# await sdr.stop()
	# done
	sdr.close()

Ejemplo n.º 25
0
if sirka_volba is 'b':
    pocet_vzorku = 32 * 512

if sirka_volba == 'c':
    pocet_vzorku = 128 * 512

if sirka_volba == 'd':
    pocet_vzorku = 1024 * 1024

sdr = RtlSdr()
pocet_oken = f_stop - f_start
f_start = f_start * 1e6
f_stop = f_stop * 1e6
sdr.sample_rate = 1.2e6  # Hz
sdr.freq_correction = +30  # korekce ochylky hodin, v PPM
sdr.gain = 12

sdr.center_freq = f_start + 0.5e6  # Hz
x = np.linspace(f_start, f_stop,
                pocet_oken * (int(round(pocet_vzorku * (1 / 1.2))))
                )  # definice velikosti pole pro vyslednou FFT - jen pro indexy

data = sdr.read_samples(
    pocet_vzorku)  # testovaci aktivace prijimace, prvni vzorky nejsou kvalitni
provede_mereni = 1
pozadi_temp = 0
if pozadi_volba == 'a':
    pozadi_temp = 1
    raw_input("Probehne mereni pozadi, pro pokracovani stiskni ENTER")
Ejemplo n.º 26
0
    offset = measured - freq

    maxEmptyBinary = 10  # For deciding when to reset the signal tracker

    print()
    print("Wanted Frequency: " + (str)(trunc(freq)) +
          " Hz! Actual Frequency: " + (str)(trunc(measured)) + " Hz!")
    print("Offset: {0:0.0f} and Squelch: {1}".format(offset, squelch))
    # Trunc does not want to cooperate with offset for some reason...
    print()

    #sys.exit()

    sdr.sample_rate = 2.048e6  # Hz - Sample Rate is the number of samples of audio carried per second. (https://manual.audacityteam.org/man/sample_rates.html)
    sdr.center_freq = measured  # Hz
    sdr.freq_correction = 60  # PPM - I Don't Know How This is Set - Something to Do With rtl_test -p 10
    sdr.gain = 'auto'

    try:
        client = SDRKeyFob()
        #plugin = RemotePlugin(client,
        #                  name="hello",
        #                  version="0.0.1",
        #                  bg_host='127.0.0.1',
        #                  bg_port=2337)
        #plugin.run()
        client.listen(sdr)
        #client.printMe(sdr);
        #client.plotMe(sdr); # Great for Debugging
    except SystemExit as error:
        print('\n' + str(error))
Ejemplo n.º 27
0
from pylab import *
import sounddevice as sd
from scipy.io.wavfile import write
import matplotlib.pyplot as plt

F_station = int(88.7e6)  # Rutgers Radio
F_offset = 250000  # Offset to capture at
# We capture at an offset to avoid DC spike
Fc = F_station - F_offset  # Capture center frequency
Fs = int(1140000)  # Sample rate
N = int(4 * 8192000)  # Samples to capture

sdr = RtlSdr()
sdr.sample_rate = Fs  # Hz
sdr.center_freq = Fc  # Hz s
sdr.freq_correction = 60  # PPM (Parts Per Million)
sdr.gain = 'auto'  #pick gain value
samples = sdr.read_samples(N)
print(samples)
sdr.close()

# Read in the samples:
IQ = np.array(samples, dtype=np.complex)
print("IQ (Saad): ", IQ)
multiplied = IQ[:-1] * np.conj(IQ[1:])
demodulated = np.angle(multiplied)
print("Demodulted (IQ Mert): ", demodulated)

plt.specgram(IQ, NFFT=2048, Fs=Fs)
plt.title("x1")
plt.ylim(-Fs / 2, Fs / 2)
Ejemplo n.º 28
0
"""
Created on Sun Jun  7 19:35:14 2020

@author: ord
"""
import numpy as np
from rtlsdr import RtlSdr
from matplotlib import pyplot as plt
import scipy.signal as signal

sdr = RtlSdr()

#conigure device
sdr.sample_rate = 2.048e6  #Hz
sdr.center_freq = 105.5e6  #Hz
sdr.freq_correction = 60  #ppm
sdr.gain = 12.5
sdr.set_agc_mode(False)
#sdr.bandwidth = 10e6 #Hz

n = 500
nfft = 1024
tiempo_muestreo = n * nfft / sdr.sample_rate
iq = sdr.read_samples(n * nfft)

sdr.close()

# plt.specgram(iq, NFFT=1024, Fs=sdr.sample_rate, Fc = sdr.center_freq/1e6)
# plt.title("PSD of 'signal' loaded from file")
# plt.xlabel("Time")
# plt.ylabel("Frequency (MHz)")
Ejemplo n.º 29
0
"""

from matplotlib import mlab
from rtlsdr import RtlSdr
import numpy as np
from PIL import Image
import pygame

DISPLAY_WIDTH = 256
DISPLAY_HEIGHT = 200

SDR = RtlSdr()
# configure device
SDR.sample_rate = 2.4e6  # Hz
SDR.center_freq = 94.7e6  # Hz
SDR.freq_correction = 60  # PPM
SDR.gain = 'auto'

IMAGE = []


def get_data():
    """
    Reads new samples and updates output image.
    """

    samples = SDR.read_samples(16 * 1024)
    power, _ = mlab.psd(samples, NFFT=1024, Fs=SDR.sample_rate / 1e6)

    max_pow = 0
    min_pow = 10
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import time
import glob
from rtlsdr import RtlSdr
from scipy.signal import medfilt

flist = glob.glob('./ring/*.wav')
print(flist)
sdr = RtlSdr()

# configure device
sdr.sample_rate = 2.3e5  # Hz
sdr.center_freq = 433e6  # Hz
sdr.freq_correction = 1  # PPM
sdr.gain = 80

z = np.load("template.npy")
N = 2**16
M = 2
y = np.zeros(N * M, dtype=np.complex_)


def listen(y, N, M):
    for i in range(M):
        idx = np.arange(N) + i * N
        x = np.array(sdr.read_samples(N))
        y[idx] = x
    y = np.absolute(y)
    y = medfilt(y, 5)
Ejemplo n.º 31
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 "];"