Advertisement
Guest User

Untitled

a guest
Jul 2nd, 2015
259
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.33 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Sun Apr  5 19:06:56 2015
  5.  
  6. @author: madengr
  7. @Modified by: Ashraf
  8. """
  9.  
  10. from gnuradio import gr
  11. from gnuradio import uhd
  12. from gnuradio import filter # Warning: redefining built-in filter()
  13. from gnuradio import blocks
  14. from gps import *
  15. import MySQLdb
  16. import threading
  17. import time
  18. import numpy as np
  19.  
  20. gpsd = None
  21.  
  22. db = MySQLdb.connect(host="********", user="******", passwd="******", db="*******") #Log in to database
  23. cur = db.cursor() #Cursor for the database
  24. 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
  25.  
  26. freq = []
  27. date = ""
  28. time1 = ""
  29. deviceId = ""
  30. lat = ""
  31. longi = ""
  32. alti = ""
  33. speed = ""
  34. freqString = []
  35. powerDbm = []
  36.  
  37. def str_to_floats(data):
  38.     """Convert string of floats to list of floats
  39.    
  40.    Used for converting GNU Radio message queue strings
  41.    """
  42.     import struct
  43.      
  44.     floats = []
  45.     for i in range(0,len(data),4):
  46.         floats.append(struct.unpack_from('f',data[i:i+4])[0])
  47.     return np.array(floats)
  48.  
  49. class ScannerTopBlock(gr.top_block):
  50.     """ Class for the GNU Radio GSM channel scanner flow
  51.    """
  52.    
  53.     def __init__(self):
  54.         # Call the initialization method from the parent class
  55.         gr.top_block.__init__(self, "GSM Channel Scanner")
  56.        
  57.         # Define the constants
  58.         uhd_args = "type=b200, master_clock_rate=50E6"
  59.         src_samp_rate = 1E6
  60.         rx_freq = 1830.2E6
  61.         src_gain_dB = 20
  62.         rssi_cal_offset_dB = -24.2
  63.     antennaOption = input('Enter 1 for GHz or 2 for MHz: ')
  64.     if antennaOption == 2:
  65.         antenna = 'TX/RX'
  66.     else:
  67.         antenna = 'RX2'
  68.  
  69.     # Creating list of frequnecies from file
  70.     global freq #so I can use it in main()
  71.     freqH = []
  72.     freqL = []
  73.     with open('nFreq') as fr:
  74.         lines = fr.read().splitlines()
  75.         fr.close()
  76.     for i in range(0, len(lines) - 1):
  77.         lines[i].replace('\r\n', "")
  78.         lines[i] = float(lines[i])
  79.         if antennaOption == 1 and lines[i] > 2.4 * 1000000000:
  80.         freqH.append(lines[i])
  81.         elif antennaOption == 2 and lines[i] < 2.4 * 1000000000:
  82.         freqL.append(lines[i])
  83.     if antennaOption == 1:
  84.         freq = freqH
  85.     else:
  86.         freq = freqL
  87.        
  88.         # Initialize a queue
  89.         self.sink_queue = gr.msg_queue()
  90.        
  91.         # Setup the USRP source
  92.         self.src = uhd.usrp_source(uhd_args, uhd.io_type_t.COMPLEX_FLOAT32, 1)
  93.         self.src.set_samp_rate(src_samp_rate)
  94.         self.src.set_gain(src_gain_dB, 0)
  95.         self.src.set_center_freq(rx_freq, 0)
  96.     self.src.set_antenna(antenna, 0)
  97.            
  98.         # Generate taps for frequency translating FIR filter
  99.         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)
  100.        
  101.         # Channel filter        
  102.         channel_filter = filter.fir_filter_ccc(1, filter_taps)
  103.        
  104.         # Calculate power for RSSI
  105.         c2magsqr = blocks.complex_to_mag_squared(1)
  106.  
  107.         # Integrate for mean power and decimate down to 100 Hz
  108.         integrator = blocks.integrate_ff(10000)
  109.  
  110.         # Take 10*Log10() and offset for calibrated power and src gain
  111.         logten = blocks.nlog10_ff(10, 1, rssi_cal_offset_dB-src_gain_dB)
  112.  
  113.         # Message sink
  114.         self.msg_sink = blocks.message_sink(gr.sizeof_float, self.sink_queue, False)
  115.        
  116.         # Connect the blocks for the RSSI
  117.         self.connect(self.src, channel_filter, c2magsqr, integrator, logten, self.msg_sink)
  118.  
  119.  
  120. class GpsPoller(threading.Thread):
  121.   def __init__(self):
  122.     threading.Thread.__init__(self)
  123.     global gpsd #bring it in scope
  124.     gpsd = gps(mode=WATCH_ENABLE) #starting the stream of info
  125.     self.current_value = None
  126.     self.running = True #setting the thread running to true
  127.  
  128.   def run(self):
  129.     global gpsd
  130.     while gpsp.running:
  131.       gpsd.next() #this will continue to loop and grab EACH set of gpsd info to clear the buffer
  132.        
  133.  
  134. def main():
  135.     """ Start the flow """
  136.     # Set a threshold in dBm to log the channel
  137.     threshold_dBm = -88
  138.    
  139.     # Lets offset tune to avoid DC spike    
  140.     lo_offset_freq = 1.1E6
  141.  
  142.     # Start the flow
  143.     tb = ScannerTopBlock()
  144.     tb.start()
  145.    
  146.     # Get the time so we know how long it takes to scan
  147.     print "Starting GSM channel scan"
  148.     t0 = time.time()  
  149.  
  150.     date = (str(time.strftime("%Y-%m-%d")))
  151.     time1 = (str(time.strftime("%H:%M:%S")))
  152.     deviceId = (str(2))
  153.     lat = (str(gpsd.fix.latitude))
  154.     longi = (str(gpsd.fix.longitude))
  155.     alti = (str(gpsd.fix.altitude))
  156.     speed = (str(gpsd.fix.speed))  
  157.    
  158.     # Scan thru ARFCN
  159.     for n in range(0, len(freq) - 1):
  160.        
  161.         channel_freq = freq[n]
  162.         if not tb.src.set_center_freq(uhd.tune_request(channel_freq, lo_offset_freq)):
  163.             print '[ERROR] Failed to set base frequency.'
  164.             raise SystemExit, 1
  165.        
  166.         # Flush the queue
  167.         tb.sink_queue.flush()
  168.            
  169.         # Wait for queue to fill and flush again to clean integrator
  170.         while tb.sink_queue.count() == 0:
  171.             pass
  172.         tb.sink_queue.flush()
  173.        
  174.         # Wait for queue to fill then pull a sample
  175.         while tb.sink_queue.count() == 0:
  176.             pass
  177.         rssi_str = tb.sink_queue.delete_head_nowait().to_string()
  178.        
  179.         # Convert to float value and log
  180.         rssi = str_to_floats(rssi_str)[0]
  181.        
  182.         # Creating string structure for output with threshold value    
  183.     if rssi < threshold_dBm:          
  184.         freqString.append(str(freq[n]))
  185.         powerDbm.append(str(rssi))
  186.          
  187.     # Print the elapsed time it took to scan
  188.     print str(time.time() - t0) + " seconds to scan"
  189.     print freq
  190.    
  191.     # Stop the flow
  192.     tb.stop()
  193.     tb.wait()
  194.  
  195. if __name__ == '__main__':
  196.     gpsp = GpsPoller()
  197.     try:
  198.     gpsp.start()
  199.         main()
  200.     gpsp.running = False
  201.     gpsp.join()
  202.     for l in range(0, len(freqString) - 1):
  203.         cur.execute(addData, (date[l], time1[l], deviceId[l], lat[l], longi[l], alti[l], speed[l], freqString[l], powerDbm[l]))
  204.     db.commit()
  205.         cur.close()
  206.         db.close()
  207.     except KeyboardInterrupt:
  208.     gpsp.running = False
  209.     gpsp.join()
  210.     db.commit()
  211.         cur.close()
  212.         db.close()
  213.         pass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement