Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- """
- Created on Sun Apr 5 19:06:56 2015
- @author: madengr
- @Modified by: Ashraf
- """
- from gnuradio import gr
- from gnuradio import uhd
- from gnuradio import filter # Warning: redefining built-in filter()
- from gnuradio import blocks
- from gps import *
- import MySQLdb
- import threading
- import time
- import numpy as np
- gpsd = None
- db = MySQLdb.connect(host="********", user="******", passwd="******", db="*******") #Log in to database
- cur = db.cursor() #Cursor for the database
- addData = ("INSERT INTO *****" "(Date, Time, Device_ID, Latitude, Longitude, Altitude, Speed, Frequency, Power) " "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)") #Database structure
- freq = []
- date = ""
- time1 = ""
- deviceId = ""
- lat = ""
- longi = ""
- alti = ""
- speed = ""
- freqString = []
- powerDbm = []
- def str_to_floats(data):
- """Convert string of floats to list of floats
- Used for converting GNU Radio message queue strings
- """
- import struct
- floats = []
- for i in range(0,len(data),4):
- floats.append(struct.unpack_from('f',data[i:i+4])[0])
- return np.array(floats)
- class ScannerTopBlock(gr.top_block):
- """ Class for the GNU Radio GSM channel scanner flow
- """
- def __init__(self):
- # Call the initialization method from the parent class
- gr.top_block.__init__(self, "GSM Channel Scanner")
- # Define the constants
- uhd_args = "type=b200, master_clock_rate=50E6"
- src_samp_rate = 1E6
- rx_freq = 1830.2E6
- src_gain_dB = 20
- rssi_cal_offset_dB = -24.2
- antennaOption = input('Enter 1 for GHz or 2 for MHz: ')
- if antennaOption == 2:
- antenna = 'TX/RX'
- else:
- antenna = 'RX2'
- # Creating list of frequnecies from file
- global freq #so I can use it in main()
- freqH = []
- freqL = []
- with open('nFreq') as fr:
- lines = fr.read().splitlines()
- fr.close()
- for i in range(0, len(lines) - 1):
- lines[i].replace('\r\n', "")
- lines[i] = float(lines[i])
- if antennaOption == 1 and lines[i] > 2.4 * 1000000000:
- freqH.append(lines[i])
- elif antennaOption == 2 and lines[i] < 2.4 * 1000000000:
- freqL.append(lines[i])
- if antennaOption == 1:
- freq = freqH
- else:
- freq = freqL
- # Initialize a queue
- self.sink_queue = gr.msg_queue()
- # Setup the USRP source
- self.src = uhd.usrp_source(uhd_args, uhd.io_type_t.COMPLEX_FLOAT32, 1)
- self.src.set_samp_rate(src_samp_rate)
- self.src.set_gain(src_gain_dB, 0)
- self.src.set_center_freq(rx_freq, 0)
- self.src.set_antenna(antenna, 0)
- # Generate taps for frequency translating FIR filter
- filter_taps = filter.firdes.low_pass(gain=1.0, sampling_freq=src_samp_rate, cutoff_freq=100E3, transition_width=25E3, window=filter.firdes.WIN_HAMMING)
- # Channel filter
- channel_filter = filter.fir_filter_ccc(1, filter_taps)
- # Calculate power for RSSI
- c2magsqr = blocks.complex_to_mag_squared(1)
- # Integrate for mean power and decimate down to 100 Hz
- integrator = blocks.integrate_ff(10000)
- # Take 10*Log10() and offset for calibrated power and src gain
- logten = blocks.nlog10_ff(10, 1, rssi_cal_offset_dB-src_gain_dB)
- # Message sink
- self.msg_sink = blocks.message_sink(gr.sizeof_float, self.sink_queue, False)
- # Connect the blocks for the RSSI
- self.connect(self.src, channel_filter, c2magsqr, integrator, logten, self.msg_sink)
- class GpsPoller(threading.Thread):
- def __init__(self):
- threading.Thread.__init__(self)
- global gpsd #bring it in scope
- gpsd = gps(mode=WATCH_ENABLE) #starting the stream of info
- self.current_value = None
- self.running = True #setting the thread running to true
- def run(self):
- global gpsd
- while gpsp.running:
- gpsd.next() #this will continue to loop and grab EACH set of gpsd info to clear the buffer
- def main():
- """ Start the flow """
- # Set a threshold in dBm to log the channel
- threshold_dBm = -88
- # Lets offset tune to avoid DC spike
- lo_offset_freq = 1.1E6
- # Start the flow
- tb = ScannerTopBlock()
- tb.start()
- # Get the time so we know how long it takes to scan
- print "Starting GSM channel scan"
- t0 = time.time()
- date = (str(time.strftime("%Y-%m-%d")))
- time1 = (str(time.strftime("%H:%M:%S")))
- deviceId = (str(2))
- lat = (str(gpsd.fix.latitude))
- longi = (str(gpsd.fix.longitude))
- alti = (str(gpsd.fix.altitude))
- speed = (str(gpsd.fix.speed))
- # Scan thru ARFCN
- for n in range(0, len(freq) - 1):
- channel_freq = freq[n]
- if not tb.src.set_center_freq(uhd.tune_request(channel_freq, lo_offset_freq)):
- print '[ERROR] Failed to set base frequency.'
- raise SystemExit, 1
- # Flush the queue
- tb.sink_queue.flush()
- # Wait for queue to fill and flush again to clean integrator
- while tb.sink_queue.count() == 0:
- pass
- tb.sink_queue.flush()
- # Wait for queue to fill then pull a sample
- while tb.sink_queue.count() == 0:
- pass
- rssi_str = tb.sink_queue.delete_head_nowait().to_string()
- # Convert to float value and log
- rssi = str_to_floats(rssi_str)[0]
- # Creating string structure for output with threshold value
- if rssi < threshold_dBm:
- freqString.append(str(freq[n]))
- powerDbm.append(str(rssi))
- # Print the elapsed time it took to scan
- print str(time.time() - t0) + " seconds to scan"
- print freq
- # Stop the flow
- tb.stop()
- tb.wait()
- if __name__ == '__main__':
- gpsp = GpsPoller()
- try:
- gpsp.start()
- main()
- gpsp.running = False
- gpsp.join()
- for l in range(0, len(freqString) - 1):
- cur.execute(addData, (date[l], time1[l], deviceId[l], lat[l], longi[l], alti[l], speed[l], freqString[l], powerDbm[l]))
- db.commit()
- cur.close()
- db.close()
- except KeyboardInterrupt:
- gpsp.running = False
- gpsp.join()
- db.commit()
- cur.close()
- db.close()
- pass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement