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
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()
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)
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))
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()
async def streaming(): sdr = RtlSdr() sdr.sample_rate = 1.2e6 sdr.center_freq = 91.8e6 prev = None device.write(np.array([0] * 100000).astype('int16')) async for samples in sdr.stream(): samples = np.array(samples).astype('complex64') samples = signal.decimate(samples, int(1.2e6 / 200e3)) if prev is not None: samples = np.insert(samples, 0, prev) prev = samples[-1] samples = np.angle(samples[1:] * np.conj(samples[:-1])) x = np.exp(-1 / (200e3 * 75e-6)) samples = signal.lfilter([1 - x], [1, -x], samples) samples = signal.decimate(samples, int(200e3 / 50e3)) samples *= 10000 device.write(samples.astype('int16')) await sdr.stop() sdr.close()
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 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()
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
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);
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)
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
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))
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 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 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()
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 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()
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
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()
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
def from_rtl(self, freq=93.3e6, rate=256000, samples=8192000): try: sdr = RtlSdr() # configure device # in Hz sdr.sample_rate = int(rate) sdr.center_freq = freq sdr.gain = 'auto' # Read samples samples = sdr.read_samples(samples) # Clean up the SDR device sdr.close() del (sdr) self.data = np.array(samples).astype('complex64') self.dtype = self.data.dtype self.rate = rate * u.Hz self.center_freq = freq * u.Hz self.nitems = len(self.data) self.exptime = (self.nitems / self.rate) except: raise IOError("Could not read from RTLSDR")
F_station = int(89.2e6) #Radio Disney F_offset = 250000 #Offset Fc = F_station - F_offset #center frequency Fs = int(1140000) #Sample rate 1140000 N = int(8192000) #Samples to capture 8192000 f_bw = 200000 n_taps = 64 audio_freq = 44100.0 tone_len = 0.125 filter_freq = 600 amp_thresh = 1.5 #1.5 on computer, 0.46 far away #configure sdr.sample_rate = Fs sdr.center_freq = Fc sdr.gain = 'auto' #Read samples print('Starting Audio Stream') samples = sdr.read_samples(N) print('Ending Audio Stream') #print(samples) # Clean up sdr.close() del (sdr) #numpy array x1 = np.array(samples).astype("complex64")
# -------------------------------------------parameters for time_analyse N = 1 # times of sample, we use only one time Nu = 56 M=256 # frequency bins to calculate power 512 best NN=100 # times for loop # --------------------------------------------Get a list of detected device #first sensor serial_numbers = RtlSdr.get_device_serial_addresses() print(serial_numbers) sdr0 = RtlSdr(serial_number='10') sdr0.sample_rate = myglobals.sample_rate sdr0.center_freq = myglobals.center_freq sdr0.gain = 1 # second sensor sdr1 = RtlSdr(serial_number='11') sdr1.sample_rate = myglobals.sample_rate sdr1.center_freq = myglobals.center_freq sdr1.gain = 1 # third sensor sdr2 = RtlSdr(serial_number='12') sdr2.sample_rate = myglobals.sample_rate sdr2.center_freq = myglobals.center_freq sdr2.gain = 1 # fourth sensor sdr3 = RtlSdr(serial_number='13') sdr3.sample_rate = myglobals.sample_rate sdr3.center_freq = myglobals.center_freq
Fs = 2.048e6 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()
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!")
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
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)
parser.add_argument('-g', '--gain', type=int, help='sets the SDR gain (default: 496).', default=496) parser.add_argument('-d', '--device', type=int, help='sets the SDR device (default: 0).', default=0) args = parser.parse_args() # configure SDR device sdr = RtlSdr(args.device) sdr.sample_rate = 2.4e6 sdr.center_freq = args.frequency * 1e6 sdr.gain = args.gain sdr.set_agc_mode(0) #print_sdr_config(sdr) # read from specified webcam cap = cv2.VideoCapture(args.camera) if cap is None or not cap.isOpened(): print('Error: unable to open video source: ', args.camera) else: # wait some time for the camera to be ready time.sleep(2.0) # initialize variables powermap = None firstFrame = None
#print "Stepsize = " + str(stepsize*10) print "Steps = " + str(steps) X = np.linspace(freq_int*10, freq_int*10 + int(bw), samples) print args.output_path + '--' + csvfile + '.csv' sys.stdout.flush() for x in range(0, 1000000): time.sleep(5) cent_freq = (int(low_freq) + (x%steps)) # configure device sample_rate = samp_rate # sdr.freq_correction = 82 #freq = 1379.913e6 # freq = [freq_int*10)+stepsize*x*10 if freq_int*10<(freq_int*10+int(bw)) else cent_freq] print 'low_freq,',low_freq sdr.sample_rate = sample_rate # Hz sdr.center_freq = cent_freq # Hz sdr.gain = 'auto' sampnumber = 8192*2*2*2*2*2*2 samples2 = sdr.read_samples(sampnumber) #ser.write("\x8f\x78" + freq_str + stepsize_str + samples_str) # print freq time.sleep(1) #print "please wait..." #print s # byte_list = map(ord,t) bdrate = 2000 phasesarr=[] phases=np.arctan2((samples2.imag),(samples2.real)) codeword="001001011101010111000000110011101000100110010000111101101100100101000110000110111111011110011100110110100010101000111111001100010111011001101111000010010011011010111001111001000000100001100011"
from radio_params import * from radio_transmit import * record_len = 75 ## configure SDR sdr = RtlSdr() freq_offset = 93.2e3 sample_rate = 240e3 center_freq = 443.592e6 - freq_offset #center_freq = 145.442e6 #- freq_offset sdr.sample_rate = sample_rate sdr.center_freq = center_freq sdr.gain = 10 ## get samples samples = [] def callback(ss, obj): samples.append(ss) #obj.cancel_read_async() print('Ready to record!') raw_input("Press Enter to record...") print('recording...') N_samples = sample_rate*0.5 # approximately seconds sdr.read_samples_async(limit_time(record_len)(callback), N_samples) # get samples
#echos rtlsdr read_samples output (without lines starting with hyphen) to console and to ~/finaldata.txt import os from rtlsdr import RtlSdr os.chdir(os.path.expanduser("~/")) sdr = RtlSdr() sdr.sample_rate = 2.048e6 #Hz sdr.center_freq = 70e6 # Hz sdr.freq_correction = 60 # PPM sdr.gain = 'auto' sdroutput = str(sdr.read_samples(512)) savefile = open('finaldata.txt', 'w') sdr1 = sdroutput.translate(None, '[]').split() sdr2 = sdr1 finaldata = '' for line in sdr2: if not "-" in line: finaldata+=line+"\n" print finaldata savefile.write(finaldata) savefile.close()
config.sample_num = int(sys.argv[i+1]) 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 "];"
from rtlsdr import RtlSdr sdr = RtlSdr() # configure device sdr.sample_rate = 240e3 # Hz sdr.center_freq = 101.7e6 # Hz sdr.freq_correction = 0 # PPM sdr.gain = 'auto' print(sdr.read_samples(512))
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()
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
import numpy as np import time from rtlsdr import RtlSdr sdr = RtlSdr() #config sdr.samle_rate = 2.048e6 sdr.center_freq = 433888000 #sdr.freq_correction = 60 sdr.gain = 'auto' #print(sdr.read_samples(512)) burst = 0 burst_time = 0 overall_avg = 20 while True: samples = sdr.read_samples(512*2); #run an FFT and take absolute value to get freq magnitudes freqs = np.absolute(np.fft.fft(samples)) #ignore the mean/DC values at ends freqs = freqs[1:-1] #Shift FFT result positions to put center frequency in center freqs = np.fft.fftshift(freqs) #convert to decibels freqs = 20.0*np.log10(freqs) mean = np.mean(freqs) min = np.min(freqs)
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
import matplotlib.pyplot as plt from rtlsdr import RtlSdr import time from SSN_modul.Received_power import received_power from SSN_modul.Received_power import received_power2 from SSN_modul.self_psd import selfpsd # Get a list of detected device serial numbers (str) serial_numbers = RtlSdr.get_device_serial_addresses() #---------------------------------------------------------first sensor # Find the device index for a given serial number device_index0 = RtlSdr.get_device_index_by_serial(serial_numbers[0]) sdr0 = RtlSdr(device_index0) sdr0.sample_rate = 3.2e6 sdr0.center_freq = 1600*1e6 sdr0.gain = 4 #---------------------------------------------------------second sensor device_index1 = RtlSdr.get_device_index_by_serial(serial_numbers[1]) sdr1 = RtlSdr(device_index1) sdr1.sample_rate = 3.2e6 sdr1.center_freq = 1600*1e6 sdr1.gain = 4 N = 1 M=128 NN=100 def receive_power1(): rec=NN # time of samples while rec: rec=rec-1 raw_data = np.zeros((N, 1024))
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
return (num,den); fmDemod = FMDemod(); fileRead = FileReader(); audioPlay = AudioPlay(); dataQueue = Queue.Queue([1]); audioQueue = Queue.Queue([1]); sdr = RtlSdr(); # configure device sdr.sample_rate = 250e3; # Hz numSampsRead = 1024*600; freq = raw_input('Choose a station frequency: '); try: freq = float(freq); sdr.center_freq = freq; sdr.gain = 'auto'; #fileRead.start(); fmDemod.start(); audioPlay.start(); sdr.read_samples_async(sdrCallback, numSampsRead); except ValueError: print("Invalid number");
from rtlsdr import RtlSdr import numpy as np from pylab import psd sdr = RtlSdr() sdr.sample_rate = 2.4e6 sdr.center_freq = 105e6 sdr.gain = 4 passes = 1000 fftbins = 1024 samples = sdr.read_samples(passes * fftbins) sdr.close() print(samples[0]) spectra = psd(samples, NFFT=fftbins, Fs=sdr.sample_rate / 1e6, Fc=sdr.center_freq / 1e6) print(spectra[0]) print(spectra[1])
import cv2 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